Merge branch 'MDL-62181-33-enfix' of git://github.com/mudrd8mz/moodle into MOODLE_33_...
[moodle.git] / lib / navigationlib.php
blob345e0120e4a4aba40b1abb51f9676d4d1c2bbe07
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the navigation structures within Moodle.
20 * @since Moodle 2.0
21 * @package core
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
34 /**
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
43 * @package core
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF = 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH = 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN = null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY = 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
77 /** @var int Setting node type, used only within settings nav 80 */
78 const TYPE_USER = 80;
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
136 /** @var array */
137 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting',71=>'siteadmin', 80=>'user');
138 /** @var moodle_url */
139 protected static $fullmeurl = null;
140 /** @var bool toogles auto matching of active node */
141 public static $autofindactive = true;
142 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
143 protected static $loadadmintree = false;
144 /** @var mixed If set to an int, that section will be included even if it has no activities */
145 public $includesectionnum = false;
146 /** @var bool does the node need to be loaded via ajax */
147 public $requiresajaxloading = false;
148 /** @var bool If set to true this node will be added to the "flat" navigation */
149 public $showinflatnavigation = false;
152 * Constructs a new navigation_node
154 * @param array|string $properties Either an array of properties or a string to use
155 * as the text for the node
157 public function __construct($properties) {
158 if (is_array($properties)) {
159 // Check the array for each property that we allow to set at construction.
160 // text - The main content for the node
161 // shorttext - A short text if required for the node
162 // icon - The icon to display for the node
163 // type - The type of the node
164 // key - The key to use to identify the node
165 // parent - A reference to the nodes parent
166 // action - The action to attribute to this node, usually a URL to link to
167 if (array_key_exists('text', $properties)) {
168 $this->text = $properties['text'];
170 if (array_key_exists('shorttext', $properties)) {
171 $this->shorttext = $properties['shorttext'];
173 if (!array_key_exists('icon', $properties)) {
174 $properties['icon'] = new pix_icon('i/navigationitem', '');
176 $this->icon = $properties['icon'];
177 if ($this->icon instanceof pix_icon) {
178 if (empty($this->icon->attributes['class'])) {
179 $this->icon->attributes['class'] = 'navicon';
180 } else {
181 $this->icon->attributes['class'] .= ' navicon';
184 if (array_key_exists('type', $properties)) {
185 $this->type = $properties['type'];
186 } else {
187 $this->type = self::TYPE_CUSTOM;
189 if (array_key_exists('key', $properties)) {
190 $this->key = $properties['key'];
192 // This needs to happen last because of the check_if_active call that occurs
193 if (array_key_exists('action', $properties)) {
194 $this->action = $properties['action'];
195 if (is_string($this->action)) {
196 $this->action = new moodle_url($this->action);
198 if (self::$autofindactive) {
199 $this->check_if_active();
202 if (array_key_exists('parent', $properties)) {
203 $this->set_parent($properties['parent']);
205 } else if (is_string($properties)) {
206 $this->text = $properties;
208 if ($this->text === null) {
209 throw new coding_exception('You must set the text for the node when you create it.');
211 // Instantiate a new navigation node collection for this nodes children
212 $this->children = new navigation_node_collection();
216 * Checks if this node is the active node.
218 * This is determined by comparing the action for the node against the
219 * defined URL for the page. A match will see this node marked as active.
221 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
222 * @return bool
224 public function check_if_active($strength=URL_MATCH_EXACT) {
225 global $FULLME, $PAGE;
226 // Set fullmeurl if it hasn't already been set
227 if (self::$fullmeurl == null) {
228 if ($PAGE->has_set_url()) {
229 self::override_active_url(new moodle_url($PAGE->url));
230 } else {
231 self::override_active_url(new moodle_url($FULLME));
235 // Compare the action of this node against the fullmeurl
236 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
237 $this->make_active();
238 return true;
240 return false;
244 * True if this nav node has siblings in the tree.
246 * @return bool
248 public function has_siblings() {
249 if (empty($this->parent) || empty($this->parent->children)) {
250 return false;
252 if ($this->parent->children instanceof navigation_node_collection) {
253 $count = $this->parent->children->count();
254 } else {
255 $count = count($this->parent->children);
257 return ($count > 1);
261 * Get a list of sibling navigation nodes at the same level as this one.
263 * @return bool|array of navigation_node
265 public function get_siblings() {
266 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
267 // the in-page links or the breadcrumb links.
268 $siblings = false;
270 if ($this->has_siblings()) {
271 $siblings = [];
272 foreach ($this->parent->children as $child) {
273 if ($child->display) {
274 $siblings[] = $child;
278 return $siblings;
282 * This sets the URL that the URL of new nodes get compared to when locating
283 * the active node.
285 * The active node is the node that matches the URL set here. By default this
286 * is either $PAGE->url or if that hasn't been set $FULLME.
288 * @param moodle_url $url The url to use for the fullmeurl.
289 * @param bool $loadadmintree use true if the URL point to administration tree
291 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
292 // Clone the URL, in case the calling script changes their URL later.
293 self::$fullmeurl = new moodle_url($url);
294 // True means we do not want AJAX loaded admin tree, required for all admin pages.
295 if ($loadadmintree) {
296 // Do not change back to false if already set.
297 self::$loadadmintree = true;
302 * Use when page is linked from the admin tree,
303 * if not used navigation could not find the page using current URL
304 * because the tree is not fully loaded.
306 public static function require_admin_tree() {
307 self::$loadadmintree = true;
311 * Creates a navigation node, ready to add it as a child using add_node
312 * function. (The created node needs to be added before you can use it.)
313 * @param string $text
314 * @param moodle_url|action_link $action
315 * @param int $type
316 * @param string $shorttext
317 * @param string|int $key
318 * @param pix_icon $icon
319 * @return navigation_node
321 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
322 $shorttext=null, $key=null, pix_icon $icon=null) {
323 // Properties array used when creating the new navigation node
324 $itemarray = array(
325 'text' => $text,
326 'type' => $type
328 // Set the action if one was provided
329 if ($action!==null) {
330 $itemarray['action'] = $action;
332 // Set the shorttext if one was provided
333 if ($shorttext!==null) {
334 $itemarray['shorttext'] = $shorttext;
336 // Set the icon if one was provided
337 if ($icon!==null) {
338 $itemarray['icon'] = $icon;
340 // Set the key
341 $itemarray['key'] = $key;
342 // Construct and return
343 return new navigation_node($itemarray);
347 * Adds a navigation node as a child of this node.
349 * @param string $text
350 * @param moodle_url|action_link $action
351 * @param int $type
352 * @param string $shorttext
353 * @param string|int $key
354 * @param pix_icon $icon
355 * @return navigation_node
357 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
358 // Create child node
359 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
361 // Add the child to end and return
362 return $this->add_node($childnode);
366 * Adds a navigation node as a child of this one, given a $node object
367 * created using the create function.
368 * @param navigation_node $childnode Node to add
369 * @param string $beforekey
370 * @return navigation_node The added node
372 public function add_node(navigation_node $childnode, $beforekey=null) {
373 // First convert the nodetype for this node to a branch as it will now have children
374 if ($this->nodetype !== self::NODETYPE_BRANCH) {
375 $this->nodetype = self::NODETYPE_BRANCH;
377 // Set the parent to this node
378 $childnode->set_parent($this);
380 // Default the key to the number of children if not provided
381 if ($childnode->key === null) {
382 $childnode->key = $this->children->count();
385 // Add the child using the navigation_node_collections add method
386 $node = $this->children->add($childnode, $beforekey);
388 // If added node is a category node or the user is logged in and it's a course
389 // then mark added node as a branch (makes it expandable by AJAX)
390 $type = $childnode->type;
391 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
392 ($type === self::TYPE_SITE_ADMIN)) {
393 $node->nodetype = self::NODETYPE_BRANCH;
395 // If this node is hidden mark it's children as hidden also
396 if ($this->hidden) {
397 $node->hidden = true;
399 // Return added node (reference returned by $this->children->add()
400 return $node;
404 * Return a list of all the keys of all the child nodes.
405 * @return array the keys.
407 public function get_children_key_list() {
408 return $this->children->get_key_list();
412 * Searches for a node of the given type with the given key.
414 * This searches this node plus all of its children, and their children....
415 * If you know the node you are looking for is a child of this node then please
416 * use the get method instead.
418 * @param int|string $key The key of the node we are looking for
419 * @param int $type One of navigation_node::TYPE_*
420 * @return navigation_node|false
422 public function find($key, $type) {
423 return $this->children->find($key, $type);
427 * Walk the tree building up a list of all the flat navigation nodes.
429 * @param flat_navigation $nodes List of the found flat navigation nodes.
430 * @param boolean $showdivider Show a divider before the first node.
432 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false) {
433 if ($this->showinflatnavigation) {
434 $indent = 0;
435 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
436 $indent = 1;
438 $flat = new flat_navigation_node($this, $indent);
439 $flat->set_showdivider($showdivider);
440 $nodes->add($flat);
442 foreach ($this->children as $child) {
443 $child->build_flat_navigation_list($nodes, false);
448 * Get the child of this node that has the given key + (optional) type.
450 * If you are looking for a node and want to search all children + their children
451 * then please use the find method instead.
453 * @param int|string $key The key of the node we are looking for
454 * @param int $type One of navigation_node::TYPE_*
455 * @return navigation_node|false
457 public function get($key, $type=null) {
458 return $this->children->get($key, $type);
462 * Removes this node.
464 * @return bool
466 public function remove() {
467 return $this->parent->children->remove($this->key, $this->type);
471 * Checks if this node has or could have any children
473 * @return bool Returns true if it has children or could have (by AJAX expansion)
475 public function has_children() {
476 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
480 * Marks this node as active and forces it open.
482 * Important: If you are here because you need to mark a node active to get
483 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
484 * You can use it to specify a different URL to match the active navigation node on
485 * rather than having to locate and manually mark a node active.
487 public function make_active() {
488 $this->isactive = true;
489 $this->add_class('active_tree_node');
490 $this->force_open();
491 if ($this->parent !== null) {
492 $this->parent->make_inactive();
497 * Marks a node as inactive and recusised back to the base of the tree
498 * doing the same to all parents.
500 public function make_inactive() {
501 $this->isactive = false;
502 $this->remove_class('active_tree_node');
503 if ($this->parent !== null) {
504 $this->parent->make_inactive();
509 * Forces this node to be open and at the same time forces open all
510 * parents until the root node.
512 * Recursive.
514 public function force_open() {
515 $this->forceopen = true;
516 if ($this->parent !== null) {
517 $this->parent->force_open();
522 * Adds a CSS class to this node.
524 * @param string $class
525 * @return bool
527 public function add_class($class) {
528 if (!in_array($class, $this->classes)) {
529 $this->classes[] = $class;
531 return true;
535 * Removes a CSS class from this node.
537 * @param string $class
538 * @return bool True if the class was successfully removed.
540 public function remove_class($class) {
541 if (in_array($class, $this->classes)) {
542 $key = array_search($class,$this->classes);
543 if ($key!==false) {
544 unset($this->classes[$key]);
545 return true;
548 return false;
552 * Sets the title for this node and forces Moodle to utilise it.
553 * @param string $title
555 public function title($title) {
556 $this->title = $title;
557 $this->forcetitle = true;
561 * Resets the page specific information on this node if it is being unserialised.
563 public function __wakeup(){
564 $this->forceopen = false;
565 $this->isactive = false;
566 $this->remove_class('active_tree_node');
570 * Checks if this node or any of its children contain the active node.
572 * Recursive.
574 * @return bool
576 public function contains_active_node() {
577 if ($this->isactive) {
578 return true;
579 } else {
580 foreach ($this->children as $child) {
581 if ($child->isactive || $child->contains_active_node()) {
582 return true;
586 return false;
590 * To better balance the admin tree, we want to group all the short top branches together.
592 * This means < 8 nodes and no subtrees.
594 * @return bool
596 public function is_short_branch() {
597 $limit = 8;
598 if ($this->children->count() >= $limit) {
599 return false;
601 foreach ($this->children as $child) {
602 if ($child->has_children()) {
603 return false;
606 return true;
610 * Finds the active node.
612 * Searches this nodes children plus all of the children for the active node
613 * and returns it if found.
615 * Recursive.
617 * @return navigation_node|false
619 public function find_active_node() {
620 if ($this->isactive) {
621 return $this;
622 } else {
623 foreach ($this->children as &$child) {
624 $outcome = $child->find_active_node();
625 if ($outcome !== false) {
626 return $outcome;
630 return false;
634 * Searches all children for the best matching active node
635 * @return navigation_node|false
637 public function search_for_active_node() {
638 if ($this->check_if_active(URL_MATCH_BASE)) {
639 return $this;
640 } else {
641 foreach ($this->children as &$child) {
642 $outcome = $child->search_for_active_node();
643 if ($outcome !== false) {
644 return $outcome;
648 return false;
652 * Gets the content for this node.
654 * @param bool $shorttext If true shorttext is used rather than the normal text
655 * @return string
657 public function get_content($shorttext=false) {
658 if ($shorttext && $this->shorttext!==null) {
659 return format_string($this->shorttext);
660 } else {
661 return format_string($this->text);
666 * Gets the title to use for this node.
668 * @return string
670 public function get_title() {
671 if ($this->forcetitle || $this->action != null){
672 return $this->title;
673 } else {
674 return '';
679 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
681 * @return boolean
683 public function has_action() {
684 return !empty($this->action);
688 * Gets the CSS class to add to this node to describe its type
690 * @return string
692 public function get_css_type() {
693 if (array_key_exists($this->type, $this->namedtypes)) {
694 return 'type_'.$this->namedtypes[$this->type];
696 return 'type_unknown';
700 * Finds all nodes that are expandable by AJAX
702 * @param array $expandable An array by reference to populate with expandable nodes.
704 public function find_expandable(array &$expandable) {
705 foreach ($this->children as &$child) {
706 if ($child->display && $child->has_children() && $child->children->count() == 0) {
707 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
708 $this->add_class('canexpand');
709 $child->requiresajaxloading = true;
710 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
712 $child->find_expandable($expandable);
717 * Finds all nodes of a given type (recursive)
719 * @param int $type One of navigation_node::TYPE_*
720 * @return array
722 public function find_all_of_type($type) {
723 $nodes = $this->children->type($type);
724 foreach ($this->children as &$node) {
725 $childnodes = $node->find_all_of_type($type);
726 $nodes = array_merge($nodes, $childnodes);
728 return $nodes;
732 * Removes this node if it is empty
734 public function trim_if_empty() {
735 if ($this->children->count() == 0) {
736 $this->remove();
741 * Creates a tab representation of this nodes children that can be used
742 * with print_tabs to produce the tabs on a page.
744 * call_user_func_array('print_tabs', $node->get_tabs_array());
746 * @param array $inactive
747 * @param bool $return
748 * @return array Array (tabs, selected, inactive, activated, return)
750 public function get_tabs_array(array $inactive=array(), $return=false) {
751 $tabs = array();
752 $rows = array();
753 $selected = null;
754 $activated = array();
755 foreach ($this->children as $node) {
756 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
757 if ($node->contains_active_node()) {
758 if ($node->children->count() > 0) {
759 $activated[] = $node->key;
760 foreach ($node->children as $child) {
761 if ($child->contains_active_node()) {
762 $selected = $child->key;
764 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
766 } else {
767 $selected = $node->key;
771 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
775 * Sets the parent for this node and if this node is active ensures that the tree is properly
776 * adjusted as well.
778 * @param navigation_node $parent
780 public function set_parent(navigation_node $parent) {
781 // Set the parent (thats the easy part)
782 $this->parent = $parent;
783 // Check if this node is active (this is checked during construction)
784 if ($this->isactive) {
785 // Force all of the parent nodes open so you can see this node
786 $this->parent->force_open();
787 // Make all parents inactive so that its clear where we are.
788 $this->parent->make_inactive();
793 * Hides the node and any children it has.
795 * @since Moodle 2.5
796 * @param array $typestohide Optional. An array of node types that should be hidden.
797 * If null all nodes will be hidden.
798 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
799 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
801 public function hide(array $typestohide = null) {
802 if ($typestohide === null || in_array($this->type, $typestohide)) {
803 $this->display = false;
804 if ($this->has_children()) {
805 foreach ($this->children as $child) {
806 $child->hide($typestohide);
813 * Get the action url for this navigation node.
814 * Called from templates.
816 * @since Moodle 3.2
818 public function action() {
819 if ($this->action instanceof moodle_url) {
820 return $this->action;
821 } else if ($this->action instanceof action_link) {
822 return $this->action->url;
824 return $this->action;
829 * Navigation node collection
831 * This class is responsible for managing a collection of navigation nodes.
832 * It is required because a node's unique identifier is a combination of both its
833 * key and its type.
835 * Originally an array was used with a string key that was a combination of the two
836 * however it was decided that a better solution would be to use a class that
837 * implements the standard IteratorAggregate interface.
839 * @package core
840 * @category navigation
841 * @copyright 2010 Sam Hemelryk
842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
844 class navigation_node_collection implements IteratorAggregate {
846 * A multidimensional array to where the first key is the type and the second
847 * key is the nodes key.
848 * @var array
850 protected $collection = array();
852 * An array that contains references to nodes in the same order they were added.
853 * This is maintained as a progressive array.
854 * @var array
856 protected $orderedcollection = array();
858 * A reference to the last node that was added to the collection
859 * @var navigation_node
861 protected $last = null;
863 * The total number of items added to this array.
864 * @var int
866 protected $count = 0;
869 * Adds a navigation node to the collection
871 * @param navigation_node $node Node to add
872 * @param string $beforekey If specified, adds before a node with this key,
873 * otherwise adds at end
874 * @return navigation_node Added node
876 public function add(navigation_node $node, $beforekey=null) {
877 global $CFG;
878 $key = $node->key;
879 $type = $node->type;
881 // First check we have a 2nd dimension for this type
882 if (!array_key_exists($type, $this->orderedcollection)) {
883 $this->orderedcollection[$type] = array();
885 // Check for a collision and report if debugging is turned on
886 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
887 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
890 // Find the key to add before
891 $newindex = $this->count;
892 $last = true;
893 if ($beforekey !== null) {
894 foreach ($this->collection as $index => $othernode) {
895 if ($othernode->key === $beforekey) {
896 $newindex = $index;
897 $last = false;
898 break;
901 if ($newindex === $this->count) {
902 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
903 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
907 // Add the node to the appropriate place in the by-type structure (which
908 // is not ordered, despite the variable name)
909 $this->orderedcollection[$type][$key] = $node;
910 if (!$last) {
911 // Update existing references in the ordered collection (which is the
912 // one that isn't called 'ordered') to shuffle them along if required
913 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
914 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
917 // Add a reference to the node to the progressive collection.
918 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
919 // Update the last property to a reference to this new node.
920 $this->last = $this->orderedcollection[$type][$key];
922 // Reorder the array by index if needed
923 if (!$last) {
924 ksort($this->collection);
926 $this->count++;
927 // Return the reference to the now added node
928 return $node;
932 * Return a list of all the keys of all the nodes.
933 * @return array the keys.
935 public function get_key_list() {
936 $keys = array();
937 foreach ($this->collection as $node) {
938 $keys[] = $node->key;
940 return $keys;
944 * Fetches a node from this collection.
946 * @param string|int $key The key of the node we want to find.
947 * @param int $type One of navigation_node::TYPE_*.
948 * @return navigation_node|null
950 public function get($key, $type=null) {
951 if ($type !== null) {
952 // If the type is known then we can simply check and fetch
953 if (!empty($this->orderedcollection[$type][$key])) {
954 return $this->orderedcollection[$type][$key];
956 } else {
957 // Because we don't know the type we look in the progressive array
958 foreach ($this->collection as $node) {
959 if ($node->key === $key) {
960 return $node;
964 return false;
968 * Searches for a node with matching key and type.
970 * This function searches both the nodes in this collection and all of
971 * the nodes in each collection belonging to the nodes in this collection.
973 * Recursive.
975 * @param string|int $key The key of the node we want to find.
976 * @param int $type One of navigation_node::TYPE_*.
977 * @return navigation_node|null
979 public function find($key, $type=null) {
980 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
981 return $this->orderedcollection[$type][$key];
982 } else {
983 $nodes = $this->getIterator();
984 // Search immediate children first
985 foreach ($nodes as &$node) {
986 if ($node->key === $key && ($type === null || $type === $node->type)) {
987 return $node;
990 // Now search each childs children
991 foreach ($nodes as &$node) {
992 $result = $node->children->find($key, $type);
993 if ($result !== false) {
994 return $result;
998 return false;
1002 * Fetches the last node that was added to this collection
1004 * @return navigation_node
1006 public function last() {
1007 return $this->last;
1011 * Fetches all nodes of a given type from this collection
1013 * @param string|int $type node type being searched for.
1014 * @return array ordered collection
1016 public function type($type) {
1017 if (!array_key_exists($type, $this->orderedcollection)) {
1018 $this->orderedcollection[$type] = array();
1020 return $this->orderedcollection[$type];
1023 * Removes the node with the given key and type from the collection
1025 * @param string|int $key The key of the node we want to find.
1026 * @param int $type
1027 * @return bool
1029 public function remove($key, $type=null) {
1030 $child = $this->get($key, $type);
1031 if ($child !== false) {
1032 foreach ($this->collection as $colkey => $node) {
1033 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
1034 unset($this->collection[$colkey]);
1035 $this->collection = array_values($this->collection);
1036 break;
1039 unset($this->orderedcollection[$child->type][$child->key]);
1040 $this->count--;
1041 return true;
1043 return false;
1047 * Gets the number of nodes in this collection
1049 * This option uses an internal count rather than counting the actual options to avoid
1050 * a performance hit through the count function.
1052 * @return int
1054 public function count() {
1055 return $this->count;
1058 * Gets an array iterator for the collection.
1060 * This is required by the IteratorAggregator interface and is used by routines
1061 * such as the foreach loop.
1063 * @return ArrayIterator
1065 public function getIterator() {
1066 return new ArrayIterator($this->collection);
1071 * The global navigation class used for... the global navigation
1073 * This class is used by PAGE to store the global navigation for the site
1074 * and is then used by the settings nav and navbar to save on processing and DB calls
1076 * See
1077 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1078 * {@link lib/ajax/getnavbranch.php} Called by ajax
1080 * @package core
1081 * @category navigation
1082 * @copyright 2009 Sam Hemelryk
1083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1085 class global_navigation extends navigation_node {
1086 /** @var moodle_page The Moodle page this navigation object belongs to. */
1087 protected $page;
1088 /** @var bool switch to let us know if the navigation object is initialised*/
1089 protected $initialised = false;
1090 /** @var array An array of course information */
1091 protected $mycourses = array();
1092 /** @var navigation_node[] An array for containing root navigation nodes */
1093 protected $rootnodes = array();
1094 /** @var bool A switch for whether to show empty sections in the navigation */
1095 protected $showemptysections = true;
1096 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1097 protected $showcategories = null;
1098 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1099 protected $showmycategories = null;
1100 /** @var array An array of stdClasses for users that the navigation is extended for */
1101 protected $extendforuser = array();
1102 /** @var navigation_cache */
1103 protected $cache;
1104 /** @var array An array of course ids that are present in the navigation */
1105 protected $addedcourses = array();
1106 /** @var bool */
1107 protected $allcategoriesloaded = false;
1108 /** @var array An array of category ids that are included in the navigation */
1109 protected $addedcategories = array();
1110 /** @var int expansion limit */
1111 protected $expansionlimit = 0;
1112 /** @var int userid to allow parent to see child's profile page navigation */
1113 protected $useridtouseforparentchecks = 0;
1114 /** @var cache_session A cache that stores information on expanded courses */
1115 protected $cacheexpandcourse = null;
1117 /** Used when loading categories to load all top level categories [parent = 0] **/
1118 const LOAD_ROOT_CATEGORIES = 0;
1119 /** Used when loading categories to load all categories **/
1120 const LOAD_ALL_CATEGORIES = -1;
1123 * Constructs a new global navigation
1125 * @param moodle_page $page The page this navigation object belongs to
1127 public function __construct(moodle_page $page) {
1128 global $CFG, $SITE, $USER;
1130 if (during_initial_install()) {
1131 return;
1134 if (get_home_page() == HOMEPAGE_SITE) {
1135 // We are using the site home for the root element
1136 $properties = array(
1137 'key' => 'home',
1138 'type' => navigation_node::TYPE_SYSTEM,
1139 'text' => get_string('home'),
1140 'action' => new moodle_url('/')
1142 } else {
1143 // We are using the users my moodle for the root element
1144 $properties = array(
1145 'key' => 'myhome',
1146 'type' => navigation_node::TYPE_SYSTEM,
1147 'text' => get_string('myhome'),
1148 'action' => new moodle_url('/my/')
1152 // Use the parents constructor.... good good reuse
1153 parent::__construct($properties);
1154 $this->showinflatnavigation = true;
1156 // Initalise and set defaults
1157 $this->page = $page;
1158 $this->forceopen = true;
1159 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1163 * Mutator to set userid to allow parent to see child's profile
1164 * page navigation. See MDL-25805 for initial issue. Linked to it
1165 * is an issue explaining why this is a REALLY UGLY HACK thats not
1166 * for you to use!
1168 * @param int $userid userid of profile page that parent wants to navigate around.
1170 public function set_userid_for_parent_checks($userid) {
1171 $this->useridtouseforparentchecks = $userid;
1176 * Initialises the navigation object.
1178 * This causes the navigation object to look at the current state of the page
1179 * that it is associated with and then load the appropriate content.
1181 * This should only occur the first time that the navigation structure is utilised
1182 * which will normally be either when the navbar is called to be displayed or
1183 * when a block makes use of it.
1185 * @return bool
1187 public function initialise() {
1188 global $CFG, $SITE, $USER;
1189 // Check if it has already been initialised
1190 if ($this->initialised || during_initial_install()) {
1191 return true;
1193 $this->initialised = true;
1195 // Set up the five base root nodes. These are nodes where we will put our
1196 // content and are as follows:
1197 // site: Navigation for the front page.
1198 // myprofile: User profile information goes here.
1199 // currentcourse: The course being currently viewed.
1200 // mycourses: The users courses get added here.
1201 // courses: Additional courses are added here.
1202 // users: Other users information loaded here.
1203 $this->rootnodes = array();
1204 if (get_home_page() == HOMEPAGE_SITE) {
1205 // The home element should be my moodle because the root element is the site
1206 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1207 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1208 $this->rootnodes['home']->showinflatnavigation = true;
1210 } else {
1211 // The home element should be the site because the root node is my moodle
1212 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1213 $this->rootnodes['home']->showinflatnavigation = true;
1214 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1215 // We need to stop automatic redirection
1216 $this->rootnodes['home']->action->param('redirect', '0');
1219 $this->rootnodes['site'] = $this->add_course($SITE);
1220 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1221 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1222 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1223 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1224 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1226 // We always load the frontpage course to ensure it is available without
1227 // JavaScript enabled.
1228 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1229 $this->load_course_sections($SITE, $this->rootnodes['site']);
1231 $course = $this->page->course;
1232 $this->load_courses_enrolled();
1234 // $issite gets set to true if the current pages course is the sites frontpage course
1235 $issite = ($this->page->course->id == $SITE->id);
1237 // Determine if the user is enrolled in any course.
1238 $enrolledinanycourse = enrol_user_sees_own_courses();
1240 $this->rootnodes['currentcourse']->mainnavonly = true;
1241 if ($enrolledinanycourse) {
1242 $this->rootnodes['mycourses']->isexpandable = true;
1243 $this->rootnodes['mycourses']->showinflatnavigation = true;
1244 if ($CFG->navshowallcourses) {
1245 // When we show all courses we need to show both the my courses and the regular courses branch.
1246 $this->rootnodes['courses']->isexpandable = true;
1248 } else {
1249 $this->rootnodes['courses']->isexpandable = true;
1251 $this->rootnodes['mycourses']->forceopen = true;
1253 $canviewcourseprofile = true;
1255 // Next load context specific content into the navigation
1256 switch ($this->page->context->contextlevel) {
1257 case CONTEXT_SYSTEM :
1258 // Nothing left to do here I feel.
1259 break;
1260 case CONTEXT_COURSECAT :
1261 // This is essential, we must load categories.
1262 $this->load_all_categories($this->page->context->instanceid, true);
1263 break;
1264 case CONTEXT_BLOCK :
1265 case CONTEXT_COURSE :
1266 if ($issite) {
1267 // Nothing left to do here.
1268 break;
1271 // Load the course associated with the current page into the navigation.
1272 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1273 // If the course wasn't added then don't try going any further.
1274 if (!$coursenode) {
1275 $canviewcourseprofile = false;
1276 break;
1279 // If the user is not enrolled then we only want to show the
1280 // course node and not populate it.
1282 // Not enrolled, can't view, and hasn't switched roles
1283 if (!can_access_course($course, null, '', true)) {
1284 if ($coursenode->isexpandable === true) {
1285 // Obviously the situation has changed, update the cache and adjust the node.
1286 // This occurs if the user access to a course has been revoked (one way or another) after
1287 // initially logging in for this session.
1288 $this->get_expand_course_cache()->set($course->id, 1);
1289 $coursenode->isexpandable = true;
1290 $coursenode->nodetype = self::NODETYPE_BRANCH;
1292 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1293 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1294 if (!$this->current_user_is_parent_role()) {
1295 $coursenode->make_active();
1296 $canviewcourseprofile = false;
1297 break;
1299 } else if ($coursenode->isexpandable === false) {
1300 // Obviously the situation has changed, update the cache and adjust the node.
1301 // This occurs if the user has been granted access to a course (one way or another) after initially
1302 // logging in for this session.
1303 $this->get_expand_course_cache()->set($course->id, 1);
1304 $coursenode->isexpandable = true;
1305 $coursenode->nodetype = self::NODETYPE_BRANCH;
1308 // Add the essentials such as reports etc...
1309 $this->add_course_essentials($coursenode, $course);
1310 // Extend course navigation with it's sections/activities
1311 $this->load_course_sections($course, $coursenode);
1312 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1313 $coursenode->make_active();
1316 break;
1317 case CONTEXT_MODULE :
1318 if ($issite) {
1319 // If this is the site course then most information will have
1320 // already been loaded.
1321 // However we need to check if there is more content that can
1322 // yet be loaded for the specific module instance.
1323 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1324 if ($activitynode) {
1325 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1327 break;
1330 $course = $this->page->course;
1331 $cm = $this->page->cm;
1333 // Load the course associated with the page into the navigation
1334 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1336 // If the course wasn't added then don't try going any further.
1337 if (!$coursenode) {
1338 $canviewcourseprofile = false;
1339 break;
1342 // If the user is not enrolled then we only want to show the
1343 // course node and not populate it.
1344 if (!can_access_course($course, null, '', true)) {
1345 $coursenode->make_active();
1346 $canviewcourseprofile = false;
1347 break;
1350 $this->add_course_essentials($coursenode, $course);
1352 // Load the course sections into the page
1353 $this->load_course_sections($course, $coursenode, null, $cm);
1354 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1355 if (!empty($activity)) {
1356 // Finally load the cm specific navigaton information
1357 $this->load_activity($cm, $course, $activity);
1358 // Check if we have an active ndoe
1359 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1360 // And make the activity node active.
1361 $activity->make_active();
1364 break;
1365 case CONTEXT_USER :
1366 if ($issite) {
1367 // The users profile information etc is already loaded
1368 // for the front page.
1369 break;
1371 $course = $this->page->course;
1372 // Load the course associated with the user into the navigation
1373 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1375 // If the course wasn't added then don't try going any further.
1376 if (!$coursenode) {
1377 $canviewcourseprofile = false;
1378 break;
1381 // If the user is not enrolled then we only want to show the
1382 // course node and not populate it.
1383 if (!can_access_course($course, null, '', true)) {
1384 $coursenode->make_active();
1385 $canviewcourseprofile = false;
1386 break;
1388 $this->add_course_essentials($coursenode, $course);
1389 $this->load_course_sections($course, $coursenode);
1390 break;
1393 // Load for the current user
1394 $this->load_for_user();
1395 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1396 $this->load_for_user(null, true);
1398 // Load each extending user into the navigation.
1399 foreach ($this->extendforuser as $user) {
1400 if ($user->id != $USER->id) {
1401 $this->load_for_user($user);
1405 // Give the local plugins a chance to include some navigation if they want.
1406 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1407 $function($this);
1410 // Remove any empty root nodes
1411 foreach ($this->rootnodes as $node) {
1412 // Dont remove the home node
1413 /** @var navigation_node $node */
1414 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1415 $node->remove();
1419 if (!$this->contains_active_node()) {
1420 $this->search_for_active_node();
1423 // If the user is not logged in modify the navigation structure as detailed
1424 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1425 if (!isloggedin()) {
1426 $activities = clone($this->rootnodes['site']->children);
1427 $this->rootnodes['site']->remove();
1428 $children = clone($this->children);
1429 $this->children = new navigation_node_collection();
1430 foreach ($activities as $child) {
1431 $this->children->add($child);
1433 foreach ($children as $child) {
1434 $this->children->add($child);
1437 return true;
1441 * Returns true if the current user is a parent of the user being currently viewed.
1443 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1444 * other user being viewed this function returns false.
1445 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1447 * @since Moodle 2.4
1448 * @return bool
1450 protected function current_user_is_parent_role() {
1451 global $USER, $DB;
1452 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1453 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1454 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1455 return false;
1457 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1458 return true;
1461 return false;
1465 * Returns true if courses should be shown within categories on the navigation.
1467 * @param bool $ismycourse Set to true if you are calculating this for a course.
1468 * @return bool
1470 protected function show_categories($ismycourse = false) {
1471 global $CFG, $DB;
1472 if ($ismycourse) {
1473 return $this->show_my_categories();
1475 if ($this->showcategories === null) {
1476 $show = false;
1477 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1478 $show = true;
1479 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1480 $show = true;
1482 $this->showcategories = $show;
1484 return $this->showcategories;
1488 * Returns true if we should show categories in the My Courses branch.
1489 * @return bool
1491 protected function show_my_categories() {
1492 global $CFG;
1493 if ($this->showmycategories === null) {
1494 require_once('coursecatlib.php');
1495 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && coursecat::count_all() > 1;
1497 return $this->showmycategories;
1501 * Loads the courses in Moodle into the navigation.
1503 * @global moodle_database $DB
1504 * @param string|array $categoryids An array containing categories to load courses
1505 * for, OR null to load courses for all categories.
1506 * @return array An array of navigation_nodes one for each course
1508 protected function load_all_courses($categoryids = null) {
1509 global $CFG, $DB, $SITE;
1511 // Work out the limit of courses.
1512 $limit = 20;
1513 if (!empty($CFG->navcourselimit)) {
1514 $limit = $CFG->navcourselimit;
1517 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1519 // If we are going to show all courses AND we are showing categories then
1520 // to save us repeated DB calls load all of the categories now
1521 if ($this->show_categories()) {
1522 $this->load_all_categories($toload);
1525 // Will be the return of our efforts
1526 $coursenodes = array();
1528 // Check if we need to show categories.
1529 if ($this->show_categories()) {
1530 // Hmmm we need to show categories... this is going to be painful.
1531 // We now need to fetch up to $limit courses for each category to
1532 // be displayed.
1533 if ($categoryids !== null) {
1534 if (!is_array($categoryids)) {
1535 $categoryids = array($categoryids);
1537 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1538 $categorywhere = 'WHERE cc.id '.$categorywhere;
1539 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1540 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1541 $categoryparams = array();
1542 } else {
1543 $categorywhere = '';
1544 $categoryparams = array();
1547 // First up we are going to get the categories that we are going to
1548 // need so that we can determine how best to load the courses from them.
1549 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1550 FROM {course_categories} cc
1551 LEFT JOIN {course} c ON c.category = cc.id
1552 {$categorywhere}
1553 GROUP BY cc.id";
1554 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1555 $fullfetch = array();
1556 $partfetch = array();
1557 foreach ($categories as $category) {
1558 if (!$this->can_add_more_courses_to_category($category->id)) {
1559 continue;
1561 if ($category->coursecount > $limit * 5) {
1562 $partfetch[] = $category->id;
1563 } else if ($category->coursecount > 0) {
1564 $fullfetch[] = $category->id;
1567 $categories->close();
1569 if (count($fullfetch)) {
1570 // First up fetch all of the courses in categories where we know that we are going to
1571 // need the majority of courses.
1572 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1573 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1574 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1575 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1576 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1577 FROM {course} c
1578 $ccjoin
1579 WHERE c.category {$categoryids}
1580 ORDER BY c.sortorder ASC";
1581 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1582 foreach ($coursesrs as $course) {
1583 if ($course->id == $SITE->id) {
1584 // This should not be necessary, frontpage is not in any category.
1585 continue;
1587 if (array_key_exists($course->id, $this->addedcourses)) {
1588 // It is probably better to not include the already loaded courses
1589 // directly in SQL because inequalities may confuse query optimisers
1590 // and may interfere with query caching.
1591 continue;
1593 if (!$this->can_add_more_courses_to_category($course->category)) {
1594 continue;
1596 context_helper::preload_from_record($course);
1597 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1598 continue;
1600 $coursenodes[$course->id] = $this->add_course($course);
1602 $coursesrs->close();
1605 if (count($partfetch)) {
1606 // Next we will work our way through the categories where we will likely only need a small
1607 // proportion of the courses.
1608 foreach ($partfetch as $categoryid) {
1609 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1610 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1611 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1612 FROM {course} c
1613 $ccjoin
1614 WHERE c.category = :categoryid
1615 ORDER BY c.sortorder ASC";
1616 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1617 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1618 foreach ($coursesrs as $course) {
1619 if ($course->id == $SITE->id) {
1620 // This should not be necessary, frontpage is not in any category.
1621 continue;
1623 if (array_key_exists($course->id, $this->addedcourses)) {
1624 // It is probably better to not include the already loaded courses
1625 // directly in SQL because inequalities may confuse query optimisers
1626 // and may interfere with query caching.
1627 // This also helps to respect expected $limit on repeated executions.
1628 continue;
1630 if (!$this->can_add_more_courses_to_category($course->category)) {
1631 break;
1633 context_helper::preload_from_record($course);
1634 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1635 continue;
1637 $coursenodes[$course->id] = $this->add_course($course);
1639 $coursesrs->close();
1642 } else {
1643 // Prepare the SQL to load the courses and their contexts
1644 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1645 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1646 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1647 $courseparams['contextlevel'] = CONTEXT_COURSE;
1648 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1649 FROM {course} c
1650 $ccjoin
1651 WHERE c.id {$courseids}
1652 ORDER BY c.sortorder ASC";
1653 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1654 foreach ($coursesrs as $course) {
1655 if ($course->id == $SITE->id) {
1656 // frotpage is not wanted here
1657 continue;
1659 if ($this->page->course && ($this->page->course->id == $course->id)) {
1660 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1661 continue;
1663 context_helper::preload_from_record($course);
1664 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1665 continue;
1667 $coursenodes[$course->id] = $this->add_course($course);
1668 if (count($coursenodes) >= $limit) {
1669 break;
1672 $coursesrs->close();
1675 return $coursenodes;
1679 * Returns true if more courses can be added to the provided category.
1681 * @param int|navigation_node|stdClass $category
1682 * @return bool
1684 protected function can_add_more_courses_to_category($category) {
1685 global $CFG;
1686 $limit = 20;
1687 if (!empty($CFG->navcourselimit)) {
1688 $limit = (int)$CFG->navcourselimit;
1690 if (is_numeric($category)) {
1691 if (!array_key_exists($category, $this->addedcategories)) {
1692 return true;
1694 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1695 } else if ($category instanceof navigation_node) {
1696 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1697 return false;
1699 $coursecount = count($category->children->type(self::TYPE_COURSE));
1700 } else if (is_object($category) && property_exists($category,'id')) {
1701 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1703 return ($coursecount <= $limit);
1707 * Loads all categories (top level or if an id is specified for that category)
1709 * @param int $categoryid The category id to load or null/0 to load all base level categories
1710 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1711 * as the requested category and any parent categories.
1712 * @return navigation_node|void returns a navigation node if a category has been loaded.
1714 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1715 global $CFG, $DB;
1717 // Check if this category has already been loaded
1718 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1719 return true;
1722 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1723 $sqlselect = "SELECT cc.*, $catcontextsql
1724 FROM {course_categories} cc
1725 JOIN {context} ctx ON cc.id = ctx.instanceid";
1726 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1727 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1728 $params = array();
1730 $categoriestoload = array();
1731 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1732 // We are going to load all categories regardless... prepare to fire
1733 // on the database server!
1734 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1735 // We are going to load all of the first level categories (categories without parents)
1736 $sqlwhere .= " AND cc.parent = 0";
1737 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1738 // The category itself has been loaded already so we just need to ensure its subcategories
1739 // have been loaded
1740 $addedcategories = $this->addedcategories;
1741 unset($addedcategories[$categoryid]);
1742 if (count($addedcategories) > 0) {
1743 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1744 if ($showbasecategories) {
1745 // We need to include categories with parent = 0 as well
1746 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1747 } else {
1748 // All we need is categories that match the parent
1749 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1752 $params['categoryid'] = $categoryid;
1753 } else {
1754 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1755 // and load this category plus all its parents and subcategories
1756 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1757 $categoriestoload = explode('/', trim($category->path, '/'));
1758 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1759 // We are going to use select twice so double the params
1760 $params = array_merge($params, $params);
1761 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1762 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1765 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1766 $categories = array();
1767 foreach ($categoriesrs as $category) {
1768 // Preload the context.. we'll need it when adding the category in order
1769 // to format the category name.
1770 context_helper::preload_from_record($category);
1771 if (array_key_exists($category->id, $this->addedcategories)) {
1772 // Do nothing, its already been added.
1773 } else if ($category->parent == '0') {
1774 // This is a root category lets add it immediately
1775 $this->add_category($category, $this->rootnodes['courses']);
1776 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1777 // This categories parent has already been added we can add this immediately
1778 $this->add_category($category, $this->addedcategories[$category->parent]);
1779 } else {
1780 $categories[] = $category;
1783 $categoriesrs->close();
1785 // Now we have an array of categories we need to add them to the navigation.
1786 while (!empty($categories)) {
1787 $category = reset($categories);
1788 if (array_key_exists($category->id, $this->addedcategories)) {
1789 // Do nothing
1790 } else if ($category->parent == '0') {
1791 $this->add_category($category, $this->rootnodes['courses']);
1792 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1793 $this->add_category($category, $this->addedcategories[$category->parent]);
1794 } else {
1795 // This category isn't in the navigation and niether is it's parent (yet).
1796 // We need to go through the category path and add all of its components in order.
1797 $path = explode('/', trim($category->path, '/'));
1798 foreach ($path as $catid) {
1799 if (!array_key_exists($catid, $this->addedcategories)) {
1800 // This category isn't in the navigation yet so add it.
1801 $subcategory = $categories[$catid];
1802 if ($subcategory->parent == '0') {
1803 // Yay we have a root category - this likely means we will now be able
1804 // to add categories without problems.
1805 $this->add_category($subcategory, $this->rootnodes['courses']);
1806 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1807 // The parent is in the category (as we'd expect) so add it now.
1808 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1809 // Remove the category from the categories array.
1810 unset($categories[$catid]);
1811 } else {
1812 // We should never ever arrive here - if we have then there is a bigger
1813 // problem at hand.
1814 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1819 // Remove the category from the categories array now that we know it has been added.
1820 unset($categories[$category->id]);
1822 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1823 $this->allcategoriesloaded = true;
1825 // Check if there are any categories to load.
1826 if (count($categoriestoload) > 0) {
1827 $readytoloadcourses = array();
1828 foreach ($categoriestoload as $category) {
1829 if ($this->can_add_more_courses_to_category($category)) {
1830 $readytoloadcourses[] = $category;
1833 if (count($readytoloadcourses)) {
1834 $this->load_all_courses($readytoloadcourses);
1838 // Look for all categories which have been loaded
1839 if (!empty($this->addedcategories)) {
1840 $categoryids = array();
1841 foreach ($this->addedcategories as $category) {
1842 if ($this->can_add_more_courses_to_category($category)) {
1843 $categoryids[] = $category->key;
1846 if ($categoryids) {
1847 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1848 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1849 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1850 FROM {course_categories} cc
1851 JOIN {course} c ON c.category = cc.id
1852 WHERE cc.id {$categoriessql}
1853 GROUP BY cc.id
1854 HAVING COUNT(c.id) > :limit";
1855 $excessivecategories = $DB->get_records_sql($sql, $params);
1856 foreach ($categories as &$category) {
1857 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1858 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1859 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1867 * Adds a structured category to the navigation in the correct order/place
1869 * @param stdClass $category category to be added in navigation.
1870 * @param navigation_node $parent parent navigation node
1871 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1872 * @return void.
1874 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1875 if (array_key_exists($category->id, $this->addedcategories)) {
1876 return;
1878 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1879 $context = context_coursecat::instance($category->id);
1880 $categoryname = format_string($category->name, true, array('context' => $context));
1881 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1882 if (empty($category->visible)) {
1883 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1884 $categorynode->hidden = true;
1885 } else {
1886 $categorynode->display = false;
1889 $this->addedcategories[$category->id] = $categorynode;
1893 * Loads the given course into the navigation
1895 * @param stdClass $course
1896 * @return navigation_node
1898 protected function load_course(stdClass $course) {
1899 global $SITE;
1900 if ($course->id == $SITE->id) {
1901 // This is always loaded during initialisation
1902 return $this->rootnodes['site'];
1903 } else if (array_key_exists($course->id, $this->addedcourses)) {
1904 // The course has already been loaded so return a reference
1905 return $this->addedcourses[$course->id];
1906 } else {
1907 // Add the course
1908 return $this->add_course($course);
1913 * Loads all of the courses section into the navigation.
1915 * This function calls method from current course format, see
1916 * {@link format_base::extend_course_navigation()}
1917 * If course module ($cm) is specified but course format failed to create the node,
1918 * the activity node is created anyway.
1920 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1922 * @param stdClass $course Database record for the course
1923 * @param navigation_node $coursenode The course node within the navigation
1924 * @param null|int $sectionnum If specified load the contents of section with this relative number
1925 * @param null|cm_info $cm If specified make sure that activity node is created (either
1926 * in containg section or by calling load_stealth_activity() )
1928 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1929 global $CFG, $SITE;
1930 require_once($CFG->dirroot.'/course/lib.php');
1931 if (isset($cm->sectionnum)) {
1932 $sectionnum = $cm->sectionnum;
1934 if ($sectionnum !== null) {
1935 $this->includesectionnum = $sectionnum;
1937 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1938 if (isset($cm->id)) {
1939 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1940 if (empty($activity)) {
1941 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1947 * Generates an array of sections and an array of activities for the given course.
1949 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1951 * @param stdClass $course
1952 * @return array Array($sections, $activities)
1954 protected function generate_sections_and_activities(stdClass $course) {
1955 global $CFG;
1956 require_once($CFG->dirroot.'/course/lib.php');
1958 $modinfo = get_fast_modinfo($course);
1959 $sections = $modinfo->get_section_info_all();
1961 // For course formats using 'numsections' trim the sections list
1962 $courseformatoptions = course_get_format($course)->get_format_options();
1963 if (isset($courseformatoptions['numsections'])) {
1964 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1967 $activities = array();
1969 foreach ($sections as $key => $section) {
1970 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1971 $sections[$key] = clone($section);
1972 unset($sections[$key]->summary);
1973 $sections[$key]->hasactivites = false;
1974 if (!array_key_exists($section->section, $modinfo->sections)) {
1975 continue;
1977 foreach ($modinfo->sections[$section->section] as $cmid) {
1978 $cm = $modinfo->cms[$cmid];
1979 $activity = new stdClass;
1980 $activity->id = $cm->id;
1981 $activity->course = $course->id;
1982 $activity->section = $section->section;
1983 $activity->name = $cm->name;
1984 $activity->icon = $cm->icon;
1985 $activity->iconcomponent = $cm->iconcomponent;
1986 $activity->hidden = (!$cm->visible);
1987 $activity->modname = $cm->modname;
1988 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1989 $activity->onclick = $cm->onclick;
1990 $url = $cm->url;
1991 if (!$url) {
1992 $activity->url = null;
1993 $activity->display = false;
1994 } else {
1995 $activity->url = $url->out();
1996 $activity->display = $cm->is_visible_on_course_page() ? true : false;
1997 if (self::module_extends_navigation($cm->modname)) {
1998 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
2001 $activities[$cmid] = $activity;
2002 if ($activity->display) {
2003 $sections[$key]->hasactivites = true;
2008 return array($sections, $activities);
2012 * Generically loads the course sections into the course's navigation.
2014 * @param stdClass $course
2015 * @param navigation_node $coursenode
2016 * @return array An array of course section nodes
2018 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
2019 global $CFG, $DB, $USER, $SITE;
2020 require_once($CFG->dirroot.'/course/lib.php');
2022 list($sections, $activities) = $this->generate_sections_and_activities($course);
2024 $navigationsections = array();
2025 foreach ($sections as $sectionid => $section) {
2026 $section = clone($section);
2027 if ($course->id == $SITE->id) {
2028 $this->load_section_activities($coursenode, $section->section, $activities);
2029 } else {
2030 if (!$section->uservisible || (!$this->showemptysections &&
2031 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
2032 continue;
2035 $sectionname = get_section_name($course, $section);
2036 $url = course_get_url($course, $section->section, array('navigation' => true));
2038 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
2039 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
2040 $sectionnode->hidden = (!$section->visible || !$section->available);
2041 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
2042 $this->load_section_activities($sectionnode, $section->section, $activities);
2044 $section->sectionnode = $sectionnode;
2045 $navigationsections[$sectionid] = $section;
2048 return $navigationsections;
2052 * Loads all of the activities for a section into the navigation structure.
2054 * @param navigation_node $sectionnode
2055 * @param int $sectionnumber
2056 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2057 * @param stdClass $course The course object the section and activities relate to.
2058 * @return array Array of activity nodes
2060 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
2061 global $CFG, $SITE;
2062 // A static counter for JS function naming
2063 static $legacyonclickcounter = 0;
2065 $activitynodes = array();
2066 if (empty($activities)) {
2067 return $activitynodes;
2070 if (!is_object($course)) {
2071 $activity = reset($activities);
2072 $courseid = $activity->course;
2073 } else {
2074 $courseid = $course->id;
2076 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
2078 foreach ($activities as $activity) {
2079 if ($activity->section != $sectionnumber) {
2080 continue;
2082 if ($activity->icon) {
2083 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
2084 } else {
2085 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
2088 // Prepare the default name and url for the node
2089 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
2090 $action = new moodle_url($activity->url);
2092 // Check if the onclick property is set (puke!)
2093 if (!empty($activity->onclick)) {
2094 // Increment the counter so that we have a unique number.
2095 $legacyonclickcounter++;
2096 // Generate the function name we will use
2097 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2098 $propogrationhandler = '';
2099 // Check if we need to cancel propogation. Remember inline onclick
2100 // events would return false if they wanted to prevent propogation and the
2101 // default action.
2102 if (strpos($activity->onclick, 'return false')) {
2103 $propogrationhandler = 'e.halt();';
2105 // Decode the onclick - it has already been encoded for display (puke)
2106 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
2107 // Build the JS function the click event will call
2108 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2109 $this->page->requires->js_amd_inline($jscode);
2110 // Override the default url with the new action link
2111 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2114 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
2115 $activitynode->title(get_string('modulename', $activity->modname));
2116 $activitynode->hidden = $activity->hidden;
2117 $activitynode->display = $showactivities && $activity->display;
2118 $activitynode->nodetype = $activity->nodetype;
2119 $activitynodes[$activity->id] = $activitynode;
2122 return $activitynodes;
2125 * Loads a stealth module from unavailable section
2126 * @param navigation_node $coursenode
2127 * @param stdClass $modinfo
2128 * @return navigation_node or null if not accessible
2130 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2131 if (empty($modinfo->cms[$this->page->cm->id])) {
2132 return null;
2134 $cm = $modinfo->cms[$this->page->cm->id];
2135 if ($cm->icon) {
2136 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2137 } else {
2138 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2140 $url = $cm->url;
2141 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2142 $activitynode->title(get_string('modulename', $cm->modname));
2143 $activitynode->hidden = (!$cm->visible);
2144 if (!$cm->is_visible_on_course_page()) {
2145 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2146 // Also there may be no exception at all in case when teacher is logged in as student.
2147 $activitynode->display = false;
2148 } else if (!$url) {
2149 // Don't show activities that don't have links!
2150 $activitynode->display = false;
2151 } else if (self::module_extends_navigation($cm->modname)) {
2152 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2154 return $activitynode;
2157 * Loads the navigation structure for the given activity into the activities node.
2159 * This method utilises a callback within the modules lib.php file to load the
2160 * content specific to activity given.
2162 * The callback is a method: {modulename}_extend_navigation()
2163 * Examples:
2164 * * {@link forum_extend_navigation()}
2165 * * {@link workshop_extend_navigation()}
2167 * @param cm_info|stdClass $cm
2168 * @param stdClass $course
2169 * @param navigation_node $activity
2170 * @return bool
2172 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2173 global $CFG, $DB;
2175 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2176 if (!($cm instanceof cm_info)) {
2177 $modinfo = get_fast_modinfo($course);
2178 $cm = $modinfo->get_cm($cm->id);
2180 $activity->nodetype = navigation_node::NODETYPE_LEAF;
2181 $activity->make_active();
2182 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2183 $function = $cm->modname.'_extend_navigation';
2185 if (file_exists($file)) {
2186 require_once($file);
2187 if (function_exists($function)) {
2188 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2189 $function($activity, $course, $activtyrecord, $cm);
2193 // Allow the active advanced grading method plugin to append module navigation
2194 $featuresfunc = $cm->modname.'_supports';
2195 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2196 require_once($CFG->dirroot.'/grade/grading/lib.php');
2197 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
2198 $gradingman->extend_navigation($this, $activity);
2201 return $activity->has_children();
2204 * Loads user specific information into the navigation in the appropriate place.
2206 * If no user is provided the current user is assumed.
2208 * @param stdClass $user
2209 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2210 * @return bool
2212 protected function load_for_user($user=null, $forceforcontext=false) {
2213 global $DB, $CFG, $USER, $SITE;
2215 if ($user === null) {
2216 // We can't require login here but if the user isn't logged in we don't
2217 // want to show anything
2218 if (!isloggedin() || isguestuser()) {
2219 return false;
2221 $user = $USER;
2222 } else if (!is_object($user)) {
2223 // If the user is not an object then get them from the database
2224 $select = context_helper::get_preload_record_columns_sql('ctx');
2225 $sql = "SELECT u.*, $select
2226 FROM {user} u
2227 JOIN {context} ctx ON u.id = ctx.instanceid
2228 WHERE u.id = :userid AND
2229 ctx.contextlevel = :contextlevel";
2230 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2231 context_helper::preload_from_record($user);
2234 $iscurrentuser = ($user->id == $USER->id);
2236 $usercontext = context_user::instance($user->id);
2238 // Get the course set against the page, by default this will be the site
2239 $course = $this->page->course;
2240 $baseargs = array('id'=>$user->id);
2241 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2242 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2243 $baseargs['course'] = $course->id;
2244 $coursecontext = context_course::instance($course->id);
2245 $issitecourse = false;
2246 } else {
2247 // Load all categories and get the context for the system
2248 $coursecontext = context_system::instance();
2249 $issitecourse = true;
2252 // Create a node to add user information under.
2253 $usersnode = null;
2254 if (!$issitecourse) {
2255 // Not the current user so add it to the participants node for the current course.
2256 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2257 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2258 } else if ($USER->id != $user->id) {
2259 // This is the site so add a users node to the root branch.
2260 $usersnode = $this->rootnodes['users'];
2261 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2262 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
2264 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2266 if (!$usersnode) {
2267 // We should NEVER get here, if the course hasn't been populated
2268 // with a participants node then the navigaiton either wasn't generated
2269 // for it (you are missing a require_login or set_context call) or
2270 // you don't have access.... in the interests of no leaking informatin
2271 // we simply quit...
2272 return false;
2274 // Add a branch for the current user.
2275 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2276 $viewprofile = true;
2277 if (!$iscurrentuser) {
2278 require_once($CFG->dirroot . '/user/lib.php');
2279 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2280 $viewprofile = false;
2281 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2282 $viewprofile = false;
2284 if (!$viewprofile) {
2285 $viewprofile = user_can_view_profile($user, null, $usercontext);
2289 // Now, conditionally add the user node.
2290 if ($viewprofile) {
2291 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2292 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
2293 } else {
2294 $usernode = $usersnode->add(get_string('user'));
2297 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2298 $usernode->make_active();
2301 // Add user information to the participants or user node.
2302 if ($issitecourse) {
2304 // If the user is the current user or has permission to view the details of the requested
2305 // user than add a view profile link.
2306 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2307 has_capability('moodle/user:viewdetails', $usercontext)) {
2308 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2309 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2310 } else {
2311 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2315 if (!empty($CFG->navadduserpostslinks)) {
2316 // Add nodes for forum posts and discussions if the user can view either or both
2317 // There are no capability checks here as the content of the page is based
2318 // purely on the forums the current user has access too.
2319 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2320 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2321 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2322 array_merge($baseargs, array('mode' => 'discussions'))));
2325 // Add blog nodes.
2326 if (!empty($CFG->enableblogs)) {
2327 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2328 require_once($CFG->dirroot.'/blog/lib.php');
2329 // Get all options for the user.
2330 $options = blog_get_options_for_user($user);
2331 $this->cache->set('userblogoptions'.$user->id, $options);
2332 } else {
2333 $options = $this->cache->{'userblogoptions'.$user->id};
2336 if (count($options) > 0) {
2337 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2338 foreach ($options as $type => $option) {
2339 if ($type == "rss") {
2340 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2341 new pix_icon('i/rss', ''));
2342 } else {
2343 $blogs->add($option['string'], $option['link']);
2349 // Add the messages link.
2350 // It is context based so can appear in the user's profile and in course participants information.
2351 if (!empty($CFG->messaging)) {
2352 $messageargs = array('user1' => $USER->id);
2353 if ($USER->id != $user->id) {
2354 $messageargs['user2'] = $user->id;
2356 $url = new moodle_url('/message/index.php', $messageargs);
2357 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2360 // Add the "My private files" link.
2361 // This link doesn't have a unique display for course context so only display it under the user's profile.
2362 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2363 $url = new moodle_url('/user/files.php');
2364 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2367 // Add a node to view the users notes if permitted.
2368 if (!empty($CFG->enablenotes) &&
2369 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2370 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
2371 if ($coursecontext->instanceid != SITEID) {
2372 $url->param('course', $coursecontext->instanceid);
2374 $usernode->add(get_string('notes', 'notes'), $url);
2377 // Show the grades node.
2378 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2379 require_once($CFG->dirroot . '/user/lib.php');
2380 // Set the grades node to link to the "Grades" page.
2381 if ($course->id == SITEID) {
2382 $url = user_mygrades_url($user->id, $course->id);
2383 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2384 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2386 if ($USER->id != $user->id) {
2387 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
2388 } else {
2389 $usernode->add(get_string('grades', 'grades'), $url);
2393 // If the user is the current user add the repositories for the current user.
2394 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2395 if (!$iscurrentuser &&
2396 $course->id == $SITE->id &&
2397 has_capability('moodle/user:viewdetails', $usercontext) &&
2398 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2400 // Add view grade report is permitted.
2401 $reports = core_component::get_plugin_list('gradereport');
2402 arsort($reports); // User is last, we want to test it first.
2404 $userscourses = enrol_get_users_courses($user->id, false, '*');
2405 $userscoursesnode = $usernode->add(get_string('courses'));
2407 $count = 0;
2408 foreach ($userscourses as $usercourse) {
2409 if ($count === (int)$CFG->navcourselimit) {
2410 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2411 $userscoursesnode->add(get_string('showallcourses'), $url);
2412 break;
2414 $count++;
2415 $usercoursecontext = context_course::instance($usercourse->id);
2416 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2417 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2418 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
2420 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2421 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2422 foreach ($reports as $plugin => $plugindir) {
2423 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2424 // Stop when the first visible plugin is found.
2425 $gradeavailable = true;
2426 break;
2431 if ($gradeavailable) {
2432 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
2433 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2434 new pix_icon('i/grades', ''));
2437 // Add a node to view the users notes if permitted.
2438 if (!empty($CFG->enablenotes) &&
2439 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2440 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
2441 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2444 if (can_access_course($usercourse, $user->id, '', true)) {
2445 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2446 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2449 $reporttab = $usercoursenode->add(get_string('activityreports'));
2451 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2452 foreach ($reportfunctions as $reportfunction) {
2453 $reportfunction($reporttab, $user, $usercourse);
2456 $reporttab->trim_if_empty();
2460 // Let plugins hook into user navigation.
2461 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2462 foreach ($pluginsfunction as $plugintype => $plugins) {
2463 if ($plugintype != 'report') {
2464 foreach ($plugins as $pluginfunction) {
2465 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2470 return true;
2474 * This method simply checks to see if a given module can extend the navigation.
2476 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2478 * @param string $modname
2479 * @return bool
2481 public static function module_extends_navigation($modname) {
2482 global $CFG;
2483 static $extendingmodules = array();
2484 if (!array_key_exists($modname, $extendingmodules)) {
2485 $extendingmodules[$modname] = false;
2486 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2487 if (file_exists($file)) {
2488 $function = $modname.'_extend_navigation';
2489 require_once($file);
2490 $extendingmodules[$modname] = (function_exists($function));
2493 return $extendingmodules[$modname];
2496 * Extends the navigation for the given user.
2498 * @param stdClass $user A user from the database
2500 public function extend_for_user($user) {
2501 $this->extendforuser[] = $user;
2505 * Returns all of the users the navigation is being extended for
2507 * @return array An array of extending users.
2509 public function get_extending_users() {
2510 return $this->extendforuser;
2513 * Adds the given course to the navigation structure.
2515 * @param stdClass $course
2516 * @param bool $forcegeneric
2517 * @param bool $ismycourse
2518 * @return navigation_node
2520 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2521 global $CFG, $SITE;
2523 // We found the course... we can return it now :)
2524 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2525 return $this->addedcourses[$course->id];
2528 $coursecontext = context_course::instance($course->id);
2530 if ($course->id != $SITE->id && !$course->visible) {
2531 if (is_role_switched($course->id)) {
2532 // user has to be able to access course in order to switch, let's skip the visibility test here
2533 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2534 return false;
2538 $issite = ($course->id == $SITE->id);
2539 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2540 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2541 // This is the name that will be shown for the course.
2542 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2544 if ($coursetype == self::COURSE_CURRENT) {
2545 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2546 return $coursenode;
2547 } else {
2548 $coursetype = self::COURSE_OTHER;
2552 // Can the user expand the course to see its content.
2553 $canexpandcourse = true;
2554 if ($issite) {
2555 $parent = $this;
2556 $url = null;
2557 if (empty($CFG->usesitenameforsitepages)) {
2558 $coursename = get_string('sitepages');
2560 } else if ($coursetype == self::COURSE_CURRENT) {
2561 $parent = $this->rootnodes['currentcourse'];
2562 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2563 $canexpandcourse = $this->can_expand_course($course);
2564 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2565 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2566 // Nothing to do here the above statement set $parent to the category within mycourses.
2567 } else {
2568 $parent = $this->rootnodes['mycourses'];
2570 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2571 } else {
2572 $parent = $this->rootnodes['courses'];
2573 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2574 // They can only expand the course if they can access it.
2575 $canexpandcourse = $this->can_expand_course($course);
2576 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2577 if (!$this->is_category_fully_loaded($course->category)) {
2578 // We need to load the category structure for this course
2579 $this->load_all_categories($course->category, false);
2581 if (array_key_exists($course->category, $this->addedcategories)) {
2582 $parent = $this->addedcategories[$course->category];
2583 // This could lead to the course being created so we should check whether it is the case again
2584 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2585 return $this->addedcourses[$course->id];
2591 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2592 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
2594 $coursenode->hidden = (!$course->visible);
2595 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
2596 if ($canexpandcourse) {
2597 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2598 $coursenode->nodetype = self::NODETYPE_BRANCH;
2599 $coursenode->isexpandable = true;
2600 } else {
2601 $coursenode->nodetype = self::NODETYPE_LEAF;
2602 $coursenode->isexpandable = false;
2604 if (!$forcegeneric) {
2605 $this->addedcourses[$course->id] = $coursenode;
2608 return $coursenode;
2612 * Returns a cache instance to use for the expand course cache.
2613 * @return cache_session
2615 protected function get_expand_course_cache() {
2616 if ($this->cacheexpandcourse === null) {
2617 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2619 return $this->cacheexpandcourse;
2623 * Checks if a user can expand a course in the navigation.
2625 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2626 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2627 * permits stale data.
2628 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2629 * will be stale.
2630 * It is brought up to date in only one of two ways.
2631 * 1. The user logs out and in again.
2632 * 2. The user browses to the course they've just being given access to.
2634 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2636 * @param stdClass $course
2637 * @return bool
2639 protected function can_expand_course($course) {
2640 $cache = $this->get_expand_course_cache();
2641 $canexpand = $cache->get($course->id);
2642 if ($canexpand === false) {
2643 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2644 $canexpand = (int)$canexpand;
2645 $cache->set($course->id, $canexpand);
2647 return ($canexpand === 1);
2651 * Returns true if the category has already been loaded as have any child categories
2653 * @param int $categoryid
2654 * @return bool
2656 protected function is_category_fully_loaded($categoryid) {
2657 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2661 * Adds essential course nodes to the navigation for the given course.
2663 * This method adds nodes such as reports, blogs and participants
2665 * @param navigation_node $coursenode
2666 * @param stdClass $course
2667 * @return bool returns true on successful addition of a node.
2669 public function add_course_essentials($coursenode, stdClass $course) {
2670 global $CFG, $SITE;
2671 require_once($CFG->dirroot . '/course/lib.php');
2673 if ($course->id == $SITE->id) {
2674 return $this->add_front_page_course_essentials($coursenode, $course);
2677 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2678 return true;
2681 $navoptions = course_get_user_navigation_options($this->page->context, $course);
2683 //Participants
2684 if ($navoptions->participants) {
2685 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2687 if ($navoptions->blogs) {
2688 $blogsurls = new moodle_url('/blog/index.php');
2689 if ($currentgroup = groups_get_course_group($course, true)) {
2690 $blogsurls->param('groupid', $currentgroup);
2691 } else {
2692 $blogsurls->param('courseid', $course->id);
2694 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
2697 if ($navoptions->notes) {
2698 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
2700 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2701 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2704 // Badges.
2705 if ($navoptions->badges) {
2706 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2708 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2709 navigation_node::TYPE_SETTING, null, 'badgesview',
2710 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2713 // Check access to the course and competencies page.
2714 if ($navoptions->competencies) {
2715 // Just a link to course competency.
2716 $title = get_string('competencies', 'core_competency');
2717 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
2718 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2719 new pix_icon('i/competencies', ''));
2721 if ($navoptions->grades) {
2722 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2723 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2726 return true;
2729 * This generates the structure of the course that won't be generated when
2730 * the modules and sections are added.
2732 * Things such as the reports branch, the participants branch, blogs... get
2733 * added to the course node by this method.
2735 * @param navigation_node $coursenode
2736 * @param stdClass $course
2737 * @return bool True for successfull generation
2739 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2740 global $CFG, $USER;
2741 require_once($CFG->dirroot . '/course/lib.php');
2743 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2744 return true;
2747 $sitecontext = context_system::instance();
2748 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2750 // Hidden node that we use to determine if the front page navigation is loaded.
2751 // This required as there are not other guaranteed nodes that may be loaded.
2752 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2754 // Participants.
2755 if ($navoptions->participants) {
2756 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2759 // Blogs.
2760 if ($navoptions->blogs) {
2761 $blogsurls = new moodle_url('/blog/index.php');
2762 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
2765 $filterselect = 0;
2767 // Badges.
2768 if ($navoptions->badges) {
2769 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2770 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2773 // Notes.
2774 if ($navoptions->notes) {
2775 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2776 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
2779 // Tags
2780 if ($navoptions->tags) {
2781 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2782 self::TYPE_SETTING, null, 'tags');
2785 // Search.
2786 if ($navoptions->search) {
2787 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2788 self::TYPE_SETTING, null, 'search');
2791 if ($navoptions->calendar) {
2792 // Calendar
2793 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2794 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2795 $node->showinflatnavigation = true;
2798 if (isloggedin()) {
2799 $usercontext = context_user::instance($USER->id);
2800 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2801 $url = new moodle_url('/user/files.php');
2802 $node = $coursenode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
2803 $node->display = false;
2804 $node->showinflatnavigation = true;
2808 return true;
2812 * Clears the navigation cache
2814 public function clear_cache() {
2815 $this->cache->clear();
2819 * Sets an expansion limit for the navigation
2821 * The expansion limit is used to prevent the display of content that has a type
2822 * greater than the provided $type.
2824 * Can be used to ensure things such as activities or activity content don't get
2825 * shown on the navigation.
2826 * They are still generated in order to ensure the navbar still makes sense.
2828 * @param int $type One of navigation_node::TYPE_*
2829 * @return bool true when complete.
2831 public function set_expansion_limit($type) {
2832 global $SITE;
2833 $nodes = $this->find_all_of_type($type);
2835 // We only want to hide specific types of nodes.
2836 // Only nodes that represent "structure" in the navigation tree should be hidden.
2837 // If we hide all nodes then we risk hiding vital information.
2838 $typestohide = array(
2839 self::TYPE_CATEGORY,
2840 self::TYPE_COURSE,
2841 self::TYPE_SECTION,
2842 self::TYPE_ACTIVITY
2845 foreach ($nodes as $node) {
2846 // We need to generate the full site node
2847 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2848 continue;
2850 foreach ($node->children as $child) {
2851 $child->hide($typestohide);
2854 return true;
2857 * Attempts to get the navigation with the given key from this nodes children.
2859 * This function only looks at this nodes children, it does NOT look recursivily.
2860 * If the node can't be found then false is returned.
2862 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2864 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2865 * may be of more use to you.
2867 * @param string|int $key The key of the node you wish to receive.
2868 * @param int $type One of navigation_node::TYPE_*
2869 * @return navigation_node|false
2871 public function get($key, $type = null) {
2872 if (!$this->initialised) {
2873 $this->initialise();
2875 return parent::get($key, $type);
2879 * Searches this nodes children and their children to find a navigation node
2880 * with the matching key and type.
2882 * This method is recursive and searches children so until either a node is
2883 * found or there are no more nodes to search.
2885 * If you know that the node being searched for is a child of this node
2886 * then use the {@link global_navigation::get()} method instead.
2888 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2889 * may be of more use to you.
2891 * @param string|int $key The key of the node you wish to receive.
2892 * @param int $type One of navigation_node::TYPE_*
2893 * @return navigation_node|false
2895 public function find($key, $type) {
2896 if (!$this->initialised) {
2897 $this->initialise();
2899 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2900 return $this->rootnodes[$key];
2902 return parent::find($key, $type);
2906 * They've expanded the 'my courses' branch.
2908 protected function load_courses_enrolled() {
2909 global $CFG;
2911 $limit = (int) $CFG->navcourselimit;
2913 $sortorder = 'visible DESC';
2914 // Prevent undefined $CFG->navsortmycoursessort errors.
2915 if (empty($CFG->navsortmycoursessort)) {
2916 $CFG->navsortmycoursessort = 'sortorder';
2918 // Append the chosen sortorder.
2919 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2920 $courses = enrol_get_my_courses('*', $sortorder);
2921 $flatnavcourses = [];
2923 // Go through the courses and see which ones we want to display in the flatnav.
2924 foreach ($courses as $course) {
2925 $classify = course_classify_for_timeline($course);
2927 if ($classify == COURSE_TIMELINE_INPROGRESS) {
2928 $flatnavcourses[$course->id] = $course;
2932 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2933 $numtotalcourses = count($courses);
2934 $numtotalflatnavcourses = count($flatnavcourses);
2936 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2937 $courses = array_slice($courses, 0, $limit, true);
2938 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
2940 // Get the number of courses we are going to show for each.
2941 $numshowncourses = count($courses);
2942 $numshownflatnavcourses = count($flatnavcourses);
2943 if ($numshowncourses && $this->show_my_categories()) {
2944 // Generate an array containing unique values of all the courses' categories.
2945 $categoryids = array();
2946 foreach ($courses as $course) {
2947 if (in_array($course->category, $categoryids)) {
2948 continue;
2950 $categoryids[] = $course->category;
2953 // Array of category IDs that include the categories of the user's courses and the related course categories.
2954 $fullpathcategoryids = [];
2955 // Get the course categories for the enrolled courses' category IDs.
2956 require_once('coursecatlib.php');
2957 $mycoursecategories = coursecat::get_many($categoryids);
2958 // Loop over each of these categories and build the category tree using each category's path.
2959 foreach ($mycoursecategories as $mycoursecat) {
2960 $pathcategoryids = explode('/', $mycoursecat->path);
2961 // First element of the exploded path is empty since paths begin with '/'.
2962 array_shift($pathcategoryids);
2963 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
2964 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
2967 // Fetch all of the categories related to the user's courses.
2968 $pathcategories = coursecat::get_many($fullpathcategoryids);
2969 // Loop over each of these categories and build the category tree.
2970 foreach ($pathcategories as $coursecat) {
2971 // No need to process categories that have already been added.
2972 if (isset($this->addedcategories[$coursecat->id])) {
2973 continue;
2976 // Get this course category's parent node.
2977 $parent = null;
2978 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
2979 $parent = $this->addedcategories[$coursecat->parent];
2981 if (!$parent) {
2982 // If it has no parent, then it should be right under the My courses node.
2983 $parent = $this->rootnodes['mycourses'];
2986 // Build the category object based from the coursecat object.
2987 $mycategory = new stdClass();
2988 $mycategory->id = $coursecat->id;
2989 $mycategory->name = $coursecat->name;
2990 $mycategory->visible = $coursecat->visible;
2992 // Add this category to the nav tree.
2993 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
2997 // Go through each course now and add it to the nav block, and the flatnav if applicable.
2998 foreach ($courses as $course) {
2999 $node = $this->add_course($course, false, self::COURSE_MY);
3000 if ($node) {
3001 $node->showinflatnavigation = false;
3002 // Check if we should also add this to the flat nav as well.
3003 if (isset($flatnavcourses[$course->id])) {
3004 $node->showinflatnavigation = true;
3009 // Go through each course in the flatnav now.
3010 foreach ($flatnavcourses as $course) {
3011 // Check if we haven't already added it.
3012 if (!isset($courses[$course->id])) {
3013 // Ok, add it to the flatnav only.
3014 $node = $this->add_course($course, false, self::COURSE_MY);
3015 $node->display = false;
3016 $node->showinflatnavigation = true;
3020 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3021 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3022 // Show a link to the course page if there are more courses the user is enrolled in.
3023 if ($showmorelinkinnav || $showmorelinkinflatnav) {
3024 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3025 $url = new moodle_url('/course/index.php#');
3026 $parent = $this->rootnodes['mycourses'];
3027 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE);
3029 if ($showmorelinkinnav) {
3030 $coursenode->display = true;
3033 if ($showmorelinkinflatnav) {
3034 $coursenode->showinflatnavigation = true;
3041 * The global navigation class used especially for AJAX requests.
3043 * The primary methods that are used in the global navigation class have been overriden
3044 * to ensure that only the relevant branch is generated at the root of the tree.
3045 * This can be done because AJAX is only used when the backwards structure for the
3046 * requested branch exists.
3047 * This has been done only because it shortens the amounts of information that is generated
3048 * which of course will speed up the response time.. because no one likes laggy AJAX.
3050 * @package core
3051 * @category navigation
3052 * @copyright 2009 Sam Hemelryk
3053 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3055 class global_navigation_for_ajax extends global_navigation {
3057 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3058 protected $branchtype;
3060 /** @var int the instance id */
3061 protected $instanceid;
3063 /** @var array Holds an array of expandable nodes */
3064 protected $expandable = array();
3067 * Constructs the navigation for use in an AJAX request
3069 * @param moodle_page $page moodle_page object
3070 * @param int $branchtype
3071 * @param int $id
3073 public function __construct($page, $branchtype, $id) {
3074 $this->page = $page;
3075 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3076 $this->children = new navigation_node_collection();
3077 $this->branchtype = $branchtype;
3078 $this->instanceid = $id;
3079 $this->initialise();
3082 * Initialise the navigation given the type and id for the branch to expand.
3084 * @return array An array of the expandable nodes
3086 public function initialise() {
3087 global $DB, $SITE;
3089 if ($this->initialised || during_initial_install()) {
3090 return $this->expandable;
3092 $this->initialised = true;
3094 $this->rootnodes = array();
3095 $this->rootnodes['site'] = $this->add_course($SITE);
3096 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
3097 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
3098 // The courses branch is always displayed, and is always expandable (although may be empty).
3099 // This mimicks what is done during {@link global_navigation::initialise()}.
3100 $this->rootnodes['courses']->isexpandable = true;
3102 // Branchtype will be one of navigation_node::TYPE_*
3103 switch ($this->branchtype) {
3104 case 0:
3105 if ($this->instanceid === 'mycourses') {
3106 $this->load_courses_enrolled();
3107 } else if ($this->instanceid === 'courses') {
3108 $this->load_courses_other();
3110 break;
3111 case self::TYPE_CATEGORY :
3112 $this->load_category($this->instanceid);
3113 break;
3114 case self::TYPE_MY_CATEGORY :
3115 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
3116 break;
3117 case self::TYPE_COURSE :
3118 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
3119 if (!can_access_course($course, null, '', true)) {
3120 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3121 // add the course node and break. This leads to an empty node.
3122 $this->add_course($course);
3123 break;
3125 require_course_login($course, true, null, false, true);
3126 $this->page->set_context(context_course::instance($course->id));
3127 $coursenode = $this->add_course($course);
3128 $this->add_course_essentials($coursenode, $course);
3129 $this->load_course_sections($course, $coursenode);
3130 break;
3131 case self::TYPE_SECTION :
3132 $sql = 'SELECT c.*, cs.section AS sectionnumber
3133 FROM {course} c
3134 LEFT JOIN {course_sections} cs ON cs.course = c.id
3135 WHERE cs.id = ?';
3136 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
3137 require_course_login($course, true, null, false, true);
3138 $this->page->set_context(context_course::instance($course->id));
3139 $coursenode = $this->add_course($course);
3140 $this->add_course_essentials($coursenode, $course);
3141 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
3142 break;
3143 case self::TYPE_ACTIVITY :
3144 $sql = "SELECT c.*
3145 FROM {course} c
3146 JOIN {course_modules} cm ON cm.course = c.id
3147 WHERE cm.id = :cmid";
3148 $params = array('cmid' => $this->instanceid);
3149 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
3150 $modinfo = get_fast_modinfo($course);
3151 $cm = $modinfo->get_cm($this->instanceid);
3152 require_course_login($course, true, $cm, false, true);
3153 $this->page->set_context(context_module::instance($cm->id));
3154 $coursenode = $this->load_course($course);
3155 $this->load_course_sections($course, $coursenode, null, $cm);
3156 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
3157 if ($activitynode) {
3158 $modulenode = $this->load_activity($cm, $course, $activitynode);
3160 break;
3161 default:
3162 throw new Exception('Unknown type');
3163 return $this->expandable;
3166 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
3167 $this->load_for_user(null, true);
3170 $this->find_expandable($this->expandable);
3171 return $this->expandable;
3175 * They've expanded the general 'courses' branch.
3177 protected function load_courses_other() {
3178 $this->load_all_courses();
3182 * Loads a single category into the AJAX navigation.
3184 * This function is special in that it doesn't concern itself with the parent of
3185 * the requested category or its siblings.
3186 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3187 * request that.
3189 * @global moodle_database $DB
3190 * @param int $categoryid id of category to load in navigation.
3191 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3192 * @return void.
3194 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
3195 global $CFG, $DB;
3197 $limit = 20;
3198 if (!empty($CFG->navcourselimit)) {
3199 $limit = (int)$CFG->navcourselimit;
3202 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
3203 $sql = "SELECT cc.*, $catcontextsql
3204 FROM {course_categories} cc
3205 JOIN {context} ctx ON cc.id = ctx.instanceid
3206 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
3207 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3208 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3209 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3210 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3211 $categorylist = array();
3212 $subcategories = array();
3213 $basecategory = null;
3214 foreach ($categories as $category) {
3215 $categorylist[] = $category->id;
3216 context_helper::preload_from_record($category);
3217 if ($category->id == $categoryid) {
3218 $this->add_category($category, $this, $nodetype);
3219 $basecategory = $this->addedcategories[$category->id];
3220 } else {
3221 $subcategories[$category->id] = $category;
3224 $categories->close();
3227 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3228 // else show all courses.
3229 if ($nodetype === self::TYPE_MY_CATEGORY) {
3230 $courses = enrol_get_my_courses('*');
3231 $categoryids = array();
3233 // Only search for categories if basecategory was found.
3234 if (!is_null($basecategory)) {
3235 // Get course parent category ids.
3236 foreach ($courses as $course) {
3237 $categoryids[] = $course->category;
3240 // Get a unique list of category ids which a part of the path
3241 // to user's courses.
3242 $coursesubcategories = array();
3243 $addedsubcategories = array();
3245 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3246 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3248 foreach ($categories as $category){
3249 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
3251 $coursesubcategories = array_unique($coursesubcategories);
3253 // Only add a subcategory if it is part of the path to user's course and
3254 // wasn't already added.
3255 foreach ($subcategories as $subid => $subcategory) {
3256 if (in_array($subid, $coursesubcategories) &&
3257 !in_array($subid, $addedsubcategories)) {
3258 $this->add_category($subcategory, $basecategory, $nodetype);
3259 $addedsubcategories[] = $subid;
3264 foreach ($courses as $course) {
3265 // Add course if it's in category.
3266 if (in_array($course->category, $categorylist)) {
3267 $this->add_course($course, true, self::COURSE_MY);
3270 } else {
3271 if (!is_null($basecategory)) {
3272 foreach ($subcategories as $key=>$category) {
3273 $this->add_category($category, $basecategory, $nodetype);
3276 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3277 foreach ($courses as $course) {
3278 $this->add_course($course);
3280 $courses->close();
3285 * Returns an array of expandable nodes
3286 * @return array
3288 public function get_expandable() {
3289 return $this->expandable;
3294 * Navbar class
3296 * This class is used to manage the navbar, which is initialised from the navigation
3297 * object held by PAGE
3299 * @package core
3300 * @category navigation
3301 * @copyright 2009 Sam Hemelryk
3302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3304 class navbar extends navigation_node {
3305 /** @var bool A switch for whether the navbar is initialised or not */
3306 protected $initialised = false;
3307 /** @var mixed keys used to reference the nodes on the navbar */
3308 protected $keys = array();
3309 /** @var null|string content of the navbar */
3310 protected $content = null;
3311 /** @var moodle_page object the moodle page that this navbar belongs to */
3312 protected $page;
3313 /** @var bool A switch for whether to ignore the active navigation information */
3314 protected $ignoreactive = false;
3315 /** @var bool A switch to let us know if we are in the middle of an install */
3316 protected $duringinstall = false;
3317 /** @var bool A switch for whether the navbar has items */
3318 protected $hasitems = false;
3319 /** @var array An array of navigation nodes for the navbar */
3320 protected $items;
3321 /** @var array An array of child node objects */
3322 public $children = array();
3323 /** @var bool A switch for whether we want to include the root node in the navbar */
3324 public $includesettingsbase = false;
3325 /** @var breadcrumb_navigation_node[] $prependchildren */
3326 protected $prependchildren = array();
3329 * The almighty constructor
3331 * @param moodle_page $page
3333 public function __construct(moodle_page $page) {
3334 global $CFG;
3335 if (during_initial_install()) {
3336 $this->duringinstall = true;
3337 return false;
3339 $this->page = $page;
3340 $this->text = get_string('home');
3341 $this->shorttext = get_string('home');
3342 $this->action = new moodle_url($CFG->wwwroot);
3343 $this->nodetype = self::NODETYPE_BRANCH;
3344 $this->type = self::TYPE_SYSTEM;
3348 * Quick check to see if the navbar will have items in.
3350 * @return bool Returns true if the navbar will have items, false otherwise
3352 public function has_items() {
3353 if ($this->duringinstall) {
3354 return false;
3355 } else if ($this->hasitems !== false) {
3356 return true;
3358 if (count($this->children) > 0 || count($this->prependchildren) > 0) {
3359 // There have been manually added items - there are definitely items.
3360 $outcome = true;
3361 } else if (!$this->ignoreactive) {
3362 // We will need to initialise the navigation structure to check if there are active items.
3363 $this->page->navigation->initialise($this->page);
3364 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node());
3366 $this->hasitems = $outcome;
3367 return $outcome;
3371 * Turn on/off ignore active
3373 * @param bool $setting
3375 public function ignore_active($setting=true) {
3376 $this->ignoreactive = ($setting);
3380 * Gets a navigation node
3382 * @param string|int $key for referencing the navbar nodes
3383 * @param int $type breadcrumb_navigation_node::TYPE_*
3384 * @return breadcrumb_navigation_node|bool
3386 public function get($key, $type = null) {
3387 foreach ($this->children as &$child) {
3388 if ($child->key === $key && ($type == null || $type == $child->type)) {
3389 return $child;
3392 foreach ($this->prependchildren as &$child) {
3393 if ($child->key === $key && ($type == null || $type == $child->type)) {
3394 return $child;
3397 return false;
3400 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3402 * @return array
3404 public function get_items() {
3405 global $CFG;
3406 $items = array();
3407 // Make sure that navigation is initialised
3408 if (!$this->has_items()) {
3409 return $items;
3411 if ($this->items !== null) {
3412 return $this->items;
3415 if (count($this->children) > 0) {
3416 // Add the custom children.
3417 $items = array_reverse($this->children);
3420 // Check if navigation contains the active node
3421 if (!$this->ignoreactive) {
3422 // We will need to ensure the navigation has been initialised.
3423 $this->page->navigation->initialise($this->page);
3424 // Now find the active nodes on both the navigation and settings.
3425 $navigationactivenode = $this->page->navigation->find_active_node();
3426 $settingsactivenode = $this->page->settingsnav->find_active_node();
3428 if ($navigationactivenode && $settingsactivenode) {
3429 // Parse a combined navigation tree
3430 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3431 if (!$settingsactivenode->mainnavonly) {
3432 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3434 $settingsactivenode = $settingsactivenode->parent;
3436 if (!$this->includesettingsbase) {
3437 // Removes the first node from the settings (root node) from the list
3438 array_pop($items);
3440 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3441 if (!$navigationactivenode->mainnavonly) {
3442 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3444 if (!empty($CFG->navshowcategories) &&
3445 $navigationactivenode->type === self::TYPE_COURSE &&
3446 $navigationactivenode->parent->key === 'currentcourse') {
3447 foreach ($this->get_course_categories() as $item) {
3448 $items[] = new breadcrumb_navigation_node($item);
3451 $navigationactivenode = $navigationactivenode->parent;
3453 } else if ($navigationactivenode) {
3454 // Parse the navigation tree to get the active node
3455 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3456 if (!$navigationactivenode->mainnavonly) {
3457 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3459 if (!empty($CFG->navshowcategories) &&
3460 $navigationactivenode->type === self::TYPE_COURSE &&
3461 $navigationactivenode->parent->key === 'currentcourse') {
3462 foreach ($this->get_course_categories() as $item) {
3463 $items[] = new breadcrumb_navigation_node($item);
3466 $navigationactivenode = $navigationactivenode->parent;
3468 } else if ($settingsactivenode) {
3469 // Parse the settings navigation to get the active node
3470 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3471 if (!$settingsactivenode->mainnavonly) {
3472 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3474 $settingsactivenode = $settingsactivenode->parent;
3479 $items[] = new breadcrumb_navigation_node(array(
3480 'text' => $this->page->navigation->text,
3481 'shorttext' => $this->page->navigation->shorttext,
3482 'key' => $this->page->navigation->key,
3483 'action' => $this->page->navigation->action
3486 if (count($this->prependchildren) > 0) {
3487 // Add the custom children
3488 $items = array_merge($items, array_reverse($this->prependchildren));
3491 $last = reset($items);
3492 if ($last) {
3493 $last->set_last(true);
3495 $this->items = array_reverse($items);
3496 return $this->items;
3500 * Get the list of categories leading to this course.
3502 * This function is used by {@link navbar::get_items()} to add back the "courses"
3503 * node and category chain leading to the current course. Note that this is only ever
3504 * called for the current course, so we don't need to bother taking in any parameters.
3506 * @return array
3508 private function get_course_categories() {
3509 global $CFG;
3510 require_once($CFG->dirroot.'/course/lib.php');
3511 require_once($CFG->libdir.'/coursecatlib.php');
3513 $categories = array();
3514 $cap = 'moodle/category:viewhiddencategories';
3515 $showcategories = coursecat::count_all() > 1;
3517 if ($showcategories) {
3518 foreach ($this->page->categories as $category) {
3519 if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
3520 continue;
3522 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3523 $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3524 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3525 if (!$category->visible) {
3526 $categorynode->hidden = true;
3528 $categories[] = $categorynode;
3532 // Don't show the 'course' node if enrolled in this course.
3533 if (!is_enrolled(context_course::instance($this->page->course->id, null, '', true))) {
3534 $courses = $this->page->navigation->get('courses');
3535 if (!$courses) {
3536 // Courses node may not be present.
3537 $courses = breadcrumb_navigation_node::create(
3538 get_string('courses'),
3539 new moodle_url('/course/index.php'),
3540 self::TYPE_CONTAINER
3543 $categories[] = $courses;
3546 return $categories;
3550 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3552 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3553 * the way nodes get added to allow us to simply call add and have the node added to the
3554 * end of the navbar
3556 * @param string $text
3557 * @param string|moodle_url|action_link $action An action to associate with this node.
3558 * @param int $type One of navigation_node::TYPE_*
3559 * @param string $shorttext
3560 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3561 * @param pix_icon $icon An optional icon to use for this node.
3562 * @return navigation_node
3564 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3565 if ($this->content !== null) {
3566 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3569 // Properties array used when creating the new navigation node
3570 $itemarray = array(
3571 'text' => $text,
3572 'type' => $type
3574 // Set the action if one was provided
3575 if ($action!==null) {
3576 $itemarray['action'] = $action;
3578 // Set the shorttext if one was provided
3579 if ($shorttext!==null) {
3580 $itemarray['shorttext'] = $shorttext;
3582 // Set the icon if one was provided
3583 if ($icon!==null) {
3584 $itemarray['icon'] = $icon;
3586 // Default the key to the number of children if not provided
3587 if ($key === null) {
3588 $key = count($this->children);
3590 // Set the key
3591 $itemarray['key'] = $key;
3592 // Set the parent to this node
3593 $itemarray['parent'] = $this;
3594 // Add the child using the navigation_node_collections add method
3595 $this->children[] = new breadcrumb_navigation_node($itemarray);
3596 return $this;
3600 * Prepends a new navigation_node to the start of the navbar
3602 * @param string $text
3603 * @param string|moodle_url|action_link $action An action to associate with this node.
3604 * @param int $type One of navigation_node::TYPE_*
3605 * @param string $shorttext
3606 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3607 * @param pix_icon $icon An optional icon to use for this node.
3608 * @return navigation_node
3610 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3611 if ($this->content !== null) {
3612 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3614 // Properties array used when creating the new navigation node.
3615 $itemarray = array(
3616 'text' => $text,
3617 'type' => $type
3619 // Set the action if one was provided.
3620 if ($action!==null) {
3621 $itemarray['action'] = $action;
3623 // Set the shorttext if one was provided.
3624 if ($shorttext!==null) {
3625 $itemarray['shorttext'] = $shorttext;
3627 // Set the icon if one was provided.
3628 if ($icon!==null) {
3629 $itemarray['icon'] = $icon;
3631 // Default the key to the number of children if not provided.
3632 if ($key === null) {
3633 $key = count($this->children);
3635 // Set the key.
3636 $itemarray['key'] = $key;
3637 // Set the parent to this node.
3638 $itemarray['parent'] = $this;
3639 // Add the child node to the prepend list.
3640 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray);
3641 return $this;
3646 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3647 * in particular adding extra metadata for search engine robots to leverage.
3649 * @package core
3650 * @category navigation
3651 * @copyright 2015 Brendan Heywood
3652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3654 class breadcrumb_navigation_node extends navigation_node {
3656 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3657 private $last = false;
3660 * A proxy constructor
3662 * @param mixed $navnode A navigation_node or an array
3664 public function __construct($navnode) {
3665 if (is_array($navnode)) {
3666 parent::__construct($navnode);
3667 } else if ($navnode instanceof navigation_node) {
3669 // Just clone everything.
3670 $objvalues = get_object_vars($navnode);
3671 foreach ($objvalues as $key => $value) {
3672 $this->$key = $value;
3674 } else {
3675 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3680 * Getter for "last"
3681 * @return boolean
3683 public function is_last() {
3684 return $this->last;
3688 * Setter for "last"
3689 * @param $val boolean
3691 public function set_last($val) {
3692 $this->last = $val;
3697 * Subclass of navigation_node allowing different rendering for the flat navigation
3698 * in particular allowing dividers and indents.
3700 * @package core
3701 * @category navigation
3702 * @copyright 2016 Damyon Wiese
3703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3705 class flat_navigation_node extends navigation_node {
3707 /** @var $indent integer The indent level */
3708 private $indent = 0;
3710 /** @var $showdivider bool Show a divider before this element */
3711 private $showdivider = false;
3714 * A proxy constructor
3716 * @param mixed $navnode A navigation_node or an array
3718 public function __construct($navnode, $indent) {
3719 if (is_array($navnode)) {
3720 parent::__construct($navnode);
3721 } else if ($navnode instanceof navigation_node) {
3723 // Just clone everything.
3724 $objvalues = get_object_vars($navnode);
3725 foreach ($objvalues as $key => $value) {
3726 $this->$key = $value;
3728 } else {
3729 throw new coding_exception('Not a valid flat_navigation_node');
3731 $this->indent = $indent;
3735 * Does this node represent a course section link.
3736 * @return boolean
3738 public function is_section() {
3739 return $this->type == navigation_node::TYPE_SECTION;
3743 * In flat navigation - sections are active if we are looking at activities in the section.
3744 * @return boolean
3746 public function isactive() {
3747 global $PAGE;
3749 if ($this->is_section()) {
3750 $active = $PAGE->navigation->find_active_node();
3751 while ($active = $active->parent) {
3752 if ($active->key == $this->key && $active->type == $this->type) {
3753 return true;
3757 return $this->isactive;
3761 * Getter for "showdivider"
3762 * @return boolean
3764 public function showdivider() {
3765 return $this->showdivider;
3769 * Setter for "showdivider"
3770 * @param $val boolean
3772 public function set_showdivider($val) {
3773 $this->showdivider = $val;
3777 * Getter for "indent"
3778 * @return boolean
3780 public function get_indent() {
3781 return $this->indent;
3785 * Setter for "indent"
3786 * @param $val boolean
3788 public function set_indent($val) {
3789 $this->indent = $val;
3795 * Class used to generate a collection of navigation nodes most closely related
3796 * to the current page.
3798 * @package core
3799 * @copyright 2016 Damyon Wiese
3800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3802 class flat_navigation extends navigation_node_collection {
3803 /** @var moodle_page the moodle page that the navigation belongs to */
3804 protected $page;
3807 * Constructor.
3809 * @param moodle_page $page
3811 public function __construct(moodle_page &$page) {
3812 if (during_initial_install()) {
3813 return false;
3815 $this->page = $page;
3819 * Build the list of navigation nodes based on the current navigation and settings trees.
3822 public function initialise() {
3823 global $PAGE, $USER, $OUTPUT, $CFG;
3824 if (during_initial_install()) {
3825 return;
3828 $current = false;
3830 $course = $PAGE->course;
3832 $this->page->navigation->initialise();
3834 // First walk the nav tree looking for "flat_navigation" nodes.
3835 if ($course->id > 1) {
3836 // It's a real course.
3837 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3839 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3840 // This is the name that will be shown for the course.
3841 $coursename = empty($CFG->navshowfullcoursenames) ?
3842 format_string($course->shortname, true, array('context' => $coursecontext)) :
3843 format_string($course->fullname, true, array('context' => $coursecontext));
3845 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
3846 $flat->key = 'coursehome';
3848 $courseformat = course_get_format($course);
3849 $coursenode = $PAGE->navigation->find_active_node();
3850 $targettype = navigation_node::TYPE_COURSE;
3852 // Single activity format has no course node - the course node is swapped for the activity node.
3853 if (!$courseformat->has_view_page()) {
3854 $targettype = navigation_node::TYPE_ACTIVITY;
3857 while (!empty($coursenode) && ($coursenode->type != $targettype)) {
3858 $coursenode = $coursenode->parent;
3860 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3861 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3862 if ($coursenode && $coursenode->key != SITEID) {
3863 $this->add($flat);
3864 foreach ($coursenode->children as $child) {
3865 if ($child->action) {
3866 $flat = new flat_navigation_node($child, 0);
3867 $this->add($flat);
3872 $this->page->navigation->build_flat_navigation_list($this, true);
3873 } else {
3874 $this->page->navigation->build_flat_navigation_list($this, false);
3877 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
3878 if (!$admin) {
3879 // Try again - crazy nav tree!
3880 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
3882 if ($admin) {
3883 $flat = new flat_navigation_node($admin, 0);
3884 $flat->set_showdivider(true);
3885 $flat->key = 'sitesettings';
3886 $this->add($flat);
3889 // Add-a-block in editing mode.
3890 if (isset($this->page->theme->addblockposition) &&
3891 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
3892 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3893 ($addable = $PAGE->blocks->get_addable_blocks())) {
3894 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3895 $addablock = navigation_node::create(get_string('addblock'), $url);
3896 $flat = new flat_navigation_node($addablock, 0);
3897 $flat->set_showdivider(true);
3898 $flat->key = 'addblock';
3899 $this->add($flat);
3900 $blocks = [];
3901 foreach ($addable as $block) {
3902 $blocks[] = $block->name;
3904 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3905 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
3912 * Class used to manage the settings option for the current page
3914 * This class is used to manage the settings options in a tree format (recursively)
3915 * and was created initially for use with the settings blocks.
3917 * @package core
3918 * @category navigation
3919 * @copyright 2009 Sam Hemelryk
3920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3922 class settings_navigation extends navigation_node {
3923 /** @var stdClass the current context */
3924 protected $context;
3925 /** @var moodle_page the moodle page that the navigation belongs to */
3926 protected $page;
3927 /** @var string contains administration section navigation_nodes */
3928 protected $adminsection;
3929 /** @var bool A switch to see if the navigation node is initialised */
3930 protected $initialised = false;
3931 /** @var array An array of users that the nodes can extend for. */
3932 protected $userstoextendfor = array();
3933 /** @var navigation_cache **/
3934 protected $cache;
3937 * Sets up the object with basic settings and preparse it for use
3939 * @param moodle_page $page
3941 public function __construct(moodle_page &$page) {
3942 if (during_initial_install()) {
3943 return false;
3945 $this->page = $page;
3946 // Initialise the main navigation. It is most important that this is done
3947 // before we try anything
3948 $this->page->navigation->initialise();
3949 // Initialise the navigation cache
3950 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3951 $this->children = new navigation_node_collection();
3955 * Initialise the settings navigation based on the current context
3957 * This function initialises the settings navigation tree for a given context
3958 * by calling supporting functions to generate major parts of the tree.
3961 public function initialise() {
3962 global $DB, $SESSION, $SITE;
3964 if (during_initial_install()) {
3965 return false;
3966 } else if ($this->initialised) {
3967 return true;
3969 $this->id = 'settingsnav';
3970 $this->context = $this->page->context;
3972 $context = $this->context;
3973 if ($context->contextlevel == CONTEXT_BLOCK) {
3974 $this->load_block_settings();
3975 $context = $context->get_parent_context();
3977 switch ($context->contextlevel) {
3978 case CONTEXT_SYSTEM:
3979 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3980 $this->load_front_page_settings(($context->id == $this->context->id));
3982 break;
3983 case CONTEXT_COURSECAT:
3984 $this->load_category_settings();
3985 break;
3986 case CONTEXT_COURSE:
3987 if ($this->page->course->id != $SITE->id) {
3988 $this->load_course_settings(($context->id == $this->context->id));
3989 } else {
3990 $this->load_front_page_settings(($context->id == $this->context->id));
3992 break;
3993 case CONTEXT_MODULE:
3994 $this->load_module_settings();
3995 $this->load_course_settings();
3996 break;
3997 case CONTEXT_USER:
3998 if ($this->page->course->id != $SITE->id) {
3999 $this->load_course_settings();
4001 break;
4004 $usersettings = $this->load_user_settings($this->page->course->id);
4006 $adminsettings = false;
4007 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
4008 $isadminpage = $this->is_admin_tree_needed();
4010 if (has_capability('moodle/site:configview', context_system::instance())) {
4011 if (has_capability('moodle/site:config', context_system::instance())) {
4012 // Make sure this works even if config capability changes on the fly
4013 // and also make it fast for admin right after login.
4014 $SESSION->load_navigation_admin = 1;
4015 if ($isadminpage) {
4016 $adminsettings = $this->load_administration_settings();
4019 } else if (!isset($SESSION->load_navigation_admin)) {
4020 $adminsettings = $this->load_administration_settings();
4021 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
4023 } else if ($SESSION->load_navigation_admin) {
4024 if ($isadminpage) {
4025 $adminsettings = $this->load_administration_settings();
4029 // Print empty navigation node, if needed.
4030 if ($SESSION->load_navigation_admin && !$isadminpage) {
4031 if ($adminsettings) {
4032 // Do not print settings tree on pages that do not need it, this helps with performance.
4033 $adminsettings->remove();
4034 $adminsettings = false;
4036 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4037 self::TYPE_SITE_ADMIN, null, 'siteadministration');
4038 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' .
4039 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
4040 $siteadminnode->requiresajaxloading = 'true';
4045 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
4046 $adminsettings->force_open();
4047 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
4048 $usersettings->force_open();
4051 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4052 $this->load_local_plugin_settings();
4054 foreach ($this->children as $key=>$node) {
4055 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) {
4056 // Site administration is shown as link.
4057 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
4058 continue;
4060 $node->remove();
4063 $this->initialised = true;
4066 * Override the parent function so that we can add preceeding hr's and set a
4067 * root node class against all first level element
4069 * It does this by first calling the parent's add method {@link navigation_node::add()}
4070 * and then proceeds to use the key to set class and hr
4072 * @param string $text text to be used for the link.
4073 * @param string|moodle_url $url url for the new node
4074 * @param int $type the type of node navigation_node::TYPE_*
4075 * @param string $shorttext
4076 * @param string|int $key a key to access the node by.
4077 * @param pix_icon $icon An icon that appears next to the node.
4078 * @return navigation_node with the new node added to it.
4080 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4081 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
4082 $node->add_class('root_node');
4083 return $node;
4087 * This function allows the user to add something to the start of the settings
4088 * navigation, which means it will be at the top of the settings navigation block
4090 * @param string $text text to be used for the link.
4091 * @param string|moodle_url $url url for the new node
4092 * @param int $type the type of node navigation_node::TYPE_*
4093 * @param string $shorttext
4094 * @param string|int $key a key to access the node by.
4095 * @param pix_icon $icon An icon that appears next to the node.
4096 * @return navigation_node $node with the new node added to it.
4098 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
4099 $children = $this->children;
4100 $childrenclass = get_class($children);
4101 $this->children = new $childrenclass;
4102 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4103 foreach ($children as $child) {
4104 $this->children->add($child);
4106 return $node;
4110 * Does this page require loading of full admin tree or is
4111 * it enough rely on AJAX?
4113 * @return bool
4115 protected function is_admin_tree_needed() {
4116 if (self::$loadadmintree) {
4117 // Usually external admin page or settings page.
4118 return true;
4121 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
4122 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4123 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
4124 return false;
4126 return true;
4129 return false;
4133 * Load the site administration tree
4135 * This function loads the site administration tree by using the lib/adminlib library functions
4137 * @param navigation_node $referencebranch A reference to a branch in the settings
4138 * navigation tree
4139 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4140 * tree and start at the beginning
4141 * @return mixed A key to access the admin tree by
4143 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
4144 global $CFG;
4146 // Check if we are just starting to generate this navigation.
4147 if ($referencebranch === null) {
4149 // Require the admin lib then get an admin structure
4150 if (!function_exists('admin_get_root')) {
4151 require_once($CFG->dirroot.'/lib/adminlib.php');
4153 $adminroot = admin_get_root(false, false);
4154 // This is the active section identifier
4155 $this->adminsection = $this->page->url->param('section');
4157 // Disable the navigation from automatically finding the active node
4158 navigation_node::$autofindactive = false;
4159 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root');
4160 foreach ($adminroot->children as $adminbranch) {
4161 $this->load_administration_settings($referencebranch, $adminbranch);
4163 navigation_node::$autofindactive = true;
4165 // Use the admin structure to locate the active page
4166 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
4167 $currentnode = $this;
4168 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
4169 $currentnode = $currentnode->get($pathkey);
4171 if ($currentnode) {
4172 $currentnode->make_active();
4174 } else {
4175 $this->scan_for_active_node($referencebranch);
4177 return $referencebranch;
4178 } else if ($adminbranch->check_access()) {
4179 // We have a reference branch that we can access and is not hidden `hurrah`
4180 // Now we need to display it and any children it may have
4181 $url = null;
4182 $icon = null;
4183 if ($adminbranch instanceof admin_settingpage) {
4184 $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
4185 } else if ($adminbranch instanceof admin_externalpage) {
4186 $url = $adminbranch->url;
4187 } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
4188 $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
4191 // Add the branch
4192 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
4194 if ($adminbranch->is_hidden()) {
4195 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
4196 $reference->add_class('hidden');
4197 } else {
4198 $reference->display = false;
4202 // Check if we are generating the admin notifications and whether notificiations exist
4203 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
4204 $reference->add_class('criticalnotification');
4206 // Check if this branch has children
4207 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
4208 foreach ($adminbranch->children as $branch) {
4209 // Generate the child branches as well now using this branch as the reference
4210 $this->load_administration_settings($reference, $branch);
4212 } else {
4213 $reference->icon = new pix_icon('i/settings', '');
4219 * This function recursivily scans nodes until it finds the active node or there
4220 * are no more nodes.
4221 * @param navigation_node $node
4223 protected function scan_for_active_node(navigation_node $node) {
4224 if (!$node->check_if_active() && $node->children->count()>0) {
4225 foreach ($node->children as &$child) {
4226 $this->scan_for_active_node($child);
4232 * Gets a navigation node given an array of keys that represent the path to
4233 * the desired node.
4235 * @param array $path
4236 * @return navigation_node|false
4238 protected function get_by_path(array $path) {
4239 $node = $this->get(array_shift($path));
4240 foreach ($path as $key) {
4241 $node->get($key);
4243 return $node;
4247 * This function loads the course settings that are available for the user
4249 * @param bool $forceopen If set to true the course node will be forced open
4250 * @return navigation_node|false
4252 protected function load_course_settings($forceopen = false) {
4253 global $CFG;
4254 require_once($CFG->dirroot . '/course/lib.php');
4256 $course = $this->page->course;
4257 $coursecontext = context_course::instance($course->id);
4258 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4260 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4262 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
4263 if ($forceopen) {
4264 $coursenode->force_open();
4268 if ($adminoptions->update) {
4269 // Add the course settings link
4270 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
4271 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
4274 if ($this->page->user_allowed_editing()) {
4275 // Add the turn on/off settings
4277 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
4278 // We are on the course page, retain the current page params e.g. section.
4279 $baseurl = clone($this->page->url);
4280 $baseurl->param('sesskey', sesskey());
4281 } else {
4282 // Edit on the main course page.
4283 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
4286 $editurl = clone($baseurl);
4287 if ($this->page->user_is_editing()) {
4288 $editurl->param('edit', 'off');
4289 $editstring = get_string('turneditingoff');
4290 } else {
4291 $editurl->param('edit', 'on');
4292 $editstring = get_string('turneditingon');
4294 $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4297 if ($adminoptions->editcompletion) {
4298 // Add the course completion settings link
4299 $url = new moodle_url('/course/completion.php', array('id' => $course->id));
4300 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null,
4301 new pix_icon('i/settings', ''));
4304 if (!$adminoptions->update && $adminoptions->tags) {
4305 $url = new moodle_url('/course/tags.php', array('id' => $course->id));
4306 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', ''));
4309 // add enrol nodes
4310 enrol_add_course_navigation($coursenode, $course);
4312 // Manage filters
4313 if ($adminoptions->filters) {
4314 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
4315 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
4318 // View course reports.
4319 if ($adminoptions->reports) {
4320 $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'coursereports',
4321 new pix_icon('i/stats', ''));
4322 $coursereports = core_component::get_plugin_list('coursereport');
4323 foreach ($coursereports as $report => $dir) {
4324 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
4325 if (file_exists($libfile)) {
4326 require_once($libfile);
4327 $reportfunction = $report.'_report_extend_navigation';
4328 if (function_exists($report.'_report_extend_navigation')) {
4329 $reportfunction($reportnav, $course, $coursecontext);
4334 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4335 foreach ($reports as $reportfunction) {
4336 $reportfunction($reportnav, $course, $coursecontext);
4340 // Check if we can view the gradebook's setup page.
4341 if ($adminoptions->gradebook) {
4342 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id));
4343 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING,
4344 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4347 // Add outcome if permitted
4348 if ($adminoptions->outcomes) {
4349 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
4350 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
4353 //Add badges navigation
4354 if ($adminoptions->badges) {
4355 require_once($CFG->libdir .'/badgeslib.php');
4356 badges_add_course_navigation($coursenode, $course);
4359 // Backup this course
4360 if ($adminoptions->backup) {
4361 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
4362 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
4365 // Restore to this course
4366 if ($adminoptions->restore) {
4367 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
4368 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
4371 // Import data from other courses
4372 if ($adminoptions->import) {
4373 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
4374 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
4377 // Publish course on a hub
4378 if ($adminoptions->publish) {
4379 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
4380 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
4383 // Reset this course
4384 if ($adminoptions->reset) {
4385 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
4386 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', ''));
4389 // Questions
4390 require_once($CFG->libdir . '/questionlib.php');
4391 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4393 if ($adminoptions->update) {
4394 // Repository Instances
4395 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
4396 require_once($CFG->dirroot . '/repository/lib.php');
4397 $editabletypes = repository::get_editable_types($coursecontext);
4398 $haseditabletypes = !empty($editabletypes);
4399 unset($editabletypes);
4400 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
4401 } else {
4402 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
4404 if ($haseditabletypes) {
4405 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
4406 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
4410 // Manage files
4411 if ($adminoptions->files) {
4412 // hidden in new courses and courses where legacy files were turned off
4413 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
4414 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
4418 // Let plugins hook into course navigation.
4419 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4420 foreach ($pluginsfunction as $plugintype => $plugins) {
4421 // Ignore the report plugin as it was already loaded above.
4422 if ($plugintype == 'report') {
4423 continue;
4425 foreach ($plugins as $pluginfunction) {
4426 $pluginfunction($coursenode, $course, $coursecontext);
4430 // Return we are done
4431 return $coursenode;
4435 * This function calls the module function to inject module settings into the
4436 * settings navigation tree.
4438 * This only gets called if there is a corrosponding function in the modules
4439 * lib file.
4441 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4443 * @return navigation_node|false
4445 protected function load_module_settings() {
4446 global $CFG;
4448 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
4449 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
4450 $this->page->set_cm($cm, $this->page->course);
4453 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
4454 if (file_exists($file)) {
4455 require_once($file);
4458 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
4459 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH;
4460 $modulenode->force_open();
4462 // Settings for the module
4463 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
4464 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
4465 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
4467 // Assign local roles
4468 if (count(get_assignable_roles($this->page->cm->context))>0) {
4469 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
4470 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
4472 // Override roles
4473 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
4474 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
4475 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
4477 // Check role permissions
4478 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
4479 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
4480 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
4482 // Manage filters
4483 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
4484 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
4485 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
4487 // Add reports
4488 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4489 foreach ($reports as $reportfunction) {
4490 $reportfunction($modulenode, $this->page->cm);
4492 // Add a backup link
4493 $featuresfunc = $this->page->activityname.'_supports';
4494 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
4495 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
4496 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
4499 // Restore this activity
4500 $featuresfunc = $this->page->activityname.'_supports';
4501 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
4502 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
4503 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
4506 // Allow the active advanced grading method plugin to append its settings
4507 $featuresfunc = $this->page->activityname.'_supports';
4508 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
4509 require_once($CFG->dirroot.'/grade/grading/lib.php');
4510 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname);
4511 $gradingman->extend_settings_navigation($this, $modulenode);
4514 $function = $this->page->activityname.'_extend_settings_navigation';
4515 if (function_exists($function)) {
4516 $function($this, $modulenode);
4519 // Remove the module node if there are no children.
4520 if ($modulenode->children->count() <= 0) {
4521 $modulenode->remove();
4524 return $modulenode;
4528 * Loads the user settings block of the settings nav
4530 * This function is simply works out the userid and whether we need to load
4531 * just the current users profile settings, or the current user and the user the
4532 * current user is viewing.
4534 * This function has some very ugly code to work out the user, if anyone has
4535 * any bright ideas please feel free to intervene.
4537 * @param int $courseid The course id of the current course
4538 * @return navigation_node|false
4540 protected function load_user_settings($courseid = SITEID) {
4541 global $USER, $CFG;
4543 if (isguestuser() || !isloggedin()) {
4544 return false;
4547 $navusers = $this->page->navigation->get_extending_users();
4549 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
4550 $usernode = null;
4551 foreach ($this->userstoextendfor as $userid) {
4552 if ($userid == $USER->id) {
4553 continue;
4555 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4556 if (is_null($usernode)) {
4557 $usernode = $node;
4560 foreach ($navusers as $user) {
4561 if ($user->id == $USER->id) {
4562 continue;
4564 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
4565 if (is_null($usernode)) {
4566 $usernode = $node;
4569 $this->generate_user_settings($courseid, $USER->id);
4570 } else {
4571 $usernode = $this->generate_user_settings($courseid, $USER->id);
4573 return $usernode;
4577 * Extends the settings navigation for the given user.
4579 * Note: This method gets called automatically if you call
4580 * $PAGE->navigation->extend_for_user($userid)
4582 * @param int $userid
4584 public function extend_for_user($userid) {
4585 global $CFG;
4587 if (!in_array($userid, $this->userstoextendfor)) {
4588 $this->userstoextendfor[] = $userid;
4589 if ($this->initialised) {
4590 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
4591 $children = array();
4592 foreach ($this->children as $child) {
4593 $children[] = $child;
4595 array_unshift($children, array_pop($children));
4596 $this->children = new navigation_node_collection();
4597 foreach ($children as $child) {
4598 $this->children->add($child);
4605 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4606 * what can be shown/done
4608 * @param int $courseid The current course' id
4609 * @param int $userid The user id to load for
4610 * @param string $gstitle The string to pass to get_string for the branch title
4611 * @return navigation_node|false
4613 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4614 global $DB, $CFG, $USER, $SITE;
4616 if ($courseid != $SITE->id) {
4617 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
4618 $course = $this->page->course;
4619 } else {
4620 $select = context_helper::get_preload_record_columns_sql('ctx');
4621 $sql = "SELECT c.*, $select
4622 FROM {course} c
4623 JOIN {context} ctx ON c.id = ctx.instanceid
4624 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4625 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
4626 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
4627 context_helper::preload_from_record($course);
4629 } else {
4630 $course = $SITE;
4633 $coursecontext = context_course::instance($course->id); // Course context
4634 $systemcontext = context_system::instance();
4635 $currentuser = ($USER->id == $userid);
4637 if ($currentuser) {
4638 $user = $USER;
4639 $usercontext = context_user::instance($user->id); // User context
4640 } else {
4641 $select = context_helper::get_preload_record_columns_sql('ctx');
4642 $sql = "SELECT u.*, $select
4643 FROM {user} u
4644 JOIN {context} ctx ON u.id = ctx.instanceid
4645 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4646 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
4647 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
4648 if (!$user) {
4649 return false;
4651 context_helper::preload_from_record($user);
4653 // Check that the user can view the profile
4654 $usercontext = context_user::instance($user->id); // User context
4655 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4657 if ($course->id == $SITE->id) {
4658 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4659 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4660 return false;
4662 } else {
4663 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4664 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
4665 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
4666 return false;
4668 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4669 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
4670 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4671 if ($courseid == $this->page->course->id) {
4672 $mygroups = get_fast_modinfo($this->page->course)->groups;
4673 } else {
4674 $mygroups = groups_get_user_groups($courseid);
4676 $usergroups = groups_get_user_groups($courseid, $userid);
4677 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4678 return false;
4684 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
4686 $key = $gstitle;
4687 $prefurl = new moodle_url('/user/preferences.php');
4688 if ($gstitle != 'usercurrentsettings') {
4689 $key .= $userid;
4690 $prefurl->param('userid', $userid);
4693 // Add a user setting branch.
4694 if ($gstitle == 'usercurrentsettings') {
4695 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
4696 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4697 // breadcrumb.
4698 $dashboard->display = false;
4699 if (get_home_page() == HOMEPAGE_MY) {
4700 $dashboard->mainnavonly = true;
4703 $iscurrentuser = ($user->id == $USER->id);
4705 $baseargs = array('id' => $user->id);
4706 if ($course->id != $SITE->id && !$iscurrentuser) {
4707 $baseargs['course'] = $course->id;
4708 $issitecourse = false;
4709 } else {
4710 // Load all categories and get the context for the system.
4711 $issitecourse = true;
4714 // Add the user profile to the dashboard.
4715 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4716 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
4718 if (!empty($CFG->navadduserpostslinks)) {
4719 // Add nodes for forum posts and discussions if the user can view either or both
4720 // There are no capability checks here as the content of the page is based
4721 // purely on the forums the current user has access too.
4722 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4723 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4724 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4725 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4728 // Add blog nodes.
4729 if (!empty($CFG->enableblogs)) {
4730 if (!$this->cache->cached('userblogoptions'.$user->id)) {
4731 require_once($CFG->dirroot.'/blog/lib.php');
4732 // Get all options for the user.
4733 $options = blog_get_options_for_user($user);
4734 $this->cache->set('userblogoptions'.$user->id, $options);
4735 } else {
4736 $options = $this->cache->{'userblogoptions'.$user->id};
4739 if (count($options) > 0) {
4740 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
4741 foreach ($options as $type => $option) {
4742 if ($type == "rss") {
4743 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null,
4744 new pix_icon('i/rss', ''));
4745 } else {
4746 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
4752 // Add the messages link.
4753 // It is context based so can appear in the user's profile and in course participants information.
4754 if (!empty($CFG->messaging)) {
4755 $messageargs = array('user1' => $USER->id);
4756 if ($USER->id != $user->id) {
4757 $messageargs['user2'] = $user->id;
4759 $url = new moodle_url('/message/index.php', $messageargs);
4760 $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
4763 // Add the "My private files" link.
4764 // This link doesn't have a unique display for course context so only display it under the user's profile.
4765 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4766 $url = new moodle_url('/user/files.php');
4767 $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
4770 // Add a node to view the users notes if permitted.
4771 if (!empty($CFG->enablenotes) &&
4772 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4773 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
4774 if ($coursecontext->instanceid != SITEID) {
4775 $url->param('course', $coursecontext->instanceid);
4777 $profilenode->add(get_string('notes', 'notes'), $url);
4780 // Show the grades node.
4781 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
4782 require_once($CFG->dirroot . '/user/lib.php');
4783 // Set the grades node to link to the "Grades" page.
4784 if ($course->id == SITEID) {
4785 $url = user_mygrades_url($user->id, $course->id);
4786 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4787 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
4789 $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
4792 // Let plugins hook into user navigation.
4793 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4794 foreach ($pluginsfunction as $plugintype => $plugins) {
4795 if ($plugintype != 'report') {
4796 foreach ($plugins as $pluginfunction) {
4797 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4802 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4803 $dashboard->add_node($usersetting);
4804 } else {
4805 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
4806 $usersetting->display = false;
4808 $usersetting->id = 'usersettings';
4810 // Check if the user has been deleted.
4811 if ($user->deleted) {
4812 if (!has_capability('moodle/user:update', $coursecontext)) {
4813 // We can't edit the user so just show the user deleted message.
4814 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
4815 } else {
4816 // We can edit the user so show the user deleted message and link it to the profile.
4817 if ($course->id == $SITE->id) {
4818 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
4819 } else {
4820 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
4822 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
4824 return true;
4827 $userauthplugin = false;
4828 if (!empty($user->auth)) {
4829 $userauthplugin = get_auth_plugin($user->auth);
4832 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
4834 // Add the profile edit link.
4835 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4836 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) &&
4837 has_capability('moodle/user:update', $systemcontext)) {
4838 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
4839 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4840 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4841 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4842 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4843 $url = $userauthplugin->edit_profile_url();
4844 if (empty($url)) {
4845 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
4847 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile');
4852 // Change password link.
4853 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() &&
4854 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4855 $passwordchangeurl = $userauthplugin->change_password_url();
4856 if (empty($passwordchangeurl)) {
4857 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
4859 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
4862 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4863 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4864 has_capability('moodle/user:editprofile', $usercontext)) {
4865 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
4866 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
4869 $pluginmanager = core_plugin_manager::instance();
4870 $enabled = $pluginmanager->get_enabled_plugins('mod');
4871 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4872 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4873 has_capability('moodle/user:editprofile', $usercontext)) {
4874 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
4875 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
4878 $editors = editors_get_enabled();
4879 if (count($editors) > 1) {
4880 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4881 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4882 has_capability('moodle/user:editprofile', $usercontext)) {
4883 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
4884 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
4889 // Add "Course preferences" link.
4890 if (isloggedin() && !isguestuser($user)) {
4891 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4892 has_capability('moodle/user:editprofile', $usercontext)) {
4893 $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
4894 $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
4898 // Add "Calendar preferences" link.
4899 if (isloggedin() && !isguestuser($user)) {
4900 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4901 has_capability('moodle/user:editprofile', $usercontext)) {
4902 $url = new moodle_url('/user/calendar.php', array('id' => $user->id));
4903 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar');
4907 // View the roles settings.
4908 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4909 'moodle/role:manage'), $usercontext)) {
4910 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
4912 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
4913 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
4915 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
4917 if (!empty($assignableroles)) {
4918 $url = new moodle_url('/admin/roles/assign.php',
4919 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4920 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
4923 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
4924 $url = new moodle_url('/admin/roles/permissions.php',
4925 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4926 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
4929 $url = new moodle_url('/admin/roles/check.php',
4930 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
4931 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
4934 // Repositories.
4935 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
4936 require_once($CFG->dirroot . '/repository/lib.php');
4937 $editabletypes = repository::get_editable_types($usercontext);
4938 $haseditabletypes = !empty($editabletypes);
4939 unset($editabletypes);
4940 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
4941 } else {
4942 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
4944 if ($haseditabletypes) {
4945 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
4946 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4947 array('contextid' => $usercontext->id)));
4950 // Portfolio.
4951 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
4952 require_once($CFG->libdir . '/portfoliolib.php');
4953 if (portfolio_has_visible_instances()) {
4954 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
4956 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
4957 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
4959 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
4960 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
4964 $enablemanagetokens = false;
4965 if (!empty($CFG->enablerssfeeds)) {
4966 $enablemanagetokens = true;
4967 } else if (!is_siteadmin($USER->id)
4968 && !empty($CFG->enablewebservices)
4969 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
4970 $enablemanagetokens = true;
4972 // Security keys.
4973 if ($currentuser && $enablemanagetokens) {
4974 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4975 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
4978 // Messaging.
4979 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) &&
4980 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
4981 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id));
4982 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id));
4983 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING);
4984 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING);
4987 // Blogs.
4988 if ($currentuser && !empty($CFG->enableblogs)) {
4989 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
4990 if (has_capability('moodle/blog:view', $systemcontext)) {
4991 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
4992 navigation_node::TYPE_SETTING);
4994 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 &&
4995 has_capability('moodle/blog:manageexternal', $systemcontext)) {
4996 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
4997 navigation_node::TYPE_SETTING);
4998 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
4999 navigation_node::TYPE_SETTING);
5001 // Remove the blog node if empty.
5002 $blog->trim_if_empty();
5005 // Badges.
5006 if ($currentuser && !empty($CFG->enablebadges)) {
5007 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
5008 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5009 $url = new moodle_url('/badges/mybadges.php');
5010 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
5012 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5013 navigation_node::TYPE_SETTING);
5014 if (!empty($CFG->badges_allowexternalbackpack)) {
5015 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5016 navigation_node::TYPE_SETTING);
5020 // Let plugins hook into user settings navigation.
5021 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5022 foreach ($pluginsfunction as $plugintype => $plugins) {
5023 foreach ($plugins as $pluginfunction) {
5024 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5028 return $usersetting;
5032 * Loads block specific settings in the navigation
5034 * @return navigation_node
5036 protected function load_block_settings() {
5037 global $CFG;
5039 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
5040 $blocknode->force_open();
5042 // Assign local roles
5043 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) {
5044 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id));
5045 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null,
5046 'roles', new pix_icon('i/assignroles', ''));
5049 // Override roles
5050 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
5051 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
5052 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null,
5053 'permissions', new pix_icon('i/permissions', ''));
5055 // Check role permissions
5056 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
5057 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
5058 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null,
5059 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5062 return $blocknode;
5066 * Loads category specific settings in the navigation
5068 * @return navigation_node
5070 protected function load_category_settings() {
5071 global $CFG;
5073 // We can land here while being in the context of a block, in which case we
5074 // should get the parent context which should be the category one. See self::initialise().
5075 if ($this->context->contextlevel == CONTEXT_BLOCK) {
5076 $catcontext = $this->context->get_parent_context();
5077 } else {
5078 $catcontext = $this->context;
5081 // Let's make sure that we always have the right context when getting here.
5082 if ($catcontext->contextlevel != CONTEXT_COURSECAT) {
5083 throw new coding_exception('Unexpected context while loading category settings.');
5086 $categorynodetype = navigation_node::TYPE_CONTAINER;
5087 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5088 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH;
5089 $categorynode->force_open();
5091 if (can_edit_in_category($catcontext->instanceid)) {
5092 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid));
5093 $editstring = get_string('managecategorythis');
5094 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5097 if (has_capability('moodle/category:manage', $catcontext)) {
5098 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid));
5099 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
5101 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid));
5102 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5105 // Assign local roles
5106 $assignableroles = get_assignable_roles($catcontext);
5107 if (!empty($assignableroles)) {
5108 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id));
5109 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
5112 // Override roles
5113 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5114 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id));
5115 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
5117 // Check role permissions
5118 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5119 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5120 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id));
5121 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5124 // Cohorts
5125 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5126 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5127 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
5130 // Manage filters
5131 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5132 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id));
5133 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
5136 // Restore.
5137 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5138 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id));
5139 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
5142 // Let plugins hook into category settings navigation.
5143 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5144 foreach ($pluginsfunction as $plugintype => $plugins) {
5145 foreach ($plugins as $pluginfunction) {
5146 $pluginfunction($categorynode, $catcontext);
5150 return $categorynode;
5154 * Determine whether the user is assuming another role
5156 * This function checks to see if the user is assuming another role by means of
5157 * role switching. In doing this we compare each RSW key (context path) against
5158 * the current context path. This ensures that we can provide the switching
5159 * options against both the course and any page shown under the course.
5161 * @return bool|int The role(int) if the user is in another role, false otherwise
5163 protected function in_alternative_role() {
5164 global $USER;
5165 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
5166 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
5167 return $USER->access['rsw'][$this->page->context->path];
5169 foreach ($USER->access['rsw'] as $key=>$role) {
5170 if (strpos($this->context->path,$key)===0) {
5171 return $role;
5175 return false;
5179 * This function loads all of the front page settings into the settings navigation.
5180 * This function is called when the user is on the front page, or $COURSE==$SITE
5181 * @param bool $forceopen (optional)
5182 * @return navigation_node
5184 protected function load_front_page_settings($forceopen = false) {
5185 global $SITE, $CFG;
5186 require_once($CFG->dirroot . '/course/lib.php');
5188 $course = clone($SITE);
5189 $coursecontext = context_course::instance($course->id); // Course context
5190 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5192 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
5193 if ($forceopen) {
5194 $frontpage->force_open();
5196 $frontpage->id = 'frontpagesettings';
5198 if ($this->page->user_allowed_editing()) {
5200 // Add the turn on/off settings
5201 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
5202 if ($this->page->user_is_editing()) {
5203 $url->param('edit', 'off');
5204 $editstring = get_string('turneditingoff');
5205 } else {
5206 $url->param('edit', 'on');
5207 $editstring = get_string('turneditingon');
5209 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
5212 if ($adminoptions->update) {
5213 // Add the course settings link
5214 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5215 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
5218 // add enrol nodes
5219 enrol_add_course_navigation($frontpage, $course);
5221 // Manage filters
5222 if ($adminoptions->filters) {
5223 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
5224 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
5227 // View course reports.
5228 if ($adminoptions->reports) {
5229 $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, 'frontpagereports',
5230 new pix_icon('i/stats', ''));
5231 $coursereports = core_component::get_plugin_list('coursereport');
5232 foreach ($coursereports as $report=>$dir) {
5233 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
5234 if (file_exists($libfile)) {
5235 require_once($libfile);
5236 $reportfunction = $report.'_report_extend_navigation';
5237 if (function_exists($report.'_report_extend_navigation')) {
5238 $reportfunction($frontpagenav, $course, $coursecontext);
5243 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5244 foreach ($reports as $reportfunction) {
5245 $reportfunction($frontpagenav, $course, $coursecontext);
5249 // Backup this course
5250 if ($adminoptions->backup) {
5251 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
5252 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
5255 // Restore to this course
5256 if ($adminoptions->restore) {
5257 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
5258 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
5261 // Questions
5262 require_once($CFG->libdir . '/questionlib.php');
5263 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5265 // Manage files
5266 if ($adminoptions->files) {
5267 //hiden in new installs
5268 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
5269 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
5272 // Let plugins hook into frontpage navigation.
5273 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5274 foreach ($pluginsfunction as $plugintype => $plugins) {
5275 foreach ($plugins as $pluginfunction) {
5276 $pluginfunction($frontpage, $course, $coursecontext);
5280 return $frontpage;
5284 * This function gives local plugins an opportunity to modify the settings navigation.
5286 protected function load_local_plugin_settings() {
5288 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5289 $function($this, $this->context);
5294 * This function marks the cache as volatile so it is cleared during shutdown
5296 public function clear_cache() {
5297 $this->cache->volatile();
5301 * Checks to see if there are child nodes available in the specific user's preference node.
5302 * If so, then they have the appropriate permissions view this user's preferences.
5304 * @since Moodle 2.9.3
5305 * @param int $userid The user's ID.
5306 * @return bool True if child nodes exist to view, otherwise false.
5308 public function can_view_user_preferences($userid) {
5309 if (is_siteadmin()) {
5310 return true;
5312 // See if any nodes are present in the preferences section for this user.
5313 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5314 if ($preferencenode && $preferencenode->has_children()) {
5315 // Run through each child node.
5316 foreach ($preferencenode->children as $childnode) {
5317 // If the child node has children then this user has access to a link in the preferences page.
5318 if ($childnode->has_children()) {
5319 return true;
5323 // No links found for the user to access on the preferences page.
5324 return false;
5329 * Class used to populate site admin navigation for ajax.
5331 * @package core
5332 * @category navigation
5333 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5336 class settings_navigation_ajax extends settings_navigation {
5338 * Constructs the navigation for use in an AJAX request
5340 * @param moodle_page $page
5342 public function __construct(moodle_page &$page) {
5343 $this->page = $page;
5344 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
5345 $this->children = new navigation_node_collection();
5346 $this->initialise();
5350 * Initialise the site admin navigation.
5352 * @return array An array of the expandable nodes
5354 public function initialise() {
5355 if ($this->initialised || during_initial_install()) {
5356 return false;
5358 $this->context = $this->page->context;
5359 $this->load_administration_settings();
5361 // Check if local plugins is adding node to site admin.
5362 $this->load_local_plugin_settings();
5364 $this->initialised = true;
5369 * Simple class used to output a navigation branch in XML
5371 * @package core
5372 * @category navigation
5373 * @copyright 2009 Sam Hemelryk
5374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5376 class navigation_json {
5377 /** @var array An array of different node types */
5378 protected $nodetype = array('node','branch');
5379 /** @var array An array of node keys and types */
5380 protected $expandable = array();
5382 * Turns a branch and all of its children into XML
5384 * @param navigation_node $branch
5385 * @return string XML string
5387 public function convert($branch) {
5388 $xml = $this->convert_child($branch);
5389 return $xml;
5392 * Set the expandable items in the array so that we have enough information
5393 * to attach AJAX events
5394 * @param array $expandable
5396 public function set_expandable($expandable) {
5397 foreach ($expandable as $node) {
5398 $this->expandable[$node['key'].':'.$node['type']] = $node;
5402 * Recusively converts a child node and its children to XML for output
5404 * @param navigation_node $child The child to convert
5405 * @param int $depth Pointlessly used to track the depth of the XML structure
5406 * @return string JSON
5408 protected function convert_child($child, $depth=1) {
5409 if (!$child->display) {
5410 return '';
5412 $attributes = array();
5413 $attributes['id'] = $child->id;
5414 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
5415 $attributes['type'] = $child->type;
5416 $attributes['key'] = $child->key;
5417 $attributes['class'] = $child->get_css_type();
5418 $attributes['requiresajaxloading'] = $child->requiresajaxloading;
5420 if ($child->icon instanceof pix_icon) {
5421 $attributes['icon'] = array(
5422 'component' => $child->icon->component,
5423 'pix' => $child->icon->pix,
5425 foreach ($child->icon->attributes as $key=>$value) {
5426 if ($key == 'class') {
5427 $attributes['icon']['classes'] = explode(' ', $value);
5428 } else if (!array_key_exists($key, $attributes['icon'])) {
5429 $attributes['icon'][$key] = $value;
5433 } else if (!empty($child->icon)) {
5434 $attributes['icon'] = (string)$child->icon;
5437 if ($child->forcetitle || $child->title !== $child->text) {
5438 $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
5440 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
5441 $attributes['expandable'] = $child->key;
5442 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
5445 if (count($child->classes)>0) {
5446 $attributes['class'] .= ' '.join(' ',$child->classes);
5448 if (is_string($child->action)) {
5449 $attributes['link'] = $child->action;
5450 } else if ($child->action instanceof moodle_url) {
5451 $attributes['link'] = $child->action->out();
5452 } else if ($child->action instanceof action_link) {
5453 $attributes['link'] = $child->action->url->out();
5455 $attributes['hidden'] = ($child->hidden);
5456 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
5457 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
5459 if ($child->children->count() > 0) {
5460 $attributes['children'] = array();
5461 foreach ($child->children as $subchild) {
5462 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
5466 if ($depth > 1) {
5467 return $attributes;
5468 } else {
5469 return json_encode($attributes);
5475 * The cache class used by global navigation and settings navigation.
5477 * It is basically an easy access point to session with a bit of smarts to make
5478 * sure that the information that is cached is valid still.
5480 * Example use:
5481 * <code php>
5482 * if (!$cache->viewdiscussion()) {
5483 * // Code to do stuff and produce cachable content
5484 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5486 * $content = $cache->viewdiscussion;
5487 * </code>
5489 * @package core
5490 * @category navigation
5491 * @copyright 2009 Sam Hemelryk
5492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5494 class navigation_cache {
5495 /** @var int represents the time created */
5496 protected $creation;
5497 /** @var array An array of session keys */
5498 protected $session;
5500 * The string to use to segregate this particular cache. It can either be
5501 * unique to start a fresh cache or if you want to share a cache then make
5502 * it the string used in the original cache.
5503 * @var string
5505 protected $area;
5506 /** @var int a time that the information will time out */
5507 protected $timeout;
5508 /** @var stdClass The current context */
5509 protected $currentcontext;
5510 /** @var int cache time information */
5511 const CACHETIME = 0;
5512 /** @var int cache user id */
5513 const CACHEUSERID = 1;
5514 /** @var int cache value */
5515 const CACHEVALUE = 2;
5516 /** @var null|array An array of navigation cache areas to expire on shutdown */
5517 public static $volatilecaches;
5520 * Contructor for the cache. Requires two arguments
5522 * @param string $area The string to use to segregate this particular cache
5523 * it can either be unique to start a fresh cache or if you want
5524 * to share a cache then make it the string used in the original
5525 * cache
5526 * @param int $timeout The number of seconds to time the information out after
5528 public function __construct($area, $timeout=1800) {
5529 $this->creation = time();
5530 $this->area = $area;
5531 $this->timeout = time() - $timeout;
5532 if (rand(0,100) === 0) {
5533 $this->garbage_collection();
5538 * Used to set up the cache within the SESSION.
5540 * This is called for each access and ensure that we don't put anything into the session before
5541 * it is required.
5543 protected function ensure_session_cache_initialised() {
5544 global $SESSION;
5545 if (empty($this->session)) {
5546 if (!isset($SESSION->navcache)) {
5547 $SESSION->navcache = new stdClass;
5549 if (!isset($SESSION->navcache->{$this->area})) {
5550 $SESSION->navcache->{$this->area} = array();
5552 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
5557 * Magic Method to retrieve something by simply calling using = cache->key
5559 * @param mixed $key The identifier for the information you want out again
5560 * @return void|mixed Either void or what ever was put in
5562 public function __get($key) {
5563 if (!$this->cached($key)) {
5564 return;
5566 $information = $this->session[$key][self::CACHEVALUE];
5567 return unserialize($information);
5571 * Magic method that simply uses {@link set();} to store something in the cache
5573 * @param string|int $key
5574 * @param mixed $information
5576 public function __set($key, $information) {
5577 $this->set($key, $information);
5581 * Sets some information against the cache (session) for later retrieval
5583 * @param string|int $key
5584 * @param mixed $information
5586 public function set($key, $information) {
5587 global $USER;
5588 $this->ensure_session_cache_initialised();
5589 $information = serialize($information);
5590 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
5593 * Check the existence of the identifier in the cache
5595 * @param string|int $key
5596 * @return bool
5598 public function cached($key) {
5599 global $USER;
5600 $this->ensure_session_cache_initialised();
5601 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) {
5602 return false;
5604 return true;
5607 * Compare something to it's equivilant in the cache
5609 * @param string $key
5610 * @param mixed $value
5611 * @param bool $serialise Whether to serialise the value before comparison
5612 * this should only be set to false if the value is already
5613 * serialised
5614 * @return bool If the value is the same false if it is not set or doesn't match
5616 public function compare($key, $value, $serialise = true) {
5617 if ($this->cached($key)) {
5618 if ($serialise) {
5619 $value = serialize($value);
5621 if ($this->session[$key][self::CACHEVALUE] === $value) {
5622 return true;
5625 return false;
5628 * Wipes the entire cache, good to force regeneration
5630 public function clear() {
5631 global $SESSION;
5632 unset($SESSION->navcache);
5633 $this->session = null;
5636 * Checks all cache entries and removes any that have expired, good ole cleanup
5638 protected function garbage_collection() {
5639 if (empty($this->session)) {
5640 return true;
5642 foreach ($this->session as $key=>$cachedinfo) {
5643 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
5644 unset($this->session[$key]);
5650 * Marks the cache as being volatile (likely to change)
5652 * Any caches marked as volatile will be destroyed at the on shutdown by
5653 * {@link navigation_node::destroy_volatile_caches()} which is registered
5654 * as a shutdown function if any caches are marked as volatile.
5656 * @param bool $setting True to destroy the cache false not too
5658 public function volatile($setting = true) {
5659 if (self::$volatilecaches===null) {
5660 self::$volatilecaches = array();
5661 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
5664 if ($setting) {
5665 self::$volatilecaches[$this->area] = $this->area;
5666 } else if (array_key_exists($this->area, self::$volatilecaches)) {
5667 unset(self::$volatilecaches[$this->area]);
5672 * Destroys all caches marked as volatile
5674 * This function is static and works in conjunction with the static volatilecaches
5675 * property of navigation cache.
5676 * Because this function is static it manually resets the cached areas back to an
5677 * empty array.
5679 public static function destroy_volatile_caches() {
5680 global $SESSION;
5681 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
5682 foreach (self::$volatilecaches as $area) {
5683 $SESSION->navcache->{$area} = array();
5685 } else {
5686 $SESSION->navcache = new stdClass;