3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node implements renderable {
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF = 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH = 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN = null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE = 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM = 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY = 10;
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 Setting node type, used only within settings nav 80 */
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER = 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
82 /** @var string|int The identifier for the node, used to retrieve the node */
84 /** @var string The text to use for the node */
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self::TYPE_UNKNOWN;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self::NODETYPE_LEAF;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
132 * Constructs a new navigation_node
134 * @param array|string $properties Either an array of properties or a string to use
135 * as the text for the node
137 public function __construct($properties) {
138 if (is_array($properties)) {
139 // Check the array for each property that we allow to set at construction.
140 // text - The main content for the node
141 // shorttext - A short text if required for the node
142 // icon - The icon to display for the node
143 // type - The type of the node
144 // key - The key to use to identify the node
145 // parent - A reference to the nodes parent
146 // action - The action to attribute to this node, usually a URL to link to
147 if (array_key_exists('text', $properties)) {
148 $this->text = $properties['text'];
150 if (array_key_exists('shorttext', $properties)) {
151 $this->shorttext = $properties['shorttext'];
153 if (!array_key_exists('icon', $properties)) {
154 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
156 $this->icon = $properties['icon'];
157 if ($this->icon instanceof pix_icon) {
158 if (empty($this->icon->attributes['class'])) {
159 $this->icon->attributes['class'] = 'navicon';
161 $this->icon->attributes['class'] .= ' navicon';
164 if (array_key_exists('type', $properties)) {
165 $this->type = $properties['type'];
167 $this->type = self::TYPE_CUSTOM;
169 if (array_key_exists('key', $properties)) {
170 $this->key = $properties['key'];
172 if (array_key_exists('parent', $properties)) {
173 $this->parent = $properties['parent'];
175 // This needs to happen last because of the check_if_active call that occurs
176 if (array_key_exists('action', $properties)) {
177 $this->action = $properties['action'];
178 if (is_string($this->action)) {
179 $this->action = new moodle_url($this->action);
181 if (self::$autofindactive) {
182 $this->check_if_active();
185 } else if (is_string($properties)) {
186 $this->text = $properties;
188 if ($this->text === null) {
189 throw new coding_exception('You must set the text for the node when you create it.');
191 // Default the title to the text
192 $this->title = $this->text;
193 // Instantiate a new navigation node collection for this nodes children
194 $this->children = new navigation_node_collection();
198 * Checks if this node is the active node.
200 * This is determined by comparing the action for the node against the
201 * defined URL for the page. A match will see this node marked as active.
203 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
206 public function check_if_active($strength=URL_MATCH_EXACT) {
207 global $FULLME, $PAGE;
208 // Set fullmeurl if it hasn't already been set
209 if (self::$fullmeurl == null) {
210 if ($PAGE->has_set_url()) {
211 self::override_active_url(new moodle_url($PAGE->url));
213 self::override_active_url(new moodle_url($FULLME));
217 // Compare the action of this node against the fullmeurl
218 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
219 $this->make_active();
226 * This sets the URL that the URL of new nodes get compared to when locating
229 * The active node is the node that matches the URL set here. By default this
230 * is either $PAGE->url or if that hasn't been set $FULLME.
232 * @param moodle_url $url The url to use for the fullmeurl.
234 public static function override_active_url(moodle_url $url) {
235 // Clone the URL, in case the calling script changes their URL later.
236 self::$fullmeurl = new moodle_url($url);
240 * Adds a navigation node as a child of this node.
242 * @param string $text
243 * @param moodle_url|action_link $action
245 * @param string $shorttext
246 * @param string|int $key
247 * @param pix_icon $icon
248 * @return navigation_node
250 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
251 // First convert the nodetype for this node to a branch as it will now have children
252 if ($this->nodetype !== self::NODETYPE_BRANCH) {
253 $this->nodetype = self::NODETYPE_BRANCH;
255 // Properties array used when creating the new navigation node
260 // Set the action if one was provided
261 if ($action!==null) {
262 $itemarray['action'] = $action;
264 // Set the shorttext if one was provided
265 if ($shorttext!==null) {
266 $itemarray['shorttext'] = $shorttext;
268 // Set the icon if one was provided
270 $itemarray['icon'] = $icon;
272 // Default the key to the number of children if not provided
274 $key = $this->children->count();
277 $itemarray['key'] = $key;
278 // Set the parent to this node
279 $itemarray['parent'] = $this;
280 // Add the child using the navigation_node_collections add method
281 $node = $this->children->add(new navigation_node($itemarray));
282 // If the node is a category node or the user is logged in and its a course
283 // then mark this node as a branch (makes it expandable by AJAX)
284 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
285 $node->nodetype = self::NODETYPE_BRANCH;
287 // If this node is hidden mark it's children as hidden also
289 $node->hidden = true;
291 // Return the node (reference returned by $this->children->add()
296 * Searches for a node of the given type with the given key.
298 * This searches this node plus all of its children, and their children....
299 * If you know the node you are looking for is a child of this node then please
300 * use the get method instead.
302 * @param int|string $key The key of the node we are looking for
303 * @param int $type One of navigation_node::TYPE_*
304 * @return navigation_node|false
306 public function find($key, $type) {
307 return $this->children->find($key, $type);
311 * Get ths child of this node that has the given key + (optional) type.
313 * If you are looking for a node and want to search all children + thier children
314 * then please use the find method instead.
316 * @param int|string $key The key of the node we are looking for
317 * @param int $type One of navigation_node::TYPE_*
318 * @return navigation_node|false
320 public function get($key, $type=null) {
321 return $this->children->get($key, $type);
329 public function remove() {
330 return $this->parent->children->remove($this->key, $this->type);
334 * Checks if this node has or could have any children
336 * @return bool Returns true if it has children or could have (by AJAX expansion)
338 public function has_children() {
339 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
343 * Marks this node as active and forces it open.
345 * Important: If you are here because you need to mark a node active to get
346 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
347 * You can use it to specify a different URL to match the active navigation node on
348 * rather than having to locate and manually mark a node active.
350 public function make_active() {
351 $this->isactive = true;
352 $this->add_class('active_tree_node');
354 if ($this->parent !== null) {
355 $this->parent->make_inactive();
360 * Marks a node as inactive and recusised back to the base of the tree
361 * doing the same to all parents.
363 public function make_inactive() {
364 $this->isactive = false;
365 $this->remove_class('active_tree_node');
366 if ($this->parent !== null) {
367 $this->parent->make_inactive();
372 * Forces this node to be open and at the same time forces open all
373 * parents until the root node.
377 public function force_open() {
378 $this->forceopen = true;
379 if ($this->parent !== null) {
380 $this->parent->force_open();
385 * Adds a CSS class to this node.
387 * @param string $class
390 public function add_class($class) {
391 if (!in_array($class, $this->classes)) {
392 $this->classes[] = $class;
398 * Removes a CSS class from this node.
400 * @param string $class
401 * @return bool True if the class was successfully removed.
403 public function remove_class($class) {
404 if (in_array($class, $this->classes)) {
405 $key = array_search($class,$this->classes);
407 unset($this->classes[$key]);
415 * Sets the title for this node and forces Moodle to utilise it.
416 * @param string $title
418 public function title($title) {
419 $this->title = $title;
420 $this->forcetitle = true;
424 * Resets the page specific information on this node if it is being unserialised.
426 public function __wakeup(){
427 $this->forceopen = false;
428 $this->isactive = false;
429 $this->remove_class('active_tree_node');
433 * Checks if this node or any of its children contain the active node.
439 public function contains_active_node() {
440 if ($this->isactive) {
443 foreach ($this->children as $child) {
444 if ($child->isactive || $child->contains_active_node()) {
453 * Finds the active node.
455 * Searches this nodes children plus all of the children for the active node
456 * and returns it if found.
460 * @return navigation_node|false
462 public function find_active_node() {
463 if ($this->isactive) {
466 foreach ($this->children as &$child) {
467 $outcome = $child->find_active_node();
468 if ($outcome !== false) {
477 * Searches all children for the best matching active node
478 * @return navigation_node|false
480 public function search_for_active_node() {
481 if ($this->check_if_active(URL_MATCH_BASE)) {
484 foreach ($this->children as &$child) {
485 $outcome = $child->search_for_active_node();
486 if ($outcome !== false) {
495 * Gets the content for this node.
497 * @param bool $shorttext If true shorttext is used rather than the normal text
500 public function get_content($shorttext=false) {
501 if ($shorttext && $this->shorttext!==null) {
502 return format_string($this->shorttext);
504 return format_string($this->text);
509 * Gets the title to use for this node.
513 public function get_title() {
514 if ($this->forcetitle || $this->action != null){
522 * Gets the CSS class to add to this node to describe its type
526 public function get_css_type() {
527 if (array_key_exists($this->type, $this->namedtypes)) {
528 return 'type_'.$this->namedtypes[$this->type];
530 return 'type_unknown';
534 * Finds all nodes that are expandable by AJAX
536 * @param array $expandable An array by reference to populate with expandable nodes.
538 public function find_expandable(array &$expandable) {
539 $isloggedin = (isloggedin() && !isguestuser());
540 if (!$isloggedin && $this->type > self::TYPE_CATEGORY) {
543 foreach ($this->children as &$child) {
544 if (!$isloggedin && $child->type > self::TYPE_CATEGORY) {
547 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count()==0 && $child->display) {
548 $child->id = 'expandable_branch_'.(count($expandable)+1);
549 $this->add_class('canexpand');
550 $expandable[] = array('id'=>$child->id,'branchid'=>$child->key,'type'=>$child->type);
552 $child->find_expandable($expandable);
557 * Finds all nodes of a given type (recursive)
559 * @param int $type On of navigation_node::TYPE_*
562 public function find_all_of_type($type) {
563 $nodes = $this->children->type($type);
564 foreach ($this->children as &$node) {
565 $childnodes = $node->find_all_of_type($type);
566 $nodes = array_merge($nodes, $childnodes);
572 * Removes this node if it is empty
574 public function trim_if_empty() {
575 if ($this->children->count() == 0) {
581 * Creates a tab representation of this nodes children that can be used
582 * with print_tabs to produce the tabs on a page.
584 * call_user_func_array('print_tabs', $node->get_tabs_array());
586 * @param array $inactive
587 * @param bool $return
588 * @return array Array (tabs, selected, inactive, activated, return)
590 public function get_tabs_array(array $inactive=array(), $return=false) {
594 $activated = array();
595 foreach ($this->children as $node) {
596 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
597 if ($node->contains_active_node()) {
598 if ($node->children->count() > 0) {
599 $activated[] = $node->key;
600 foreach ($node->children as $child) {
601 if ($child->contains_active_node()) {
602 $selected = $child->key;
604 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
607 $selected = $node->key;
611 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
616 * Navigation node collection
618 * This class is responsible for managing a collection of navigation nodes.
619 * It is required because a node's unique identifier is a combination of both its
622 * Originally an array was used with a string key that was a combination of the two
623 * however it was decided that a better solution would be to use a class that
624 * implements the standard IteratorAggregate interface.
626 * @package moodlecore
627 * @subpackage navigation
628 * @copyright 2010 Sam Hemelryk
629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
631 class navigation_node_collection implements IteratorAggregate {
633 * A multidimensional array to where the first key is the type and the second
634 * key is the nodes key.
637 protected $collection = array();
639 * An array that contains references to nodes in the same order they were added.
640 * This is maintained as a progressive array.
643 protected $orderedcollection = array();
645 * A reference to the last node that was added to the collection
646 * @var navigation_node
648 protected $last = null;
650 * The total number of items added to this array.
653 protected $count = 0;
655 * Adds a navigation node to the collection
657 * @param navigation_node $node
658 * @return navigation_node
660 public function add(navigation_node $node) {
664 // First check we have a 2nd dimension for this type
665 if (!array_key_exists($type, $this->orderedcollection)) {
666 $this->orderedcollection[$type] = array();
668 // Check for a collision and report if debugging is turned on
669 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
670 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
672 // Add the node to the appropriate place in the ordered structure.
673 $this->orderedcollection[$type][$key] = $node;
674 // Add a reference to the node to the progressive collection.
675 $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
676 // Update the last property to a reference to this new node.
677 $this->last = &$this->orderedcollection[$type][$key];
679 // Return the reference to the now added node
684 * Fetches a node from this collection.
686 * @param string|int $key The key of the node we want to find.
687 * @param int $type One of navigation_node::TYPE_*.
688 * @return navigation_node|null
690 public function get($key, $type=null) {
691 if ($type !== null) {
692 // If the type is known then we can simply check and fetch
693 if (!empty($this->orderedcollection[$type][$key])) {
694 return $this->orderedcollection[$type][$key];
697 // Because we don't know the type we look in the progressive array
698 foreach ($this->collection as $node) {
699 if ($node->key === $key) {
707 * Searches for a node with matching key and type.
709 * This function searches both the nodes in this collection and all of
710 * the nodes in each collection belonging to the nodes in this collection.
714 * @param string|int $key The key of the node we want to find.
715 * @param int $type One of navigation_node::TYPE_*.
716 * @return navigation_node|null
718 public function find($key, $type=null) {
719 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
720 return $this->orderedcollection[$type][$key];
722 $nodes = $this->getIterator();
723 // Search immediate children first
724 foreach ($nodes as &$node) {
725 if ($node->key === $key && ($type === null || $type === $node->type)) {
729 // Now search each childs children
730 foreach ($nodes as &$node) {
731 $result = $node->children->find($key, $type);
732 if ($result !== false) {
741 * Fetches the last node that was added to this collection
743 * @return navigation_node
745 public function last() {
749 * Fetches all nodes of a given type from this collection
751 public function type($type) {
752 if (!array_key_exists($type, $this->orderedcollection)) {
753 $this->orderedcollection[$type] = array();
755 return $this->orderedcollection[$type];
758 * Removes the node with the given key and type from the collection
760 * @param string|int $key
764 public function remove($key, $type=null) {
765 $child = $this->get($key, $type);
766 if ($child !== false) {
767 foreach ($this->collection as $colkey => $node) {
768 if ($node->key == $key && $node->type == $type) {
769 unset($this->collection[$colkey]);
773 unset($this->orderedcollection[$child->type][$child->key]);
781 * Gets the number of nodes in this collection
784 public function count() {
785 return count($this->collection);
788 * Gets an array iterator for the collection.
790 * This is required by the IteratorAggregator interface and is used by routines
791 * such as the foreach loop.
793 * @return ArrayIterator
795 public function getIterator() {
796 return new ArrayIterator($this->collection);
801 * The global navigation class used for... the global navigation
803 * This class is used by PAGE to store the global navigation for the site
804 * and is then used by the settings nav and navbar to save on processing and DB calls
808 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
809 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
812 * @package moodlecore
813 * @subpackage navigation
814 * @copyright 2009 Sam Hemelryk
815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
817 class global_navigation extends navigation_node {
819 * The Moodle page this navigation object belongs to.
824 protected $initialised = false;
826 protected $mycourses = array();
828 protected $rootnodes = array();
830 protected $showemptysections = false;
832 protected $extendforuser = array();
833 /** @var navigation_cache */
836 protected $addedcourses = array();
838 protected $expansionlimit = 0;
841 * Constructs a new global navigation
843 * @param moodle_page $page The page this navigation object belongs to
845 public function __construct(moodle_page $page) {
846 global $CFG, $SITE, $USER;
848 if (during_initial_install()) {
852 if (get_home_page() == HOMEPAGE_SITE) {
853 // We are using the site home for the root element
856 'type' => navigation_node::TYPE_SYSTEM,
857 'text' => get_string('home'),
858 'action' => new moodle_url('/')
861 // We are using the users my moodle for the root element
864 'type' => navigation_node::TYPE_SYSTEM,
865 'text' => get_string('myhome'),
866 'action' => new moodle_url('/my/')
870 // Use the parents consturctor.... good good reuse
871 parent::__construct($properties);
873 // Initalise and set defaults
875 $this->forceopen = true;
876 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
878 // Check if we need to clear the cache
879 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
880 if ($regenerate === 'navigation') {
881 $this->cache->clear();
886 * Initialises the navigation object.
888 * This causes the navigation object to look at the current state of the page
889 * that it is associated with and then load the appropriate content.
891 * This should only occur the first time that the navigation structure is utilised
892 * which will normally be either when the navbar is called to be displayed or
893 * when a block makes use of it.
897 public function initialise() {
898 global $CFG, $SITE, $USER, $DB;
899 // Check if it has alread been initialised
900 if ($this->initialised || during_initial_install()) {
903 $this->initialised = true;
905 // Set up the five base root nodes. These are nodes where we will put our
906 // content and are as follows:
907 // site: Navigation for the front page.
908 // myprofile: User profile information goes here.
909 // mycourses: The users courses get added here.
910 // courses: Additional courses are added here.
911 // users: Other users information loaded here.
912 $this->rootnodes = array();
913 if (get_home_page() == HOMEPAGE_SITE) {
914 // The home element should be my moodle because the root element is the site
915 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
916 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
919 // The home element should be the site because the root node is my moodle
920 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
921 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
922 // We need to stop automatic redirection
923 $this->rootnodes['home']->action->param('redirect', '0');
926 $this->rootnodes['site'] = $this->add_course($SITE);
927 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
928 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
929 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
930 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
932 // Fetch all of the users courses.
934 if (!empty($CFG->navcourselimit)) {
935 $limit = $CFG->navcourselimit;
938 if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') == 1) {
939 // There is only one category so we don't want to show categories
940 $CFG->navshowcategories = false;
943 $this->mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
944 $showallcourses = (count($this->mycourses) == 0 || !empty($CFG->navshowallcourses));
945 $showcategories = ($showallcourses && !empty($CFG->navshowcategories));
947 // Check if any courses were returned.
948 if (count($this->mycourses) > 0) {
949 // Add all of the users courses to the navigation
950 foreach ($this->mycourses as &$course) {
951 $course->coursenode = $this->add_course($course);
955 if ($showcategories) {
956 // Load all categories (ensures we get the base categories)
957 $this->load_all_categories();
958 } else if ($showallcourses) {
960 $this->load_all_courses();
963 // We always load the frontpage course to ensure it is available without
964 // JavaScript enabled.
965 $frontpagecourse = $this->load_course($SITE);
966 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
968 $canviewcourseprofile = true;
970 // Next load context specific content into the navigation
971 switch ($this->page->context->contextlevel) {
972 case CONTEXT_SYSTEM :
973 case CONTEXT_COURSECAT :
974 // This has already been loaded we just need to map the variable
975 $coursenode = $frontpagecourse;
978 case CONTEXT_COURSE :
979 // Load the course associated with the page into the navigation
980 $course = $this->page->course;
981 $coursenode = $this->load_course($course);
982 // If the user is not enrolled then we only want to show the
983 // course node and not populate it.
984 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
985 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext)) {
986 $coursenode->make_active();
987 $canviewcourseprofile = false;
990 // Add the essentials such as reports etc...
991 $this->add_course_essentials($coursenode, $course);
992 if ($this->format_display_course_content($course->format)) {
993 // Load the course sections
994 $sections = $this->load_course_sections($course, $coursenode);
996 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
997 $coursenode->make_active();
1000 case CONTEXT_MODULE :
1001 $course = $this->page->course;
1002 $cm = $this->page->cm;
1003 // Load the course associated with the page into the navigation
1004 $coursenode = $this->load_course($course);
1006 // If the user is not enrolled then we only want to show the
1007 // course node and not populate it.
1008 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1009 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext)) {
1010 $coursenode->make_active();
1011 $canviewcourseprofile = false;
1015 $this->add_course_essentials($coursenode, $course);
1016 // Load the course sections into the page
1017 $sections = $this->load_course_sections($course, $coursenode);
1018 if ($course->id !== SITEID) {
1019 // Find the section for the $CM associated with the page and collect
1020 // its section number.
1021 foreach ($sections as $section) {
1022 if ($section->id == $cm->section) {
1023 $cm->sectionnumber = $section->section;
1028 // Load all of the section activities for the section the cm belongs to.
1029 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1031 $activities = array();
1032 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1034 // Finally load the cm specific navigaton information
1035 $this->load_activity($cm, $course, $activities[$cm->id]);
1036 // Check if we have an active ndoe
1037 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1038 // And make the activity node active.
1039 $activities[$cm->id]->make_active();
1043 $course = $this->page->course;
1044 if ($course->id != SITEID) {
1045 // Load the course associated with the user into the navigation
1046 $coursenode = $this->load_course($course);
1047 // If the user is not enrolled then we only want to show the
1048 // course node and not populate it.
1049 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1050 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext)) {
1051 $coursenode->make_active();
1052 $canviewcourseprofile = false;
1055 $this->add_course_essentials($coursenode, $course);
1056 $sections = $this->load_course_sections($course, $coursenode);
1062 if (!empty($CFG->navcourselimit)) {
1063 $limit = $CFG->navcourselimit;
1065 if ($showcategories) {
1066 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1067 foreach ($categories as &$category) {
1068 if ($category->children->count() >= $limit) {
1069 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1070 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1073 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1074 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1077 // Load for the current user
1078 $this->load_for_user();
1079 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1080 $this->load_for_user(null, true);
1082 // Load each extending user into the navigation.
1083 foreach ($this->extendforuser as $user) {
1084 if ($user->id !== $USER->id) {
1085 $this->load_for_user($user);
1089 // Give the local plugins a chance to include some navigation if they want.
1090 foreach (get_list_of_plugins('local') as $plugin) {
1091 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1094 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1095 $function = $plugin.'_extends_navigation';
1096 if (function_exists($function)) {
1101 // Remove any empty root nodes
1102 foreach ($this->rootnodes as $node) {
1103 // Dont remove the home node
1104 if ($node->key !== 'home' && !$node->has_children()) {
1109 if (!$this->contains_active_node()) {
1110 $this->search_for_active_node();
1113 // If the user is not logged in modify the navigation structure as detailed
1114 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1115 if (!isloggedin()) {
1116 $activities = clone($this->rootnodes['site']->children);
1117 $this->rootnodes['site']->remove();
1118 $children = clone($this->children);
1119 $this->children = new navigation_node_collection();
1120 foreach ($activities as $child) {
1121 $this->children->add($child);
1123 foreach ($children as $child) {
1124 $this->children->add($child);
1130 * Checks the course format to see whether it wants the navigation to load
1131 * additional information for the course.
1133 * This function utilises a callback that can exist within the course format lib.php file
1134 * The callback should be a function called:
1135 * callback_{formatname}_display_content()
1136 * It doesn't get any arguments and should return true if additional content is
1137 * desired. If the callback doesn't exist we assume additional content is wanted.
1139 * @param string $format The course format
1142 protected function format_display_course_content($format) {
1144 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1145 if (file_exists($formatlib)) {
1146 require_once($formatlib);
1147 $displayfunc = 'callback_'.$format.'_display_content';
1148 if (function_exists($displayfunc) && !$displayfunc()) {
1149 return $displayfunc();
1156 * Loads of the the courses in Moodle into the navigation.
1158 * @param string|array $categoryids Either a string or array of category ids to load courses for
1159 * @return array An array of navigation_node
1161 protected function load_all_courses($categoryids=null) {
1162 global $CFG, $DB, $USER;
1164 if ($categoryids !== null) {
1165 if (is_array($categoryids)) {
1166 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1169 $params = array($categoryids);
1171 array_unshift($params, SITEID);
1172 $select = ' AND c.category '.$select;
1174 $params = array(SITEID);
1178 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1179 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1182 LEFT JOIN {course_categories} cat ON cat.id=c.category
1183 WHERE c.id <> ?$select
1184 ORDER BY c.sortorder ASC";
1186 if (!empty($CFG->navcourselimit)) {
1187 $limit = $CFG->navcourselimit;
1189 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1191 $coursenodes = array();
1192 foreach ($courses as $course) {
1193 context_instance_preload($course);
1194 $coursenodes[$course->id] = $this->add_course($course);
1196 return $coursenodes;
1200 * Loads all categories (top level or if an id is specified for that category)
1202 * @param int $categoryid
1205 protected function load_all_categories($categoryid=null) {
1207 if ($categoryid == null) {
1208 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1210 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1211 $wantedids = explode('/', trim($category->path, '/'));
1212 list($select, $params) = $DB->get_in_or_equal($wantedids);
1213 $select = 'id '.$select.' OR parent '.$select;
1214 $params = array_merge($params, $params);
1215 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1217 $structured = array();
1218 $categoriestoload = array();
1219 foreach ($categories as $category) {
1220 if ($category->parent == '0') {
1221 $structured[$category->id] = array('category'=>$category, 'children'=>array());
1223 if ($category->parent == $categoryid) {
1224 $categoriestoload[] = $category->id;
1227 $id = $category->parent;
1228 while ($id != '0') {
1230 if (!array_key_exists($id, $categories)) {
1231 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST);
1233 $id = $categories[$id]->parent;
1235 $parents = array_reverse($parents);
1236 $parentref = &$structured[array_shift($parents)];
1237 foreach ($parents as $parent) {
1238 if (!array_key_exists($parent, $parentref['children'])) {
1239 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1241 $parentref = &$parentref['children'][$parent];
1243 if (!array_key_exists($category->id, $parentref['children'])) {
1244 $parentref['children'][$category->id] = array('category'=>$category, 'children'=>array());
1249 foreach ($structured as $category) {
1250 $this->add_category($category, $this->rootnodes['courses']);
1253 if ($categoryid !== null && count($wantedids)) {
1254 foreach ($wantedids as $catid) {
1255 $this->load_all_courses($catid);
1261 * Adds a structured category to the navigation in the correct order/place
1263 * @param object $cat
1264 * @param navigation_node $parent
1266 protected function add_category($cat, navigation_node $parent) {
1267 $category = $parent->get($cat['category']->id, navigation_node::TYPE_CATEGORY);
1269 $category = $cat['category'];
1270 $url = new moodle_url('/course/category.php', array('id'=>$category->id));
1271 $category = $parent->add($category->name, null, self::TYPE_CATEGORY, $category->name, $category->id);
1273 foreach ($cat['children'] as $child) {
1274 $this->add_category($child, $category);
1279 * Loads the given course into the navigation
1281 * @param stdClass $course
1282 * @return navigation_node
1284 protected function load_course(stdClass $course) {
1285 if ($course->id == SITEID) {
1286 $coursenode = $this->rootnodes['site'];
1287 } else if (array_key_exists($course->id, $this->mycourses)) {
1288 if (!isset($this->mycourses[$course->id]->coursenode)) {
1289 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
1291 $coursenode = $this->mycourses[$course->id]->coursenode;
1293 $coursenode = $this->add_course($course);
1299 * Loads all of the courses section into the navigation.
1301 * This function utilisies a callback that can be implemented within the course
1302 * formats lib.php file to customise the navigation that is generated at this
1303 * point for the course.
1305 * By default (if not defined) the method {@see load_generic_course_sections} is
1308 * @param stdClass $course Database record for the course
1309 * @param navigation_node $coursenode The course node within the navigation
1310 * @return array Array of navigation nodes for the section with key = section id
1312 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1314 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1315 $structurefunc = 'callback_'.$course->format.'_load_content';
1316 if (function_exists($structurefunc)) {
1317 return $structurefunc($this, $course, $coursenode);
1318 } else if (file_exists($structurefile)) {
1319 require_once $structurefile;
1320 if (function_exists($structurefunc)) {
1321 return $structurefunc($this, $course, $coursenode);
1323 return $this->load_generic_course_sections($course, $coursenode);
1326 return $this->load_generic_course_sections($course, $coursenode);
1331 * Generically loads the course sections into the course's navigation.
1333 * @param stdClass $course
1334 * @param navigation_node $coursenode
1335 * @param string $name The string that identifies each section. e.g Topic, or Week
1336 * @param string $activeparam The url used to identify the active section
1337 * @return array An array of course section nodes
1339 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1340 global $CFG, $DB, $USER;
1342 require_once($CFG->dirroot.'/course/lib.php');
1344 $modinfo = get_fast_modinfo($course);
1345 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1346 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1348 if (isloggedin() && !isguestuser()) {
1349 $activesection = $DB->get_field("course_display", "display", array("userid"=>$USER->id, "course"=>$course->id));
1351 $activesection = null;
1354 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1355 $namingfunctionexists = (function_exists($namingfunction));
1357 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1358 if (function_exists($activeparamfunction)) {
1359 $activeparam = $activeparamfunction();
1361 $activeparam = 'section';
1363 $navigationsections = array();
1364 foreach ($sections as $sectionid=>$section) {
1365 $section = clone($section);
1366 if ($course->id == SITEID) {
1367 $this->load_section_activities($coursenode, $section->section, $modinfo);
1369 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1372 if ($namingfunctionexists) {
1373 $sectionname = $namingfunction($course, $section, $sections);
1375 $sectionname = get_string('section').' '.$section->section;
1377 $url = new moodle_url('/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1378 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1379 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1380 $sectionnode->hidden = (!$section->visible);
1381 if ($this->page->context->contextlevel != CONTEXT_MODULE && ($sectionnode->isactive || ($activesection != null && $section->section == $activesection))) {
1382 $sectionnode->force_open();
1383 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1385 $section->sectionnode = $sectionnode;
1386 $navigationsections[$sectionid] = $section;
1389 return $navigationsections;
1392 * Loads all of the activities for a section into the navigation structure.
1394 * @param navigation_node $sectionnode
1395 * @param int $sectionnumber
1396 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1397 * @return array Array of activity nodes
1399 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1400 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1404 $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page->context);
1406 $activities = array();
1408 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1409 $cm = $modinfo->cms[$cmid];
1410 if (!$viewhiddenactivities && !$cm->visible) {
1414 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1416 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1418 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1419 $activitynode = $sectionnode->add($cm->name, $url, navigation_node::TYPE_ACTIVITY, $cm->name, $cm->id, $icon);
1420 $activitynode->title(get_string('modulename', $cm->modname));
1421 $activitynode->hidden = (!$cm->visible);
1422 if ($this->module_extends_navigation($cm->modname)) {
1423 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1425 $activities[$cmid] = $activitynode;
1431 * Loads the navigation structure for the given activity into the activities node.
1433 * This method utilises a callback within the modules lib.php file to load the
1434 * content specific to activity given.
1436 * The callback is a method: {modulename}_extend_navigation()
1438 * * {@see forum_extend_navigation()}
1439 * * {@see workshop_extend_navigation()}
1441 * @param stdClass $cm
1442 * @param stdClass $course
1443 * @param navigation_node $activity
1446 protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1449 $activity->make_active();
1450 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1451 $function = $cm->modname.'_extend_navigation';
1453 if (file_exists($file)) {
1454 require_once($file);
1455 if (function_exists($function)) {
1456 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1457 $function($activity, $course, $activtyrecord, $cm);
1461 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1465 * Loads user specific information into the navigation in the appopriate place.
1467 * If no user is provided the current user is assumed.
1469 * @param stdClass $user
1472 protected function load_for_user($user=null, $forceforcontext=false) {
1473 global $DB, $CFG, $USER;
1475 $iscurrentuser = false;
1476 if ($user === null) {
1477 // We can't require login here but if the user isn't logged in we don't
1478 // want to show anything
1479 if (!isloggedin() || isguestuser()) {
1483 $iscurrentuser = true;
1484 } else if (!is_object($user)) {
1485 // If the user is not an object then get them from the database
1486 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1488 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1490 // Get the course set against the page, by default this will be the site
1491 $course = $this->page->course;
1492 $baseargs = array('id'=>$user->id);
1493 if ($course->id !== SITEID && (!$iscurrentuser || $forceforcontext)) {
1494 if (array_key_exists($course->id, $this->mycourses)) {
1495 $coursenode = $this->mycourses[$course->id]->coursenode;
1497 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1499 $coursenode = $this->load_course($course);
1502 $baseargs['course'] = $course->id;
1503 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1504 $issitecourse = false;
1506 // Load all categories and get the context for the system
1507 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1508 $issitecourse = true;
1511 // Create a node to add user information under.
1512 if ($iscurrentuser && !$forceforcontext) {
1513 // If it's the current user the information will go under the profile root node
1514 $usernode = $this->rootnodes['myprofile'];
1516 if (!$issitecourse) {
1517 // Not the current user so add it to the participants node for the current course
1518 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1519 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1521 // This is the site so add a users node to the root branch
1522 $usersnode = $this->rootnodes['users'];
1523 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1524 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1526 // Add a branch for the current user
1527 $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);
1529 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1530 $usernode->make_active();
1534 // If the user is the current user or has permission to view the details of the requested
1535 // user than add a view profile link.
1536 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1537 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1538 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1540 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1544 // Add nodes for forum posts and discussions if the user can view either or both
1545 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1546 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
1547 if ($canviewposts || $canviewdiscussions) {
1548 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1549 if ($canviewposts) {
1550 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1552 if ($canviewdiscussions) {
1553 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions', 'course'=>$course->id))));
1558 if (!empty($CFG->bloglevel)) {
1559 require_once($CFG->dirroot.'/blog/lib.php');
1560 // Get all options for the user
1561 $options = blog_get_options_for_user($user);
1562 if (count($options) > 0) {
1563 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1564 foreach ($options as $option) {
1565 $blogs->add($option['string'], $option['link']);
1570 if (!empty($CFG->messaging)) {
1571 $messageargs = null;
1572 if ($USER->id!=$user->id) {
1573 $messageargs = array('id'=>$user->id);
1575 $url = new moodle_url('/message/index.php',$messageargs);
1576 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
1579 // TODO: Private file capability check
1580 if ($iscurrentuser) {
1581 $url = new moodle_url('/user/files.php');
1582 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
1585 // Add a node to view the users notes if permitted
1586 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1587 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1588 if ($coursecontext->instanceid) {
1589 $url->param('course', $coursecontext->instanceid);
1591 $usernode->add(get_string('notes', 'notes'), $url);
1594 // Add a reports tab and then add reports the the user has permission to see.
1595 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1597 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext));
1599 $reporttab = $usernode->add(get_string('activityreports'));
1600 $reportargs = array('user'=>$user->id);
1601 if (!empty($course->id)) {
1602 $reportargs['id'] = $course->id;
1604 $reportargs['id'] = SITEID;
1606 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1607 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1608 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1611 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1612 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1615 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1616 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1619 if (!empty($CFG->enablestats)) {
1620 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1621 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1625 $gradeaccess = false;
1626 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1627 //ok - can view all course grades
1628 $gradeaccess = true;
1629 } else if ($course->showgrades) {
1630 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1631 //ok - can view own grades
1632 $gradeaccess = true;
1633 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1634 // ok - can view grades of this user - parent most probably
1635 $gradeaccess = true;
1636 } else if ($anyreport) {
1637 // ok - can view grades of this user - parent most probably
1638 $gradeaccess = true;
1642 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1645 // Check the number of nodes in the report node... if there are none remove
1647 if (count($reporttab->children)===0) {
1648 $usernode->remove_child($reporttab);
1652 // If the user is the current user add the repositories for the current user
1653 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
1654 if ($iscurrentuser) {
1655 require_once($CFG->dirroot . '/repository/lib.php');
1656 $editabletypes = repository::get_editable_types($usercontext);
1657 if (!empty($editabletypes)) {
1658 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1660 } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
1662 // Add view grade report is permitted
1663 $reports = get_plugin_list('gradereport');
1664 arsort($reports); // user is last, we want to test it first
1666 $userscourses = enrol_get_users_courses($user->id);
1667 $userscoursesnode = $usernode->add(get_string('courses'));
1669 foreach ($userscourses as $usercourse) {
1670 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
1671 $usercoursenode = $userscoursesnode->add($usercourse->shortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
1673 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
1674 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
1675 foreach ($reports as $plugin => $plugindir) {
1676 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
1677 //stop when the first visible plugin is found
1678 $gradeavailable = true;
1684 if ($gradeavailable) {
1685 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
1686 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
1689 // Add a node to view the users notes if permitted
1690 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
1691 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
1692 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
1695 if (has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $usercourse->id))) {
1696 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
1699 $outlinetreport = ($anyreport || has_capability('coursereport/outline:view', $usercoursecontext));
1700 $logtodayreport = ($anyreport || has_capability('coursereport/log:viewtoday', $usercoursecontext));
1701 $logreport = ($anyreport || has_capability('coursereport/log:view', $usercoursecontext));
1702 $statsreport = ($anyreport || has_capability('coursereport/stats:view', $usercoursecontext));
1703 if ($outlinetreport || $logtodayreport || $logreport || $statsreport) {
1704 $reporttab = $usercoursenode->add(get_string('activityreports'));
1705 $reportargs = array('user'=>$user->id, 'id'=>$usercourse->id);
1706 if ($outlinetreport) {
1707 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1708 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1711 if ($logtodayreport) {
1712 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1716 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1719 if (!empty($CFG->enablestats) && $statsreport) {
1720 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1729 * This method simply checks to see if a given module can extend the navigation.
1731 * @param string $modname
1734 protected function module_extends_navigation($modname) {
1736 if ($this->cache->cached($modname.'_extends_navigation')) {
1737 return $this->cache->{$modname.'_extends_navigation'};
1739 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1740 $function = $modname.'_extend_navigation';
1741 if (function_exists($function)) {
1742 $this->cache->{$modname.'_extends_navigation'} = true;
1744 } else if (file_exists($file)) {
1745 require_once($file);
1746 if (function_exists($function)) {
1747 $this->cache->{$modname.'_extends_navigation'} = true;
1751 $this->cache->{$modname.'_extends_navigation'} = false;
1755 * Extends the navigation for the given user.
1757 * @param stdClass $user A user from the database
1759 public function extend_for_user($user) {
1760 $this->extendforuser[] = $user;
1764 * Returns all of the users the navigation is being extended for
1768 public function get_extending_users() {
1769 return $this->extendforuser;
1772 * Adds the given course to the navigation structure.
1774 * @param stdClass $course
1775 * @return navigation_node
1777 public function add_course(stdClass $course, $forcegeneric = false) {
1779 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1780 if ($course->id !== SITEID && !$canviewhidden && !$course->visible) {
1784 $issite = ($course->id == SITEID);
1785 $ismycourse = (array_key_exists($course->id, $this->mycourses) && !$forcegeneric);
1786 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories));
1787 $shortname = $course->shortname;
1792 $shortname = get_string('sitepages');
1793 } else if ($ismycourse) {
1794 $parent = $this->rootnodes['mycourses'];
1795 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1797 $parent = $this->rootnodes['courses'];
1798 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1801 if ($displaycategories) {
1802 // We need to load the category structure for this course
1803 $categoryfound = false;
1804 if (!empty($course->categorypath)) {
1805 $categories = explode('/', trim($course->categorypath, '/'));
1806 $category = $parent;
1807 while ($category && $categoryid = array_shift($categories)) {
1808 $category = $category->get($categoryid, self::TYPE_CATEGORY);
1810 if ($category instanceof navigation_node) {
1811 $parent = $category;
1812 $categoryfound = true;
1814 if (!$categoryfound && $forcegeneric) {
1815 $this->load_all_categories($course->category);
1816 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1817 $parent = $category;
1818 $categoryfound = true;
1821 } else if (!empty($course->category)) {
1822 $this->load_all_categories($course->category);
1823 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1824 $parent = $category;
1825 $categoryfound = true;
1827 if (!$categoryfound && !$forcegeneric) {
1828 $this->load_all_categories($course->category);
1829 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1830 $parent = $category;
1831 $categoryfound = true;
1837 // We found the course... we can return it now :)
1838 if ($coursenode = $parent->get($course->id, self::TYPE_COURSE)) {
1842 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
1843 $coursenode->nodetype = self::NODETYPE_BRANCH;
1844 $coursenode->hidden = (!$course->visible);
1845 $coursenode->title($course->fullname);
1846 $this->addedcourses[$course->id] = &$coursenode;
1847 if ($ismycourse && !empty($CFG->navshowallcourses)) {
1848 // We need to add this course to the general courses node as well as the
1849 // my courses node, rerun the function with the kill param
1850 $genericcourse = $this->add_course($course, true);
1851 if ($genericcourse->isactive) {
1852 $genericcourse->make_inactive();
1853 $genericcourse->collapse = true;
1854 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
1855 $parent = $genericcourse->parent;
1856 while ($parent && $parent->type == self::TYPE_CATEGORY) {
1857 $parent->collapse = true;
1858 $parent = $parent->parent;
1866 * Adds essential course nodes to the navigation for the given course.
1868 * This method adds nodes such as reports, blogs and participants
1870 * @param navigation_node $coursenode
1871 * @param stdClass $course
1874 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1877 if ($course->id == SITEID) {
1878 return $this->add_front_page_course_essentials($coursenode, $course);
1881 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1886 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1887 require_once($CFG->dirroot.'/blog/lib.php');
1888 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1889 $currentgroup = groups_get_course_group($course, true);
1890 if ($course->id == SITEID) {
1892 } else if ($course->id && !$currentgroup) {
1893 $filterselect = $course->id;
1895 $filterselect = $currentgroup;
1897 $filterselect = clean_param($filterselect, PARAM_INT);
1898 if ($CFG->bloglevel >= 3) {
1899 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1900 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1902 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1903 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1905 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
1906 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1909 // View course reports
1910 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1911 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1912 $coursereports = get_plugin_list('coursereport');
1913 foreach ($coursereports as $report=>$dir) {
1914 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1915 if (file_exists($libfile)) {
1916 require_once($libfile);
1917 $reportfunction = $report.'_report_extend_navigation';
1918 if (function_exists($report.'_report_extend_navigation')) {
1919 $reportfunction($reportnav, $course, $this->page->context);
1927 * This generates the the structure of the course that won't be generated when
1928 * the modules and sections are added.
1930 * Things such as the reports branch, the participants branch, blogs... get
1931 * added to the course node by this method.
1933 * @param navigation_node $coursenode
1934 * @param stdClass $course
1935 * @return bool True for successfull generation
1937 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1940 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1945 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1946 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1949 $currentgroup = groups_get_course_group($course, true);
1950 if ($course->id == SITEID) {
1952 } else if ($course->id && !$currentgroup) {
1953 $filterselect = $course->id;
1955 $filterselect = $currentgroup;
1957 $filterselect = clean_param($filterselect, PARAM_INT);
1960 if (has_capability('moodle/blog:view', $this->page->context)) {
1961 require_once($CFG->dirroot.'/blog/lib.php');
1962 if (blog_is_enabled_for_user()) {
1963 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1964 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1969 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1970 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1974 if (!empty($CFG->usetags) && isloggedin()) {
1975 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
1979 // View course reports
1980 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1981 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1982 $coursereports = get_plugin_list('coursereport');
1983 foreach ($coursereports as $report=>$dir) {
1984 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1985 if (file_exists($libfile)) {
1986 require_once($libfile);
1987 $reportfunction = $report.'_report_extend_navigation';
1988 if (function_exists($report.'_report_extend_navigation')) {
1989 $reportfunction($reportnav, $course, $this->page->context);
1998 * Clears the navigation cache
2000 public function clear_cache() {
2001 $this->cache->clear();
2005 * Sets an expansion limit for the navigation
2007 * The expansion limit is used to prevent the display of content that has a type
2008 * greater than the provided $type.
2010 * Can be used to ensure things such as activities or activity content don't get
2011 * shown on the navigation.
2012 * They are still generated in order to ensure the navbar still makes sense.
2014 * @param int $type One of navigation_node::TYPE_*
2017 public function set_expansion_limit($type) {
2018 $nodes = $this->find_all_of_type($type);
2019 foreach ($nodes as &$node) {
2020 // We need to generate the full site node
2021 if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2024 foreach ($node->children as &$child) {
2025 // We still want to show course reports and participants containers
2026 // or there will be navigation missing.
2027 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2030 $child->display = false;
2036 * Attempts to get the navigation with the given key from this nodes children.
2038 * This function only looks at this nodes children, it does NOT look recursivily.
2039 * If the node can't be found then false is returned.
2041 * If you need to search recursivily then use the {@see find()} method.
2043 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2044 * may be of more use to you.
2046 * @param string|int $key The key of the node you wish to receive.
2047 * @param int $type One of navigation_node::TYPE_*
2048 * @return navigation_node|false
2050 public function get($key, $type = null) {
2051 if (!$this->initialised) {
2052 $this->initialise();
2054 return parent::get($key, $type);
2058 * Searches this nodes children and thier children to find a navigation node
2059 * with the matching key and type.
2061 * This method is recursive and searches children so until either a node is
2062 * found of there are no more nodes to search.
2064 * If you know that the node being searched for is a child of this node
2065 * then use the {@see get()} method instead.
2067 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2068 * may be of more use to you.
2070 * @param string|int $key The key of the node you wish to receive.
2071 * @param int $type One of navigation_node::TYPE_*
2072 * @return navigation_node|false
2074 public function find($key, $type) {
2075 if (!$this->initialised) {
2076 $this->initialise();
2078 return parent::find($key, $type);
2083 * The limited global navigation class used for the AJAX extension of the global
2086 * The primary methods that are used in the global navigation class have been overriden
2087 * to ensure that only the relevant branch is generated at the root of the tree.
2088 * This can be done because AJAX is only used when the backwards structure for the
2089 * requested branch exists.
2090 * This has been done only because it shortens the amounts of information that is generated
2091 * which of course will speed up the response time.. because no one likes laggy AJAX.
2093 * @package moodlecore
2094 * @subpackage navigation
2095 * @copyright 2009 Sam Hemelryk
2096 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2098 class global_navigation_for_ajax extends global_navigation {
2101 protected $expandable = array();
2104 * Constructs the navigation for use in AJAX request
2106 public function __construct($page, $branchtype, $id) {
2107 $this->page = $page;
2108 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2109 $this->children = new navigation_node_collection();
2110 $this->initialise($branchtype, $id);
2113 * Initialise the navigation given the type and id for the branch to expand.
2115 * @param int $branchtype One of navigation_node::TYPE_*
2117 * @return array The expandable nodes
2119 public function initialise($branchtype, $id) {
2120 global $CFG, $DB, $PAGE, $SITE, $USER;
2122 if ($this->initialised || during_initial_install()) {
2123 return $this->expandable;
2125 $this->initialised = true;
2127 $this->rootnodes = array();
2128 $this->rootnodes['site'] = $this->add_course($SITE);
2129 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2131 // Branchtype will be one of navigation_node::TYPE_*
2132 switch ($branchtype) {
2133 case self::TYPE_CATEGORY :
2134 $this->load_all_categories($id);
2136 if (!empty($CFG->navcourselimit)) {
2137 $limit = (int)$CFG->navcourselimit;
2139 $courses = $DB->get_records('course', array('category' => $id), 'sortorder','*', 0, $limit);
2140 foreach ($courses as $course) {
2141 $this->add_course($course);
2144 case self::TYPE_COURSE :
2145 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
2146 require_course_login($course);
2147 $this->page = $PAGE;
2148 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2149 $coursenode = $this->add_course($course);
2150 $this->add_course_essentials($coursenode, $course);
2151 if ($this->format_display_course_content($course->format)) {
2152 $this->load_course_sections($course, $coursenode);
2155 case self::TYPE_SECTION :
2156 $sql = 'SELECT c.*, cs.section AS sectionnumber
2158 LEFT JOIN {course_sections} cs ON cs.course = c.id
2160 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
2161 require_course_login($course);
2162 $this->page = $PAGE;
2163 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2164 $coursenode = $this->add_course($course);
2165 $this->add_course_essentials($coursenode, $course);
2166 $sections = $this->load_course_sections($course, $coursenode);
2167 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
2169 case self::TYPE_ACTIVITY :
2170 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
2171 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2172 require_course_login($course, true, $cm);
2173 $this->page = $PAGE;
2174 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2175 $coursenode = $this->load_course($course);
2176 $sections = $this->load_course_sections($course, $coursenode);
2177 foreach ($sections as $section) {
2178 if ($section->id == $cm->section) {
2179 $cm->sectionnumber = $section->section;
2183 if ($course->id == SITEID) {
2184 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2186 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
2187 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2191 throw new Exception('Unknown type');
2192 return $this->expandable;
2195 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2196 $this->load_for_user(null, true);
2199 $this->find_expandable($this->expandable);
2200 return $this->expandable;
2204 * Returns an array of expandable nodes
2207 public function get_expandable() {
2208 return $this->expandable;
2215 * This class is used to manage the navbar, which is initialised from the navigation
2216 * object held by PAGE
2218 * @package moodlecore
2219 * @subpackage navigation
2220 * @copyright 2009 Sam Hemelryk
2221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2223 class navbar extends navigation_node {
2225 protected $initialised = false;
2227 protected $keys = array();
2228 /** @var null|string */
2229 protected $content = null;
2230 /** @var moodle_page object */
2233 protected $ignoreactive = false;
2235 protected $duringinstall = false;
2237 protected $hasitems = false;
2241 public $children = array();
2243 public $includesettingsbase = false;
2245 * The almighty constructor
2247 * @param moodle_page $page
2249 public function __construct(moodle_page $page) {
2251 if (during_initial_install()) {
2252 $this->duringinstall = true;
2255 $this->page = $page;
2256 $this->text = get_string('home');
2257 $this->shorttext = get_string('home');
2258 $this->action = new moodle_url($CFG->wwwroot);
2259 $this->nodetype = self::NODETYPE_BRANCH;
2260 $this->type = self::TYPE_SYSTEM;
2264 * Quick check to see if the navbar will have items in.
2266 * @return bool Returns true if the navbar will have items, false otherwise
2268 public function has_items() {
2269 if ($this->duringinstall) {
2271 } else if ($this->hasitems !== false) {
2274 $this->page->navigation->initialise($this->page);
2276 $activenodefound = ($this->page->navigation->contains_active_node() ||
2277 $this->page->settingsnav->contains_active_node());
2279 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2280 $this->hasitems = $outcome;
2285 * Turn on/off ignore active
2287 * @param bool $setting
2289 public function ignore_active($setting=true) {
2290 $this->ignoreactive = ($setting);
2292 public function get($key, $type = null) {
2293 foreach ($this->children as &$child) {
2294 if ($child->key === $key && ($type == null || $type == $child->type)) {
2301 * Returns an array of navigation_node's that make up the navbar.
2305 public function get_items() {
2307 // Make sure that navigation is initialised
2308 if (!$this->has_items()) {
2311 if ($this->items !== null) {
2312 return $this->items;
2315 if (count($this->children) > 0) {
2316 // Add the custom children
2317 $items = array_reverse($this->children);
2320 $navigationactivenode = $this->page->navigation->find_active_node();
2321 $settingsactivenode = $this->page->settingsnav->find_active_node();
2323 // Check if navigation contains the active node
2324 if (!$this->ignoreactive) {
2326 if ($navigationactivenode && $settingsactivenode) {
2327 // Parse a combined navigation tree
2328 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2329 if (!$settingsactivenode->mainnavonly) {
2330 $items[] = $settingsactivenode;
2332 $settingsactivenode = $settingsactivenode->parent;
2334 if (!$this->includesettingsbase) {
2335 // Removes the first node from the settings (root node) from the list
2338 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2339 if (!$navigationactivenode->mainnavonly) {
2340 $items[] = $navigationactivenode;
2342 $navigationactivenode = $navigationactivenode->parent;
2344 } else if ($navigationactivenode) {
2345 // Parse the navigation tree to get the active node
2346 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2347 if (!$navigationactivenode->mainnavonly) {
2348 $items[] = $navigationactivenode;
2350 $navigationactivenode = $navigationactivenode->parent;
2352 } else if ($settingsactivenode) {
2353 // Parse the settings navigation to get the active node
2354 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2355 if (!$settingsactivenode->mainnavonly) {
2356 $items[] = $settingsactivenode;
2358 $settingsactivenode = $settingsactivenode->parent;
2363 $items[] = new navigation_node(array(
2364 'text'=>$this->page->navigation->text,
2365 'shorttext'=>$this->page->navigation->shorttext,
2366 'key'=>$this->page->navigation->key,
2367 'action'=>$this->page->navigation->action
2370 $this->items = array_reverse($items);
2371 return $this->items;
2375 * Add a new navigation_node to the navbar, overrides parent::add
2377 * This function overrides {@link navigation_node::add()} so that we can change
2378 * the way nodes get added to allow us to simply call add and have the node added to the
2381 * @param string $text
2382 * @param string|moodle_url $action
2384 * @param string|int $key
2385 * @param string $shorttext
2386 * @param string $icon
2387 * @return navigation_node
2389 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2390 if ($this->content !== null) {
2391 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2394 // Properties array used when creating the new navigation node
2399 // Set the action if one was provided
2400 if ($action!==null) {
2401 $itemarray['action'] = $action;
2403 // Set the shorttext if one was provided
2404 if ($shorttext!==null) {
2405 $itemarray['shorttext'] = $shorttext;
2407 // Set the icon if one was provided
2409 $itemarray['icon'] = $icon;
2411 // Default the key to the number of children if not provided
2412 if ($key === null) {
2413 $key = count($this->children);
2416 $itemarray['key'] = $key;
2417 // Set the parent to this node
2418 $itemarray['parent'] = $this;
2419 // Add the child using the navigation_node_collections add method
2420 $this->children[] = new navigation_node($itemarray);
2426 * Class used to manage the settings option for the current page
2428 * This class is used to manage the settings options in a tree format (recursively)
2429 * and was created initially for use with the settings blocks.
2431 * @package moodlecore
2432 * @subpackage navigation
2433 * @copyright 2009 Sam Hemelryk
2434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2436 class settings_navigation extends navigation_node {
2437 /** @var stdClass */
2439 /** @var navigation_cache */
2441 /** @var moodle_page */
2444 protected $adminsection;
2446 protected $initialised = false;
2448 protected $userstoextendfor = array();
2451 * Sets up the object with basic settings and preparse it for use
2453 * @param moodle_page $page
2455 public function __construct(moodle_page &$page) {
2456 if (during_initial_install()) {
2459 $this->page = $page;
2460 // Initialise the main navigation. It is most important that this is done
2461 // before we try anything
2462 $this->page->navigation->initialise();
2463 // Initialise the navigation cache
2464 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2465 $this->children = new navigation_node_collection();
2468 * Initialise the settings navigation based on the current context
2470 * This function initialises the settings navigation tree for a given context
2471 * by calling supporting functions to generate major parts of the tree.
2474 public function initialise() {
2477 if (during_initial_install()) {
2479 } else if ($this->initialised) {
2482 $this->id = 'settingsnav';
2483 $this->context = $this->page->context;
2485 $context = $this->context;
2486 if ($context->contextlevel == CONTEXT_BLOCK) {
2487 $this->load_block_settings();
2488 $context = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid));
2491 switch ($context->contextlevel) {
2492 case CONTEXT_SYSTEM:
2493 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2494 $this->load_front_page_settings(($context->id == $this->context->id));
2497 case CONTEXT_COURSECAT:
2498 $this->load_category_settings();
2500 case CONTEXT_COURSE:
2501 if ($this->page->course->id != SITEID) {
2502 $this->load_course_settings(($context->id == $this->context->id));
2504 $this->load_front_page_settings(($context->id == $this->context->id));
2507 case CONTEXT_MODULE:
2508 $this->load_module_settings();
2509 $this->load_course_settings();
2512 if ($this->page->course->id != SITEID) {
2513 $this->load_course_settings();
2518 $settings = $this->load_user_settings($this->page->course->id);
2519 $admin = $this->load_administration_settings();
2521 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2522 $admin->force_open();
2523 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2524 $settings->force_open();
2527 // Check if the user is currently logged in as another user
2528 if (session_is_loggedinas()) {
2529 // Get the actual user, we need this so we can display an informative return link
2530 $realuser = session_get_realuser();
2531 // Add the informative return to original user link
2532 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2533 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2536 // Make sure the first child doesnt have proceed with hr set to true
2538 foreach ($this->children as $key=>$node) {
2539 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2543 $this->initialised = true;
2546 * Override the parent function so that we can add preceeding hr's and set a
2547 * root node class against all first level element
2549 * It does this by first calling the parent's add method {@link navigation_node::add()}
2550 * and then proceeds to use the key to set class and hr
2552 * @param string $text
2553 * @param sting|moodle_url $url
2554 * @param string $shorttext
2555 * @param string|int $key
2557 * @param string $icon
2558 * @return navigation_node
2560 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2561 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2562 $node->add_class('root_node');
2567 * This function allows the user to add something to the start of the settings
2568 * navigation, which means it will be at the top of the settings navigation block
2570 * @param string $text
2571 * @param sting|moodle_url $url
2572 * @param string $shorttext
2573 * @param string|int $key
2575 * @param string $icon
2576 * @return navigation_node
2578 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2579 $children = $this->children;
2580 $childrenclass = get_class($children);
2581 $this->children = new $childrenclass;
2582 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2583 foreach ($children as $child) {
2584 $this->children->add($child);
2589 * Load the site administration tree
2591 * This function loads the site administration tree by using the lib/adminlib library functions
2593 * @param navigation_node $referencebranch A reference to a branch in the settings
2595 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2596 * tree and start at the beginning
2597 * @return mixed A key to access the admin tree by
2599 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2602 // Check if we are just starting to generate this navigation.
2603 if ($referencebranch === null) {
2605 // Require the admin lib then get an admin structure
2606 if (!function_exists('admin_get_root')) {
2607 require_once($CFG->dirroot.'/lib/adminlib.php');
2609 $adminroot = admin_get_root(false, false);
2610 // This is the active section identifier
2611 $this->adminsection = $this->page->url->param('section');
2613 // Disable the navigation from automatically finding the active node
2614 navigation_node::$autofindactive = false;
2615 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2616 foreach ($adminroot->children as $adminbranch) {
2617 $this->load_administration_settings($referencebranch, $adminbranch);
2619 navigation_node::$autofindactive = true;
2621 // Use the admin structure to locate the active page
2622 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2623 $currentnode = $this;
2624 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2625 $currentnode = $currentnode->get($pathkey);
2628 $currentnode->make_active();
2631 $this->scan_for_active_node($referencebranch);
2633 return $referencebranch;
2634 } else if ($adminbranch->check_access()) {
2635 // We have a reference branch that we can access and is not hidden `hurrah`
2636 // Now we need to display it and any children it may have
2639 if ($adminbranch instanceof admin_settingpage) {
2640 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2641 } else if ($adminbranch instanceof admin_externalpage) {
2642 $url = $adminbranch->url;
2646 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2648 if ($adminbranch->is_hidden()) {
2649 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2650 $reference->add_class('hidden');
2652 $reference->display = false;
2656 // Check if we are generating the admin notifications and whether notificiations exist
2657 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2658 $reference->add_class('criticalnotification');
2660 // Check if this branch has children
2661 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2662 foreach ($adminbranch->children as $branch) {
2663 // Generate the child branches as well now using this branch as the reference
2664 $this->load_administration_settings($reference, $branch);
2667 $reference->icon = new pix_icon('i/settings', '');
2673 * This function recursivily scans nodes until it finds the active node or there
2674 * are no more nodes.
2675 * @param navigation_node $node
2677 protected function scan_for_active_node(navigation_node $node) {
2678 if (!$node->check_if_active() && $node->children->count()>0) {
2679 foreach ($node->children as &$child) {
2680 $this->scan_for_active_node($child);
2686 * Gets a navigation node given an array of keys that represent the path to
2689 * @param array $path
2690 * @return navigation_node|false
2692 protected function get_by_path(array $path) {
2693 $node = $this->get(array_shift($path));
2694 foreach ($path as $key) {
2701 * Generate the list of modules for the given course.
2703 * The array of resources and activities that can be added to a course is then
2704 * stored in the cache so that we can access it for anywhere.
2705 * It saves us generating it all the time
2708 * // To get resources:
2709 * $this->cache->{'course'.$courseid.'resources'}
2710 * // To get activities:
2711 * $this->cache->{'course'.$courseid.'activities'}
2714 * @param stdClass $course The course to get modules for
2716 protected function get_course_modules($course) {
2718 $mods = $modnames = $modnamesplural = $modnamesused = array();
2719 // This function is included when we include course/lib.php at the top
2721 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2722 $resources = array();
2723 $activities = array();
2724 foreach($modnames as $modname=>$modnamestr) {
2725 if (!course_allowed_module($course, $modname)) {
2729 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2730 if (!file_exists($libfile)) {
2733 include_once($libfile);
2734 $gettypesfunc = $modname.'_get_types';
2735 if (function_exists($gettypesfunc)) {
2736 $types = $gettypesfunc();
2737 foreach($types as $type) {
2738 if (!isset($type->modclass) || !isset($type->typestr)) {
2739 debugging('Incorrect activity type in '.$modname);
2742 if ($type->modclass == MOD_CLASS_RESOURCE) {
2743 $resources[html_entity_decode($type->type)] = $type->typestr;
2745 $activities[html_entity_decode($type->type)] = $type->typestr;
2749 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2750 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2751 $resources[$modname] = $modnamestr;
2753 // all other archetypes are considered activity
2754 $activities[$modname] = $modnamestr;
2758 $this->cache->{'course'.$course->id.'resources'} = $resources;
2759 $this->cache->{'course'.$course->id.'activities'} = $activities;
2763 * This function loads the course settings that are available for the user
2765 * @param bool $forceopen If set to true the course node will be forced open
2766 * @return navigation_node|false
2768 protected function load_course_settings($forceopen = false) {
2769 global $CFG, $USER, $SESSION, $OUTPUT;
2771 $course = $this->page->course;
2772 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2774 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
2776 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2778 $coursenode->force_open();
2781 if (has_capability('moodle/course:update', $coursecontext)) {
2782 // Add the turn on/off settings
2783 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2784 if ($this->page->user_is_editing()) {
2785 $url->param('edit', 'off');
2786 $editstring = get_string('turneditingoff');
2788 $url->param('edit', 'on');
2789 $editstring = get_string('turneditingon');
2791 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2793 if ($this->page->user_is_editing()) {
2794 // Removed as per MDL-22732
2795 // $this->add_course_editing_links($course);
2798 // Add the course settings link
2799 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2800 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2802 // Add the course completion settings link
2803 if ($CFG->enablecompletion && $course->enablecompletion) {
2804 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2805 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2810 enrol_add_course_navigation($coursenode, $course);
2813 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2814 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2815 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2818 // Add view grade report is permitted
2819 $reportavailable = false;
2820 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2821 $reportavailable = true;
2822 } else if (!empty($course->showgrades)) {
2823 $reports = get_plugin_list('gradereport');
2824 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2825 arsort($reports); // user is last, we want to test it first
2826 foreach ($reports as $plugin => $plugindir) {
2827 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2828 //stop when the first visible plugin is found
2829 $reportavailable = true;
2835 if ($reportavailable) {
2836 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2837 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2840 // Add outcome if permitted
2841 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2842 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2843 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
2846 // Backup this course
2847 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2848 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2849 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
2852 // Restore to this course
2853 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2854 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
2855 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
2858 // Import data from other courses
2859 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2860 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
2861 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
2864 // Publish course on a hub
2865 if (has_capability('moodle/course:publish', $coursecontext)) {
2866 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2867 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
2870 // Reset this course
2871 if (has_capability('moodle/course:reset', $coursecontext)) {
2872 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2873 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2877 require_once($CFG->dirroot.'/question/editlib.php');
2878 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
2880 // Repository Instances
2881 require_once($CFG->dirroot.'/repository/lib.php');
2882 $editabletypes = repository::get_editable_types($coursecontext);
2883 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2884 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id));
2885 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
2889 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
2890 // hidden in new courses and courses where legacy files were turned off
2891 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
2892 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
2897 $assumedrole = $this->in_alternative_role();
2898 if ($assumedrole!==false) {
2899 $roles[0] = get_string('switchrolereturn');
2901 if (has_capability('moodle/role:switchroles', $coursecontext)) {
2902 $availableroles = get_switchable_roles($coursecontext);
2903 if (is_array($availableroles)) {
2904 foreach ($availableroles as $key=>$role) {
2905 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2908 $roles[$key] = $role;
2912 if (is_array($roles) && count($roles)>0) {
2913 $switchroles = $this->add(get_string('switchroleto'));
2914 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2915 $switchroles->force_open();
2917 $returnurl = $this->page->url;
2918 $returnurl->param('sesskey', sesskey());
2919 $SESSION->returnurl = serialize($returnurl);
2920 foreach ($roles as $key=>$name) {
2921 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2922 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
2925 // Return we are done
2930 * Adds branches and links to the settings navigation to add course activities
2933 * @param stdClass $course
2935 protected function add_course_editing_links($course) {
2938 require_once($CFG->dirroot.'/course/lib.php');
2940 // Add `add` resources|activities branches
2941 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2942 if (file_exists($structurefile)) {
2943 require_once($structurefile);
2944 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2945 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2947 $formatstring = get_string('topic');
2948 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2951 $sections = get_all_sections($course->id);
2953 $addresource = $this->add(get_string('addresource'));
2954 $addactivity = $this->add(get_string('addactivity'));
2955 if ($formatidentifier!==0) {
2956 $addresource->force_open();
2957 $addactivity->force_open();
2960 if (!$this->cache->cached('course'.$course->id.'resources')) {
2961 $this->get_course_modules($course);
2963 $resources = $this->cache->{'course'.$course->id.'resources'};
2964 $activities = $this->cache->{'course'.$course->id.'activities'};
2966 $textlib = textlib_get_instance();
2968 foreach ($sections as $section) {
2969 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2972 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
2973 if ($section->section == 0) {
2974 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2975 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2977 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2978 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2980 foreach ($resources as $value=>$resource) {
2981 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2982 $pos = strpos($value, '&type=');
2984 $url->param('add', $textlib->substr($value, 0,$pos));
2985 $url->param('type', $textlib->substr($value, $pos+6));
2987 $url->param('add', $value);
2989 $sectionresources->add($resource, $url, self::TYPE_SETTING);
2992 foreach ($activities as $activityname=>$activity) {
2993 if ($activity==='--') {
2997 if (strpos($activity, '--')===0) {
2998 $subbranch = $sectionactivities->add(trim($activity, '-'));
3001 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3002 $pos = strpos($activityname, '&type=');
3004 $url->param('add', $textlib->substr($activityname, 0,$pos));
3005 $url->param('type', $textlib->substr($activityname, $pos+6));
3007 $url->param('add', $activityname);
3009 if ($subbranch !== false) {
3010 $subbranch->add($activity, $url, self::TYPE_SETTING);
3012 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3019 * This function calls the module function to inject module settings into the
3020 * settings navigation tree.
3022 * This only gets called if there is a corrosponding function in the modules
3025 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3027 * @return navigation_node|false
3029 protected function load_module_settings() {
3032 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3033 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3034 $this->page->set_cm($cm, $this->page->course);
3037 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3038 if (file_exists($file)) {
3039 require_once($file);
3042 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
3043 $modulenode->force_open();
3045 // Settings for the module
3046 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3047 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3048 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING);
3050 // Assign local roles
3051 if (count(get_assignable_roles($this->page->cm->context))>0) {
3052 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3053 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
3056 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3057 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3058 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3060 // Check role permissions
3061 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3062 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3063 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3066 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3067 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3068 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
3071 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
3072 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
3073 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING);
3076 // Add a backup link
3077 $featuresfunc = $this->page->activityname.'_supports';
3078 if ($featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3079 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3080 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
3083 $function = $this->page->activityname.'_extend_settings_navigation';
3084 if (!function_exists($function)) {
3088 $function($this, $modulenode);
3090 // Remove the module node if there are no children
3091 if (empty($modulenode->children)) {
3092 $modulenode->remove();
3099 * Loads the user settings block of the settings nav
3101 * This function is simply works out the userid and whether we need to load
3102 * just the current users profile settings, or the current user and the user the
3103 * current user is viewing.
3105 * This function has some very ugly code to work out the user, if anyone has
3106 * any bright ideas please feel free to intervene.
3108 * @param int $courseid The course id of the current course
3109 * @return navigation_node|false
3111 protected function load_user_settings($courseid=SITEID) {
3112 global $USER, $FULLME, $CFG;
3114 if (isguestuser() || !isloggedin()) {
3118 $navusers = $this->page->navigation->get_extending_users();
3120 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3122 foreach ($this->userstoextendfor as $userid) {
3123 if ($userid == $USER->id) {
3126 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3127 if (is_null($usernode)) {
3131 foreach ($navusers as $user) {
3132 if ($user->id == $USER->id) {
3135 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3136 if (is_null($usernode)) {
3140 $this->generate_user_settings($courseid, $USER->id);
3142 $usernode = $this->generate_user_settings($courseid, $USER->id);
3148 * Extends the settings navigation for the given user.
3150 * Note: This method gets called automatically if you call
3151 * $PAGE->navigation->extend_for_user($userid)
3153 * @param int $userid
3155 public function extend_for_user($userid) {
3158 if (!in_array($userid, $this->userstoextendfor)) {
3159 $this->userstoextendfor[] = $userid;
3160 if ($this->initialised) {
3161 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3162 $children = array();
3163 foreach ($this->children as $child) {
3164 $children[] = $child;
3166 array_unshift($children, array_pop($children));
3167 $this->children = new navigation_node_collection();
3168 foreach ($children as $child) {
3169 $this->children->add($child);
3176 * This function gets called by {@link load_user_settings()} and actually works out
3177 * what can be shown/done
3179 * @param int $courseid The current course' id
3180 * @param int $userid The user id to load for
3181 * @param string $gstitle The string to pass to get_string for the branch title
3182 * @return navigation_node|false
3184 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3185 global $DB, $CFG, $USER, $SITE;
3187 if ($courseid != SITEID) {
3188 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3189 $course = $this->page->course;
3191 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
3197 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3198 $systemcontext = get_system_context();
3199 $currentuser = ($USER->id == $userid);
3203 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3205 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
3208 // Check that the user can view the profile
3209 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3210 if ($course->id==SITEID) {
3211 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3212 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3216 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !is_enrolled($coursecontext, $user->id)) {
3219 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3220 // If groups are in use, make sure we can see that group
3226 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3229 if ($gstitle != 'usercurrentsettings') {
3233 // Add a user setting branch
3234 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3235 $usersetting->id = 'usersettings';
3236 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3237 // Automatically start by making it active
3238 $usersetting->make_active();
3241 // Check if the user has been deleted
3242 if ($user->deleted) {
3243 if (!has_capability('moodle/user:update', $coursecontext)) {
3244 // We can't edit the user so just show the user deleted message
3245 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3247 // We can edit the user so show the user deleted message and link it to the profile
3248 if ($course->id == SITEID) {
3249 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3251 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3253 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3258 // Add the profile edit link
3259 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3260 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3261 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3262 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3263 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3264 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3265 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3269 // Change password link
3270 if (!empty($user->auth)) {
3271 $userauth = get_auth_plugin($user->auth);
3272 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3273 $passwordchangeurl = $userauth->change_password_url();
3274 if (empty($passwordchangeurl)) {
3275 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3277 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3281 // View the roles settings
3282 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3283 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3285 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3286 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3288 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3290 if (!empty($assignableroles)) {
3291 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3292 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3295 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3296 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3297 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3300 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3301 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3305 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3306 require_once($CFG->libdir . '/portfoliolib.php');
3307 if (portfolio_instances(true, false)) {
3308 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3310 $config = optional_param('config', 0, PARAM_INT);
3311 $hide = optional_param('hide', 0, PARAM_INT);
3312 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3314 $url->param('hide', $hide);
3316 if ($config !== 0) {
3317 $url->param('config', $config);
3319 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);