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 if (!function_exists('get_all_sections')) {
30 /** Include course lib for its functions */
31 require_once($CFG->dirroot.'/course/lib.php');
35 * The name that will be used to separate the navigation cache within SESSION
37 define('NAVIGATION_CACHE_NAME', 'navigation');
40 * This class is used to represent a node in a navigation tree
42 * This class is used to represent a node in a navigation tree within Moodle,
43 * the tree could be one of global navigation, settings navigation, or the navbar.
44 * Each node can be one of two types either a Leaf (default) or a branch.
45 * When a node is first created it is created as a leaf, when/if children are added
46 * the node then becomes a branch.
49 * @subpackage navigation
50 * @copyright 2009 Sam Hemelryk
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class navigation_node implements renderable {
54 /** @var int Used to identify this node a leaf (default) 0 */
55 const NODETYPE_LEAF = 0;
56 /** @var int Used to identify this node a branch, happens with children 1 */
57 const NODETYPE_BRANCH = 1;
58 /** @var null Unknown node type null */
59 const TYPE_UNKNOWN = null;
60 /** @var int System node type 0 */
61 const TYPE_ROOTNODE = 0;
62 /** @var int System node type 1 */
63 const TYPE_SYSTEM = 1;
64 /** @var int Category node type 10 */
65 const TYPE_CATEGORY = 10;
66 /** @var int Course node type 20 */
67 const TYPE_COURSE = 20;
68 /** @var int Course Structure node type 30 */
69 const TYPE_SECTION = 30;
70 /** @var int Activity node type, e.g. Forum, Quiz 40 */
71 const TYPE_ACTIVITY = 40;
72 /** @var int Resource node type, e.g. Link to a file, or label 50 */
73 const TYPE_RESOURCE = 50;
74 /** @var int A custom node type, default when adding without specifing type 60 */
75 const TYPE_CUSTOM = 60;
76 /** @var int Setting node type, used only within settings nav 70 */
77 const TYPE_SETTING = 70;
78 /** @var int Setting node type, used only within settings nav 80 */
80 /** @var int Setting node type, used for containers of no importance 90 */
81 const TYPE_CONTAINER = 90;
83 /** @var int Parameter to aid the coder in tracking [optional] */
85 /** @var string|int The identifier for the node, used to retrieve the node */
87 /** @var string The text to use for the node */
89 /** @var string Short text to use if requested [optional] */
90 public $shorttext = null;
91 /** @var string The title attribute for an action if one is defined */
93 /** @var string A string that can be used to build a help button */
94 public $helpbutton = null;
95 /** @var moodle_url|action_link|null An action for the node (link) */
96 public $action = null;
97 /** @var pix_icon The path to an icon to use for this node */
99 /** @var int See TYPE_* constants defined for this class */
100 public $type = self::TYPE_UNKNOWN;
101 /** @var int See NODETYPE_* constants defined for this class */
102 public $nodetype = self::NODETYPE_LEAF;
103 /** @var bool If set to true the node will be collapsed by default */
104 public $collapse = false;
105 /** @var bool If set to true the node will be expanded by default */
106 public $forceopen = false;
107 /** @var array An array of CSS classes for the node */
108 public $classes = array();
109 /** @var navigation_node_collection An array of child nodes */
110 public $children = array();
111 /** @var bool If set to true the node will be recognised as active */
112 public $isactive = false;
113 /** @var bool If set to true the node will be dimmed */
114 public $hidden = false;
115 /** @var bool If set to false the node will not be displayed */
116 public $display = true;
117 /** @var bool If set to true then an HR will be printed before the node */
118 public $preceedwithhr = false;
119 /** @var bool If set to true the the navigation bar should ignore this node */
120 public $mainnavonly = false;
121 /** @var bool If set to true a title will be added to the action no matter what */
122 public $forcetitle = false;
123 /** @var navigation_node A reference to the node parent */
124 public $parent = null;
125 /** @var bool Override to not display the icon even if one is provided **/
126 public $hideicon = false;
128 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
129 /** @var moodle_url */
130 protected static $fullmeurl = null;
131 /** @var bool toogles auto matching of active node */
132 public static $autofindactive = true;
135 * Constructs a new navigation_node
137 * @param array|string $properties Either an array of properties or a string to use
138 * as the text for the node
140 public function __construct($properties) {
141 if (is_array($properties)) {
142 // Check the array for each property that we allow to set at construction.
143 // text - The main content for the node
144 // shorttext - A short text if required for the node
145 // icon - The icon to display for the node
146 // type - The type of the node
147 // key - The key to use to identify the node
148 // parent - A reference to the nodes parent
149 // action - The action to attribute to this node, usually a URL to link to
150 if (array_key_exists('text', $properties)) {
151 $this->text = $properties['text'];
153 if (array_key_exists('shorttext', $properties)) {
154 $this->shorttext = $properties['shorttext'];
156 if (!array_key_exists('icon', $properties)) {
157 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
159 $this->icon = $properties['icon'];
160 if ($this->icon instanceof pix_icon) {
161 if (empty($this->icon->attributes['class'])) {
162 $this->icon->attributes['class'] = 'navicon';
164 $this->icon->attributes['class'] .= ' navicon';
167 if (array_key_exists('type', $properties)) {
168 $this->type = $properties['type'];
170 $this->type = self::TYPE_CUSTOM;
172 if (array_key_exists('key', $properties)) {
173 $this->key = $properties['key'];
175 if (array_key_exists('parent', $properties)) {
176 $this->parent = $properties['parent'];
178 // This needs to happen last because of the check_if_active call that occurs
179 if (array_key_exists('action', $properties)) {
180 $this->action = $properties['action'];
181 if (is_string($this->action)) {
182 $this->action = new moodle_url($this->action);
184 if (self::$autofindactive) {
185 $this->check_if_active();
188 } else if (is_string($properties)) {
189 $this->text = $properties;
191 if ($this->text === null) {
192 throw new coding_exception('You must set the text for the node when you create it.');
194 // Default the title to the text
195 $this->title = $this->text;
196 // Instantiate a new navigation node collection for this nodes children
197 $this->children = new navigation_node_collection();
201 * Checks if this node is the active node.
203 * This is determined by comparing the action for the node against the
204 * defined URL for the page. A match will see this node marked as active.
206 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
209 public function check_if_active($strength=URL_MATCH_EXACT) {
210 global $FULLME, $PAGE;
211 // Set fullmeurl if it hasn't already been set
212 if (self::$fullmeurl == null) {
213 if ($PAGE->has_set_url()) {
214 self::override_active_url(new moodle_url($PAGE->url));
216 self::override_active_url(new moodle_url($FULLME));
220 // Compare the action of this node against the fullmeurl
221 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
222 $this->make_active();
229 * Overrides the fullmeurl variable providing
231 * @param moodle_url $url The url to use for the fullmeurl.
233 public static function override_active_url(moodle_url $url) {
234 self::$fullmeurl = $url;
238 * Adds a navigation node as a child of this node.
240 * @param string $text
241 * @param moodle_url|action_link $action
243 * @param string $shorttext
244 * @param string|int $key
245 * @param pix_icon $icon
246 * @return navigation_node
248 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
249 // First convert the nodetype for this node to a branch as it will now have children
250 if ($this->nodetype !== self::NODETYPE_BRANCH) {
251 $this->nodetype = self::NODETYPE_BRANCH;
253 // Properties array used when creating the new navigation node
258 // Set the action if one was provided
259 if ($action!==null) {
260 $itemarray['action'] = $action;
262 // Set the shorttext if one was provided
263 if ($shorttext!==null) {
264 $itemarray['shorttext'] = $shorttext;
266 // Set the icon if one was provided
268 $itemarray['icon'] = $icon;
270 // Default the key to the number of children if not provided
272 $key = $this->children->count();
275 $itemarray['key'] = $key;
276 // Set the parent to this node
277 $itemarray['parent'] = $this;
278 // Add the child using the navigation_node_collections add method
279 $node = $this->children->add(new navigation_node($itemarray));
280 // If the node is a category node or the user is logged in and its a course
281 // then mark this node as a branch (makes it expandable by AJAX)
282 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
283 $node->nodetype = self::NODETYPE_BRANCH;
285 // If this node is hidden mark it's children as hidden also
287 $node->hidden = true;
289 // Return the node (reference returned by $this->children->add()
294 * Searches for a node of the given type with the given key.
296 * This searches this node plus all of its children, and their children....
297 * If you know the node you are looking for is a child of this node then please
298 * use the get method instead.
300 * @param int|string $key The key of the node we are looking for
301 * @param int $type One of navigation_node::TYPE_*
302 * @return navigation_node|false
304 public function find($key, $type) {
305 return $this->children->find($key, $type);
309 * Get ths child of this node that has the given key + (optional) type.
311 * If you are looking for a node and want to search all children + thier children
312 * then please use the find method instead.
314 * @param int|string $key The key of the node we are looking for
315 * @param int $type One of navigation_node::TYPE_*
316 * @return navigation_node|false
318 public function get($key, $type=null) {
319 return $this->children->get($key, $type);
327 public function remove() {
328 return $this->parent->children->remove($this->key, $this->type);
332 * Checks if this node has or could have any children
334 * @return bool Returns true if it has children or could have (by AJAX expansion)
336 public function has_children() {
337 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
341 * Marks this node as active and forces it open.
343 public function make_active() {
344 $this->isactive = true;
345 $this->add_class('active_tree_node');
347 if ($this->parent !== null) {
348 $this->parent->make_inactive();
353 * Marks a node as inactive and recusised back to the base of the tree
354 * doing the same to all parents.
356 public function make_inactive() {
357 $this->isactive = false;
358 $this->remove_class('active_tree_node');
359 if ($this->parent !== null) {
360 $this->parent->make_inactive();
365 * Forces this node to be open and at the same time forces open all
366 * parents until the root node.
370 public function force_open() {
371 $this->forceopen = true;
372 if ($this->parent !== null) {
373 $this->parent->force_open();
378 * Adds a CSS class to this node.
380 * @param string $class
383 public function add_class($class) {
384 if (!in_array($class, $this->classes)) {
385 $this->classes[] = $class;
391 * Removes a CSS class from this node.
393 * @param string $class
394 * @return bool True if the class was successfully removed.
396 public function remove_class($class) {
397 if (in_array($class, $this->classes)) {
398 $key = array_search($class,$this->classes);
400 unset($this->classes[$key]);
408 * Sets the title for this node and forces Moodle to utilise it.
409 * @param string $title
411 public function title($title) {
412 $this->title = $title;
413 $this->forcetitle = true;
417 * Resets the page specific information on this node if it is being unserialised.
419 public function __wakeup(){
420 $this->forceopen = false;
421 $this->isactive = false;
422 $this->remove_class('active_tree_node');
426 * Checks if this node or any of its children contain the active node.
432 public function contains_active_node() {
433 if ($this->isactive) {
436 foreach ($this->children as $child) {
437 if ($child->isactive || $child->contains_active_node()) {
446 * Finds the active node.
448 * Searches this nodes children plus all of the children for the active node
449 * and returns it if found.
453 * @return navigation_node|false
455 public function find_active_node() {
456 if ($this->isactive) {
459 foreach ($this->children as &$child) {
460 $outcome = $child->find_active_node();
461 if ($outcome !== false) {
470 * Searches all children for the best matching active node
471 * @return navigation_node|false
473 public function search_for_active_node() {
474 if ($this->check_if_active(URL_MATCH_BASE)) {
477 foreach ($this->children as &$child) {
478 $outcome = $child->search_for_active_node();
479 if ($outcome !== false) {
488 * Gets the content for this node.
490 * @param bool $shorttext If true shorttext is used rather than the normal text
493 public function get_content($shorttext=false) {
494 if ($shorttext && $this->shorttext!==null) {
495 return format_string($this->shorttext);
497 return format_string($this->text);
502 * Gets the title to use for this node.
506 public function get_title() {
507 if ($this->forcetitle || $this->action != null){
515 * Gets the CSS class to add to this node to describe its type
519 public function get_css_type() {
520 if (array_key_exists($this->type, $this->namedtypes)) {
521 return 'type_'.$this->namedtypes[$this->type];
523 return 'type_unknown';
527 * Finds all nodes that are expandable by AJAX
529 * @param array $expandable An array by reference to populate with expandable nodes.
531 public function find_expandable(array &$expandable) {
532 $isloggedin = (isloggedin() && !isguestuser());
533 if (!$isloggedin && $this->type > self::TYPE_CATEGORY) {
536 foreach ($this->children as &$child) {
537 if (!$isloggedin && $child->type > self::TYPE_CATEGORY) {
540 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count()==0 && $child->display) {
541 $child->id = 'expandable_branch_'.(count($expandable)+1);
542 $this->add_class('canexpand');
543 $expandable[] = array('id'=>$child->id,'branchid'=>$child->key,'type'=>$child->type);
545 $child->find_expandable($expandable);
550 * Finds all nodes of a given type (recursive)
552 * @param int $type On of navigation_node::TYPE_*
555 public function find_all_of_type($type) {
556 $nodes = $this->children->type($type);
557 foreach ($this->children as &$node) {
558 $childnodes = $node->find_all_of_type($type);
559 $nodes = array_merge($nodes, $childnodes);
565 * Removes this node if it is empty
567 public function trim_if_empty() {
568 if ($this->children->count() == 0) {
574 * Creates a tab representation of this nodes children that can be used
575 * with print_tabs to produce the tabs on a page.
577 * call_user_func_array('print_tabs', $node->get_tabs_array());
579 * @param array $inactive
580 * @param bool $return
581 * @return array Array (tabs, selected, inactive, activated, return)
583 public function get_tabs_array(array $inactive=array(), $return=false) {
587 $activated = array();
588 foreach ($this->children as $node) {
589 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
590 if ($node->contains_active_node()) {
591 if ($node->children->count() > 0) {
592 $activated[] = $node->key;
593 foreach ($node->children as $child) {
594 if ($child->contains_active_node()) {
595 $selected = $child->key;
597 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
600 $selected = $node->key;
604 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
609 * Navigation node collection
611 * This class is responsible for managing a collection of navigation nodes.
612 * It is required because a node's unique identifier is a combination of both its
615 * Originally an array was used with a string key that was a combination of the two
616 * however it was decided that a better solution would be to use a class that
617 * implements the standard IteratorAggregate interface.
619 * @package moodlecore
620 * @subpackage navigation
621 * @copyright 2010 Sam Hemelryk
622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
624 class navigation_node_collection implements IteratorAggregate {
626 * A multidimensional array to where the first key is the type and the second
627 * key is the nodes key.
630 protected $collection = array();
632 * An array that contains references to nodes in the same order they were added.
633 * This is maintained as a progressive array.
636 protected $orderedcollection = array();
638 * A reference to the last node that was added to the collection
639 * @var navigation_node
641 protected $last = null;
643 * The total number of items added to this array.
646 protected $count = 0;
648 * Adds a navigation node to the collection
650 * @param navigation_node $node
651 * @return navigation_node
653 public function add(navigation_node $node) {
657 // First check we have a 2nd dimension for this type
658 if (!array_key_exists($type, $this->orderedcollection)) {
659 $this->orderedcollection[$type] = array();
661 // Check for a collision and report if debugging is turned on
662 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
663 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
665 // Add the node to the appropriate place in the ordered structure.
666 $this->orderedcollection[$type][$key] = $node;
667 // Add a reference to the node to the progressive collection.
668 $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
669 // Update the last property to a reference to this new node.
670 $this->last = &$this->orderedcollection[$type][$key];
672 // Return the reference to the now added node
677 * Fetches a node from this collection.
679 * @param string|int $key The key of the node we want to find.
680 * @param int $type One of navigation_node::TYPE_*.
681 * @return navigation_node|null
683 public function get($key, $type=null) {
684 if ($type !== null) {
685 // If the type is known then we can simply check and fetch
686 if (!empty($this->orderedcollection[$type][$key])) {
687 return $this->orderedcollection[$type][$key];
690 // Because we don't know the type we look in the progressive array
691 foreach ($this->collection as $node) {
692 if ($node->key === $key) {
700 * Searches for a node with matching key and type.
702 * This function searches both the nodes in this collection and all of
703 * the nodes in each collection belonging to the nodes in this collection.
707 * @param string|int $key The key of the node we want to find.
708 * @param int $type One of navigation_node::TYPE_*.
709 * @return navigation_node|null
711 public function find($key, $type=null) {
712 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
713 return $this->orderedcollection[$type][$key];
715 $nodes = $this->getIterator();
716 // Search immediate children first
717 foreach ($nodes as &$node) {
718 if ($node->key == $key && ($type == null || $type === $node->type)) {
722 // Now search each childs children
723 foreach ($nodes as &$node) {
724 $result = $node->children->find($key, $type);
725 if ($result !== false) {
734 * Fetches the last node that was added to this collection
736 * @return navigation_node
738 public function last() {
742 * Fetches all nodes of a given type from this collection
744 public function type($type) {
745 if (!array_key_exists($type, $this->orderedcollection)) {
746 $this->orderedcollection[$type] = array();
748 return $this->orderedcollection[$type];
751 * Removes the node with the given key and type from the collection
753 * @param string|int $key
757 public function remove($key, $type=null) {
758 $child = $this->get($key, $type);
759 if ($child !== false) {
760 foreach ($this->collection as $colkey => $node) {
761 if ($node->key == $key && $node->type == $type) {
762 unset($this->collection[$colkey]);
766 unset($this->orderedcollection[$child->type][$child->key]);
774 * Gets the number of nodes in this collection
777 public function count() {
778 return count($this->collection);
781 * Gets an array iterator for the collection.
783 * This is required by the IteratorAggregator interface and is used by routines
784 * such as the foreach loop.
786 * @return ArrayIterator
788 public function getIterator() {
789 return new ArrayIterator($this->collection);
794 * The global navigation class used for... the global navigation
796 * This class is used by PAGE to store the global navigation for the site
797 * and is then used by the settings nav and navbar to save on processing and DB calls
801 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
802 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
805 * @package moodlecore
806 * @subpackage navigation
807 * @copyright 2009 Sam Hemelryk
808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
810 class global_navigation extends navigation_node {
812 * The Moodle page this navigation object belongs to.
817 protected $initialised = false;
819 protected $mycourses = array();
821 protected $rootnodes = array();
823 protected $showemptysections = false;
825 protected $extendforuser = array();
826 /** @var navigation_cache */
829 protected $addedcourses = array();
831 protected $expansionlimit = 0;
834 * Constructs a new global navigation
836 * @param moodle_page $page The page this navigation object belongs to
838 public function __construct(moodle_page $page) {
839 global $CFG, $SITE, $USER;
841 if (during_initial_install()) {
845 if (get_home_page() == HOMEPAGE_SITE) {
846 // We are using the site home for the root element
849 'type' => navigation_node::TYPE_SYSTEM,
850 'text' => get_string('home'),
851 'action' => new moodle_url('/')
854 // We are using the users my moodle for the root element
857 'type' => navigation_node::TYPE_SYSTEM,
858 'text' => get_string('myhome'),
859 'action' => new moodle_url('/my/')
863 // Use the parents consturctor.... good good reuse
864 parent::__construct($properties);
866 // Initalise and set defaults
868 $this->forceopen = true;
869 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
871 // Check if we need to clear the cache
872 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
873 if ($regenerate === 'navigation') {
874 $this->cache->clear();
879 * Initialises the navigation object.
881 * This causes the navigation object to look at the current state of the page
882 * that it is associated with and then load the appropriate content.
884 * This should only occur the first time that the navigation structure is utilised
885 * which will normally be either when the navbar is called to be displayed or
886 * when a block makes use of it.
890 public function initialise() {
891 global $CFG, $SITE, $USER, $DB;
892 // Check if it has alread been initialised
893 if ($this->initialised || during_initial_install()) {
896 $this->initialised = true;
898 // Set up the five base root nodes. These are nodes where we will put our
899 // content and are as follows:
900 // site: Navigation for the front page.
901 // myprofile: User profile information goes here.
902 // mycourses: The users courses get added here.
903 // courses: Additional courses are added here.
904 // users: Other users information loaded here.
905 $this->rootnodes = array();
906 if (get_home_page() == HOMEPAGE_SITE) {
907 // The home element should be my moodle because the root element is the site
908 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
909 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
912 // The home element should be the site because the root node is my moodle
913 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
914 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
915 // We need to stop automatic redirection
916 $this->rootnodes['home']->action->param('redirect', '0');
919 $this->rootnodes['site'] = $this->add_course($SITE);
920 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
921 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
922 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
923 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
925 // Fetch all of the users courses.
927 if (!empty($CFG->navcourselimit)) {
928 $limit = $CFG->navcourselimit;
931 if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') == 1) {
932 // There is only one category so we don't want to show categories
933 $CFG->navshowcategories = false;
936 $this->mycourses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', null, false, $limit);
937 $showallcourses = (count($this->mycourses) == 0 || !empty($CFG->navshowallcourses));
938 $showcategories = ($showallcourses && !empty($CFG->navshowcategories));
940 // Check if any courses were returned.
941 if (count($this->mycourses) > 0) {
942 // Add all of the users courses to the navigation
943 foreach ($this->mycourses as &$course) {
944 $course->coursenode = $this->add_course($course);
948 if ($showcategories) {
949 // Load all categories (ensures we get the base categories)
950 $this->load_all_categories();
951 } else if ($showallcourses) {
953 $this->load_all_courses();
956 // Next load context specific content into the navigation
957 switch ($this->page->context->contextlevel) {
958 case CONTEXT_SYSTEM :
959 case CONTEXT_COURSECAT :
960 // Load the front page course navigation
961 $coursenode = $this->load_course($SITE);
962 $this->add_front_page_course_essentials($coursenode, $SITE);
965 case CONTEXT_COURSE :
966 // Load the course associated with the page into the navigation
967 $course = $this->page->course;
968 $coursenode = $this->load_course($course);
969 // Add the essentials such as reports etc...
970 $this->add_course_essentials($coursenode, $course);
971 if ($this->format_display_course_content($course->format)) {
972 // Load the course sections
973 $sections = $this->load_course_sections($course, $coursenode);
975 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
976 $coursenode->make_active();
979 case CONTEXT_MODULE :
980 $course = $this->page->course;
981 $cm = $this->page->cm;
982 // Load the course associated with the page into the navigation
983 $coursenode = $this->load_course($course);
984 $this->add_course_essentials($coursenode, $course);
985 // Load the course sections into the page
986 $sections = $this->load_course_sections($course, $coursenode);
987 if ($course->id !== SITEID) {
988 // Find the section for the $CM associated with the page and collect
989 // its section number.
990 foreach ($sections as $section) {
991 if ($section->id == $cm->section) {
992 $cm->sectionnumber = $section->section;
997 // Load all of the section activities for the section the cm belongs to.
998 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1000 $activities = array();
1001 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1003 // Finally load the cm specific navigaton information
1004 $this->load_activity($cm, $course, $activities[$cm->id]);
1005 // Check if we have an active ndoe
1006 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1007 // And make the activity node active.
1008 $activities[$cm->id]->make_active();
1012 $course = $this->page->course;
1013 if ($course->id != SITEID) {
1014 // Load the course associated with the user into the navigation
1015 $coursenode = $this->load_course($course);
1016 $this->add_course_essentials($coursenode, $course);
1017 $sections = $this->load_course_sections($course, $coursenode);
1023 if (!empty($CFG->navcourselimit)) {
1024 $limit = $CFG->navcourselimit;
1026 if ($showcategories) {
1027 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1028 foreach ($categories as &$category) {
1029 if ($category->children->count() >= $limit) {
1030 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1031 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1034 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1035 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1038 // Load for the current user
1039 $this->load_for_user();
1040 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
1041 $this->load_for_user(null, true);
1043 // Load each extending user into the navigation.
1044 foreach ($this->extendforuser as $user) {
1045 if ($user->id !== $USER->id) {
1046 $this->load_for_user($user);
1050 // Give the local plugins a chance to include some navigation if they want.
1051 foreach (get_list_of_plugins('local') as $plugin) {
1052 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1055 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1056 $function = $plugin.'_extends_navigation';
1057 if (function_exists($function)) {
1062 // Remove any empty root nodes
1063 foreach ($this->rootnodes as $node) {
1064 // Dont remove the home node
1065 if ($node->key !== 'home' && !$node->has_children()) {
1070 if (!$this->contains_active_node()) {
1071 $this->search_for_active_node();
1074 // If the user is not logged in modify the navigation structure as detailed
1075 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1076 if (!isloggedin()) {
1077 $activities = clone($this->rootnodes['site']->children);
1078 $this->rootnodes['site']->remove();
1079 $children = clone($this->children);
1080 $this->children = new navigation_node_collection();
1081 foreach ($activities as $child) {
1082 $this->children->add($child);
1084 foreach ($children as $child) {
1085 $this->children->add($child);
1091 * Checks the course format to see whether it wants the navigation to load
1092 * additional information for the course.
1094 * This function utilises a callback that can exist within the course format lib.php file
1095 * The callback should be a function called:
1096 * callback_{formatname}_display_content()
1097 * It doesn't get any arguments and should return true if additional content is
1098 * desired. If the callback doesn't exist we assume additional content is wanted.
1100 * @param string $format The course format
1103 protected function format_display_course_content($format) {
1105 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1106 if (file_exists($formatlib)) {
1107 require_once($formatlib);
1108 $displayfunc = 'callback_'.$format.'_display_content';
1109 if (function_exists($displayfunc) && !$displayfunc()) {
1110 return $displayfunc();
1117 * Loads of the the courses in Moodle into the navigation.
1119 * @param string|array $categoryids Either a string or array of category ids to load courses for
1120 * @return array An array of navigation_node
1122 protected function load_all_courses($categoryids=null) {
1123 global $CFG, $DB, $USER;
1125 if ($categoryids !== null) {
1126 if (is_array($categoryids)) {
1127 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1130 $params = array($categoryids);
1132 array_unshift($params, SITEID);
1133 $select = ' AND c.category '.$select;
1135 $params = array(SITEID);
1139 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1140 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1143 LEFT JOIN {course_categories} cat ON cat.id=c.category
1144 WHERE c.id <> ?$select
1145 ORDER BY c.sortorder ASC";
1147 if (!empty($CFG->navcourselimit)) {
1148 $limit = $CFG->navcourselimit;
1150 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1152 $coursenodes = array();
1153 foreach ($courses as $course) {
1154 context_instance_preload($course);
1155 $coursenodes[$course->id] = $this->add_course($course);
1157 return $coursenodes;
1161 * Loads all categories (top level or if an id is specified for that category)
1163 * @param int $categoryid
1166 protected function load_all_categories($categoryid=null) {
1168 if ($categoryid == null) {
1169 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1171 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1172 $wantedids = explode('/', trim($category->path, '/'));
1173 list($select, $params) = $DB->get_in_or_equal($wantedids);
1174 $select = 'id '.$select.' OR parent '.$select;
1175 $params = array_merge($params, $params);
1176 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1178 $structured = array();
1179 $categoriestoload = array();
1180 foreach ($categories as $category) {
1181 if ($category->parent == '0') {
1182 $structured[$category->id] = array('category'=>$category, 'children'=>array());
1184 if ($category->parent == $categoryid) {
1185 $categoriestoload[] = $category->id;
1188 $id = $category->parent;
1189 while ($id != '0') {
1191 if (!array_key_exists($id, $categories)) {
1192 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST);
1194 $id = $categories[$id]->parent;
1196 $parents = array_reverse($parents);
1197 $parentref = &$structured[array_shift($parents)];
1198 foreach ($parents as $parent) {
1199 if (!array_key_exists($parent, $parentref['children'])) {
1200 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1202 $parentref = &$parentref['children'][$parent];
1204 if (!array_key_exists($category->id, $parentref['children'])) {
1205 $parentref['children'][$category->id] = array('category'=>$category, 'children'=>array());
1210 foreach ($structured as $category) {
1211 $this->add_category($category, $this->rootnodes['courses']);
1214 if ($categoryid !== null && count($wantedids)) {
1215 foreach ($wantedids as $catid) {
1216 $this->load_all_courses($catid);
1222 * Adds a structured category to the navigation in the correct order/place
1224 * @param object $cat
1225 * @param navigation_node $parent
1227 protected function add_category($cat, navigation_node $parent) {
1228 $category = $parent->get($cat['category']->id, navigation_node::TYPE_CATEGORY);
1230 $category = $cat['category'];
1231 $url = new moodle_url('/course/category.php', array('id'=>$category->id));
1232 $category = $parent->add($category->name, null, self::TYPE_CATEGORY, $category->name, $category->id);
1234 foreach ($cat['children'] as $child) {
1235 $this->add_category($child, $category);
1240 * Loads the given course into the navigation
1242 * @param stdClass $course
1243 * @return navigation_node
1245 protected function load_course(stdClass $course) {
1246 if ($course->id == SITEID) {
1247 $coursenode = $this->rootnodes['site'];
1248 } else if (array_key_exists($course->id, $this->mycourses)) {
1249 if (!isset($this->mycourses[$course->id]->coursenode)) {
1250 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
1252 $coursenode = $this->mycourses[$course->id]->coursenode;
1254 $coursenode = $this->add_course($course);
1260 * Loads all of the courses section into the navigation.
1262 * This function utilisies a callback that can be implemented within the course
1263 * formats lib.php file to customise the navigation that is generated at this
1264 * point for the course.
1266 * By default (if not defined) the method {@see load_generic_course_sections} is
1269 * @param stdClass $course Database record for the course
1270 * @param navigation_node $coursenode The course node within the navigation
1271 * @return array Array of navigation nodes for the section with key = section id
1273 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1275 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1276 $structurefunc = 'callback_'.$course->format.'_load_content';
1277 if (function_exists($structurefunc)) {
1278 return $structurefunc($this, $course, $coursenode);
1279 } else if (file_exists($structurefile)) {
1280 require_once $structurefile;
1281 if (function_exists($structurefunc)) {
1282 return $structurefunc($this, $course, $coursenode);
1284 return $this->load_generic_course_sections($course, $coursenode);
1287 return $this->load_generic_course_sections($course, $coursenode);
1292 * Generically loads the course sections into the course's navigation.
1294 * @param stdClass $course
1295 * @param navigation_node $coursenode
1296 * @param string $name The string that identifies each section. e.g Topic, or Week
1297 * @param string $activeparam The url used to identify the active section
1298 * @return array An array of course section nodes
1300 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1303 $modinfo = get_fast_modinfo($course);
1304 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1305 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1307 if (isloggedin() && !isguestuser()) {
1308 $activesection = $DB->get_field("course_display", "display", array("userid"=>$USER->id, "course"=>$course->id));
1310 $activesection = null;
1313 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1314 $namingfunctionexists = (function_exists($namingfunction));
1316 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1317 if (function_exists($activeparamfunction)) {
1318 $activeparam = $activeparamfunction();
1320 $activeparam = 'section';
1322 $navigationsections = array();
1323 foreach ($sections as $sectionid=>$section) {
1324 $section = clone($section);
1325 if ($course->id == SITEID) {
1326 $this->load_section_activities($coursenode, $section->section, $modinfo);
1328 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1331 if ($namingfunctionexists) {
1332 $sectionname = $namingfunction($course, $section, $sections);
1334 $sectionname = get_string('section').' '.$section->section;
1336 $url = new moodle_url('/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1337 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1338 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1339 $sectionnode->hidden = (!$section->visible);
1340 if ($this->page->context->contextlevel != CONTEXT_MODULE && ($sectionnode->isactive || ($activesection != null && $section->section == $activesection))) {
1341 $sectionnode->force_open();
1342 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1344 $section->sectionnode = $sectionnode;
1345 $navigationsections[$sectionid] = $section;
1348 return $navigationsections;
1351 * Loads all of the activities for a section into the navigation structure.
1353 * @param navigation_node $sectionnode
1354 * @param int $sectionnumber
1355 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1356 * @return array Array of activity nodes
1358 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1359 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1363 $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page->context);
1365 $activities = array();
1367 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1368 $cm = $modinfo->cms[$cmid];
1369 if (!$viewhiddenactivities && !$cm->visible) {
1373 $icon = new pix_icon($cm->icon, '', $cm->iconcomponent);
1375 $icon = new pix_icon('icon', '', $cm->modname);
1377 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1378 $activitynode = $sectionnode->add($cm->name, $url, navigation_node::TYPE_ACTIVITY, $cm->name, $cm->id, $icon);
1379 $activitynode->title(get_string('modulename', $cm->modname));
1380 $activitynode->hidden = (!$cm->visible);
1381 if ($this->module_extends_navigation($cm->modname)) {
1382 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1384 $activities[$cmid] = $activitynode;
1390 * Loads the navigation structure for the given activity into the activities node.
1392 * This method utilises a callback within the modules lib.php file to load the
1393 * content specific to activity given.
1395 * The callback is a method: {modulename}_extend_navigation()
1397 * * {@see forum_extend_navigation()}
1398 * * {@see workshop_extend_navigation()}
1400 * @param stdClass $cm
1401 * @param stdClass $course
1402 * @param navigation_node $activity
1405 protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1408 $activity->make_active();
1409 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1410 $function = $cm->modname.'_extend_navigation';
1412 if (file_exists($file)) {
1413 require_once($file);
1414 if (function_exists($function)) {
1415 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1416 $function($activity, $course, $activtyrecord, $cm);
1420 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1424 * Loads user specific information into the navigation in the appopriate place.
1426 * If no user is provided the current user is assumed.
1428 * @param stdClass $user
1431 protected function load_for_user($user=null, $forceforcontext=false) {
1432 global $DB, $CFG, $USER;
1434 $iscurrentuser = false;
1435 if ($user === null) {
1436 // We can't require login here but if the user isn't logged in we don't
1437 // want to show anything
1438 if (!isloggedin() || isguestuser()) {
1442 $iscurrentuser = true;
1443 } else if (!is_object($user)) {
1444 // If the user is not an object then get them from the database
1445 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1447 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1449 // Get the course set against the page, by default this will be the site
1450 $course = $this->page->course;
1451 $baseargs = array('id'=>$user->id);
1452 if ($course->id !== SITEID && (!$iscurrentuser || $forceforcontext)) {
1453 if (array_key_exists($course->id, $this->mycourses)) {
1454 $coursenode = $this->mycourses[$course->id]->coursenode;
1456 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1458 $coursenode = $this->load_course($course);
1461 $baseargs['course'] = $course->id;
1462 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1463 $issitecourse = false;
1465 // Load all categories and get the context for the system
1466 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1467 $issitecourse = true;
1470 // Create a node to add user information under.
1471 if ($iscurrentuser && !$forceforcontext) {
1472 // If it's the current user the information will go under the profile root node
1473 $usernode = $this->rootnodes['myprofile'];
1475 if (!$issitecourse) {
1476 // Not the current user so add it to the participants node for the current course
1477 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1479 // This is the site so add a users node to the root branch
1480 $usersnode = $this->rootnodes['users'];
1481 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1483 // Add a branch for the current user
1484 $usernode = $usersnode->add(fullname($user, true), null, self::TYPE_USER, null, $user->id);
1487 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1488 $usernode->force_open();
1491 // If the user is the current user or has permission to view the details of the requested
1492 // user than add a view profile link.
1493 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1494 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1495 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1497 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1501 // Add nodes for forum posts and discussions if the user can view either or both
1502 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1503 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
1504 if ($canviewposts || $canviewdiscussions) {
1505 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1506 if ($canviewposts) {
1507 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1509 if ($canviewdiscussions) {
1510 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions', 'course'=>$course->id))));
1515 if (!empty($CFG->bloglevel)) {
1516 require_once($CFG->dirroot.'/blog/lib.php');
1517 // Get all options for the user
1518 $options = blog_get_options_for_user($user);
1519 if (count($options) > 0) {
1520 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1521 foreach ($options as $option) {
1522 $blogs->add($option['string'], $option['link']);
1527 // Add a node to view the users notes if permitted
1528 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1529 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1530 if ($coursecontext->instanceid) {
1531 $url->param('course', $coursecontext->instanceid);
1533 $usernode->add(get_string('notes', 'notes'), $url);
1536 // Add a reports tab and then add reports the the user has permission to see.
1537 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1538 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser));
1540 $reporttab = $usernode->add(get_string('activityreports'));
1541 $reportargs = array('user'=>$user->id);
1542 if (!empty($course->id)) {
1543 $reportargs['id'] = $course->id;
1545 $reportargs['id'] = SITEID;
1547 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1548 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1549 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1552 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1553 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1556 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1557 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1560 if (!empty($CFG->enablestats)) {
1561 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1562 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1566 $gradeaccess = false;
1567 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1568 //ok - can view all course grades
1569 $gradeaccess = true;
1570 } else if ($course->showgrades) {
1571 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1572 //ok - can view own grades
1573 $gradeaccess = true;
1574 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1575 // ok - can view grades of this user - parent most probably
1576 $gradeaccess = true;
1577 } else if ($anyreport) {
1578 // ok - can view grades of this user - parent most probably
1579 $gradeaccess = true;
1583 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1586 // Check the number of nodes in the report node... if there are none remove
1588 if (count($reporttab->children)===0) {
1589 $usernode->remove_child($reporttab);
1594 // If the user is the current user add the repositories for the current user
1595 if ($iscurrentuser) {
1596 require_once($CFG->dirroot . '/repository/lib.php');
1597 $editabletypes = repository::get_editable_types($usercontext);
1598 if (!empty($editabletypes)) {
1599 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1606 * This method simply checks to see if a given module can extend the navigation.
1608 * @param string $modname
1611 protected function module_extends_navigation($modname) {
1613 if ($this->cache->cached($modname.'_extends_navigation')) {
1614 return $this->cache->{$modname.'_extends_navigation'};
1616 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1617 $function = $modname.'_extend_navigation';
1618 if (function_exists($function)) {
1619 $this->cache->{$modname.'_extends_navigation'} = true;
1621 } else if (file_exists($file)) {
1622 require_once($file);
1623 if (function_exists($function)) {
1624 $this->cache->{$modname.'_extends_navigation'} = true;
1628 $this->cache->{$modname.'_extends_navigation'} = false;
1632 * Extends the navigation for the given user.
1634 * @param stdClass $user A user from the database
1636 public function extend_for_user($user) {
1637 $this->extendforuser[] = $user;
1641 * Returns all of the users the navigation is being extended for
1645 public function get_extending_users() {
1646 return $this->extendforuser;
1649 * Adds the given course to the navigation structure.
1651 * @param stdClass $course
1652 * @return navigation_node
1654 public function add_course(stdClass $course, $forcegeneric = false) {
1656 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1657 if ($course->id !== SITEID && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1661 $issite = ($course->id == SITEID);
1662 $ismycourse = (array_key_exists($course->id, $this->mycourses) && !$forcegeneric);
1663 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories));
1668 $course->shortname = get_string('sitepages');
1669 } else if ($ismycourse) {
1670 $parent = $this->rootnodes['mycourses'];
1671 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1673 $parent = $this->rootnodes['courses'];
1674 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1677 if ($displaycategories) {
1678 // We need to load the category structure for this course
1679 $categoryfound = false;
1680 if (!empty($course->categorypath)) {
1681 $categories = explode('/', trim($course->categorypath, '/'));
1682 $category = $parent;
1683 while ($category && $categoryid = array_shift($categories)) {
1684 $category = $category->get($categoryid, self::TYPE_CATEGORY);
1686 if ($category instanceof navigation_node) {
1687 $parent = $category;
1688 $categoryfound = true;
1690 if (!$categoryfound && $forcegeneric) {
1691 $this->load_all_categories($course->category);
1692 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1693 $parent = $category;
1694 $categoryfound = true;
1697 } else if (!empty($course->category)) {
1698 $this->load_all_categories($course->category);
1699 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1700 $parent = $category;
1701 $categoryfound = true;
1703 if (!$categoryfound && !$forcegeneric) {
1704 $this->load_all_categories($course->category);
1705 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1706 $parent = $category;
1707 $categoryfound = true;
1713 // We found the course... we can return it now :)
1714 if ($coursenode = $parent->get($course->id, self::TYPE_COURSE)) {
1718 $coursenode = $parent->add($course->shortname, $url, self::TYPE_COURSE, $course->shortname, $course->id);
1719 $coursenode->nodetype = self::NODETYPE_BRANCH;
1720 $coursenode->hidden = (!$course->visible);
1721 $coursenode->title($course->fullname);
1722 $this->addedcourses[$course->id] = &$coursenode;
1723 if ($ismycourse && !empty($CFG->navshowallcourses)) {
1724 // We need to add this course to the general courses node as well as the
1725 // my courses node, rerun the function with the kill param
1726 $genericcourse = $this->add_course($course, true);
1727 if ($genericcourse->isactive) {
1728 $genericcourse->make_inactive();
1729 $genericcourse->collapse = true;
1730 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
1731 $parent = $genericcourse->parent;
1732 while ($parent && $parent->type == self::TYPE_CATEGORY) {
1733 $parent->collapse = true;
1734 $parent = $parent->parent;
1742 * Adds essential course nodes to the navigation for the given course.
1744 * This method adds nodes such as reports, blogs and participants
1746 * @param navigation_node $coursenode
1747 * @param stdClass $course
1750 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1753 if ($course->id == SITEID) {
1754 return $this->add_front_page_course_essentials($coursenode, $course);
1757 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1762 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1763 require_once($CFG->dirroot.'/blog/lib.php');
1764 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1765 $currentgroup = groups_get_course_group($course, true);
1766 if ($course->id == SITEID) {
1768 } else if ($course->id && !$currentgroup) {
1769 $filterselect = $course->id;
1771 $filterselect = $currentgroup;
1773 $filterselect = clean_param($filterselect, PARAM_INT);
1774 if ($CFG->bloglevel >= 3) {
1775 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1776 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1778 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1779 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1781 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
1782 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1785 // View course reports
1786 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1787 $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', ''));
1788 $coursereports = get_plugin_list('coursereport');
1789 foreach ($coursereports as $report=>$dir) {
1790 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1791 if (file_exists($libfile)) {
1792 require_once($libfile);
1793 $reportfunction = $report.'_report_extend_navigation';
1794 if (function_exists($report.'_report_extend_navigation')) {
1795 $reportfunction($reportnav, $course, $this->page->context);
1803 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1806 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1811 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1812 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1815 $currentgroup = groups_get_course_group($course, true);
1816 if ($course->id == SITEID) {
1818 } else if ($course->id && !$currentgroup) {
1819 $filterselect = $course->id;
1821 $filterselect = $currentgroup;
1823 $filterselect = clean_param($filterselect, PARAM_INT);
1826 if (has_capability('moodle/blog:view', $this->page->context)) {
1827 require_once($CFG->dirroot.'/blog/lib.php');
1828 if (blog_is_enabled_for_user()) {
1829 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1830 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1835 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1836 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1840 if (!empty($CFG->usetags) && isloggedin()) {
1841 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
1845 // View course reports
1846 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1847 $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', ''));
1848 $coursereports = get_plugin_list('coursereport');
1849 foreach ($coursereports as $report=>$dir) {
1850 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1851 if (file_exists($libfile)) {
1852 require_once($libfile);
1853 $reportfunction = $report.'_report_extend_navigation';
1854 if (function_exists($report.'_report_extend_navigation')) {
1855 $reportfunction($reportnav, $course, $this->page->context);
1864 * Clears the navigation cache
1866 public function clear_cache() {
1867 $this->cache->clear();
1870 public function set_expansion_limit($type) {
1871 $nodes = $this->find_all_of_type($type);
1872 foreach ($nodes as &$node) {
1873 foreach ($node->children as &$child) {
1874 $child->display = false;
1880 public function get($key, $type = null) {
1881 if (!$this->initialised) {
1882 $this->initialise();
1884 return parent::get($key, $type);
1887 public function find($key, $type) {
1888 if (!$this->initialised) {
1889 $this->initialise();
1891 return parent::find($key, $type);
1896 * The limited global navigation class used for the AJAX extension of the global
1899 * The primary methods that are used in the global navigation class have been overriden
1900 * to ensure that only the relevant branch is generated at the root of the tree.
1901 * This can be done because AJAX is only used when the backwards structure for the
1902 * requested branch exists.
1903 * This has been done only because it shortens the amounts of information that is generated
1904 * which of course will speed up the response time.. because no one likes laggy AJAX.
1906 * @package moodlecore
1907 * @subpackage navigation
1908 * @copyright 2009 Sam Hemelryk
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class global_navigation_for_ajax extends global_navigation {
1914 protected $expandable = array();
1917 * Constructs the navigation for use in AJAX request
1919 public function __construct($page, $branchtype, $id) {
1920 $this->page = $page;
1921 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1922 $this->children = new navigation_node_collection();
1923 $this->initialise($branchtype, $id);
1926 * Initialise the navigation given the type and id for the branch to expand.
1928 * @param int $branchtype One of navigation_node::TYPE_*
1930 * @return array The expandable nodes
1932 public function initialise($branchtype, $id) {
1933 global $CFG, $DB, $PAGE, $SITE;
1935 if ($this->initialised || during_initial_install()) {
1936 return $this->expandable;
1938 $this->initialised = true;
1940 $this->rootnodes = array();
1941 $this->rootnodes['site'] = $this->add_course($SITE);
1942 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1944 // Branchtype will be one of navigation_node::TYPE_*
1945 switch ($branchtype) {
1946 case self::TYPE_CATEGORY :
1947 $this->load_all_categories($id);
1949 if (!empty($CFG->navcourselimit)) {
1950 $limit = (int)$CFG->navcourselimit;
1952 $courses = $DB->get_records('course', array('category' => $id), 'sortorder','*', 0, $limit);
1953 foreach ($courses as $course) {
1954 $this->add_course($course);
1957 case self::TYPE_COURSE :
1958 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
1959 require_course_login($course);
1960 $this->page = $PAGE;
1961 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
1962 $coursenode = $this->add_course($course);
1963 $this->add_course_essentials($coursenode, $course);
1964 if ($this->format_display_course_content($course->format)) {
1965 $this->load_course_sections($course, $coursenode);
1968 case self::TYPE_SECTION :
1969 $sql = 'SELECT c.*, cs.section AS sectionnumber
1971 LEFT JOIN {course_sections} cs ON cs.course = c.id
1973 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
1974 require_course_login($course);
1975 $this->page = $PAGE;
1976 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
1977 $coursenode = $this->add_course($course);
1978 $this->add_course_essentials($coursenode, $course);
1979 $sections = $this->load_course_sections($course, $coursenode);
1980 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
1982 case self::TYPE_ACTIVITY :
1983 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
1984 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1985 require_course_login($course, true, $cm);
1986 $this->page = $PAGE;
1987 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
1988 $coursenode = $this->load_course($course);
1989 $sections = $this->load_course_sections($course, $coursenode);
1990 foreach ($sections as $section) {
1991 if ($section->id == $cm->section) {
1992 $cm->sectionnumber = $section->section;
1996 if ($course->id == SITEID) {
1997 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
1999 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
2000 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2004 throw new Exception('Unknown type');
2005 return $this->expandable;
2007 $this->find_expandable($this->expandable);
2008 return $this->expandable;
2011 public function get_expandable() {
2012 return $this->expandable;
2019 * This class is used to manage the navbar, which is initialised from the navigation
2020 * object held by PAGE
2022 * @package moodlecore
2023 * @subpackage navigation
2024 * @copyright 2009 Sam Hemelryk
2025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2027 class navbar extends navigation_node {
2029 protected $initialised = false;
2031 protected $keys = array();
2032 /** @var null|string */
2033 protected $content = null;
2034 /** @var moodle_page object */
2037 protected $ignoreactive = false;
2039 protected $duringinstall = false;
2041 protected $hasitems = false;
2045 public $children = array();
2047 public $includesettingsbase = false;
2049 * The almighty constructor
2051 * @param moodle_page $page
2053 public function __construct(moodle_page $page) {
2055 if (during_initial_install()) {
2056 $this->duringinstall = true;
2059 $this->page = $page;
2060 $this->text = get_string('home');
2061 $this->shorttext = get_string('home');
2062 $this->action = new moodle_url($CFG->wwwroot);
2063 $this->nodetype = self::NODETYPE_BRANCH;
2064 $this->type = self::TYPE_SYSTEM;
2068 * Quick check to see if the navbar will have items in.
2070 * @return bool Returns true if the navbar will have items, false otherwise
2072 public function has_items() {
2073 if ($this->duringinstall) {
2075 } else if ($this->hasitems !== false) {
2078 $this->page->navigation->initialise($this->page);
2080 $activenodefound = ($this->page->navigation->contains_active_node() ||
2081 $this->page->settingsnav->contains_active_node());
2083 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2084 $this->hasitems = $outcome;
2089 * Turn on/off ignore active
2091 * @param bool $setting
2093 public function ignore_active($setting=true) {
2094 $this->ignoreactive = ($setting);
2096 public function get($key, $type = null) {
2097 foreach ($this->children as &$child) {
2098 if ($child->key === $key && ($type == null || $type == $child->type)) {
2105 * Returns an array of navigation_node's that make up the navbar.
2109 public function get_items() {
2111 // Make sure that navigation is initialised
2112 if (!$this->has_items()) {
2115 if ($this->items !== null) {
2116 return $this->items;
2119 if (count($this->children) > 0) {
2120 // Add the custom children
2121 $items = array_reverse($this->children);
2124 $navigationactivenode = $this->page->navigation->find_active_node();
2125 $settingsactivenode = $this->page->settingsnav->find_active_node();
2127 // Check if navigation contains the active node
2128 if (!$this->ignoreactive) {
2130 if ($navigationactivenode && $settingsactivenode) {
2131 // Parse a combined navigation tree
2132 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2133 if (!$settingsactivenode->mainnavonly) {
2134 $items[] = $settingsactivenode;
2136 $settingsactivenode = $settingsactivenode->parent;
2138 if (!$this->includesettingsbase) {
2139 // Removes the first node from the settings (root node) from the list
2142 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2143 if (!$navigationactivenode->mainnavonly) {
2144 $items[] = $navigationactivenode;
2146 $navigationactivenode = $navigationactivenode->parent;
2148 } else if ($navigationactivenode) {
2149 // Parse the navigation tree to get the active node
2150 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2151 if (!$navigationactivenode->mainnavonly) {
2152 $items[] = $navigationactivenode;
2154 $navigationactivenode = $navigationactivenode->parent;
2156 } else if ($settingsactivenode) {
2157 // Parse the settings navigation to get the active node
2158 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2159 if (!$settingsactivenode->mainnavonly) {
2160 $items[] = $settingsactivenode;
2162 $settingsactivenode = $settingsactivenode->parent;
2167 $items[] = new navigation_node(array(
2168 'text'=>$this->page->navigation->text,
2169 'shorttext'=>$this->page->navigation->shorttext,
2170 'key'=>$this->page->navigation->key,
2171 'action'=>$this->page->navigation->action
2174 $this->items = array_reverse($items);
2175 return $this->items;
2179 * Add a new navigation_node to the navbar, overrides parent::add
2181 * This function overrides {@link navigation_node::add()} so that we can change
2182 * the way nodes get added to allow us to simply call add and have the node added to the
2185 * @param string $text
2186 * @param string|moodle_url $action
2188 * @param string|int $key
2189 * @param string $shorttext
2190 * @param string $icon
2191 * @return navigation_node
2193 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2194 if ($this->content !== null) {
2195 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2198 // Properties array used when creating the new navigation node
2203 // Set the action if one was provided
2204 if ($action!==null) {
2205 $itemarray['action'] = $action;
2207 // Set the shorttext if one was provided
2208 if ($shorttext!==null) {
2209 $itemarray['shorttext'] = $shorttext;
2211 // Set the icon if one was provided
2213 $itemarray['icon'] = $icon;
2215 // Default the key to the number of children if not provided
2216 if ($key === null) {
2217 $key = count($this->children);
2220 $itemarray['key'] = $key;
2221 // Set the parent to this node
2222 $itemarray['parent'] = $this;
2223 // Add the child using the navigation_node_collections add method
2224 $this->children[] = new navigation_node($itemarray);
2230 * Class used to manage the settings option for the current page
2232 * This class is used to manage the settings options in a tree format (recursively)
2233 * and was created initially for use with the settings blocks.
2235 * @package moodlecore
2236 * @subpackage navigation
2237 * @copyright 2009 Sam Hemelryk
2238 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2240 class settings_navigation extends navigation_node {
2241 /** @var stdClass */
2243 /** @var navigation_cache */
2245 /** @var moodle_page */
2248 protected $adminsection;
2250 protected $initialised = false;
2252 protected $userstoextendfor = array();
2255 * Sets up the object with basic settings and preparse it for use
2257 * @param moodle_page $page
2259 public function __construct(moodle_page &$page) {
2260 if (during_initial_install()) {
2263 $this->page = $page;
2264 // Initialise the main navigation. It is most important that this is done
2265 // before we try anything
2266 $this->page->navigation->initialise();
2267 // Initialise the navigation cache
2268 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2269 $this->children = new navigation_node_collection();
2272 * Initialise the settings navigation based on the current context
2274 * This function initialises the settings navigation tree for a given context
2275 * by calling supporting functions to generate major parts of the tree.
2278 public function initialise() {
2281 if (during_initial_install()) {
2283 } else if ($this->initialised) {
2286 $this->id = 'settingsnav';
2287 $this->context = $this->page->context;
2289 $context = $this->context;
2290 if ($context->contextlevel == CONTEXT_BLOCK) {
2291 $this->load_block_settings();
2292 $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));
2295 switch ($context->contextlevel) {
2296 case CONTEXT_SYSTEM:
2297 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2298 $this->load_front_page_settings(($context->id == $this->context->id));
2301 case CONTEXT_COURSECAT:
2302 $this->load_category_settings();
2304 case CONTEXT_COURSE:
2305 if ($this->page->course->id != SITEID) {
2306 $this->load_course_settings(($context->id == $this->context->id));
2308 $this->load_front_page_settings(($context->id == $this->context->id));
2311 case CONTEXT_MODULE:
2312 $this->load_module_settings();
2313 $this->load_course_settings();
2316 if ($this->page->course->id != SITEID) {
2317 $this->load_course_settings();
2322 $settings = $this->load_user_settings($this->page->course->id);
2323 $admin = $this->load_administration_settings();
2325 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2326 $admin->force_open();
2327 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2328 $settings->force_open();
2331 // Check if the user is currently logged in as another user
2332 if (session_is_loggedinas()) {
2333 // Get the actual user, we need this so we can display an informative return link
2334 $realuser = session_get_realuser();
2335 // Add the informative return to original user link
2336 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2337 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2340 // Make sure the first child doesnt have proceed with hr set to true
2342 foreach ($this->children as $key=>$node) {
2343 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2347 $this->initialised = true;
2350 * Override the parent function so that we can add preceeding hr's and set a
2351 * root node class against all first level element
2353 * It does this by first calling the parent's add method {@link navigation_node::add()}
2354 * and then proceeds to use the key to set class and hr
2356 * @param string $text
2357 * @param sting|moodle_url $url
2358 * @param string $shorttext
2359 * @param string|int $key
2361 * @param string $icon
2362 * @return navigation_node
2364 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2365 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2366 $node->add_class('root_node');
2371 * This function allows the user to add something to the start of the settings
2372 * navigation, which means it will be at the top of the settings navigation block
2374 * @param string $text
2375 * @param sting|moodle_url $url
2376 * @param string $shorttext
2377 * @param string|int $key
2379 * @param string $icon
2380 * @return navigation_node
2382 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2383 $children = $this->children;
2384 $childrenclass = get_class($children);
2385 $this->children = new $childrenclass;
2386 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2387 foreach ($children as $child) {
2388 $this->children->add($child);
2393 * Load the site administration tree
2395 * This function loads the site administration tree by using the lib/adminlib library functions
2397 * @param navigation_node $referencebranch A reference to a branch in the settings
2399 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2400 * tree and start at the beginning
2401 * @return mixed A key to access the admin tree by
2403 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2406 // Check if we are just starting to generate this navigation.
2407 if ($referencebranch === null) {
2409 // Require the admin lib then get an admin structure
2410 if (!function_exists('admin_get_root')) {
2411 require_once($CFG->dirroot.'/lib/adminlib.php');
2413 $adminroot = admin_get_root(false, false);
2414 // This is the active section identifier
2415 $this->adminsection = $this->page->url->param('section');
2417 // Disable the navigation from automatically finding the active node
2418 navigation_node::$autofindactive = false;
2419 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2420 foreach ($adminroot->children as $adminbranch) {
2421 $this->load_administration_settings($referencebranch, $adminbranch);
2423 navigation_node::$autofindactive = true;
2425 // Use the admin structure to locate the active page
2426 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2427 $currentnode = $this;
2428 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2429 $currentnode = $currentnode->get($pathkey);
2432 $currentnode->make_active();
2435 $this->scan_for_active_node($referencebranch);
2437 return $referencebranch;
2438 } else if ($adminbranch->check_access()) {
2439 // We have a reference branch that we can access and is not hidden `hurrah`
2440 // Now we need to display it and any children it may have
2443 if ($adminbranch instanceof admin_settingpage) {
2444 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2445 } else if ($adminbranch instanceof admin_externalpage) {
2446 $url = $adminbranch->url;
2450 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2452 if ($adminbranch->is_hidden()) {
2453 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2454 $reference->add_class('hidden');
2456 $reference->display = false;
2460 // Check if we are generating the admin notifications and whether notificiations exist
2461 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2462 $reference->add_class('criticalnotification');
2464 // Check if this branch has children
2465 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2466 foreach ($adminbranch->children as $branch) {
2467 // Generate the child branches as well now using this branch as the reference
2468 $this->load_administration_settings($reference, $branch);
2471 $reference->icon = new pix_icon('i/settings', '');
2477 * This function recursivily scans nodes until it finds the active node or there
2478 * are no more nodes.
2479 * @param navigation_node $node
2481 protected function scan_for_active_node(navigation_node $node) {
2482 if (!$node->check_if_active() && $node->children->count()>0) {
2483 foreach ($node->children as &$child) {
2484 $this->scan_for_active_node($child);
2490 * Gets a navigation node given an array of keys that represent the path to
2493 * @param array $path
2494 * @return navigation_node|false
2496 protected function get_by_path(array $path) {
2497 $node = $this->get(array_shift($path));
2498 foreach ($path as $key) {
2505 * Generate the list of modules for the given course.
2507 * The array of resources and activities that can be added to a course is then
2508 * stored in the cache so that we can access it for anywhere.
2509 * It saves us generating it all the time
2512 * // To get resources:
2513 * $this->cache->{'course'.$courseid.'resources'}
2514 * // To get activities:
2515 * $this->cache->{'course'.$courseid.'activities'}
2518 * @param stdClass $course The course to get modules for
2520 protected function get_course_modules($course) {
2522 $mods = $modnames = $modnamesplural = $modnamesused = array();
2523 // This function is included when we include course/lib.php at the top
2525 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2526 $resources = array();
2527 $activities = array();
2528 foreach($modnames as $modname=>$modnamestr) {
2529 if (!course_allowed_module($course, $modname)) {
2533 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2534 if (!file_exists($libfile)) {
2537 include_once($libfile);
2538 $gettypesfunc = $modname.'_get_types';
2539 if (function_exists($gettypesfunc)) {
2540 $types = $gettypesfunc();
2541 foreach($types as $type) {
2542 if (!isset($type->modclass) || !isset($type->typestr)) {
2543 debugging('Incorrect activity type in '.$modname);
2546 if ($type->modclass == MOD_CLASS_RESOURCE) {
2547 $resources[html_entity_decode($type->type)] = $type->typestr;
2549 $activities[html_entity_decode($type->type)] = $type->typestr;
2553 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2554 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2555 $resources[$modname] = $modnamestr;
2557 // all other archetypes are considered activity
2558 $activities[$modname] = $modnamestr;
2562 $this->cache->{'course'.$course->id.'resources'} = $resources;
2563 $this->cache->{'course'.$course->id.'activities'} = $activities;
2567 * This function loads the course settings that are available for the user
2569 * @param bool $forceopen If set to true the course node will be forced open
2570 * @return navigation_node|false
2572 protected function load_course_settings($forceopen = false) {
2573 global $CFG, $USER, $SESSION, $OUTPUT;
2575 $course = $this->page->course;
2576 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2577 if (!$this->cache->cached('canviewcourse'.$course->id)) {
2578 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
2580 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2584 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2586 $coursenode->force_open();
2589 if (has_capability('moodle/course:update', $coursecontext)) {
2590 // Add the turn on/off settings
2591 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2592 if ($this->page->user_is_editing()) {
2593 $url->param('edit', 'off');
2594 $editstring = get_string('turneditingoff');
2596 $url->param('edit', 'on');
2597 $editstring = get_string('turneditingon');
2599 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2601 if ($this->page->user_is_editing()) {
2602 // Removed as per MDL-22732
2603 // $this->add_course_editing_links($course);
2606 // Add the course settings link
2607 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2608 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2610 // Add the course completion settings link
2611 if ($CFG->enablecompletion && $course->enablecompletion) {
2612 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2613 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2617 if (has_capability('moodle/role:assign', $coursecontext)) {
2618 // Add assign or override roles if allowed
2619 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
2620 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2622 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2623 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
2624 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/permissions', ''));
2626 // Check role permissions
2627 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2628 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
2629 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/checkpermissions', ''));
2632 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2633 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2634 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2638 // Add view grade report is permitted
2639 $reportavailable = false;
2640 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2641 $reportavailable = true;
2642 } else if (!empty($course->showgrades)) {
2643 $reports = get_plugin_list('gradereport');
2644 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2645 arsort($reports); // user is last, we want to test it first
2646 foreach ($reports as $plugin => $plugindir) {
2647 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2648 //stop when the first visible plugin is found
2649 $reportavailable = true;
2655 if ($reportavailable) {
2656 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2657 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2660 // Add outcome if permitted
2661 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2662 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2663 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
2666 // Add meta course links
2667 if ($course->metacourse) {
2668 if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
2669 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
2670 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2671 } else if (has_capability('moodle/role:assign', $coursecontext)) {
2672 $roleassign = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2673 $roleassign->hidden = true;
2677 // Manage groups in this course
2678 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
2679 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
2680 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
2683 // Backup this course
2684 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2685 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2686 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
2689 // Restore to this course
2690 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2691 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2692 $url = null; // Disabled until restore is implemented. MDL-21432
2693 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
2696 // Import data from other courses
2697 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2698 $url = new moodle_url('/course/import.php', array('id'=>$course->id));
2699 $url = null; // Disabled until restore is implemented. MDL-21432
2700 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
2703 // Publish course on a hub
2704 if (has_capability('moodle/course:publish', $coursecontext)) {
2705 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2706 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
2709 // Reset this course
2710 if (has_capability('moodle/course:reset', $coursecontext)) {
2711 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2712 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2716 require_once($CFG->dirroot.'/question/editlib.php');
2717 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
2719 // Repository Instances
2720 require_once($CFG->dirroot.'/repository/lib.php');
2721 $editabletypes = repository::get_editable_types($coursecontext);
2722 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2723 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id));
2724 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
2728 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
2729 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'filearea'=>'course_content'));
2730 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
2734 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2735 require_once($CFG->dirroot.'/enrol/authorize/const.php');
2736 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
2737 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2738 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2739 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2741 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
2742 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2748 if (empty($course->metacourse) && ($course->id!==SITEID)) {
2749 if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2750 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
2751 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2752 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2755 } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2756 // inspector, manager, etc. - do not show anything
2758 // access because otherwise they would not get into this course at all
2759 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2760 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2766 $assumedrole = $this->in_alternative_role();
2767 if ($assumedrole!==false) {
2768 $roles[0] = get_string('switchrolereturn');
2770 if (has_capability('moodle/role:switchroles', $coursecontext)) {
2771 $availableroles = get_switchable_roles($coursecontext);
2772 if (is_array($availableroles)) {
2773 foreach ($availableroles as $key=>$role) {
2774 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2777 $roles[$key] = $role;
2781 if (is_array($roles) && count($roles)>0) {
2782 $switchroles = $this->add(get_string('switchroleto'));
2783 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2784 $switchroles->force_open();
2786 $returnurl = $this->page->url;
2787 $returnurl->param('sesskey', sesskey());
2788 $SESSION->returnurl = serialize($returnurl);
2789 foreach ($roles as $key=>$name) {
2790 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2791 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
2794 // Return we are done
2799 * Adds branches and links to the settings navigaiton to add course activities
2802 * @param stdClass $course
2804 protected function add_course_editing_links($course) {
2805 // Add `add` resources|activities branches
2806 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2807 if (file_exists($structurefile)) {
2808 require_once($structurefile);
2809 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2810 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2812 $formatstring = get_string('topic');
2813 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2816 $sections = get_all_sections($course->id);
2818 $addresource = $this->add(get_string('addresource'));
2819 $addactivity = $this->add(get_string('addactivity'));
2820 if ($formatidentifier!==0) {
2821 $addresource->force_open();
2822 $addactivity->force_open();
2825 if (!$this->cache->cached('course'.$course->id.'resources')) {
2826 $this->get_course_modules($course);
2828 $resources = $this->cache->{'course'.$course->id.'resources'};
2829 $activities = $this->cache->{'course'.$course->id.'activities'};
2831 $textlib = textlib_get_instance();
2833 foreach ($sections as $section) {
2834 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2837 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
2838 if ($section->section == 0) {
2839 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2840 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2842 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2843 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2845 foreach ($resources as $value=>$resource) {
2846 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2847 $pos = strpos($value, '&type=');
2849 $url->param('add', $textlib->substr($value, 0,$pos));
2850 $url->param('type', $textlib->substr($value, $pos+6));
2852 $url->param('add', $value);
2854 $sectionresources->add($resource, $url, self::TYPE_SETTING);
2857 foreach ($activities as $activityname=>$activity) {
2858 if ($activity==='--') {
2862 if (strpos($activity, '--')===0) {
2863 $subbranch = $sectionactivities->add(trim($activity, '-'));
2866 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2867 $pos = strpos($activityname, '&type=');
2869 $url->param('add', $textlib->substr($activityname, 0,$pos));
2870 $url->param('type', $textlib->substr($activityname, $pos+6));
2872 $url->param('add', $activityname);
2874 if ($subbranch !== false) {
2875 $subbranch->add($activity, $url, self::TYPE_SETTING);
2877 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
2884 * This function calls the module function to inject module settings into the
2885 * settings navigation tree.
2887 * This only gets called if there is a corrosponding function in the modules
2890 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2892 * @return navigation_node|false
2894 protected function load_module_settings() {
2897 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
2898 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
2899 $this->page->set_cm($cm, $this->page->course);
2902 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2903 $modulenode->force_open();
2905 // Settings for the module
2906 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2907 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2908 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2910 // Assign local roles
2911 if (count(get_assignable_roles($this->page->cm->context))>0) {
2912 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2913 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2916 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2917 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2918 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2920 // Check role permissions
2921 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2922 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2923 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2926 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2927 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2928 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2931 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
2932 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
2933 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING);
2936 // Add a backup link
2937 $featuresfunc = $this->page->activityname.'_supports';
2938 if ($featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
2939 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
2940 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
2943 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2944 $function = $this->page->activityname.'_extend_settings_navigation';
2946 if (file_exists($file)) {
2947 require_once($file);
2949 if (!function_exists($function)) {
2953 $function($this, $modulenode);
2955 // Remove the module node if there are no children
2956 if (empty($modulenode->children)) {
2957 $modulenode->remove();
2964 * Loads the user settings block of the settings nav
2966 * This function is simply works out the userid and whether we need to load
2967 * just the current users profile settings, or the current user and the user the
2968 * current user is viewing.
2970 * This function has some very ugly code to work out the user, if anyone has
2971 * any bright ideas please feel free to intervene.
2973 * @param int $courseid The course id of the current course
2974 * @return navigation_node|false
2976 protected function load_user_settings($courseid=SITEID) {
2977 global $USER, $FULLME, $CFG;
2979 if (isguestuser() || !isloggedin()) {
2983 $navusers = $this->page->navigation->get_extending_users();
2985 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
2987 foreach ($this->userstoextendfor as $userid) {
2988 if ($userid == $USER->id) {
2991 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
2992 if (is_null($usernode)) {
2996 foreach ($navusers as $user) {
2997 if ($user->id == $USER->id) {
3000 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3001 if (is_null($usernode)) {
3005 $this->generate_user_settings($courseid, $USER->id);
3007 $usernode = $this->generate_user_settings($courseid, $USER->id);
3012 public function extend_for_user($userid) {
3015 if (!in_array($userid, $this->userstoextendfor)) {
3016 $this->userstoextendfor[] = $userid;
3017 if ($this->initialised) {
3018 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3019 $children = array();
3020 foreach ($this->children as $child) {
3021 $children[] = $child;
3023 array_unshift($children, array_pop($children));
3024 $this->children = new navigation_node_collection();
3025 foreach ($children as $child) {
3026 $this->children->add($child);
3033 * This function gets called by {@link load_user_settings()} and actually works out
3034 * what can be shown/done
3036 * @param int $courseid The current course' id
3037 * @param int $userid The user id to load for
3038 * @param string $gstitle The string to pass to get_string for the branch title
3039 * @return navigation_node|false
3041 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3042 global $DB, $CFG, $USER, $SITE;
3044 if ($courseid != SITEID) {
3045 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3046 $course = $this->page->course;
3048 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
3054 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3055 $systemcontext = get_system_context();
3056 $currentuser = ($USER->id == $userid);
3060 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3062 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
3065 // Check that the user can view the profile
3066 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3067 if ($course->id==SITEID) {
3068 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3069 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3073 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
3076 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3077 // If groups are in use, make sure we can see that group
3083 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3086 if ($gstitle != 'usercurrentsettings') {
3090 // Add a user setting branch
3091 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3092 $usersetting->id = 'usersettings';
3094 // Check if the user has been deleted
3095 if ($user->deleted) {
3096 if (!has_capability('moodle/user:update', $coursecontext)) {
3097 // We can't edit the user so just show the user deleted message
3098 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3100 // We can edit the user so show the user deleted message and link it to the profile
3101 if ($course->id == SITEID) {
3102 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3104 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3106 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3111 // Add the profile edit link
3112 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3113 if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
3114 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3115 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3116 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3117 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3118 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3122 // Change password link
3123 if (!empty($user->auth)) {
3124 $userauth = get_auth_plugin($user->auth);
3125 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3126 $passwordchangeurl = $userauth->change_password_url();
3127 if (!$passwordchangeurl) {
3128 if (empty($CFG->loginhttps)) {
3129 $wwwroot = $CFG->wwwroot;
3131 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
3133 $passwordchangeurl = new moodle_url('/login/change_password.php');
3135 $urlbits = explode($passwordchangeurl. '?', 1);
3136 $passwordchangeurl = new moodle_url($urlbits[0]);
3137 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
3138 foreach ($matches as $pair) {
3139 $fullmeurl->param($pair[1],$pair[2]);
3143 $passwordchangeurl->param('id', $course->id);
3144 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3148 // View the roles settings
3149 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3150 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3152 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3153 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3155 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3157 if (!empty($assignableroles)) {
3158 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3159 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3162 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3163 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3164 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3167 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3168 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3172 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3173 require_once($CFG->libdir . '/portfoliolib.php');
3174 if (portfolio_instances(true, false)) {
3175 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3176 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
3177 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
3181 $enablemanagetokens = false;
3182 if (!empty($CFG->enablerssfeeds)) {
3183 $enablemanagetokens = true;
3184 } else if (!is_siteadmin($USER->id)
3185 && !empty($CFG->enablewebservices)
3186 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3187 $enablemanagetokens = true;
3190 if ($currentuser && $enablemanagetokens) {
3191 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3192 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3196 if (!$currentuser) {
3197 require_once($CFG->dirroot . '/repository/lib.php');
3198 $editabletypes = repository::get_editable_types($usercontext);
3199 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
3200 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3201 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3206 // TODO this is adding itself to the messaging settings for other people based on one's own setting
3207 if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
3208 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3209 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
3213 if (!empty($CFG->bloglevel)) {
3214 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3215 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3216 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
3217 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3218 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3223 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3224 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3225 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3228 return $usersetting;
3232 * Loads block specific settings in the navigation
3234 * @return navigation_node
3236 protected function load_block_settings() {
3239 $blocknode = $this->add(print_context_name($this->context));
3240 $blocknode->force_open();
3242 // Assign local roles
3243 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3244 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3247 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3248 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3249 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3251 // Check role permissions
3252 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3253 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3254 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3261 * Loads category specific settings in the navigation
3263 * @return navigation_node
3265 protected function load_category_settings() {
3268 $categorynode = $this->add(print_context_name($this->context));
3269 $categorynode->force_open();
3271 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
3272 $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid)));
3273 $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid)));
3276 // Assign local roles
3277 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3278 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3281 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3282 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3283 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3285 // Check role permissions
3286 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3287 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3288 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3291 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
3292 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
3293 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
3296 return $categorynode;
3300 * Determine whether the user is assuming another role
3302 * This function checks to see if the user is assuming another role by means of
3303 * role switching. In doing this we compare each RSW key (context path) against
3304 * the current context path. This ensures that we can provide the switching
3305 * options against both the course and any page shown under the course.
3307 * @return bool|int The role(int) if the user is in another role, false otherwise
3309 protected function in_alternative_role() {
3311 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
3312 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
3313 return $USER->access['rsw'][$this->page->context->path];
3315 foreach ($USER->access['rsw'] as $key=>$role) {
3316 if (strpos($this->context->path,$key)===0) {