Merge branch 'master_MDL-57324' of git://github.com/danmarsden/moodle
[moodle.git] / lib / navigationlib.php
blobd858fb2dad4a85c9a826a89d5be1e735743c4f9c
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;
88 /** @var int Parameter to aid the coder in tracking [optional] */
89 public $id = null;
90 /** @var string|int The identifier for the node, used to retrieve the node */
91 public $key = null;
92 /** @var string The text to use for the node */
93 public $text = null;
94 /** @var string Short text to use if requested [optional] */
95 public $shorttext = null;
96 /** @var string The title attribute for an action if one is defined */
97 public $title = null;
98 /** @var string A string that can be used to build a help button */
99 public $helpbutton = null;
100 /** @var moodle_url|action_link|null An action for the node (link) */
101 public $action = null;
102 /** @var pix_icon The path to an icon to use for this node */
103 public $icon = null;
104 /** @var int See TYPE_* constants defined for this class */
105 public $type = self::TYPE_UNKNOWN;
106 /** @var int See NODETYPE_* constants defined for this class */
107 public $nodetype = self::NODETYPE_LEAF;
108 /** @var bool If set to true the node will be collapsed by default */
109 public $collapse = false;
110 /** @var bool If set to true the node will be expanded by default */
111 public $forceopen = false;
112 /** @var array An array of CSS classes for the node */
113 public $classes = array();
114 /** @var navigation_node_collection An array of child nodes */
115 public $children = array();
116 /** @var bool If set to true the node will be recognised as active */
117 public $isactive = false;
118 /** @var bool If set to true the node will be dimmed */
119 public $hidden = false;
120 /** @var bool If set to false the node will not be displayed */
121 public $display = true;
122 /** @var bool If set to true then an HR will be printed before the node */
123 public $preceedwithhr = false;
124 /** @var bool If set to true the the navigation bar should ignore this node */
125 public $mainnavonly = false;
126 /** @var bool If set to true a title will be added to the action no matter what */
127 public $forcetitle = false;
128 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
129 public $parent = null;
130 /** @var bool Override to not display the icon even if one is provided **/
131 public $hideicon = false;
132 /** @var bool Set to true if we KNOW that this node can be expanded. */
133 public $isexpandable = false;
134 /** @var array */
135 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting',71=>'siteadmin', 80=>'user');
136 /** @var moodle_url */
137 protected static $fullmeurl = null;
138 /** @var bool toogles auto matching of active node */
139 public static $autofindactive = true;
140 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
141 protected static $loadadmintree = false;
142 /** @var mixed If set to an int, that section will be included even if it has no activities */
143 public $includesectionnum = false;
144 /** @var bool does the node need to be loaded via ajax */
145 public $requiresajaxloading = false;
146 /** @var bool If set to true this node will be added to the "flat" navigation */
147 public $showinflatnavigation = false;
150 * Constructs a new navigation_node
152 * @param array|string $properties Either an array of properties or a string to use
153 * as the text for the node
155 public function __construct($properties) {
156 if (is_array($properties)) {
157 // Check the array for each property that we allow to set at construction.
158 // text - The main content for the node
159 // shorttext - A short text if required for the node
160 // icon - The icon to display for the node
161 // type - The type of the node
162 // key - The key to use to identify the node
163 // parent - A reference to the nodes parent
164 // action - The action to attribute to this node, usually a URL to link to
165 if (array_key_exists('text', $properties)) {
166 $this->text = $properties['text'];
168 if (array_key_exists('shorttext', $properties)) {
169 $this->shorttext = $properties['shorttext'];
171 if (!array_key_exists('icon', $properties)) {
172 $properties['icon'] = new pix_icon('i/navigationitem', '');
174 $this->icon = $properties['icon'];
175 if ($this->icon instanceof pix_icon) {
176 if (empty($this->icon->attributes['class'])) {
177 $this->icon->attributes['class'] = 'navicon';
178 } else {
179 $this->icon->attributes['class'] .= ' navicon';
182 if (array_key_exists('type', $properties)) {
183 $this->type = $properties['type'];
184 } else {
185 $this->type = self::TYPE_CUSTOM;
187 if (array_key_exists('key', $properties)) {
188 $this->key = $properties['key'];
190 // This needs to happen last because of the check_if_active call that occurs
191 if (array_key_exists('action', $properties)) {
192 $this->action = $properties['action'];
193 if (is_string($this->action)) {
194 $this->action = new moodle_url($this->action);
196 if (self::$autofindactive) {
197 $this->check_if_active();
200 if (array_key_exists('parent', $properties)) {
201 $this->set_parent($properties['parent']);
203 } else if (is_string($properties)) {
204 $this->text = $properties;
206 if ($this->text === null) {
207 throw new coding_exception('You must set the text for the node when you create it.');
209 // Instantiate a new navigation node collection for this nodes children
210 $this->children = new navigation_node_collection();
214 * Checks if this node is the active node.
216 * This is determined by comparing the action for the node against the
217 * defined URL for the page. A match will see this node marked as active.
219 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
220 * @return bool
222 public function check_if_active($strength=URL_MATCH_EXACT) {
223 global $FULLME, $PAGE;
224 // Set fullmeurl if it hasn't already been set
225 if (self::$fullmeurl == null) {
226 if ($PAGE->has_set_url()) {
227 self::override_active_url(new moodle_url($PAGE->url));
228 } else {
229 self::override_active_url(new moodle_url($FULLME));
233 // Compare the action of this node against the fullmeurl
234 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
235 $this->make_active();
236 return true;
238 return false;
242 * True if this nav node has siblings in the tree.
244 * @return bool
246 public function has_siblings() {
247 if (empty($this->parent) || empty($this->parent->children)) {
248 return false;
250 if ($this->parent->children instanceof navigation_node_collection) {
251 $count = $this->parent->children->count();
252 } else {
253 $count = count($this->parent->children);
255 return ($count > 1);
259 * Get a list of sibling navigation nodes at the same level as this one.
261 * @return bool|array of navigation_node
263 public function get_siblings() {
264 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
265 // the in-page links or the breadcrumb links.
266 $siblings = false;
268 if ($this->has_siblings()) {
269 $siblings = [];
270 foreach ($this->parent->children as $child) {
271 if ($child->display) {
272 $siblings[] = $child;
276 return $siblings;
280 * This sets the URL that the URL of new nodes get compared to when locating
281 * the active node.
283 * The active node is the node that matches the URL set here. By default this
284 * is either $PAGE->url or if that hasn't been set $FULLME.
286 * @param moodle_url $url The url to use for the fullmeurl.
287 * @param bool $loadadmintree use true if the URL point to administration tree
289 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
290 // Clone the URL, in case the calling script changes their URL later.
291 self::$fullmeurl = new moodle_url($url);
292 // True means we do not want AJAX loaded admin tree, required for all admin pages.
293 if ($loadadmintree) {
294 // Do not change back to false if already set.
295 self::$loadadmintree = true;
300 * Use when page is linked from the admin tree,
301 * if not used navigation could not find the page using current URL
302 * because the tree is not fully loaded.
304 public static function require_admin_tree() {
305 self::$loadadmintree = true;
309 * Creates a navigation node, ready to add it as a child using add_node
310 * function. (The created node needs to be added before you can use it.)
311 * @param string $text
312 * @param moodle_url|action_link $action
313 * @param int $type
314 * @param string $shorttext
315 * @param string|int $key
316 * @param pix_icon $icon
317 * @return navigation_node
319 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
320 $shorttext=null, $key=null, pix_icon $icon=null) {
321 // Properties array used when creating the new navigation node
322 $itemarray = array(
323 'text' => $text,
324 'type' => $type
326 // Set the action if one was provided
327 if ($action!==null) {
328 $itemarray['action'] = $action;
330 // Set the shorttext if one was provided
331 if ($shorttext!==null) {
332 $itemarray['shorttext'] = $shorttext;
334 // Set the icon if one was provided
335 if ($icon!==null) {
336 $itemarray['icon'] = $icon;
338 // Set the key
339 $itemarray['key'] = $key;
340 // Construct and return
341 return new navigation_node($itemarray);
345 * Adds a navigation node as a child of this node.
347 * @param string $text
348 * @param moodle_url|action_link $action
349 * @param int $type
350 * @param string $shorttext
351 * @param string|int $key
352 * @param pix_icon $icon
353 * @return navigation_node
355 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
356 // Create child node
357 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
359 // Add the child to end and return
360 return $this->add_node($childnode);
364 * Adds a navigation node as a child of this one, given a $node object
365 * created using the create function.
366 * @param navigation_node $childnode Node to add
367 * @param string $beforekey
368 * @return navigation_node The added node
370 public function add_node(navigation_node $childnode, $beforekey=null) {
371 // First convert the nodetype for this node to a branch as it will now have children
372 if ($this->nodetype !== self::NODETYPE_BRANCH) {
373 $this->nodetype = self::NODETYPE_BRANCH;
375 // Set the parent to this node
376 $childnode->set_parent($this);
378 // Default the key to the number of children if not provided
379 if ($childnode->key === null) {
380 $childnode->key = $this->children->count();
383 // Add the child using the navigation_node_collections add method
384 $node = $this->children->add($childnode, $beforekey);
386 // If added node is a category node or the user is logged in and it's a course
387 // then mark added node as a branch (makes it expandable by AJAX)
388 $type = $childnode->type;
389 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
390 ($type === self::TYPE_SITE_ADMIN)) {
391 $node->nodetype = self::NODETYPE_BRANCH;
393 // If this node is hidden mark it's children as hidden also
394 if ($this->hidden) {
395 $node->hidden = true;
397 // Return added node (reference returned by $this->children->add()
398 return $node;
402 * Return a list of all the keys of all the child nodes.
403 * @return array the keys.
405 public function get_children_key_list() {
406 return $this->children->get_key_list();
410 * Searches for a node of the given type with the given key.
412 * This searches this node plus all of its children, and their children....
413 * If you know the node you are looking for is a child of this node then please
414 * use the get method instead.
416 * @param int|string $key The key of the node we are looking for
417 * @param int $type One of navigation_node::TYPE_*
418 * @return navigation_node|false
420 public function find($key, $type) {
421 return $this->children->find($key, $type);
425 * Walk the tree building up a list of all the flat navigation nodes.
427 * @param flat_navigation $nodes List of the found flat navigation nodes.
428 * @param boolean $showdivider Show a divider before the first node.
430 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false) {
431 if ($this->showinflatnavigation) {
432 $indent = 0;
433 if ($this->type == self::TYPE_COURSE) {
434 $indent = 1;
436 $flat = new flat_navigation_node($this, $indent);
437 $flat->set_showdivider($showdivider);
438 $nodes->add($flat);
440 foreach ($this->children as $child) {
441 $child->build_flat_navigation_list($nodes, false);
446 * Get the child of this node that has the given key + (optional) type.
448 * If you are looking for a node and want to search all children + their children
449 * then please use the find method instead.
451 * @param int|string $key The key of the node we are looking for
452 * @param int $type One of navigation_node::TYPE_*
453 * @return navigation_node|false
455 public function get($key, $type=null) {
456 return $this->children->get($key, $type);
460 * Removes this node.
462 * @return bool
464 public function remove() {
465 return $this->parent->children->remove($this->key, $this->type);
469 * Checks if this node has or could have any children
471 * @return bool Returns true if it has children or could have (by AJAX expansion)
473 public function has_children() {
474 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
478 * Marks this node as active and forces it open.
480 * Important: If you are here because you need to mark a node active to get
481 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
482 * You can use it to specify a different URL to match the active navigation node on
483 * rather than having to locate and manually mark a node active.
485 public function make_active() {
486 $this->isactive = true;
487 $this->add_class('active_tree_node');
488 $this->force_open();
489 if ($this->parent !== null) {
490 $this->parent->make_inactive();
495 * Marks a node as inactive and recusised back to the base of the tree
496 * doing the same to all parents.
498 public function make_inactive() {
499 $this->isactive = false;
500 $this->remove_class('active_tree_node');
501 if ($this->parent !== null) {
502 $this->parent->make_inactive();
507 * Forces this node to be open and at the same time forces open all
508 * parents until the root node.
510 * Recursive.
512 public function force_open() {
513 $this->forceopen = true;
514 if ($this->parent !== null) {
515 $this->parent->force_open();
520 * Adds a CSS class to this node.
522 * @param string $class
523 * @return bool
525 public function add_class($class) {
526 if (!in_array($class, $this->classes)) {
527 $this->classes[] = $class;
529 return true;
533 * Removes a CSS class from this node.
535 * @param string $class
536 * @return bool True if the class was successfully removed.
538 public function remove_class($class) {
539 if (in_array($class, $this->classes)) {
540 $key = array_search($class,$this->classes);
541 if ($key!==false) {
542 unset($this->classes[$key]);
543 return true;
546 return false;
550 * Sets the title for this node and forces Moodle to utilise it.
551 * @param string $title
553 public function title($title) {
554 $this->title = $title;
555 $this->forcetitle = true;
559 * Resets the page specific information on this node if it is being unserialised.
561 public function __wakeup(){
562 $this->forceopen = false;
563 $this->isactive = false;
564 $this->remove_class('active_tree_node');
568 * Checks if this node or any of its children contain the active node.
570 * Recursive.
572 * @return bool
574 public function contains_active_node() {
575 if ($this->isactive) {
576 return true;
577 } else {
578 foreach ($this->children as $child) {
579 if ($child->isactive || $child->contains_active_node()) {
580 return true;
584 return false;
588 * To better balance the admin tree, we want to group all the short top branches together.
590 * This means < 8 nodes and no subtrees.
592 * @return bool
594 public function is_short_branch() {
595 $limit = 8;
596 if ($this->children->count() >= $limit) {
597 return false;
599 foreach ($this->children as $child) {
600 if ($child->has_children()) {
601 return false;
604 return true;
608 * Finds the active node.
610 * Searches this nodes children plus all of the children for the active node
611 * and returns it if found.
613 * Recursive.
615 * @return navigation_node|false
617 public function find_active_node() {
618 if ($this->isactive) {
619 return $this;
620 } else {
621 foreach ($this->children as &$child) {
622 $outcome = $child->find_active_node();
623 if ($outcome !== false) {
624 return $outcome;
628 return false;
632 * Searches all children for the best matching active node
633 * @return navigation_node|false
635 public function search_for_active_node() {
636 if ($this->check_if_active(URL_MATCH_BASE)) {
637 return $this;
638 } else {
639 foreach ($this->children as &$child) {
640 $outcome = $child->search_for_active_node();
641 if ($outcome !== false) {
642 return $outcome;
646 return false;
650 * Gets the content for this node.
652 * @param bool $shorttext If true shorttext is used rather than the normal text
653 * @return string
655 public function get_content($shorttext=false) {
656 if ($shorttext && $this->shorttext!==null) {
657 return format_string($this->shorttext);
658 } else {
659 return format_string($this->text);
664 * Gets the title to use for this node.
666 * @return string
668 public function get_title() {
669 if ($this->forcetitle || $this->action != null){
670 return $this->title;
671 } else {
672 return '';
677 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
679 * @return boolean
681 public function has_action() {
682 return !empty($this->action);
686 * Gets the CSS class to add to this node to describe its type
688 * @return string
690 public function get_css_type() {
691 if (array_key_exists($this->type, $this->namedtypes)) {
692 return 'type_'.$this->namedtypes[$this->type];
694 return 'type_unknown';
698 * Finds all nodes that are expandable by AJAX
700 * @param array $expandable An array by reference to populate with expandable nodes.
702 public function find_expandable(array &$expandable) {
703 foreach ($this->children as &$child) {
704 if ($child->display && $child->has_children() && $child->children->count() == 0) {
705 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
706 $this->add_class('canexpand');
707 $child->requiresajaxloading = true;
708 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
710 $child->find_expandable($expandable);
715 * Finds all nodes of a given type (recursive)
717 * @param int $type One of navigation_node::TYPE_*
718 * @return array
720 public function find_all_of_type($type) {
721 $nodes = $this->children->type($type);
722 foreach ($this->children as &$node) {
723 $childnodes = $node->find_all_of_type($type);
724 $nodes = array_merge($nodes, $childnodes);
726 return $nodes;
730 * Removes this node if it is empty
732 public function trim_if_empty() {
733 if ($this->children->count() == 0) {
734 $this->remove();
739 * Creates a tab representation of this nodes children that can be used
740 * with print_tabs to produce the tabs on a page.
742 * call_user_func_array('print_tabs', $node->get_tabs_array());
744 * @param array $inactive
745 * @param bool $return
746 * @return array Array (tabs, selected, inactive, activated, return)
748 public function get_tabs_array(array $inactive=array(), $return=false) {
749 $tabs = array();
750 $rows = array();
751 $selected = null;
752 $activated = array();
753 foreach ($this->children as $node) {
754 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
755 if ($node->contains_active_node()) {
756 if ($node->children->count() > 0) {
757 $activated[] = $node->key;
758 foreach ($node->children as $child) {
759 if ($child->contains_active_node()) {
760 $selected = $child->key;
762 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
764 } else {
765 $selected = $node->key;
769 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
773 * Sets the parent for this node and if this node is active ensures that the tree is properly
774 * adjusted as well.
776 * @param navigation_node $parent
778 public function set_parent(navigation_node $parent) {
779 // Set the parent (thats the easy part)
780 $this->parent = $parent;
781 // Check if this node is active (this is checked during construction)
782 if ($this->isactive) {
783 // Force all of the parent nodes open so you can see this node
784 $this->parent->force_open();
785 // Make all parents inactive so that its clear where we are.
786 $this->parent->make_inactive();
791 * Hides the node and any children it has.
793 * @since Moodle 2.5
794 * @param array $typestohide Optional. An array of node types that should be hidden.
795 * If null all nodes will be hidden.
796 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
797 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
799 public function hide(array $typestohide = null) {
800 if ($typestohide === null || in_array($this->type, $typestohide)) {
801 $this->display = false;
802 if ($this->has_children()) {
803 foreach ($this->children as $child) {
804 $child->hide($typestohide);
811 * Get the action url for this navigation node.
812 * Called from templates.
814 * @since Moodle 3.2
816 public function action() {
817 if ($this->action instanceof moodle_url) {
818 return $this->action;
819 } else if ($this->action instanceof action_link) {
820 return $this->action->url;
822 return $this->action;
827 * Navigation node collection
829 * This class is responsible for managing a collection of navigation nodes.
830 * It is required because a node's unique identifier is a combination of both its
831 * key and its type.
833 * Originally an array was used with a string key that was a combination of the two
834 * however it was decided that a better solution would be to use a class that
835 * implements the standard IteratorAggregate interface.
837 * @package core
838 * @category navigation
839 * @copyright 2010 Sam Hemelryk
840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
842 class navigation_node_collection implements IteratorAggregate {
844 * A multidimensional array to where the first key is the type and the second
845 * key is the nodes key.
846 * @var array
848 protected $collection = array();
850 * An array that contains references to nodes in the same order they were added.
851 * This is maintained as a progressive array.
852 * @var array
854 protected $orderedcollection = array();
856 * A reference to the last node that was added to the collection
857 * @var navigation_node
859 protected $last = null;
861 * The total number of items added to this array.
862 * @var int
864 protected $count = 0;
867 * Adds a navigation node to the collection
869 * @param navigation_node $node Node to add
870 * @param string $beforekey If specified, adds before a node with this key,
871 * otherwise adds at end
872 * @return navigation_node Added node
874 public function add(navigation_node $node, $beforekey=null) {
875 global $CFG;
876 $key = $node->key;
877 $type = $node->type;
879 // First check we have a 2nd dimension for this type
880 if (!array_key_exists($type, $this->orderedcollection)) {
881 $this->orderedcollection[$type] = array();
883 // Check for a collision and report if debugging is turned on
884 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
885 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
888 // Find the key to add before
889 $newindex = $this->count;
890 $last = true;
891 if ($beforekey !== null) {
892 foreach ($this->collection as $index => $othernode) {
893 if ($othernode->key === $beforekey) {
894 $newindex = $index;
895 $last = false;
896 break;
899 if ($newindex === $this->count) {
900 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
901 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
905 // Add the node to the appropriate place in the by-type structure (which
906 // is not ordered, despite the variable name)
907 $this->orderedcollection[$type][$key] = $node;
908 if (!$last) {
909 // Update existing references in the ordered collection (which is the
910 // one that isn't called 'ordered') to shuffle them along if required
911 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
912 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
915 // Add a reference to the node to the progressive collection.
916 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
917 // Update the last property to a reference to this new node.
918 $this->last = $this->orderedcollection[$type][$key];
920 // Reorder the array by index if needed
921 if (!$last) {
922 ksort($this->collection);
924 $this->count++;
925 // Return the reference to the now added node
926 return $node;
930 * Return a list of all the keys of all the nodes.
931 * @return array the keys.
933 public function get_key_list() {
934 $keys = array();
935 foreach ($this->collection as $node) {
936 $keys[] = $node->key;
938 return $keys;
942 * Fetches a node from this collection.
944 * @param string|int $key The key of the node we want to find.
945 * @param int $type One of navigation_node::TYPE_*.
946 * @return navigation_node|null
948 public function get($key, $type=null) {
949 if ($type !== null) {
950 // If the type is known then we can simply check and fetch
951 if (!empty($this->orderedcollection[$type][$key])) {
952 return $this->orderedcollection[$type][$key];
954 } else {
955 // Because we don't know the type we look in the progressive array
956 foreach ($this->collection as $node) {
957 if ($node->key === $key) {
958 return $node;
962 return false;
966 * Searches for a node with matching key and type.
968 * This function searches both the nodes in this collection and all of
969 * the nodes in each collection belonging to the nodes in this collection.
971 * Recursive.
973 * @param string|int $key The key of the node we want to find.
974 * @param int $type One of navigation_node::TYPE_*.
975 * @return navigation_node|null
977 public function find($key, $type=null) {
978 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
979 return $this->orderedcollection[$type][$key];
980 } else {
981 $nodes = $this->getIterator();
982 // Search immediate children first
983 foreach ($nodes as &$node) {
984 if ($node->key === $key && ($type === null || $type === $node->type)) {
985 return $node;
988 // Now search each childs children
989 foreach ($nodes as &$node) {
990 $result = $node->children->find($key, $type);
991 if ($result !== false) {
992 return $result;
996 return false;
1000 * Fetches the last node that was added to this collection
1002 * @return navigation_node
1004 public function last() {
1005 return $this->last;
1009 * Fetches all nodes of a given type from this collection
1011 * @param string|int $type node type being searched for.
1012 * @return array ordered collection
1014 public function type($type) {
1015 if (!array_key_exists($type, $this->orderedcollection)) {
1016 $this->orderedcollection[$type] = array();
1018 return $this->orderedcollection[$type];
1021 * Removes the node with the given key and type from the collection
1023 * @param string|int $key The key of the node we want to find.
1024 * @param int $type
1025 * @return bool
1027 public function remove($key, $type=null) {
1028 $child = $this->get($key, $type);
1029 if ($child !== false) {
1030 foreach ($this->collection as $colkey => $node) {
1031 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1032 unset($this->collection[$colkey]);
1033 $this->collection = array_values($this->collection);
1034 break;
1037 unset($this->orderedcollection[$child->type][$child->key]);
1038 $this->count--;
1039 return true;
1041 return false;
1045 * Gets the number of nodes in this collection
1047 * This option uses an internal count rather than counting the actual options to avoid
1048 * a performance hit through the count function.
1050 * @return int
1052 public function count() {
1053 return $this->count;
1056 * Gets an array iterator for the collection.
1058 * This is required by the IteratorAggregator interface and is used by routines
1059 * such as the foreach loop.
1061 * @return ArrayIterator
1063 public function getIterator() {
1064 return new ArrayIterator($this->collection);
1069 * The global navigation class used for... the global navigation
1071 * This class is used by PAGE to store the global navigation for the site
1072 * and is then used by the settings nav and navbar to save on processing and DB calls
1074 * See
1075 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1076 * {@link lib/ajax/getnavbranch.php} Called by ajax
1078 * @package core
1079 * @category navigation
1080 * @copyright 2009 Sam Hemelryk
1081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1083 class global_navigation extends navigation_node {
1084 /** @var moodle_page The Moodle page this navigation object belongs to. */
1085 protected $page;
1086 /** @var bool switch to let us know if the navigation object is initialised*/
1087 protected $initialised = false;
1088 /** @var array An array of course information */
1089 protected $mycourses = array();
1090 /** @var navigation_node[] An array for containing root navigation nodes */
1091 protected $rootnodes = array();
1092 /** @var bool A switch for whether to show empty sections in the navigation */
1093 protected $showemptysections = true;
1094 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1095 protected $showcategories = null;
1096 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1097 protected $showmycategories = null;
1098 /** @var array An array of stdClasses for users that the navigation is extended for */
1099 protected $extendforuser = array();
1100 /** @var navigation_cache */
1101 protected $cache;
1102 /** @var array An array of course ids that are present in the navigation */
1103 protected $addedcourses = array();
1104 /** @var bool */
1105 protected $allcategoriesloaded = false;
1106 /** @var array An array of category ids that are included in the navigation */
1107 protected $addedcategories = array();
1108 /** @var int expansion limit */
1109 protected $expansionlimit = 0;
1110 /** @var int userid to allow parent to see child's profile page navigation */
1111 protected $useridtouseforparentchecks = 0;
1112 /** @var cache_session A cache that stores information on expanded courses */
1113 protected $cacheexpandcourse = null;
1115 /** Used when loading categories to load all top level categories [parent = 0] **/
1116 const LOAD_ROOT_CATEGORIES = 0;
1117 /** Used when loading categories to load all categories **/
1118 const LOAD_ALL_CATEGORIES = -1;
1121 * Constructs a new global navigation
1123 * @param moodle_page $page The page this navigation object belongs to
1125 public function __construct(moodle_page $page) {
1126 global $CFG, $SITE, $USER;
1128 if (during_initial_install()) {
1129 return;
1132 if (get_home_page() == HOMEPAGE_SITE) {
1133 // We are using the site home for the root element
1134 $properties = array(
1135 'key' => 'home',
1136 'type' => navigation_node::TYPE_SYSTEM,
1137 'text' => get_string('home'),
1138 'action' => new moodle_url('/')
1140 } else {
1141 // We are using the users my moodle for the root element
1142 $properties = array(
1143 'key' => 'myhome',
1144 'type' => navigation_node::TYPE_SYSTEM,
1145 'text' => get_string('myhome'),
1146 'action' => new moodle_url('/my/')
1150 // Use the parents constructor.... good good reuse
1151 parent::__construct($properties);
1152 $this->showinflatnavigation = true;
1154 // Initalise and set defaults
1155 $this->page = $page;
1156 $this->forceopen = true;
1157 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1161 * Mutator to set userid to allow parent to see child's profile
1162 * page navigation. See MDL-25805 for initial issue. Linked to it
1163 * is an issue explaining why this is a REALLY UGLY HACK thats not
1164 * for you to use!
1166 * @param int $userid userid of profile page that parent wants to navigate around.
1168 public function set_userid_for_parent_checks($userid) {
1169 $this->useridtouseforparentchecks = $userid;
1174 * Initialises the navigation object.
1176 * This causes the navigation object to look at the current state of the page
1177 * that it is associated with and then load the appropriate content.
1179 * This should only occur the first time that the navigation structure is utilised
1180 * which will normally be either when the navbar is called to be displayed or
1181 * when a block makes use of it.
1183 * @return bool
1185 public function initialise() {
1186 global $CFG, $SITE, $USER;
1187 // Check if it has already been initialised
1188 if ($this->initialised || during_initial_install()) {
1189 return true;
1191 $this->initialised = true;
1193 // Set up the five base root nodes. These are nodes where we will put our
1194 // content and are as follows:
1195 // site: Navigation for the front page.
1196 // myprofile: User profile information goes here.
1197 // currentcourse: The course being currently viewed.
1198 // mycourses: The users courses get added here.
1199 // courses: Additional courses are added here.
1200 // users: Other users information loaded here.
1201 $this->rootnodes = array();
1202 if (get_home_page() == HOMEPAGE_SITE) {
1203 // The home element should be my moodle because the root element is the site
1204 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1205 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1206 $this->rootnodes['home']->showinflatnavigation = true;
1208 } else {
1209 // The home element should be the site because the root node is my moodle
1210 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1211 $this->rootnodes['home']->showinflatnavigation = true;
1212 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1213 // We need to stop automatic redirection
1214 $this->rootnodes['home']->action->param('redirect', '0');
1217 $this->rootnodes['site'] = $this->add_course($SITE);
1218 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1219 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1220 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1221 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1222 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1224 // We always load the frontpage course to ensure it is available without
1225 // JavaScript enabled.
1226 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1227 $this->load_course_sections($SITE, $this->rootnodes['site']);
1229 $course = $this->page->course;
1230 $this->load_courses_enrolled();
1232 // $issite gets set to true if the current pages course is the sites frontpage course
1233 $issite = ($this->page->course->id == $SITE->id);
1235 // Determine if the user is enrolled in any course.
1236 $enrolledinanycourse = enrol_user_sees_own_courses();
1238 $this->rootnodes['currentcourse']->mainnavonly = true;
1239 if ($enrolledinanycourse) {
1240 $this->rootnodes['mycourses']->isexpandable = true;
1241 $this->rootnodes['mycourses']->showinflatnavigation = true;
1242 if ($CFG->navshowallcourses) {
1243 // When we show all courses we need to show both the my courses and the regular courses branch.
1244 $this->rootnodes['courses']->isexpandable = true;
1246 } else {
1247 $this->rootnodes['courses']->isexpandable = true;
1249 $this->rootnodes['mycourses']->forceopen = true;
1251 $canviewcourseprofile = true;
1253 // Next load context specific content into the navigation
1254 switch ($this->page->context->contextlevel) {
1255 case CONTEXT_SYSTEM :
1256 // Nothing left to do here I feel.
1257 break;
1258 case CONTEXT_COURSECAT :
1259 // This is essential, we must load categories.
1260 $this->load_all_categories($this->page->context->instanceid, true);
1261 break;
1262 case CONTEXT_BLOCK :
1263 case CONTEXT_COURSE :
1264 if ($issite) {
1265 // Nothing left to do here.
1266 break;
1269 // Load the course associated with the current page into the navigation.
1270 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1271 // If the course wasn't added then don't try going any further.
1272 if (!$coursenode) {
1273 $canviewcourseprofile = false;
1274 break;
1277 // If the user is not enrolled then we only want to show the
1278 // course node and not populate it.
1280 // Not enrolled, can't view, and hasn't switched roles
1281 if (!can_access_course($course, null, '', true)) {
1282 if ($coursenode->isexpandable === true) {
1283 // Obviously the situation has changed, update the cache and adjust the node.
1284 // This occurs if the user access to a course has been revoked (one way or another) after
1285 // initially logging in for this session.
1286 $this->get_expand_course_cache()->set($course->id, 1);
1287 $coursenode->isexpandable = true;
1288 $coursenode->nodetype = self::NODETYPE_BRANCH;
1290 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1291 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1292 if (!$this->current_user_is_parent_role()) {
1293 $coursenode->make_active();
1294 $canviewcourseprofile = false;
1295 break;
1297 } else if ($coursenode->isexpandable === false) {
1298 // Obviously the situation has changed, update the cache and adjust the node.
1299 // This occurs if the user has been granted access to a course (one way or another) after initially
1300 // logging in for this session.
1301 $this->get_expand_course_cache()->set($course->id, 1);
1302 $coursenode->isexpandable = true;
1303 $coursenode->nodetype = self::NODETYPE_BRANCH;
1306 // Add the essentials such as reports etc...
1307 $this->add_course_essentials($coursenode, $course);
1308 // Extend course navigation with it's sections/activities
1309 $this->load_course_sections($course, $coursenode);
1310 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1311 $coursenode->make_active();
1314 break;
1315 case CONTEXT_MODULE :
1316 if ($issite) {
1317 // If this is the site course then most information will have
1318 // already been loaded.
1319 // However we need to check if there is more content that can
1320 // yet be loaded for the specific module instance.
1321 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1322 if ($activitynode) {
1323 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1325 break;
1328 $course = $this->page->course;
1329 $cm = $this->page->cm;
1331 // Load the course associated with the page into the navigation
1332 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1334 // If the course wasn't added then don't try going any further.
1335 if (!$coursenode) {
1336 $canviewcourseprofile = false;
1337 break;
1340 // If the user is not enrolled then we only want to show the
1341 // course node and not populate it.
1342 if (!can_access_course($course, null, '', true)) {
1343 $coursenode->make_active();
1344 $canviewcourseprofile = false;
1345 break;
1348 $this->add_course_essentials($coursenode, $course);
1350 // Load the course sections into the page
1351 $this->load_course_sections($course, $coursenode, null, $cm);
1352 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1353 if (!empty($activity)) {
1354 // Finally load the cm specific navigaton information
1355 $this->load_activity($cm, $course, $activity);
1356 // Check if we have an active ndoe
1357 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1358 // And make the activity node active.
1359 $activity->make_active();
1362 break;
1363 case CONTEXT_USER :
1364 if ($issite) {
1365 // The users profile information etc is already loaded
1366 // for the front page.
1367 break;
1369 $course = $this->page->course;
1370 // Load the course associated with the user into the navigation
1371 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1373 // If the course wasn't added then don't try going any further.
1374 if (!$coursenode) {
1375 $canviewcourseprofile = false;
1376 break;
1379 // If the user is not enrolled then we only want to show the
1380 // course node and not populate it.
1381 if (!can_access_course($course, null, '', true)) {
1382 $coursenode->make_active();
1383 $canviewcourseprofile = false;
1384 break;
1386 $this->add_course_essentials($coursenode, $course);
1387 $this->load_course_sections($course, $coursenode);
1388 break;
1391 // Load for the current user
1392 $this->load_for_user();
1393 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1394 $this->load_for_user(null, true);
1396 // Load each extending user into the navigation.
1397 foreach ($this->extendforuser as $user) {
1398 if ($user->id != $USER->id) {
1399 $this->load_for_user($user);
1403 // Give the local plugins a chance to include some navigation if they want.
1404 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1405 $function($this);
1408 // Remove any empty root nodes
1409 foreach ($this->rootnodes as $node) {
1410 // Dont remove the home node
1411 /** @var navigation_node $node */
1412 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1413 $node->remove();
1417 if (!$this->contains_active_node()) {
1418 $this->search_for_active_node();
1421 // If the user is not logged in modify the navigation structure as detailed
1422 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1423 if (!isloggedin()) {
1424 $activities = clone($this->rootnodes['site']->children);
1425 $this->rootnodes['site']->remove();
1426 $children = clone($this->children);
1427 $this->children = new navigation_node_collection();
1428 foreach ($activities as $child) {
1429 $this->children->add($child);
1431 foreach ($children as $child) {
1432 $this->children->add($child);
1435 return true;
1439 * Returns true if the current user is a parent of the user being currently viewed.
1441 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1442 * other user being viewed this function returns false.
1443 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1445 * @since Moodle 2.4
1446 * @return bool
1448 protected function current_user_is_parent_role() {
1449 global $USER, $DB;
1450 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1451 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1452 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1453 return false;
1455 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1456 return true;
1459 return false;
1463 * Returns true if courses should be shown within categories on the navigation.
1465 * @param bool $ismycourse Set to true if you are calculating this for a course.
1466 * @return bool
1468 protected function show_categories($ismycourse = false) {
1469 global $CFG, $DB;
1470 if ($ismycourse) {
1471 return $this->show_my_categories();
1473 if ($this->showcategories === null) {
1474 $show = false;
1475 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1476 $show = true;
1477 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1478 $show = true;
1480 $this->showcategories = $show;
1482 return $this->showcategories;
1486 * Returns true if we should show categories in the My Courses branch.
1487 * @return bool
1489 protected function show_my_categories() {
1490 global $CFG, $DB;
1491 if ($this->showmycategories === null) {
1492 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1494 return $this->showmycategories;
1498 * Loads the courses in Moodle into the navigation.
1500 * @global moodle_database $DB
1501 * @param string|array $categoryids An array containing categories to load courses
1502 * for, OR null to load courses for all categories.
1503 * @return array An array of navigation_nodes one for each course
1505 protected function load_all_courses($categoryids = null) {
1506 global $CFG, $DB, $SITE;
1508 // Work out the limit of courses.
1509 $limit = 20;
1510 if (!empty($CFG->navcourselimit)) {
1511 $limit = $CFG->navcourselimit;
1514 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1516 // If we are going to show all courses AND we are showing categories then
1517 // to save us repeated DB calls load all of the categories now
1518 if ($this->show_categories()) {
1519 $this->load_all_categories($toload);
1522 // Will be the return of our efforts
1523 $coursenodes = array();
1525 // Check if we need to show categories.
1526 if ($this->show_categories()) {
1527 // Hmmm we need to show categories... this is going to be painful.
1528 // We now need to fetch up to $limit courses for each category to
1529 // be displayed.
1530 if ($categoryids !== null) {
1531 if (!is_array($categoryids)) {
1532 $categoryids = array($categoryids);
1534 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1535 $categorywhere = 'WHERE cc.id '.$categorywhere;
1536 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1537 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1538 $categoryparams = array();
1539 } else {
1540 $categorywhere = '';
1541 $categoryparams = array();
1544 // First up we are going to get the categories that we are going to
1545 // need so that we can determine how best to load the courses from them.
1546 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1547 FROM {course_categories} cc
1548 LEFT JOIN {course} c ON c.category = cc.id
1549 {$categorywhere}
1550 GROUP BY cc.id";
1551 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1552 $fullfetch = array();
1553 $partfetch = array();
1554 foreach ($categories as $category) {
1555 if (!$this->can_add_more_courses_to_category($category->id)) {
1556 continue;
1558 if ($category->coursecount > $limit * 5) {
1559 $partfetch[] = $category->id;
1560 } else if ($category->coursecount > 0) {
1561 $fullfetch[] = $category->id;
1564 $categories->close();
1566 if (count($fullfetch)) {
1567 // First up fetch all of the courses in categories where we know that we are going to
1568 // need the majority of courses.
1569 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1570 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1571 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1572 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1573 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1574 FROM {course} c
1575 $ccjoin
1576 WHERE c.category {$categoryids}
1577 ORDER BY c.sortorder ASC";
1578 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1579 foreach ($coursesrs as $course) {
1580 if ($course->id == $SITE->id) {
1581 // This should not be necessary, frontpage is not in any category.
1582 continue;
1584 if (array_key_exists($course->id, $this->addedcourses)) {
1585 // It is probably better to not include the already loaded courses
1586 // directly in SQL because inequalities may confuse query optimisers
1587 // and may interfere with query caching.
1588 continue;
1590 if (!$this->can_add_more_courses_to_category($course->category)) {
1591 continue;
1593 context_helper::preload_from_record($course);
1594 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1595 continue;
1597 $coursenodes[$course->id] = $this->add_course($course);
1599 $coursesrs->close();
1602 if (count($partfetch)) {
1603 // Next we will work our way through the categories where we will likely only need a small
1604 // proportion of the courses.
1605 foreach ($partfetch as $categoryid) {
1606 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1607 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1608 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1609 FROM {course} c
1610 $ccjoin
1611 WHERE c.category = :categoryid
1612 ORDER BY c.sortorder ASC";
1613 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1614 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1615 foreach ($coursesrs as $course) {
1616 if ($course->id == $SITE->id) {
1617 // This should not be necessary, frontpage is not in any category.
1618 continue;
1620 if (array_key_exists($course->id, $this->addedcourses)) {
1621 // It is probably better to not include the already loaded courses
1622 // directly in SQL because inequalities may confuse query optimisers
1623 // and may interfere with query caching.
1624 // This also helps to respect expected $limit on repeated executions.
1625 continue;
1627 if (!$this->can_add_more_courses_to_category($course->category)) {
1628 break;
1630 context_helper::preload_from_record($course);
1631 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1632 continue;
1634 $coursenodes[$course->id] = $this->add_course($course);
1636 $coursesrs->close();
1639 } else {
1640 // Prepare the SQL to load the courses and their contexts
1641 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1642 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1643 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1644 $courseparams['contextlevel'] = CONTEXT_COURSE;
1645 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1646 FROM {course} c
1647 $ccjoin
1648 WHERE c.id {$courseids}
1649 ORDER BY c.sortorder ASC";
1650 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1651 foreach ($coursesrs as $course) {
1652 if ($course->id == $SITE->id) {
1653 // frotpage is not wanted here
1654 continue;
1656 if ($this->page->course && ($this->page->course->id == $course->id)) {
1657 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1658 continue;
1660 context_helper::preload_from_record($course);
1661 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1662 continue;
1664 $coursenodes[$course->id] = $this->add_course($course);
1665 if (count($coursenodes) >= $limit) {
1666 break;
1669 $coursesrs->close();
1672 return $coursenodes;
1676 * Returns true if more courses can be added to the provided category.
1678 * @param int|navigation_node|stdClass $category
1679 * @return bool
1681 protected function can_add_more_courses_to_category($category) {
1682 global $CFG;
1683 $limit = 20;
1684 if (!empty($CFG->navcourselimit)) {
1685 $limit = (int)$CFG->navcourselimit;
1687 if (is_numeric($category)) {
1688 if (!array_key_exists($category, $this->addedcategories)) {
1689 return true;
1691 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1692 } else if ($category instanceof navigation_node) {
1693 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1694 return false;
1696 $coursecount = count($category->children->type(self::TYPE_COURSE));
1697 } else if (is_object($category) && property_exists($category,'id')) {
1698 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1700 return ($coursecount <= $limit);
1704 * Loads all categories (top level or if an id is specified for that category)
1706 * @param int $categoryid The category id to load or null/0 to load all base level categories
1707 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1708 * as the requested category and any parent categories.
1709 * @return navigation_node|void returns a navigation node if a category has been loaded.
1711 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1712 global $CFG, $DB;
1714 // Check if this category has already been loaded
1715 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1716 return true;
1719 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1720 $sqlselect = "SELECT cc.*, $catcontextsql
1721 FROM {course_categories} cc
1722 JOIN {context} ctx ON cc.id = ctx.instanceid";
1723 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1724 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1725 $params = array();
1727 $categoriestoload = array();
1728 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1729 // We are going to load all categories regardless... prepare to fire
1730 // on the database server!
1731 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1732 // We are going to load all of the first level categories (categories without parents)
1733 $sqlwhere .= " AND cc.parent = 0";
1734 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1735 // The category itself has been loaded already so we just need to ensure its subcategories
1736 // have been loaded
1737 $addedcategories = $this->addedcategories;
1738 unset($addedcategories[$categoryid]);
1739 if (count($addedcategories) > 0) {
1740 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1741 if ($showbasecategories) {
1742 // We need to include categories with parent = 0 as well
1743 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1744 } else {
1745 // All we need is categories that match the parent
1746 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1749 $params['categoryid'] = $categoryid;
1750 } else {
1751 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1752 // and load this category plus all its parents and subcategories
1753 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1754 $categoriestoload = explode('/', trim($category->path, '/'));
1755 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1756 // We are going to use select twice so double the params
1757 $params = array_merge($params, $params);
1758 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1759 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1762 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1763 $categories = array();
1764 foreach ($categoriesrs as $category) {
1765 // Preload the context.. we'll need it when adding the category in order
1766 // to format the category name.
1767 context_helper::preload_from_record($category);
1768 if (array_key_exists($category->id, $this->addedcategories)) {
1769 // Do nothing, its already been added.
1770 } else if ($category->parent == '0') {
1771 // This is a root category lets add it immediately
1772 $this->add_category($category, $this->rootnodes['courses']);
1773 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1774 // This categories parent has already been added we can add this immediately
1775 $this->add_category($category, $this->addedcategories[$category->parent]);
1776 } else {
1777 $categories[] = $category;
1780 $categoriesrs->close();
1782 // Now we have an array of categories we need to add them to the navigation.
1783 while (!empty($categories)) {
1784 $category = reset($categories);
1785 if (array_key_exists($category->id, $this->addedcategories)) {
1786 // Do nothing
1787 } else if ($category->parent == '0') {
1788 $this->add_category($category, $this->rootnodes['courses']);
1789 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1790 $this->add_category($category, $this->addedcategories[$category->parent]);
1791 } else {
1792 // This category isn't in the navigation and niether is it's parent (yet).
1793 // We need to go through the category path and add all of its components in order.
1794 $path = explode('/', trim($category->path, '/'));
1795 foreach ($path as $catid) {
1796 if (!array_key_exists($catid, $this->addedcategories)) {
1797 // This category isn't in the navigation yet so add it.
1798 $subcategory = $categories[$catid];
1799 if ($subcategory->parent == '0') {
1800 // Yay we have a root category - this likely means we will now be able
1801 // to add categories without problems.
1802 $this->add_category($subcategory, $this->rootnodes['courses']);
1803 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1804 // The parent is in the category (as we'd expect) so add it now.
1805 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1806 // Remove the category from the categories array.
1807 unset($categories[$catid]);
1808 } else {
1809 // We should never ever arrive here - if we have then there is a bigger
1810 // problem at hand.
1811 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1816 // Remove the category from the categories array now that we know it has been added.
1817 unset($categories[$category->id]);
1819 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1820 $this->allcategoriesloaded = true;
1822 // Check if there are any categories to load.
1823 if (count($categoriestoload) > 0) {
1824 $readytoloadcourses = array();
1825 foreach ($categoriestoload as $category) {
1826 if ($this->can_add_more_courses_to_category($category)) {
1827 $readytoloadcourses[] = $category;
1830 if (count($readytoloadcourses)) {
1831 $this->load_all_courses($readytoloadcourses);
1835 // Look for all categories which have been loaded
1836 if (!empty($this->addedcategories)) {
1837 $categoryids = array();
1838 foreach ($this->addedcategories as $category) {
1839 if ($this->can_add_more_courses_to_category($category)) {
1840 $categoryids[] = $category->key;
1843 if ($categoryids) {
1844 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1845 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1846 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1847 FROM {course_categories} cc
1848 JOIN {course} c ON c.category = cc.id
1849 WHERE cc.id {$categoriessql}
1850 GROUP BY cc.id
1851 HAVING COUNT(c.id) > :limit";
1852 $excessivecategories = $DB->get_records_sql($sql, $params);
1853 foreach ($categories as &$category) {
1854 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1855 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1856 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1864 * Adds a structured category to the navigation in the correct order/place
1866 * @param stdClass $category category to be added in navigation.
1867 * @param navigation_node $parent parent navigation node
1868 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1869 * @return void.
1871 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1872 if (array_key_exists($category->id, $this->addedcategories)) {
1873 return;
1875 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1876 $context = context_coursecat::instance($category->id);
1877 $categoryname = format_string($category->name, true, array('context' => $context));
1878 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1879 if (empty($category->visible)) {
1880 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1881 $categorynode->hidden = true;
1882 } else {
1883 $categorynode->display = false;
1886 $this->addedcategories[$category->id] = $categorynode;
1890 * Loads the given course into the navigation
1892 * @param stdClass $course
1893 * @return navigation_node
1895 protected function load_course(stdClass $course) {
1896 global $SITE;
1897 if ($course->id == $SITE->id) {
1898 // This is always loaded during initialisation
1899 return $this->rootnodes['site'];
1900 } else if (array_key_exists($course->id, $this->addedcourses)) {
1901 // The course has already been loaded so return a reference
1902 return $this->addedcourses[$course->id];
1903 } else {
1904 // Add the course
1905 return $this->add_course($course);
1910 * Loads all of the courses section into the navigation.
1912 * This function calls method from current course format, see
1913 * {@link format_base::extend_course_navigation()}
1914 * If course module ($cm) is specified but course format failed to create the node,
1915 * the activity node is created anyway.
1917 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1919 * @param stdClass $course Database record for the course
1920 * @param navigation_node $coursenode The course node within the navigation
1921 * @param null|int $sectionnum If specified load the contents of section with this relative number
1922 * @param null|cm_info $cm If specified make sure that activity node is created (either
1923 * in containg section or by calling load_stealth_activity() )
1925 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1926 global $CFG, $SITE;
1927 require_once($CFG->dirroot.'/course/lib.php');
1928 if (isset($cm->sectionnum)) {
1929 $sectionnum = $cm->sectionnum;
1931 if ($sectionnum !== null) {
1932 $this->includesectionnum = $sectionnum;
1934 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1935 if (isset($cm->id)) {
1936 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1937 if (empty($activity)) {
1938 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1944 * Generates an array of sections and an array of activities for the given course.
1946 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1948 * @param stdClass $course
1949 * @return array Array($sections, $activities)
1951 protected function generate_sections_and_activities(stdClass $course) {
1952 global $CFG;
1953 require_once($CFG->dirroot.'/course/lib.php');
1955 $modinfo = get_fast_modinfo($course);
1956 $sections = $modinfo->get_section_info_all();
1958 // For course formats using 'numsections' trim the sections list
1959 $courseformatoptions = course_get_format($course)->get_format_options();
1960 if (isset($courseformatoptions['numsections'])) {
1961 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1964 $activities = array();
1966 foreach ($sections as $key => $section) {
1967 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1968 $sections[$key] = clone($section);
1969 unset($sections[$key]->summary);
1970 $sections[$key]->hasactivites = false;
1971 if (!array_key_exists($section->section, $modinfo->sections)) {
1972 continue;
1974 foreach ($modinfo->sections[$section->section] as $cmid) {
1975 $cm = $modinfo->cms[$cmid];
1976 $activity = new stdClass;
1977 $activity->id = $cm->id;
1978 $activity->course = $course->id;
1979 $activity->section = $section->section;
1980 $activity->name = $cm->name;
1981 $activity->icon = $cm->icon;
1982 $activity->iconcomponent = $cm->iconcomponent;
1983 $activity->hidden = (!$cm->visible);
1984 $activity->modname = $cm->modname;
1985 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1986 $activity->onclick = $cm->onclick;
1987 $url = $cm->url;
1988 if (!$url) {
1989 $activity->url = null;
1990 $activity->display = false;
1991 } else {
1992 $activity->url = $url->out();
1993 $activity->display = $cm->uservisible ? true : false;
1994 if (self::module_extends_navigation($cm->modname)) {
1995 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1998 $activities[$cmid] = $activity;
1999 if ($activity->display) {
2000 $sections[$key]->hasactivites = true;
2005 return array($sections, $activities);
2009 * Generically loads the course sections into the course's navigation.
2011 * @param stdClass $course
2012 * @param navigation_node $coursenode
2013 * @return array An array of course section nodes
2015 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2016 global $CFG, $DB, $USER, $SITE;
2017 require_once($CFG->dirroot.'/course/lib.php');
2019 list($sections, $activities) = $this->generate_sections_and_activities($course);
2021 $navigationsections = array();
2022 foreach ($sections as $sectionid => $section) {
2023 $section = clone($section);
2024 if ($course->id == $SITE->id) {
2025 $this->load_section_activities($coursenode, $section->section, $activities);
2026 } else {
2027 if (!$section->uservisible || (!$this->showemptysections &&
2028 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2029 continue;
2032 $sectionname = get_section_name($course, $section);
2033 $url = course_get_url($course, $section->section, array('navigation' => true));
2035 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
2036 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2037 $sectionnode->hidden = (!$section->visible || !$section->available);
2038 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2039 $this->load_section_activities($sectionnode, $section->section, $activities);
2041 $section->sectionnode = $sectionnode;
2042 $navigationsections[$sectionid] = $section;
2045 return $navigationsections;
2049 * Loads all of the activities for a section into the navigation structure.
2051 * @param navigation_node $sectionnode
2052 * @param int $sectionnumber
2053 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2054 * @param stdClass $course The course object the section and activities relate to.
2055 * @return array Array of activity nodes
2057 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2058 global $CFG, $SITE;
2059 // A static counter for JS function naming
2060 static $legacyonclickcounter = 0;
2062 $activitynodes = array();
2063 if (empty($activities)) {
2064 return $activitynodes;
2067 if (!is_object($course)) {
2068 $activity = reset($activities);
2069 $courseid = $activity->course;
2070 } else {
2071 $courseid = $course->id;
2073 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2075 foreach ($activities as $activity) {
2076 if ($activity->section != $sectionnumber) {
2077 continue;
2079 if ($activity->icon) {
2080 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2081 } else {
2082 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2085 // Prepare the default name and url for the node
2086 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2087 $action = new moodle_url($activity->url);
2089 // Check if the onclick property is set (puke!)
2090 if (!empty($activity->onclick)) {
2091 // Increment the counter so that we have a unique number.
2092 $legacyonclickcounter++;
2093 // Generate the function name we will use
2094 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2095 $propogrationhandler = '';
2096 // Check if we need to cancel propogation. Remember inline onclick
2097 // events would return false if they wanted to prevent propogation and the
2098 // default action.
2099 if (strpos($activity->onclick, 'return false')) {
2100 $propogrationhandler = 'e.halt();';
2102 // Decode the onclick - it has already been encoded for display (puke)
2103 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2104 // Build the JS function the click event will call
2105 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2106 $this->page->requires->js_init_code($jscode);
2107 // Override the default url with the new action link
2108 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2111 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2112 $activitynode->title(get_string('modulename', $activity->modname));
2113 $activitynode->hidden = $activity->hidden;
2114 $activitynode->display = $showactivities && $activity->display;
2115 $activitynode->nodetype = $activity->nodetype;
2116 $activitynodes[$activity->id] = $activitynode;
2119 return $activitynodes;
2122 * Loads a stealth module from unavailable section
2123 * @param navigation_node $coursenode
2124 * @param stdClass $modinfo
2125 * @return navigation_node or null if not accessible
2127 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2128 if (empty($modinfo->cms[$this->page->cm->id])) {
2129 return null;
2131 $cm = $modinfo->cms[$this->page->cm->id];
2132 if ($cm->icon) {
2133 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2134 } else {
2135 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2137 $url = $cm->url;
2138 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2139 $activitynode->title(get_string('modulename', $cm->modname));
2140 $activitynode->hidden = (!$cm->visible);
2141 if (!$cm->uservisible) {
2142 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2143 // Also there may be no exception at all in case when teacher is logged in as student.
2144 $activitynode->display = false;
2145 } else if (!$url) {
2146 // Don't show activities that don't have links!
2147 $activitynode->display = false;
2148 } else if (self::module_extends_navigation($cm->modname)) {
2149 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2151 return $activitynode;
2154 * Loads the navigation structure for the given activity into the activities node.
2156 * This method utilises a callback within the modules lib.php file to load the
2157 * content specific to activity given.
2159 * The callback is a method: {modulename}_extend_navigation()
2160 * Examples:
2161 * * {@link forum_extend_navigation()}
2162 * * {@link workshop_extend_navigation()}
2164 * @param cm_info|stdClass $cm
2165 * @param stdClass $course
2166 * @param navigation_node $activity
2167 * @return bool
2169 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2170 global $CFG, $DB;
2172 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2173 if (!($cm instanceof cm_info)) {
2174 $modinfo = get_fast_modinfo($course);
2175 $cm = $modinfo->get_cm($cm->id);
2177 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2178 $activity->make_active();
2179 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2180 $function = $cm->modname.'_extend_navigation';
2182 if (file_exists($file)) {
2183 require_once($file);
2184 if (function_exists($function)) {
2185 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2186 $function($activity, $course, $activtyrecord, $cm);
2190 // Allow the active advanced grading method plugin to append module navigation
2191 $featuresfunc = $cm->modname.'_supports';
2192 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2193 require_once($CFG->dirroot.'/grade/grading/lib.php');
2194 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2195 $gradingman->extend_navigation($this, $activity);
2198 return $activity->has_children();
2201 * Loads user specific information into the navigation in the appropriate place.
2203 * If no user is provided the current user is assumed.
2205 * @param stdClass $user
2206 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2207 * @return bool
2209 protected function load_for_user($user=null, $forceforcontext=false) {
2210 global $DB, $CFG, $USER, $SITE;
2212 if ($user === null) {
2213 // We can't require login here but if the user isn't logged in we don't
2214 // want to show anything
2215 if (!isloggedin() || isguestuser()) {
2216 return false;
2218 $user = $USER;
2219 } else if (!is_object($user)) {
2220 // If the user is not an object then get them from the database
2221 $select = context_helper::get_preload_record_columns_sql('ctx');
2222 $sql = "SELECT u.*, $select
2223 FROM {user} u
2224 JOIN {context} ctx ON u.id = ctx.instanceid
2225 WHERE u.id = :userid AND
2226 ctx.contextlevel = :contextlevel";
2227 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2228 context_helper::preload_from_record($user);
2231 $iscurrentuser = ($user->id == $USER->id);
2233 $usercontext = context_user::instance($user->id);
2235 // Get the course set against the page, by default this will be the site
2236 $course = $this->page->course;
2237 $baseargs = array('id'=>$user->id);
2238 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2239 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2240 $baseargs['course'] = $course->id;
2241 $coursecontext = context_course::instance($course->id);
2242 $issitecourse = false;
2243 } else {
2244 // Load all categories and get the context for the system
2245 $coursecontext = context_system::instance();
2246 $issitecourse = true;
2249 // Create a node to add user information under.
2250 $usersnode = null;
2251 if (!$issitecourse) {
2252 // Not the current user so add it to the participants node for the current course.
2253 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2254 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2255 } else if ($USER->id != $user->id) {
2256 // This is the site so add a users node to the root branch.
2257 $usersnode = $this->rootnodes['users'];
2258 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2259 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2261 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2263 if (!$usersnode) {
2264 // We should NEVER get here, if the course hasn't been populated
2265 // with a participants node then the navigaiton either wasn't generated
2266 // for it (you are missing a require_login or set_context call) or
2267 // you don't have access.... in the interests of no leaking informatin
2268 // we simply quit...
2269 return false;
2271 // Add a branch for the current user.
2272 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2273 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2274 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2275 $usernode->make_active();
2278 // Add user information to the participants or user node.
2279 if ($issitecourse) {
2281 // If the user is the current user or has permission to view the details of the requested
2282 // user than add a view profile link.
2283 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2284 has_capability('moodle/user:viewdetails', $usercontext)) {
2285 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2286 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2287 } else {
2288 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2292 if (!empty($CFG->navadduserpostslinks)) {
2293 // Add nodes for forum posts and discussions if the user can view either or both
2294 // There are no capability checks here as the content of the page is based
2295 // purely on the forums the current user has access too.
2296 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2297 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2298 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2299 array_merge($baseargs, array('mode' => 'discussions'))));
2302 // Add blog nodes.
2303 if (!empty($CFG->enableblogs)) {
2304 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2305 require_once($CFG->dirroot.'/blog/lib.php');
2306 // Get all options for the user.
2307 $options = blog_get_options_for_user($user);
2308 $this->cache->set('userblogoptions'.$user->id, $options);
2309 } else {
2310 $options = $this->cache->{'userblogoptions'.$user->id};
2313 if (count($options) > 0) {
2314 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2315 foreach ($options as $type => $option) {
2316 if ($type == "rss") {
2317 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2318 new pix_icon('i/rss', ''));
2319 } else {
2320 $blogs->add($option['string'], $option['link']);
2326 // Add the messages link.
2327 // It is context based so can appear in the user's profile and in course participants information.
2328 if (!empty($CFG->messaging)) {
2329 $messageargs = array('user1' => $USER->id);
2330 if ($USER->id != $user->id) {
2331 $messageargs['user2'] = $user->id;
2333 $url = new moodle_url('/message/index.php', $messageargs);
2334 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2337 // Add the "My private files" link.
2338 // This link doesn't have a unique display for course context so only display it under the user's profile.
2339 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2340 $url = new moodle_url('/user/files.php');
2341 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
2344 // Add a node to view the users notes if permitted.
2345 if (!empty($CFG->enablenotes) &&
2346 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2347 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2348 if ($coursecontext->instanceid != SITEID) {
2349 $url->param('course', $coursecontext->instanceid);
2351 $usernode->add(get_string('notes', 'notes'), $url);
2354 // Show the grades node.
2355 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2356 require_once($CFG->dirroot . '/user/lib.php');
2357 // Set the grades node to link to the "Grades" page.
2358 if ($course->id == SITEID) {
2359 $url = user_mygrades_url($user->id, $course->id);
2360 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2361 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2363 if ($USER->id != $user->id) {
2364 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2365 } else {
2366 $usernode->add(get_string('grades', 'grades'), $url);
2370 // If the user is the current user add the repositories for the current user.
2371 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2372 if (!$iscurrentuser &&
2373 $course->id == $SITE->id &&
2374 has_capability('moodle/user:viewdetails', $usercontext) &&
2375 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2377 // Add view grade report is permitted.
2378 $reports = core_component::get_plugin_list('gradereport');
2379 arsort($reports); // User is last, we want to test it first.
2381 $userscourses = enrol_get_users_courses($user->id);
2382 $userscoursesnode = $usernode->add(get_string('courses'));
2384 $count = 0;
2385 foreach ($userscourses as $usercourse) {
2386 if ($count === (int)$CFG->navcourselimit) {
2387 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2388 $userscoursesnode->add(get_string('showallcourses'), $url);
2389 break;
2391 $count++;
2392 $usercoursecontext = context_course::instance($usercourse->id);
2393 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2394 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2395 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2397 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2398 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2399 foreach ($reports as $plugin => $plugindir) {
2400 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2401 // Stop when the first visible plugin is found.
2402 $gradeavailable = true;
2403 break;
2408 if ($gradeavailable) {
2409 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2410 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2411 new pix_icon('i/grades', ''));
2414 // Add a node to view the users notes if permitted.
2415 if (!empty($CFG->enablenotes) &&
2416 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2417 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2418 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2421 if (can_access_course($usercourse, $user->id, '', true)) {
2422 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2423 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2426 $reporttab = $usercoursenode->add(get_string('activityreports'));
2428 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2429 foreach ($reports as $reportfunction) {
2430 $reportfunction($reporttab, $user, $usercourse);
2433 $reporttab->trim_if_empty();
2437 // Let plugins hook into user navigation.
2438 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2439 foreach ($pluginsfunction as $plugintype => $plugins) {
2440 if ($plugintype != 'report') {
2441 foreach ($plugins as $pluginfunction) {
2442 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2447 return true;
2451 * This method simply checks to see if a given module can extend the navigation.
2453 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2455 * @param string $modname
2456 * @return bool
2458 public static function module_extends_navigation($modname) {
2459 global $CFG;
2460 static $extendingmodules = array();
2461 if (!array_key_exists($modname, $extendingmodules)) {
2462 $extendingmodules[$modname] = false;
2463 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2464 if (file_exists($file)) {
2465 $function = $modname.'_extend_navigation';
2466 require_once($file);
2467 $extendingmodules[$modname] = (function_exists($function));
2470 return $extendingmodules[$modname];
2473 * Extends the navigation for the given user.
2475 * @param stdClass $user A user from the database
2477 public function extend_for_user($user) {
2478 $this->extendforuser[] = $user;
2482 * Returns all of the users the navigation is being extended for
2484 * @return array An array of extending users.
2486 public function get_extending_users() {
2487 return $this->extendforuser;
2490 * Adds the given course to the navigation structure.
2492 * @param stdClass $course
2493 * @param bool $forcegeneric
2494 * @param bool $ismycourse
2495 * @return navigation_node
2497 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2498 global $CFG, $SITE;
2500 // We found the course... we can return it now :)
2501 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2502 return $this->addedcourses[$course->id];
2505 $coursecontext = context_course::instance($course->id);
2507 if ($course->id != $SITE->id && !$course->visible) {
2508 if (is_role_switched($course->id)) {
2509 // user has to be able to access course in order to switch, let's skip the visibility test here
2510 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2511 return false;
2515 $issite = ($course->id == $SITE->id);
2516 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2517 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2518 // This is the name that will be shown for the course.
2519 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2521 if ($coursetype == self::COURSE_CURRENT) {
2522 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2523 return $coursenode;
2524 } else {
2525 $coursetype = self::COURSE_OTHER;
2529 // Can the user expand the course to see its content.
2530 $canexpandcourse = true;
2531 if ($issite) {
2532 $parent = $this;
2533 $url = null;
2534 if (empty($CFG->usesitenameforsitepages)) {
2535 $coursename = get_string('sitepages');
2537 } else if ($coursetype == self::COURSE_CURRENT) {
2538 $parent = $this->rootnodes['currentcourse'];
2539 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2540 $canexpandcourse = $this->can_expand_course($course);
2541 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2542 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2543 // Nothing to do here the above statement set $parent to the category within mycourses.
2544 } else {
2545 $parent = $this->rootnodes['mycourses'];
2547 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2548 } else {
2549 $parent = $this->rootnodes['courses'];
2550 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2551 // They can only expand the course if they can access it.
2552 $canexpandcourse = $this->can_expand_course($course);
2553 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2554 if (!$this->is_category_fully_loaded($course->category)) {
2555 // We need to load the category structure for this course
2556 $this->load_all_categories($course->category, false);
2558 if (array_key_exists($course->category, $this->addedcategories)) {
2559 $parent = $this->addedcategories[$course->category];
2560 // This could lead to the course being created so we should check whether it is the case again
2561 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2562 return $this->addedcourses[$course->id];
2568 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2569 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2570 $coursenode->hidden = (!$course->visible);
2571 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2572 if ($canexpandcourse) {
2573 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2574 $coursenode->nodetype = self::NODETYPE_BRANCH;
2575 $coursenode->isexpandable = true;
2576 } else {
2577 $coursenode->nodetype = self::NODETYPE_LEAF;
2578 $coursenode->isexpandable = false;
2580 if (!$forcegeneric) {
2581 $this->addedcourses[$course->id] = $coursenode;
2584 return $coursenode;
2588 * Returns a cache instance to use for the expand course cache.
2589 * @return cache_session
2591 protected function get_expand_course_cache() {
2592 if ($this->cacheexpandcourse === null) {
2593 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2595 return $this->cacheexpandcourse;
2599 * Checks if a user can expand a course in the navigation.
2601 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2602 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2603 * permits stale data.
2604 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2605 * will be stale.
2606 * It is brought up to date in only one of two ways.
2607 * 1. The user logs out and in again.
2608 * 2. The user browses to the course they've just being given access to.
2610 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2612 * @param stdClass $course
2613 * @return bool
2615 protected function can_expand_course($course) {
2616 $cache = $this->get_expand_course_cache();
2617 $canexpand = $cache->get($course->id);
2618 if ($canexpand === false) {
2619 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2620 $canexpand = (int)$canexpand;
2621 $cache->set($course->id, $canexpand);
2623 return ($canexpand === 1);
2627 * Returns true if the category has already been loaded as have any child categories
2629 * @param int $categoryid
2630 * @return bool
2632 protected function is_category_fully_loaded($categoryid) {
2633 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2637 * Adds essential course nodes to the navigation for the given course.
2639 * This method adds nodes such as reports, blogs and participants
2641 * @param navigation_node $coursenode
2642 * @param stdClass $course
2643 * @return bool returns true on successful addition of a node.
2645 public function add_course_essentials($coursenode, stdClass $course) {
2646 global $CFG, $SITE;
2647 require_once($CFG->dirroot . '/course/lib.php');
2649 if ($course->id == $SITE->id) {
2650 return $this->add_front_page_course_essentials($coursenode, $course);
2653 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2654 return true;
2657 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2659 //Participants
2660 if ($navoptions->participants) {
2661 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2663 if ($navoptions->blogs) {
2664 $blogsurls = new moodle_url('/blog/index.php');
2665 if ($currentgroup = groups_get_course_group($course, true)) {
2666 $blogsurls->param('groupid', $currentgroup);
2667 } else {
2668 $blogsurls->param('courseid', $course->id);
2670 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2673 if ($navoptions->notes) {
2674 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2676 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2677 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2680 // Badges.
2681 if ($navoptions->badges) {
2682 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2684 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2685 navigation_node::TYPE_SETTING, null, 'badgesview',
2686 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2689 // Check access to the course and competencies page.
2690 if ($navoptions->competencies) {
2691 // Just a link to course competency.
2692 $title = get_string('competencies', 'core_competency');
2693 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2694 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/competencies', ''));
2696 if ($navoptions->grades) {
2697 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2698 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2701 return true;
2704 * This generates the structure of the course that won't be generated when
2705 * the modules and sections are added.
2707 * Things such as the reports branch, the participants branch, blogs... get
2708 * added to the course node by this method.
2710 * @param navigation_node $coursenode
2711 * @param stdClass $course
2712 * @return bool True for successfull generation
2714 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2715 global $CFG, $USER;
2716 require_once($CFG->dirroot . '/course/lib.php');
2718 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2719 return true;
2722 $sitecontext = context_system::instance();
2723 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2725 // Hidden node that we use to determine if the front page navigation is loaded.
2726 // This required as there are not other guaranteed nodes that may be loaded.
2727 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2729 // Participants.
2730 if ($navoptions->participants) {
2731 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2734 // Blogs.
2735 if ($navoptions->blogs) {
2736 $blogsurls = new moodle_url('/blog/index.php');
2737 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2740 $filterselect = 0;
2742 // Badges.
2743 if ($navoptions->badges) {
2744 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2745 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2748 // Notes.
2749 if ($navoptions->notes) {
2750 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2751 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2754 // Tags
2755 if ($navoptions->tags) {
2756 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2757 self::TYPE_SETTING, null, 'tags');
2760 // Search.
2761 if ($navoptions->search) {
2762 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2763 self::TYPE_SETTING, null, 'search');
2766 if ($navoptions->calendar) {
2767 // Calendar
2768 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2769 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2770 $node->showinflatnavigation = true;
2773 if (isloggedin()) {
2774 $usercontext = context_user::instance($USER->id);
2775 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2776 $url = new moodle_url('/user/files.php');
2777 $node = $coursenode->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
2778 $node->display = false;
2779 $node->showinflatnavigation = true;
2783 return true;
2787 * Clears the navigation cache
2789 public function clear_cache() {
2790 $this->cache->clear();
2794 * Sets an expansion limit for the navigation
2796 * The expansion limit is used to prevent the display of content that has a type
2797 * greater than the provided $type.
2799 * Can be used to ensure things such as activities or activity content don't get
2800 * shown on the navigation.
2801 * They are still generated in order to ensure the navbar still makes sense.
2803 * @param int $type One of navigation_node::TYPE_*
2804 * @return bool true when complete.
2806 public function set_expansion_limit($type) {
2807 global $SITE;
2808 $nodes = $this->find_all_of_type($type);
2810 // We only want to hide specific types of nodes.
2811 // Only nodes that represent "structure" in the navigation tree should be hidden.
2812 // If we hide all nodes then we risk hiding vital information.
2813 $typestohide = array(
2814 self::TYPE_CATEGORY,
2815 self::TYPE_COURSE,
2816 self::TYPE_SECTION,
2817 self::TYPE_ACTIVITY
2820 foreach ($nodes as $node) {
2821 // We need to generate the full site node
2822 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2823 continue;
2825 foreach ($node->children as $child) {
2826 $child->hide($typestohide);
2829 return true;
2832 * Attempts to get the navigation with the given key from this nodes children.
2834 * This function only looks at this nodes children, it does NOT look recursivily.
2835 * If the node can't be found then false is returned.
2837 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2839 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2840 * may be of more use to you.
2842 * @param string|int $key The key of the node you wish to receive.
2843 * @param int $type One of navigation_node::TYPE_*
2844 * @return navigation_node|false
2846 public function get($key, $type = null) {
2847 if (!$this->initialised) {
2848 $this->initialise();
2850 return parent::get($key, $type);
2854 * Searches this nodes children and their children to find a navigation node
2855 * with the matching key and type.
2857 * This method is recursive and searches children so until either a node is
2858 * found or there are no more nodes to search.
2860 * If you know that the node being searched for is a child of this node
2861 * then use the {@link global_navigation::get()} method instead.
2863 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2864 * may be of more use to you.
2866 * @param string|int $key The key of the node you wish to receive.
2867 * @param int $type One of navigation_node::TYPE_*
2868 * @return navigation_node|false
2870 public function find($key, $type) {
2871 if (!$this->initialised) {
2872 $this->initialise();
2874 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2875 return $this->rootnodes[$key];
2877 return parent::find($key, $type);
2881 * They've expanded the 'my courses' branch.
2883 protected function load_courses_enrolled() {
2884 global $CFG, $DB;
2885 $sortorder = 'visible DESC';
2886 // Prevent undefined $CFG->navsortmycoursessort errors.
2887 if (empty($CFG->navsortmycoursessort)) {
2888 $CFG->navsortmycoursessort = 'sortorder';
2890 // Append the chosen sortorder.
2891 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2892 $courses = enrol_get_my_courses(null, $sortorder);
2893 if (count($courses) && $this->show_my_categories()) {
2894 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2895 // In order to make sure we load everything required we must first find the categories that are not
2896 // base categories and work out the bottom category in thier path.
2897 $categoryids = array();
2898 foreach ($courses as $course) {
2899 $categoryids[] = $course->category;
2901 $categoryids = array_unique($categoryids);
2902 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2903 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2904 foreach ($categories as $category) {
2905 $bits = explode('/', trim($category->path,'/'));
2906 $categoryids[] = array_shift($bits);
2908 $categoryids = array_unique($categoryids);
2909 $categories->close();
2911 // Now we load the base categories.
2912 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2913 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2914 foreach ($categories as $category) {
2915 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2917 $categories->close();
2918 } else {
2919 foreach ($courses as $course) {
2920 $this->add_course($course, false, self::COURSE_MY);
2927 * The global navigation class used especially for AJAX requests.
2929 * The primary methods that are used in the global navigation class have been overriden
2930 * to ensure that only the relevant branch is generated at the root of the tree.
2931 * This can be done because AJAX is only used when the backwards structure for the
2932 * requested branch exists.
2933 * This has been done only because it shortens the amounts of information that is generated
2934 * which of course will speed up the response time.. because no one likes laggy AJAX.
2936 * @package core
2937 * @category navigation
2938 * @copyright 2009 Sam Hemelryk
2939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2941 class global_navigation_for_ajax extends global_navigation {
2943 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2944 protected $branchtype;
2946 /** @var int the instance id */
2947 protected $instanceid;
2949 /** @var array Holds an array of expandable nodes */
2950 protected $expandable = array();
2953 * Constructs the navigation for use in an AJAX request
2955 * @param moodle_page $page moodle_page object
2956 * @param int $branchtype
2957 * @param int $id
2959 public function __construct($page, $branchtype, $id) {
2960 $this->page = $page;
2961 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2962 $this->children = new navigation_node_collection();
2963 $this->branchtype = $branchtype;
2964 $this->instanceid = $id;
2965 $this->initialise();
2968 * Initialise the navigation given the type and id for the branch to expand.
2970 * @return array An array of the expandable nodes
2972 public function initialise() {
2973 global $DB, $SITE;
2975 if ($this->initialised || during_initial_install()) {
2976 return $this->expandable;
2978 $this->initialised = true;
2980 $this->rootnodes = array();
2981 $this->rootnodes['site'] = $this->add_course($SITE);
2982 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2983 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2984 // The courses branch is always displayed, and is always expandable (although may be empty).
2985 // This mimicks what is done during {@link global_navigation::initialise()}.
2986 $this->rootnodes['courses']->isexpandable = true;
2988 // Branchtype will be one of navigation_node::TYPE_*
2989 switch ($this->branchtype) {
2990 case 0:
2991 if ($this->instanceid === 'mycourses') {
2992 $this->load_courses_enrolled();
2993 } else if ($this->instanceid === 'courses') {
2994 $this->load_courses_other();
2996 break;
2997 case self::TYPE_CATEGORY :
2998 $this->load_category($this->instanceid);
2999 break;
3000 case self::TYPE_MY_CATEGORY :
3001 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3002 break;
3003 case self::TYPE_COURSE :
3004 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3005 if (!can_access_course($course, null, '', true)) {
3006 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3007 // add the course node and break. This leads to an empty node.
3008 $this->add_course($course);
3009 break;
3011 require_course_login($course, true, null, false, true);
3012 $this->page->set_context(context_course::instance($course->id));
3013 $coursenode = $this->add_course($course);
3014 $this->add_course_essentials($coursenode, $course);
3015 $this->load_course_sections($course, $coursenode);
3016 break;
3017 case self::TYPE_SECTION :
3018 $sql = 'SELECT c.*, cs.section AS sectionnumber
3019 FROM {course} c
3020 LEFT JOIN {course_sections} cs ON cs.course = c.id
3021 WHERE cs.id = ?';
3022 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3023 require_course_login($course, true, null, false, true);
3024 $this->page->set_context(context_course::instance($course->id));
3025 $coursenode = $this->add_course($course);
3026 $this->add_course_essentials($coursenode, $course);
3027 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3028 break;
3029 case self::TYPE_ACTIVITY :
3030 $sql = "SELECT c.*
3031 FROM {course} c
3032 JOIN {course_modules} cm ON cm.course = c.id
3033 WHERE cm.id = :cmid";
3034 $params = array('cmid' => $this->instanceid);
3035 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3036 $modinfo = get_fast_modinfo($course);
3037 $cm = $modinfo->get_cm($this->instanceid);
3038 require_course_login($course, true, $cm, false, true);
3039 $this->page->set_context(context_module::instance($cm->id));
3040 $coursenode = $this->load_course($course);
3041 $this->load_course_sections($course, $coursenode, null, $cm);
3042 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3043 if ($activitynode) {
3044 $modulenode = $this->load_activity($cm, $course, $activitynode);
3046 break;
3047 default:
3048 throw new Exception('Unknown type');
3049 return $this->expandable;
3052 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3053 $this->load_for_user(null, true);
3056 $this->find_expandable($this->expandable);
3057 return $this->expandable;
3061 * They've expanded the general 'courses' branch.
3063 protected function load_courses_other() {
3064 $this->load_all_courses();
3068 * Loads a single category into the AJAX navigation.
3070 * This function is special in that it doesn't concern itself with the parent of
3071 * the requested category or its siblings.
3072 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3073 * request that.
3075 * @global moodle_database $DB
3076 * @param int $categoryid id of category to load in navigation.
3077 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3078 * @return void.
3080 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3081 global $CFG, $DB;
3083 $limit = 20;
3084 if (!empty($CFG->navcourselimit)) {
3085 $limit = (int)$CFG->navcourselimit;
3088 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3089 $sql = "SELECT cc.*, $catcontextsql
3090 FROM {course_categories} cc
3091 JOIN {context} ctx ON cc.id = ctx.instanceid
3092 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3093 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3094 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3095 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3096 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3097 $categorylist = array();
3098 $subcategories = array();
3099 $basecategory = null;
3100 foreach ($categories as $category) {
3101 $categorylist[] = $category->id;
3102 context_helper::preload_from_record($category);
3103 if ($category->id == $categoryid) {
3104 $this->add_category($category, $this, $nodetype);
3105 $basecategory = $this->addedcategories[$category->id];
3106 } else {
3107 $subcategories[$category->id] = $category;
3110 $categories->close();
3113 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3114 // else show all courses.
3115 if ($nodetype === self::TYPE_MY_CATEGORY) {
3116 $courses = enrol_get_my_courses();
3117 $categoryids = array();
3119 // Only search for categories if basecategory was found.
3120 if (!is_null($basecategory)) {
3121 // Get course parent category ids.
3122 foreach ($courses as $course) {
3123 $categoryids[] = $course->category;
3126 // Get a unique list of category ids which a part of the path
3127 // to user's courses.
3128 $coursesubcategories = array();
3129 $addedsubcategories = array();
3131 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3132 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3134 foreach ($categories as $category){
3135 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3137 $coursesubcategories = array_unique($coursesubcategories);
3139 // Only add a subcategory if it is part of the path to user's course and
3140 // wasn't already added.
3141 foreach ($subcategories as $subid => $subcategory) {
3142 if (in_array($subid, $coursesubcategories) &&
3143 !in_array($subid, $addedsubcategories)) {
3144 $this->add_category($subcategory, $basecategory, $nodetype);
3145 $addedsubcategories[] = $subid;
3150 foreach ($courses as $course) {
3151 // Add course if it's in category.
3152 if (in_array($course->category, $categorylist)) {
3153 $this->add_course($course, true, self::COURSE_MY);
3156 } else {
3157 if (!is_null($basecategory)) {
3158 foreach ($subcategories as $key=>$category) {
3159 $this->add_category($category, $basecategory, $nodetype);
3162 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3163 foreach ($courses as $course) {
3164 $this->add_course($course);
3166 $courses->close();
3171 * Returns an array of expandable nodes
3172 * @return array
3174 public function get_expandable() {
3175 return $this->expandable;
3180 * Navbar class
3182 * This class is used to manage the navbar, which is initialised from the navigation
3183 * object held by PAGE
3185 * @package core
3186 * @category navigation
3187 * @copyright 2009 Sam Hemelryk
3188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3190 class navbar extends navigation_node {
3191 /** @var bool A switch for whether the navbar is initialised or not */
3192 protected $initialised = false;
3193 /** @var mixed keys used to reference the nodes on the navbar */
3194 protected $keys = array();
3195 /** @var null|string content of the navbar */
3196 protected $content = null;
3197 /** @var moodle_page object the moodle page that this navbar belongs to */
3198 protected $page;
3199 /** @var bool A switch for whether to ignore the active navigation information */
3200 protected $ignoreactive = false;
3201 /** @var bool A switch to let us know if we are in the middle of an install */
3202 protected $duringinstall = false;
3203 /** @var bool A switch for whether the navbar has items */
3204 protected $hasitems = false;
3205 /** @var array An array of navigation nodes for the navbar */
3206 protected $items;
3207 /** @var array An array of child node objects */
3208 public $children = array();
3209 /** @var bool A switch for whether we want to include the root node in the navbar */
3210 public $includesettingsbase = false;
3211 /** @var breadcrumb_navigation_node[] $prependchildren */
3212 protected $prependchildren = array();
3215 * The almighty constructor
3217 * @param moodle_page $page
3219 public function __construct(moodle_page $page) {
3220 global $CFG;
3221 if (during_initial_install()) {
3222 $this->duringinstall = true;
3223 return false;
3225 $this->page = $page;
3226 $this->text = get_string('home');
3227 $this->shorttext = get_string('home');
3228 $this->action = new moodle_url($CFG->wwwroot);
3229 $this->nodetype = self::NODETYPE_BRANCH;
3230 $this->type = self::TYPE_SYSTEM;
3234 * Quick check to see if the navbar will have items in.
3236 * @return bool Returns true if the navbar will have items, false otherwise
3238 public function has_items() {
3239 if ($this->duringinstall) {
3240 return false;
3241 } else if ($this->hasitems !== false) {
3242 return true;
3244 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3245 // There have been manually added items - there are definitely items.
3246 $outcome = true;
3247 } else if (!$this->ignoreactive) {
3248 // We will need to initialise the navigation structure to check if there are active items.
3249 $this->page->navigation->initialise($this->page);
3250 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3252 $this->hasitems = $outcome;
3253 return $outcome;
3257 * Turn on/off ignore active
3259 * @param bool $setting
3261 public function ignore_active($setting=true) {
3262 $this->ignoreactive = ($setting);
3266 * Gets a navigation node
3268 * @param string|int $key for referencing the navbar nodes
3269 * @param int $type breadcrumb_navigation_node::TYPE_*
3270 * @return breadcrumb_navigation_node|bool
3272 public function get($key, $type = null) {
3273 foreach ($this->children as &$child) {
3274 if ($child->key === $key && ($type == null || $type == $child->type)) {
3275 return $child;
3278 foreach ($this->prependchildren as &$child) {
3279 if ($child->key === $key && ($type == null || $type == $child->type)) {
3280 return $child;
3283 return false;
3286 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3288 * @return array
3290 public function get_items() {
3291 global $CFG;
3292 $items = array();
3293 // Make sure that navigation is initialised
3294 if (!$this->has_items()) {
3295 return $items;
3297 if ($this->items !== null) {
3298 return $this->items;
3301 if (count($this->children) > 0) {
3302 // Add the custom children.
3303 $items = array_reverse($this->children);
3306 // Check if navigation contains the active node
3307 if (!$this->ignoreactive) {
3308 // We will need to ensure the navigation has been initialised.
3309 $this->page->navigation->initialise($this->page);
3310 // Now find the active nodes on both the navigation and settings.
3311 $navigationactivenode = $this->page->navigation->find_active_node();
3312 $settingsactivenode = $this->page->settingsnav->find_active_node();
3314 if ($navigationactivenode && $settingsactivenode) {
3315 // Parse a combined navigation tree
3316 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3317 if (!$settingsactivenode->mainnavonly) {
3318 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3320 $settingsactivenode = $settingsactivenode->parent;
3322 if (!$this->includesettingsbase) {
3323 // Removes the first node from the settings (root node) from the list
3324 array_pop($items);
3326 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3327 if (!$navigationactivenode->mainnavonly) {
3328 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3330 if (!empty($CFG->navshowcategories) &&
3331 $navigationactivenode->type === self::TYPE_COURSE &&
3332 $navigationactivenode->parent->key === 'currentcourse') {
3333 foreach ($this->get_course_categories() as $item) {
3334 $items[] = new breadcrumb_navigation_node($item);
3337 $navigationactivenode = $navigationactivenode->parent;
3339 } else if ($navigationactivenode) {
3340 // Parse the navigation tree to get the active node
3341 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3342 if (!$navigationactivenode->mainnavonly) {
3343 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3345 if (!empty($CFG->navshowcategories) &&
3346 $navigationactivenode->type === self::TYPE_COURSE &&
3347 $navigationactivenode->parent->key === 'currentcourse') {
3348 foreach ($this->get_course_categories() as $item) {
3349 $items[] = new breadcrumb_navigation_node($item);
3352 $navigationactivenode = $navigationactivenode->parent;
3354 } else if ($settingsactivenode) {
3355 // Parse the settings navigation to get the active node
3356 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3357 if (!$settingsactivenode->mainnavonly) {
3358 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3360 $settingsactivenode = $settingsactivenode->parent;
3365 $items[] = new breadcrumb_navigation_node(array(
3366 'text' => $this->page->navigation->text,
3367 'shorttext' => $this->page->navigation->shorttext,
3368 'key' => $this->page->navigation->key,
3369 'action' => $this->page->navigation->action
3372 if (count($this->prependchildren) > 0) {
3373 // Add the custom children
3374 $items = array_merge($items, array_reverse($this->prependchildren));
3377 $last = reset($items);
3378 if ($last) {
3379 $last->set_last(true);
3381 $this->items = array_reverse($items);
3382 return $this->items;
3386 * Get the list of categories leading to this course.
3388 * This function is used by {@link navbar::get_items()} to add back the "courses"
3389 * node and category chain leading to the current course. Note that this is only ever
3390 * called for the current course, so we don't need to bother taking in any parameters.
3392 * @return array
3394 private function get_course_categories() {
3395 global $CFG;
3396 require_once($CFG->dirroot.'/course/lib.php');
3397 require_once($CFG->libdir.'/coursecatlib.php');
3399 $categories = array();
3400 $cap = 'moodle/category:viewhiddencategories';
3401 $showcategories = coursecat::count_all() > 1;
3403 if ($showcategories) {
3404 foreach ($this->page->categories as $category) {
3405 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3406 continue;
3408 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3409 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3410 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3411 if (!$category->visible) {
3412 $categorynode->hidden = true;
3414 $categories[] = $categorynode;
3418 // Don't show the 'course' node if enrolled in this course.
3419 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3420 $courses = $this->page->navigation->get('courses');
3421 if (!$courses) {
3422 // Courses node may not be present.
3423 $courses = breadcrumb_navigation_node::create(
3424 get_string('courses'),
3425 new moodle_url('/course/index.php'),
3426 self::TYPE_CONTAINER
3429 $categories[] = $courses;
3432 return $categories;
3436 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3438 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3439 * the way nodes get added to allow us to simply call add and have the node added to the
3440 * end of the navbar
3442 * @param string $text
3443 * @param string|moodle_url|action_link $action An action to associate with this node.
3444 * @param int $type One of navigation_node::TYPE_*
3445 * @param string $shorttext
3446 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3447 * @param pix_icon $icon An optional icon to use for this node.
3448 * @return navigation_node
3450 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3451 if ($this->content !== null) {
3452 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3455 // Properties array used when creating the new navigation node
3456 $itemarray = array(
3457 'text' => $text,
3458 'type' => $type
3460 // Set the action if one was provided
3461 if ($action!==null) {
3462 $itemarray['action'] = $action;
3464 // Set the shorttext if one was provided
3465 if ($shorttext!==null) {
3466 $itemarray['shorttext'] = $shorttext;
3468 // Set the icon if one was provided
3469 if ($icon!==null) {
3470 $itemarray['icon'] = $icon;
3472 // Default the key to the number of children if not provided
3473 if ($key === null) {
3474 $key = count($this->children);
3476 // Set the key
3477 $itemarray['key'] = $key;
3478 // Set the parent to this node
3479 $itemarray['parent'] = $this;
3480 // Add the child using the navigation_node_collections add method
3481 $this->children[] = new breadcrumb_navigation_node($itemarray);
3482 return $this;
3486 * Prepends a new navigation_node to the start of the navbar
3488 * @param string $text
3489 * @param string|moodle_url|action_link $action An action to associate with this node.
3490 * @param int $type One of navigation_node::TYPE_*
3491 * @param string $shorttext
3492 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3493 * @param pix_icon $icon An optional icon to use for this node.
3494 * @return navigation_node
3496 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3497 if ($this->content !== null) {
3498 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3500 // Properties array used when creating the new navigation node.
3501 $itemarray = array(
3502 'text' => $text,
3503 'type' => $type
3505 // Set the action if one was provided.
3506 if ($action!==null) {
3507 $itemarray['action'] = $action;
3509 // Set the shorttext if one was provided.
3510 if ($shorttext!==null) {
3511 $itemarray['shorttext'] = $shorttext;
3513 // Set the icon if one was provided.
3514 if ($icon!==null) {
3515 $itemarray['icon'] = $icon;
3517 // Default the key to the number of children if not provided.
3518 if ($key === null) {
3519 $key = count($this->children);
3521 // Set the key.
3522 $itemarray['key'] = $key;
3523 // Set the parent to this node.
3524 $itemarray['parent'] = $this;
3525 // Add the child node to the prepend list.
3526 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3527 return $this;
3532 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3533 * in particular adding extra metadata for search engine robots to leverage.
3535 * @package core
3536 * @category navigation
3537 * @copyright 2015 Brendan Heywood
3538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3540 class breadcrumb_navigation_node extends navigation_node {
3542 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3543 private $last = false;
3546 * A proxy constructor
3548 * @param mixed $navnode A navigation_node or an array
3550 public function __construct($navnode) {
3551 if (is_array($navnode)) {
3552 parent::__construct($navnode);
3553 } else if ($navnode instanceof navigation_node) {
3555 // Just clone everything.
3556 $objvalues = get_object_vars($navnode);
3557 foreach ($objvalues as $key => $value) {
3558 $this->$key = $value;
3560 } else {
3561 throw coding_exception('Not a valid breadcrumb_navigation_node');
3566 * Getter for "last"
3567 * @return boolean
3569 public function is_last() {
3570 return $this->last;
3574 * Setter for "last"
3575 * @param $val boolean
3577 public function set_last($val) {
3578 $this->last = $val;
3583 * Subclass of navigation_node allowing different rendering for the flat navigation
3584 * in particular allowing dividers and indents.
3586 * @package core
3587 * @category navigation
3588 * @copyright 2016 Damyon Wiese
3589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3591 class flat_navigation_node extends navigation_node {
3593 /** @var $indent integer The indent level */
3594 private $indent = 0;
3596 /** @var $showdivider bool Show a divider before this element */
3597 private $showdivider = false;
3600 * A proxy constructor
3602 * @param mixed $navnode A navigation_node or an array
3604 public function __construct($navnode, $indent) {
3605 if (is_array($navnode)) {
3606 parent::__construct($navnode);
3607 } else if ($navnode instanceof navigation_node) {
3609 // Just clone everything.
3610 $objvalues = get_object_vars($navnode);
3611 foreach ($objvalues as $key => $value) {
3612 $this->$key = $value;
3614 } else {
3615 throw coding_exception('Not a valid flat_navigation_node');
3617 $this->indent = $indent;
3621 * Does this node represent a course section link.
3622 * @return boolean
3624 public function is_section() {
3625 return $this->type == navigation_node::TYPE_SECTION;
3629 * In flat navigation - sections are active if we are looking at activities in the section.
3630 * @return boolean
3632 public function isactive() {
3633 global $PAGE;
3635 if ($this->is_section()) {
3636 $active = $PAGE->navigation->find_active_node();
3637 while ($active = $active->parent) {
3638 if ($active->key == $this->key && $active->type == $this->type) {
3639 return true;
3643 return $this->isactive;
3647 * Getter for "showdivider"
3648 * @return boolean
3650 public function showdivider() {
3651 return $this->showdivider;
3655 * Setter for "showdivider"
3656 * @param $val boolean
3658 public function set_showdivider($val) {
3659 $this->showdivider = $val;
3663 * Getter for "indent"
3664 * @return boolean
3666 public function get_indent() {
3667 return $this->indent;
3671 * Setter for "indent"
3672 * @param $val boolean
3674 public function set_indent($val) {
3675 $this->indent = $val;
3681 * Class used to generate a collection of navigation nodes most closely related
3682 * to the current page.
3684 * @package core
3685 * @copyright 2016 Damyon Wiese
3686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3688 class flat_navigation extends navigation_node_collection {
3689 /** @var moodle_page the moodle page that the navigation belongs to */
3690 protected $page;
3693 * Constructor.
3695 * @param moodle_page $page
3697 public function __construct(moodle_page &$page) {
3698 if (during_initial_install()) {
3699 return false;
3701 $this->page = $page;
3705 * Build the list of navigation nodes based on the current navigation and settings trees.
3708 public function initialise() {
3709 global $PAGE, $USER, $OUTPUT, $CFG;
3710 if (during_initial_install()) {
3711 return;
3714 $current = false;
3716 $course = $PAGE->course;
3718 $this->page->navigation->initialise();
3720 // First walk the nav tree looking for "flat_navigation" nodes.
3721 if ($course->id > 1) {
3722 // It's a real course.
3723 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3724 $flat = new flat_navigation_node(navigation_node::create($course->shortname, $url), 0);
3725 $flat->key = 'coursehome';
3727 $courseformat = course_get_format($course);
3728 $coursenode = $PAGE->navigation->find_active_node();
3729 $targettype = navigation_node::TYPE_COURSE;
3731 // Single activity format has no course node - the course node is swapped for the activity node.
3732 if (!$courseformat->has_view_page()) {
3733 $targettype = navigation_node::TYPE_ACTIVITY;
3736 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
3737 $coursenode = $coursenode->parent;
3739 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3740 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3741 if ($coursenode && $coursenode->key != SITEID) {
3742 $this->add($flat);
3743 foreach ($coursenode->children as $child) {
3744 if ($child->action) {
3745 $flat = new flat_navigation_node($child, 0);
3746 $this->add($flat);
3751 $this->page->navigation->build_flat_navigation_list($this, true);
3752 } else {
3753 $this->page->navigation->build_flat_navigation_list($this, false);
3756 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
3757 if (!$admin) {
3758 // Try again - crazy nav tree!
3759 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
3761 if ($admin) {
3762 $flat = new flat_navigation_node($admin, 0);
3763 $flat->set_showdivider(true);
3764 $flat->key = 'sitesettings';
3765 $this->add($flat);
3768 // Add-a-block in editing mode.
3769 if (isset($this->page->theme->addblockposition) &&
3770 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
3771 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3772 ($addable = $PAGE->blocks->get_addable_blocks())) {
3773 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3774 $addablock = navigation_node::create(get_string('addblock'), $url);
3775 $flat = new flat_navigation_node($addablock, 0);
3776 $flat->set_showdivider(true);
3777 $flat->key = 'addblock';
3778 $this->add($flat);
3779 $blocks = [];
3780 foreach ($addable as $block) {
3781 $blocks[] = $block->name;
3783 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3784 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
3791 * Class used to manage the settings option for the current page
3793 * This class is used to manage the settings options in a tree format (recursively)
3794 * and was created initially for use with the settings blocks.
3796 * @package core
3797 * @category navigation
3798 * @copyright 2009 Sam Hemelryk
3799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3801 class settings_navigation extends navigation_node {
3802 /** @var stdClass the current context */
3803 protected $context;
3804 /** @var moodle_page the moodle page that the navigation belongs to */
3805 protected $page;
3806 /** @var string contains administration section navigation_nodes */
3807 protected $adminsection;
3808 /** @var bool A switch to see if the navigation node is initialised */
3809 protected $initialised = false;
3810 /** @var array An array of users that the nodes can extend for. */
3811 protected $userstoextendfor = array();
3812 /** @var navigation_cache **/
3813 protected $cache;
3816 * Sets up the object with basic settings and preparse it for use
3818 * @param moodle_page $page
3820 public function __construct(moodle_page &$page) {
3821 if (during_initial_install()) {
3822 return false;
3824 $this->page = $page;
3825 // Initialise the main navigation. It is most important that this is done
3826 // before we try anything
3827 $this->page->navigation->initialise();
3828 // Initialise the navigation cache
3829 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3830 $this->children = new navigation_node_collection();
3834 * Initialise the settings navigation based on the current context
3836 * This function initialises the settings navigation tree for a given context
3837 * by calling supporting functions to generate major parts of the tree.
3840 public function initialise() {
3841 global $DB, $SESSION, $SITE;
3843 if (during_initial_install()) {
3844 return false;
3845 } else if ($this->initialised) {
3846 return true;
3848 $this->id = 'settingsnav';
3849 $this->context = $this->page->context;
3851 $context = $this->context;
3852 if ($context->contextlevel == CONTEXT_BLOCK) {
3853 $this->load_block_settings();
3854 $context = $context->get_parent_context();
3856 switch ($context->contextlevel) {
3857 case CONTEXT_SYSTEM:
3858 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3859 $this->load_front_page_settings(($context->id == $this->context->id));
3861 break;
3862 case CONTEXT_COURSECAT:
3863 $this->load_category_settings();
3864 break;
3865 case CONTEXT_COURSE:
3866 if ($this->page->course->id != $SITE->id) {
3867 $this->load_course_settings(($context->id == $this->context->id));
3868 } else {
3869 $this->load_front_page_settings(($context->id == $this->context->id));
3871 break;
3872 case CONTEXT_MODULE:
3873 $this->load_module_settings();
3874 $this->load_course_settings();
3875 break;
3876 case CONTEXT_USER:
3877 if ($this->page->course->id != $SITE->id) {
3878 $this->load_course_settings();
3880 break;
3883 $usersettings = $this->load_user_settings($this->page->course->id);
3885 $adminsettings = false;
3886 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
3887 $isadminpage = $this->is_admin_tree_needed();
3889 if (has_capability('moodle/site:config', context_system::instance())) {
3890 // Make sure this works even if config capability changes on the fly
3891 // and also make it fast for admin right after login.
3892 $SESSION->load_navigation_admin = 1;
3893 if ($isadminpage) {
3894 $adminsettings = $this->load_administration_settings();
3897 } else if (!isset($SESSION->load_navigation_admin)) {
3898 $adminsettings = $this->load_administration_settings();
3899 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
3901 } else if ($SESSION->load_navigation_admin) {
3902 if ($isadminpage) {
3903 $adminsettings = $this->load_administration_settings();
3907 // Print empty navigation node, if needed.
3908 if ($SESSION->load_navigation_admin && !$isadminpage) {
3909 if ($adminsettings) {
3910 // Do not print settings tree on pages that do not need it, this helps with performance.
3911 $adminsettings->remove();
3912 $adminsettings = false;
3914 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
3915 $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
3916 $siteadminnode->requiresajaxloading = 'true';
3920 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
3921 $adminsettings->force_open();
3922 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
3923 $usersettings->force_open();
3926 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3927 $this->load_local_plugin_settings();
3929 foreach ($this->children as $key=>$node) {
3930 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
3931 // Site administration is shown as link.
3932 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
3933 continue;
3935 $node->remove();
3938 $this->initialised = true;
3941 * Override the parent function so that we can add preceeding hr's and set a
3942 * root node class against all first level element
3944 * It does this by first calling the parent's add method {@link navigation_node::add()}
3945 * and then proceeds to use the key to set class and hr
3947 * @param string $text text to be used for the link.
3948 * @param string|moodle_url $url url for the new node
3949 * @param int $type the type of node navigation_node::TYPE_*
3950 * @param string $shorttext
3951 * @param string|int $key a key to access the node by.
3952 * @param pix_icon $icon An icon that appears next to the node.
3953 * @return navigation_node with the new node added to it.
3955 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3956 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3957 $node->add_class('root_node');
3958 return $node;
3962 * This function allows the user to add something to the start of the settings
3963 * navigation, which means it will be at the top of the settings navigation block
3965 * @param string $text text to be used for the link.
3966 * @param string|moodle_url $url url for the new node
3967 * @param int $type the type of node navigation_node::TYPE_*
3968 * @param string $shorttext
3969 * @param string|int $key a key to access the node by.
3970 * @param pix_icon $icon An icon that appears next to the node.
3971 * @return navigation_node $node with the new node added to it.
3973 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3974 $children = $this->children;
3975 $childrenclass = get_class($children);
3976 $this->children = new $childrenclass;
3977 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3978 foreach ($children as $child) {
3979 $this->children->add($child);
3981 return $node;
3985 * Does this page require loading of full admin tree or is
3986 * it enough rely on AJAX?
3988 * @return bool
3990 protected function is_admin_tree_needed() {
3991 if (self::$loadadmintree) {
3992 // Usually external admin page or settings page.
3993 return true;
3996 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
3997 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
3998 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
3999 return false;
4001 return true;
4004 return false;
4008 * Load the site administration tree
4010 * This function loads the site administration tree by using the lib/adminlib library functions
4012 * @param navigation_node $referencebranch A reference to a branch in the settings
4013 * navigation tree
4014 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4015 * tree and start at the beginning
4016 * @return mixed A key to access the admin tree by
4018 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4019 global $CFG;
4021 // Check if we are just starting to generate this navigation.
4022 if ($referencebranch === null) {
4024 // Require the admin lib then get an admin structure
4025 if (!function_exists('admin_get_root')) {
4026 require_once($CFG->dirroot.'/lib/adminlib.php');
4028 $adminroot = admin_get_root(false, false);
4029 // This is the active section identifier
4030 $this->adminsection = $this->page->url->param('section');
4032 // Disable the navigation from automatically finding the active node
4033 navigation_node::$autofindactive = false;
4034 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4035 foreach ($adminroot->children as $adminbranch) {
4036 $this->load_administration_settings($referencebranch, $adminbranch);
4038 navigation_node::$autofindactive = true;
4040 // Use the admin structure to locate the active page
4041 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4042 $currentnode = $this;
4043 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4044 $currentnode = $currentnode->get($pathkey);
4046 if ($currentnode) {
4047 $currentnode->make_active();
4049 } else {
4050 $this->scan_for_active_node($referencebranch);
4052 return $referencebranch;
4053 } else if ($adminbranch->check_access()) {
4054 // We have a reference branch that we can access and is not hidden `hurrah`
4055 // Now we need to display it and any children it may have
4056 $url = null;
4057 $icon = null;
4058 if ($adminbranch instanceof admin_settingpage) {
4059 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4060 } else if ($adminbranch instanceof admin_externalpage) {
4061 $url = $adminbranch->url;
4062 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4063 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4066 // Add the branch
4067 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4069 if ($adminbranch->is_hidden()) {
4070 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4071 $reference->add_class('hidden');
4072 } else {
4073 $reference->display = false;
4077 // Check if we are generating the admin notifications and whether notificiations exist
4078 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4079 $reference->add_class('criticalnotification');
4081 // Check if this branch has children
4082 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4083 foreach ($adminbranch->children as $branch) {
4084 // Generate the child branches as well now using this branch as the reference
4085 $this->load_administration_settings($reference, $branch);
4087 } else {
4088 $reference->icon = new pix_icon('i/settings', '');
4094 * This function recursivily scans nodes until it finds the active node or there
4095 * are no more nodes.
4096 * @param navigation_node $node
4098 protected function scan_for_active_node(navigation_node $node) {
4099 if (!$node->check_if_active() && $node->children->count()>0) {
4100 foreach ($node->children as &$child) {
4101 $this->scan_for_active_node($child);
4107 * Gets a navigation node given an array of keys that represent the path to
4108 * the desired node.
4110 * @param array $path
4111 * @return navigation_node|false
4113 protected function get_by_path(array $path) {
4114 $node = $this->get(array_shift($path));
4115 foreach ($path as $key) {
4116 $node->get($key);
4118 return $node;
4122 * This function loads the course settings that are available for the user
4124 * @param bool $forceopen If set to true the course node will be forced open
4125 * @return navigation_node|false
4127 protected function load_course_settings($forceopen = false) {
4128 global $CFG;
4129 require_once($CFG->dirroot . '/course/lib.php');
4131 $course = $this->page->course;
4132 $coursecontext = context_course::instance($course->id);
4133 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4135 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4137 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4138 if ($forceopen) {
4139 $coursenode->force_open();
4143 if ($adminoptions->update) {
4144 // Add the course settings link
4145 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4146 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4149 if ($this->page->user_allowed_editing()) {
4150 // Add the turn on/off settings
4152 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
4153 // We are on the course page, retain the current page params e.g. section.
4154 $baseurl = clone($this->page->url);
4155 $baseurl->param('sesskey', sesskey());
4156 } else {
4157 // Edit on the main course page.
4158 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
4161 $editurl = clone($baseurl);
4162 if ($this->page->user_is_editing()) {
4163 $editurl->param('edit', 'off');
4164 $editstring = get_string('turneditingoff');
4165 } else {
4166 $editurl->param('edit', 'on');
4167 $editstring = get_string('turneditingon');
4169 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4172 if ($adminoptions->update) {
4174 // Add the course completion settings link
4175 if ($CFG->enablecompletion && $course->enablecompletion) {
4176 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
4177 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
4179 } else if ($adminoptions->tags) {
4180 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4181 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4184 // add enrol nodes
4185 enrol_add_course_navigation($coursenode, $course);
4187 // Manage filters
4188 if ($adminoptions->filters) {
4189 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4190 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4193 // View course reports.
4194 if ($adminoptions->reports) {
4195 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
4196 new pix_icon('i/stats', ''));
4197 $coursereports = core_component::get_plugin_list('coursereport');
4198 foreach ($coursereports as $report => $dir) {
4199 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4200 if (file_exists($libfile)) {
4201 require_once($libfile);
4202 $reportfunction = $report.'_report_extend_navigation';
4203 if (function_exists($report.'_report_extend_navigation')) {
4204 $reportfunction($reportnav, $course, $coursecontext);
4209 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4210 foreach ($reports as $reportfunction) {
4211 $reportfunction($reportnav, $course, $coursecontext);
4215 // Check if we can view the gradebook's setup page.
4216 if ($adminoptions->gradebook) {
4217 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4218 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4219 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4222 // Add outcome if permitted
4223 if ($adminoptions->outcomes) {
4224 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4225 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4228 //Add badges navigation
4229 if ($adminoptions->badges) {
4230 require_once($CFG->libdir .'/badgeslib.php');
4231 badges_add_course_navigation($coursenode, $course);
4234 // Backup this course
4235 if ($adminoptions->backup) {
4236 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4237 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4240 // Restore to this course
4241 if ($adminoptions->restore) {
4242 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4243 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4246 // Import data from other courses
4247 if ($adminoptions->import) {
4248 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4249 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4252 // Publish course on a hub
4253 if ($adminoptions->publish) {
4254 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
4255 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
4258 // Reset this course
4259 if ($adminoptions->reset) {
4260 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4261 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4264 // Questions
4265 require_once($CFG->libdir . '/questionlib.php');
4266 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4268 if ($adminoptions->update) {
4269 // Repository Instances
4270 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4271 require_once($CFG->dirroot . '/repository/lib.php');
4272 $editabletypes = repository::get_editable_types($coursecontext);
4273 $haseditabletypes = !empty($editabletypes);
4274 unset($editabletypes);
4275 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4276 } else {
4277 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4279 if ($haseditabletypes) {
4280 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4281 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4285 // Manage files
4286 if ($adminoptions->files) {
4287 // hidden in new courses and courses where legacy files were turned off
4288 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4289 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4293 // Let plugins hook into course navigation.
4294 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4295 foreach ($pluginsfunction as $plugintype => $plugins) {
4296 // Ignore the report plugin as it was already loaded above.
4297 if ($plugintype == 'report') {
4298 continue;
4300 foreach ($plugins as $pluginfunction) {
4301 $pluginfunction($coursenode, $course, $coursecontext);
4305 // Return we are done
4306 return $coursenode;
4310 * This function calls the module function to inject module settings into the
4311 * settings navigation tree.
4313 * This only gets called if there is a corrosponding function in the modules
4314 * lib file.
4316 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4318 * @return navigation_node|false
4320 protected function load_module_settings() {
4321 global $CFG;
4323 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4324 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4325 $this->page->set_cm($cm, $this->page->course);
4328 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4329 if (file_exists($file)) {
4330 require_once($file);
4333 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4334 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4335 $modulenode->force_open();
4337 // Settings for the module
4338 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4339 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4340 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4342 // Assign local roles
4343 if (count(get_assignable_roles($this->page->cm->context))>0) {
4344 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4345 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4347 // Override roles
4348 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4349 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4350 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4352 // Check role permissions
4353 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4354 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4355 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4357 // Manage filters
4358 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4359 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4360 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4362 // Add reports
4363 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4364 foreach ($reports as $reportfunction) {
4365 $reportfunction($modulenode, $this->page->cm);
4367 // Add a backup link
4368 $featuresfunc = $this->page->activityname.'_supports';
4369 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4370 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4371 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4374 // Restore this activity
4375 $featuresfunc = $this->page->activityname.'_supports';
4376 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4377 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4378 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4381 // Allow the active advanced grading method plugin to append its settings
4382 $featuresfunc = $this->page->activityname.'_supports';
4383 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4384 require_once($CFG->dirroot.'/grade/grading/lib.php');
4385 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4386 $gradingman->extend_settings_navigation($this, $modulenode);
4389 $function = $this->page->activityname.'_extend_settings_navigation';
4390 if (function_exists($function)) {
4391 $function($this, $modulenode);
4394 // Remove the module node if there are no children.
4395 if ($modulenode->children->count() <= 0) {
4396 $modulenode->remove();
4399 return $modulenode;
4403 * Loads the user settings block of the settings nav
4405 * This function is simply works out the userid and whether we need to load
4406 * just the current users profile settings, or the current user and the user the
4407 * current user is viewing.
4409 * This function has some very ugly code to work out the user, if anyone has
4410 * any bright ideas please feel free to intervene.
4412 * @param int $courseid The course id of the current course
4413 * @return navigation_node|false
4415 protected function load_user_settings($courseid = SITEID) {
4416 global $USER, $CFG;
4418 if (isguestuser() || !isloggedin()) {
4419 return false;
4422 $navusers = $this->page->navigation->get_extending_users();
4424 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4425 $usernode = null;
4426 foreach ($this->userstoextendfor as $userid) {
4427 if ($userid == $USER->id) {
4428 continue;
4430 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4431 if (is_null($usernode)) {
4432 $usernode = $node;
4435 foreach ($navusers as $user) {
4436 if ($user->id == $USER->id) {
4437 continue;
4439 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4440 if (is_null($usernode)) {
4441 $usernode = $node;
4444 $this->generate_user_settings($courseid, $USER->id);
4445 } else {
4446 $usernode = $this->generate_user_settings($courseid, $USER->id);
4448 return $usernode;
4452 * Extends the settings navigation for the given user.
4454 * Note: This method gets called automatically if you call
4455 * $PAGE->navigation->extend_for_user($userid)
4457 * @param int $userid
4459 public function extend_for_user($userid) {
4460 global $CFG;
4462 if (!in_array($userid, $this->userstoextendfor)) {
4463 $this->userstoextendfor[] = $userid;
4464 if ($this->initialised) {
4465 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4466 $children = array();
4467 foreach ($this->children as $child) {
4468 $children[] = $child;
4470 array_unshift($children, array_pop($children));
4471 $this->children = new navigation_node_collection();
4472 foreach ($children as $child) {
4473 $this->children->add($child);
4480 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4481 * what can be shown/done
4483 * @param int $courseid The current course' id
4484 * @param int $userid The user id to load for
4485 * @param string $gstitle The string to pass to get_string for the branch title
4486 * @return navigation_node|false
4488 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4489 global $DB, $CFG, $USER, $SITE;
4491 if ($courseid != $SITE->id) {
4492 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4493 $course = $this->page->course;
4494 } else {
4495 $select = context_helper::get_preload_record_columns_sql('ctx');
4496 $sql = "SELECT c.*, $select
4497 FROM {course} c
4498 JOIN {context} ctx ON c.id = ctx.instanceid
4499 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4500 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4501 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4502 context_helper::preload_from_record($course);
4504 } else {
4505 $course = $SITE;
4508 $coursecontext = context_course::instance($course->id); // Course context
4509 $systemcontext = context_system::instance();
4510 $currentuser = ($USER->id == $userid);
4512 if ($currentuser) {
4513 $user = $USER;
4514 $usercontext = context_user::instance($user->id); // User context
4515 } else {
4516 $select = context_helper::get_preload_record_columns_sql('ctx');
4517 $sql = "SELECT u.*, $select
4518 FROM {user} u
4519 JOIN {context} ctx ON u.id = ctx.instanceid
4520 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4521 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4522 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4523 if (!$user) {
4524 return false;
4526 context_helper::preload_from_record($user);
4528 // Check that the user can view the profile
4529 $usercontext = context_user::instance($user->id); // User context
4530 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4532 if ($course->id == $SITE->id) {
4533 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4534 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4535 return false;
4537 } else {
4538 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4539 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4540 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4541 return false;
4543 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4544 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4545 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4546 if ($courseid == $this->page->course->id) {
4547 $mygroups = get_fast_modinfo($this->page->course)->groups;
4548 } else {
4549 $mygroups = groups_get_user_groups($courseid);
4551 $usergroups = groups_get_user_groups($courseid, $userid);
4552 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4553 return false;
4559 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4561 $key = $gstitle;
4562 $prefurl = new moodle_url('/user/preferences.php');
4563 if ($gstitle != 'usercurrentsettings') {
4564 $key .= $userid;
4565 $prefurl->param('userid', $userid);
4568 // Add a user setting branch.
4569 if ($gstitle == 'usercurrentsettings') {
4570 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4571 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4572 // breadcrumb.
4573 $dashboard->display = false;
4574 if (get_home_page() == HOMEPAGE_MY) {
4575 $dashboard->mainnavonly = true;
4578 $iscurrentuser = ($user->id == $USER->id);
4580 $baseargs = array('id' => $user->id);
4581 if ($course->id != $SITE->id && !$iscurrentuser) {
4582 $baseargs['course'] = $course->id;
4583 $issitecourse = false;
4584 } else {
4585 // Load all categories and get the context for the system.
4586 $issitecourse = true;
4589 // Add the user profile to the dashboard.
4590 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4591 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4593 if (!empty($CFG->navadduserpostslinks)) {
4594 // Add nodes for forum posts and discussions if the user can view either or both
4595 // There are no capability checks here as the content of the page is based
4596 // purely on the forums the current user has access too.
4597 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4598 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4599 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4600 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4603 // Add blog nodes.
4604 if (!empty($CFG->enableblogs)) {
4605 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4606 require_once($CFG->dirroot.'/blog/lib.php');
4607 // Get all options for the user.
4608 $options = blog_get_options_for_user($user);
4609 $this->cache->set('userblogoptions'.$user->id, $options);
4610 } else {
4611 $options = $this->cache->{'userblogoptions'.$user->id};
4614 if (count($options) > 0) {
4615 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4616 foreach ($options as $type => $option) {
4617 if ($type == "rss") {
4618 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4619 new pix_icon('i/rss', ''));
4620 } else {
4621 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4627 // Add the messages link.
4628 // It is context based so can appear in the user's profile and in course participants information.
4629 if (!empty($CFG->messaging)) {
4630 $messageargs = array('user1' => $USER->id);
4631 if ($USER->id != $user->id) {
4632 $messageargs['user2'] = $user->id;
4634 $url = new moodle_url('/message/index.php', $messageargs);
4635 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4638 // Add the "My private files" link.
4639 // This link doesn't have a unique display for course context so only display it under the user's profile.
4640 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4641 $url = new moodle_url('/user/files.php');
4642 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
4645 // Add a node to view the users notes if permitted.
4646 if (!empty($CFG->enablenotes) &&
4647 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4648 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4649 if ($coursecontext->instanceid != SITEID) {
4650 $url->param('course', $coursecontext->instanceid);
4652 $profilenode->add(get_string('notes', 'notes'), $url);
4655 // Show the grades node.
4656 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4657 require_once($CFG->dirroot . '/user/lib.php');
4658 // Set the grades node to link to the "Grades" page.
4659 if ($course->id == SITEID) {
4660 $url = user_mygrades_url($user->id, $course->id);
4661 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4662 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4664 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4667 // Let plugins hook into user navigation.
4668 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4669 foreach ($pluginsfunction as $plugintype => $plugins) {
4670 if ($plugintype != 'report') {
4671 foreach ($plugins as $pluginfunction) {
4672 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4677 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4678 $dashboard->add_node($usersetting);
4679 } else {
4680 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4681 $usersetting->display = false;
4683 $usersetting->id = 'usersettings';
4685 // Check if the user has been deleted.
4686 if ($user->deleted) {
4687 if (!has_capability('moodle/user:update', $coursecontext)) {
4688 // We can't edit the user so just show the user deleted message.
4689 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4690 } else {
4691 // We can edit the user so show the user deleted message and link it to the profile.
4692 if ($course->id == $SITE->id) {
4693 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4694 } else {
4695 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4697 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4699 return true;
4702 $userauthplugin = false;
4703 if (!empty($user->auth)) {
4704 $userauthplugin = get_auth_plugin($user->auth);
4707 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4709 // Add the profile edit link.
4710 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4711 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4712 has_capability('moodle/user:update', $systemcontext)) {
4713 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4714 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4715 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4716 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4717 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4718 $url = $userauthplugin->edit_profile_url();
4719 if (empty($url)) {
4720 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4722 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4727 // Change password link.
4728 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
4729 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4730 $passwordchangeurl = $userauthplugin->change_password_url();
4731 if (empty($passwordchangeurl)) {
4732 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4734 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4737 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4738 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4739 has_capability('moodle/user:editprofile', $usercontext)) {
4740 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
4741 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
4744 $pluginmanager = core_plugin_manager::instance();
4745 $enabled = $pluginmanager->get_enabled_plugins('mod');
4746 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4747 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4748 has_capability('moodle/user:editprofile', $usercontext)) {
4749 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
4750 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
4753 $editors = editors_get_enabled();
4754 if (count($editors) > 1) {
4755 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4756 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4757 has_capability('moodle/user:editprofile', $usercontext)) {
4758 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
4759 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
4764 // Add "Course preferences" link.
4765 if (isloggedin() && !isguestuser($user)) {
4766 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4767 has_capability('moodle/user:editprofile', $usercontext)) {
4768 $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
4769 $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
4773 // Add "Calendar preferences" link.
4774 if (isloggedin() && !isguestuser($user)) {
4775 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4776 has_capability('moodle/user:editprofile', $usercontext)) {
4777 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
4778 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
4782 // View the roles settings.
4783 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4784 'moodle/role:manage'), $usercontext)) {
4785 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4787 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4788 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4790 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4792 if (!empty($assignableroles)) {
4793 $url = new moodle_url('/admin/roles/assign.php',
4794 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4795 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4798 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4799 $url = new moodle_url('/admin/roles/permissions.php',
4800 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4801 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4804 $url = new moodle_url('/admin/roles/check.php',
4805 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4806 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4809 // Repositories.
4810 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4811 require_once($CFG->dirroot . '/repository/lib.php');
4812 $editabletypes = repository::get_editable_types($usercontext);
4813 $haseditabletypes = !empty($editabletypes);
4814 unset($editabletypes);
4815 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4816 } else {
4817 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4819 if ($haseditabletypes) {
4820 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
4821 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4822 array('contextid' => $usercontext->id)));
4825 // Portfolio.
4826 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4827 require_once($CFG->libdir . '/portfoliolib.php');
4828 if (portfolio_has_visible_instances()) {
4829 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4831 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4832 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4834 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4835 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4839 $enablemanagetokens = false;
4840 if (!empty($CFG->enablerssfeeds)) {
4841 $enablemanagetokens = true;
4842 } else if (!is_siteadmin($USER->id)
4843 && !empty($CFG->enablewebservices)
4844 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4845 $enablemanagetokens = true;
4847 // Security keys.
4848 if ($currentuser && $enablemanagetokens) {
4849 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4850 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4853 // Messaging.
4854 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
4855 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4856 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
4857 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
4858 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
4859 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
4862 // Blogs.
4863 if ($currentuser && !empty($CFG->enableblogs)) {
4864 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4865 if (has_capability('moodle/blog:view', $systemcontext)) {
4866 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
4867 navigation_node::TYPE_SETTING);
4869 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
4870 has_capability('moodle/blog:manageexternal', $systemcontext)) {
4871 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
4872 navigation_node::TYPE_SETTING);
4873 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
4874 navigation_node::TYPE_SETTING);
4876 // Remove the blog node if empty.
4877 $blog->trim_if_empty();
4880 // Badges.
4881 if ($currentuser && !empty($CFG->enablebadges)) {
4882 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
4883 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
4884 $url = new moodle_url('/badges/mybadges.php');
4885 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
4887 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
4888 navigation_node::TYPE_SETTING);
4889 if (!empty($CFG->badges_allowexternalbackpack)) {
4890 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
4891 navigation_node::TYPE_SETTING);
4895 // Let plugins hook into user settings navigation.
4896 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
4897 foreach ($pluginsfunction as $plugintype => $plugins) {
4898 foreach ($plugins as $pluginfunction) {
4899 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
4903 return $usersetting;
4907 * Loads block specific settings in the navigation
4909 * @return navigation_node
4911 protected function load_block_settings() {
4912 global $CFG;
4914 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
4915 $blocknode->force_open();
4917 // Assign local roles
4918 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
4919 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
4920 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
4921 'roles', new pix_icon('i/assignroles', ''));
4924 // Override roles
4925 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
4926 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
4927 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
4928 'permissions', new pix_icon('i/permissions', ''));
4930 // Check role permissions
4931 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
4932 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
4933 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
4934 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4937 return $blocknode;
4941 * Loads category specific settings in the navigation
4943 * @return navigation_node
4945 protected function load_category_settings() {
4946 global $CFG;
4948 // We can land here while being in the context of a block, in which case we
4949 // should get the parent context which should be the category one. See self::initialise().
4950 if ($this->context->contextlevel == CONTEXT_BLOCK) {
4951 $catcontext = $this->context->get_parent_context();
4952 } else {
4953 $catcontext = $this->context;
4956 // Let's make sure that we always have the right context when getting here.
4957 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
4958 throw new coding_exception('Unexpected context while loading category settings.');
4961 $categorynodetype = navigation_node::TYPE_CONTAINER;
4962 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
4963 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
4964 $categorynode->force_open();
4966 if (can_edit_in_category($catcontext->instanceid)) {
4967 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
4968 $editstring = get_string('managecategorythis');
4969 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
4972 if (has_capability('moodle/category:manage', $catcontext)) {
4973 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
4974 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
4976 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
4977 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4980 // Assign local roles
4981 $assignableroles = get_assignable_roles($catcontext);
4982 if (!empty($assignableroles)) {
4983 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
4984 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
4987 // Override roles
4988 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
4989 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
4990 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
4992 // Check role permissions
4993 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
4994 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
4995 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
4996 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4999 // Cohorts
5000 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5001 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5002 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5005 // Manage filters
5006 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5007 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5008 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5011 // Restore.
5012 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5013 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5014 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5017 // Let plugins hook into category settings navigation.
5018 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5019 foreach ($pluginsfunction as $plugintype => $plugins) {
5020 foreach ($plugins as $pluginfunction) {
5021 $pluginfunction($categorynode, $catcontext);
5025 return $categorynode;
5029 * Determine whether the user is assuming another role
5031 * This function checks to see if the user is assuming another role by means of
5032 * role switching. In doing this we compare each RSW key (context path) against
5033 * the current context path. This ensures that we can provide the switching
5034 * options against both the course and any page shown under the course.
5036 * @return bool|int The role(int) if the user is in another role, false otherwise
5038 protected function in_alternative_role() {
5039 global $USER;
5040 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5041 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5042 return $USER->access['rsw'][$this->page->context->path];
5044 foreach ($USER->access['rsw'] as $key=>$role) {
5045 if (strpos($this->context->path,$key)===0) {
5046 return $role;
5050 return false;
5054 * This function loads all of the front page settings into the settings navigation.
5055 * This function is called when the user is on the front page, or $COURSE==$SITE
5056 * @param bool $forceopen (optional)
5057 * @return navigation_node
5059 protected function load_front_page_settings($forceopen = false) {
5060 global $SITE, $CFG;
5061 require_once($CFG->dirroot . '/course/lib.php');
5063 $course = clone($SITE);
5064 $coursecontext = context_course::instance($course->id); // Course context
5065 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5067 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5068 if ($forceopen) {
5069 $frontpage->force_open();
5071 $frontpage->id = 'frontpagesettings';
5073 if ($this->page->user_allowed_editing()) {
5075 // Add the turn on/off settings
5076 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5077 if ($this->page->user_is_editing()) {
5078 $url->param('edit', 'off');
5079 $editstring = get_string('turneditingoff');
5080 } else {
5081 $url->param('edit', 'on');
5082 $editstring = get_string('turneditingon');
5084 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5087 if ($adminoptions->update) {
5088 // Add the course settings link
5089 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5090 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5093 // add enrol nodes
5094 enrol_add_course_navigation($frontpage, $course);
5096 // Manage filters
5097 if ($adminoptions->filters) {
5098 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5099 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5102 // View course reports.
5103 if ($adminoptions->reports) {
5104 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5105 new pix_icon('i/stats', ''));
5106 $coursereports = core_component::get_plugin_list('coursereport');
5107 foreach ($coursereports as $report=>$dir) {
5108 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5109 if (file_exists($libfile)) {
5110 require_once($libfile);
5111 $reportfunction = $report.'_report_extend_navigation';
5112 if (function_exists($report.'_report_extend_navigation')) {
5113 $reportfunction($frontpagenav, $course, $coursecontext);
5118 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5119 foreach ($reports as $reportfunction) {
5120 $reportfunction($frontpagenav, $course, $coursecontext);
5124 // Backup this course
5125 if ($adminoptions->backup) {
5126 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5127 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5130 // Restore to this course
5131 if ($adminoptions->restore) {
5132 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5133 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5136 // Questions
5137 require_once($CFG->libdir . '/questionlib.php');
5138 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5140 // Manage files
5141 if ($adminoptions->files) {
5142 //hiden in new installs
5143 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5144 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5147 // Let plugins hook into frontpage navigation.
5148 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5149 foreach ($pluginsfunction as $plugintype => $plugins) {
5150 foreach ($plugins as $pluginfunction) {
5151 $pluginfunction($frontpage, $course, $coursecontext);
5155 return $frontpage;
5159 * This function gives local plugins an opportunity to modify the settings navigation.
5161 protected function load_local_plugin_settings() {
5163 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5164 $function($this, $this->context);
5169 * This function marks the cache as volatile so it is cleared during shutdown
5171 public function clear_cache() {
5172 $this->cache->volatile();
5176 * Checks to see if there are child nodes available in the specific user's preference node.
5177 * If so, then they have the appropriate permissions view this user's preferences.
5179 * @since Moodle 2.9.3
5180 * @param int $userid The user's ID.
5181 * @return bool True if child nodes exist to view, otherwise false.
5183 public function can_view_user_preferences($userid) {
5184 if (is_siteadmin()) {
5185 return true;
5187 // See if any nodes are present in the preferences section for this user.
5188 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5189 if ($preferencenode && $preferencenode->has_children()) {
5190 // Run through each child node.
5191 foreach ($preferencenode->children as $childnode) {
5192 // If the child node has children then this user has access to a link in the preferences page.
5193 if ($childnode->has_children()) {
5194 return true;
5198 // No links found for the user to access on the preferences page.
5199 return false;
5204 * Class used to populate site admin navigation for ajax.
5206 * @package core
5207 * @category navigation
5208 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5211 class settings_navigation_ajax extends settings_navigation {
5213 * Constructs the navigation for use in an AJAX request
5215 * @param moodle_page $page
5217 public function __construct(moodle_page &$page) {
5218 $this->page = $page;
5219 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5220 $this->children = new navigation_node_collection();
5221 $this->initialise();
5225 * Initialise the site admin navigation.
5227 * @return array An array of the expandable nodes
5229 public function initialise() {
5230 if ($this->initialised || during_initial_install()) {
5231 return false;
5233 $this->context = $this->page->context;
5234 $this->load_administration_settings();
5236 // Check if local plugins is adding node to site admin.
5237 $this->load_local_plugin_settings();
5239 $this->initialised = true;
5244 * Simple class used to output a navigation branch in XML
5246 * @package core
5247 * @category navigation
5248 * @copyright 2009 Sam Hemelryk
5249 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5251 class navigation_json {
5252 /** @var array An array of different node types */
5253 protected $nodetype = array('node','branch');
5254 /** @var array An array of node keys and types */
5255 protected $expandable = array();
5257 * Turns a branch and all of its children into XML
5259 * @param navigation_node $branch
5260 * @return string XML string
5262 public function convert($branch) {
5263 $xml = $this->convert_child($branch);
5264 return $xml;
5267 * Set the expandable items in the array so that we have enough information
5268 * to attach AJAX events
5269 * @param array $expandable
5271 public function set_expandable($expandable) {
5272 foreach ($expandable as $node) {
5273 $this->expandable[$node['key'].':'.$node['type']] = $node;
5277 * Recusively converts a child node and its children to XML for output
5279 * @param navigation_node $child The child to convert
5280 * @param int $depth Pointlessly used to track the depth of the XML structure
5281 * @return string JSON
5283 protected function convert_child($child, $depth=1) {
5284 if (!$child->display) {
5285 return '';
5287 $attributes = array();
5288 $attributes['id'] = $child->id;
5289 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5290 $attributes['type'] = $child->type;
5291 $attributes['key'] = $child->key;
5292 $attributes['class'] = $child->get_css_type();
5293 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5295 if ($child->icon instanceof pix_icon) {
5296 $attributes['icon'] = array(
5297 'component' => $child->icon->component,
5298 'pix' => $child->icon->pix,
5300 foreach ($child->icon->attributes as $key=>$value) {
5301 if ($key == 'class') {
5302 $attributes['icon']['classes'] = explode(' ', $value);
5303 } else if (!array_key_exists($key, $attributes['icon'])) {
5304 $attributes['icon'][$key] = $value;
5308 } else if (!empty($child->icon)) {
5309 $attributes['icon'] = (string)$child->icon;
5312 if ($child->forcetitle || $child->title !== $child->text) {
5313 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5315 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5316 $attributes['expandable'] = $child->key;
5317 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5320 if (count($child->classes)>0) {
5321 $attributes['class'] .= ' '.join(' ',$child->classes);
5323 if (is_string($child->action)) {
5324 $attributes['link'] = $child->action;
5325 } else if ($child->action instanceof moodle_url) {
5326 $attributes['link'] = $child->action->out();
5327 } else if ($child->action instanceof action_link) {
5328 $attributes['link'] = $child->action->url->out();
5330 $attributes['hidden'] = ($child->hidden);
5331 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5332 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5334 if ($child->children->count() > 0) {
5335 $attributes['children'] = array();
5336 foreach ($child->children as $subchild) {
5337 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5341 if ($depth > 1) {
5342 return $attributes;
5343 } else {
5344 return json_encode($attributes);
5350 * The cache class used by global navigation and settings navigation.
5352 * It is basically an easy access point to session with a bit of smarts to make
5353 * sure that the information that is cached is valid still.
5355 * Example use:
5356 * <code php>
5357 * if (!$cache->viewdiscussion()) {
5358 * // Code to do stuff and produce cachable content
5359 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5361 * $content = $cache->viewdiscussion;
5362 * </code>
5364 * @package core
5365 * @category navigation
5366 * @copyright 2009 Sam Hemelryk
5367 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5369 class navigation_cache {
5370 /** @var int represents the time created */
5371 protected $creation;
5372 /** @var array An array of session keys */
5373 protected $session;
5375 * The string to use to segregate this particular cache. It can either be
5376 * unique to start a fresh cache or if you want to share a cache then make
5377 * it the string used in the original cache.
5378 * @var string
5380 protected $area;
5381 /** @var int a time that the information will time out */
5382 protected $timeout;
5383 /** @var stdClass The current context */
5384 protected $currentcontext;
5385 /** @var int cache time information */
5386 const CACHETIME = 0;
5387 /** @var int cache user id */
5388 const CACHEUSERID = 1;
5389 /** @var int cache value */
5390 const CACHEVALUE = 2;
5391 /** @var null|array An array of navigation cache areas to expire on shutdown */
5392 public static $volatilecaches;
5395 * Contructor for the cache. Requires two arguments
5397 * @param string $area The string to use to segregate this particular cache
5398 * it can either be unique to start a fresh cache or if you want
5399 * to share a cache then make it the string used in the original
5400 * cache
5401 * @param int $timeout The number of seconds to time the information out after
5403 public function __construct($area, $timeout=1800) {
5404 $this->creation = time();
5405 $this->area = $area;
5406 $this->timeout = time() - $timeout;
5407 if (rand(0,100) === 0) {
5408 $this->garbage_collection();
5413 * Used to set up the cache within the SESSION.
5415 * This is called for each access and ensure that we don't put anything into the session before
5416 * it is required.
5418 protected function ensure_session_cache_initialised() {
5419 global $SESSION;
5420 if (empty($this->session)) {
5421 if (!isset($SESSION->navcache)) {
5422 $SESSION->navcache = new stdClass;
5424 if (!isset($SESSION->navcache->{$this->area})) {
5425 $SESSION->navcache->{$this->area} = array();
5427 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5432 * Magic Method to retrieve something by simply calling using = cache->key
5434 * @param mixed $key The identifier for the information you want out again
5435 * @return void|mixed Either void or what ever was put in
5437 public function __get($key) {
5438 if (!$this->cached($key)) {
5439 return;
5441 $information = $this->session[$key][self::CACHEVALUE];
5442 return unserialize($information);
5446 * Magic method that simply uses {@link set();} to store something in the cache
5448 * @param string|int $key
5449 * @param mixed $information
5451 public function __set($key, $information) {
5452 $this->set($key, $information);
5456 * Sets some information against the cache (session) for later retrieval
5458 * @param string|int $key
5459 * @param mixed $information
5461 public function set($key, $information) {
5462 global $USER;
5463 $this->ensure_session_cache_initialised();
5464 $information = serialize($information);
5465 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5468 * Check the existence of the identifier in the cache
5470 * @param string|int $key
5471 * @return bool
5473 public function cached($key) {
5474 global $USER;
5475 $this->ensure_session_cache_initialised();
5476 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) {
5477 return false;
5479 return true;
5482 * Compare something to it's equivilant in the cache
5484 * @param string $key
5485 * @param mixed $value
5486 * @param bool $serialise Whether to serialise the value before comparison
5487 * this should only be set to false if the value is already
5488 * serialised
5489 * @return bool If the value is the same false if it is not set or doesn't match
5491 public function compare($key, $value, $serialise = true) {
5492 if ($this->cached($key)) {
5493 if ($serialise) {
5494 $value = serialize($value);
5496 if ($this->session[$key][self::CACHEVALUE] === $value) {
5497 return true;
5500 return false;
5503 * Wipes the entire cache, good to force regeneration
5505 public function clear() {
5506 global $SESSION;
5507 unset($SESSION->navcache);
5508 $this->session = null;
5511 * Checks all cache entries and removes any that have expired, good ole cleanup
5513 protected function garbage_collection() {
5514 if (empty($this->session)) {
5515 return true;
5517 foreach ($this->session as $key=>$cachedinfo) {
5518 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5519 unset($this->session[$key]);
5525 * Marks the cache as being volatile (likely to change)
5527 * Any caches marked as volatile will be destroyed at the on shutdown by
5528 * {@link navigation_node::destroy_volatile_caches()} which is registered
5529 * as a shutdown function if any caches are marked as volatile.
5531 * @param bool $setting True to destroy the cache false not too
5533 public function volatile($setting = true) {
5534 if (self::$volatilecaches===null) {
5535 self::$volatilecaches = array();
5536 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5539 if ($setting) {
5540 self::$volatilecaches[$this->area] = $this->area;
5541 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5542 unset(self::$volatilecaches[$this->area]);
5547 * Destroys all caches marked as volatile
5549 * This function is static and works in conjunction with the static volatilecaches
5550 * property of navigation cache.
5551 * Because this function is static it manually resets the cached areas back to an
5552 * empty array.
5554 public static function destroy_volatile_caches() {
5555 global $SESSION;
5556 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5557 foreach (self::$volatilecaches as $area) {
5558 $SESSION->navcache->{$area} = array();
5560 } else {
5561 $SESSION->navcache = new stdClass;