3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node implements renderable {
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF = 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH = 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN = null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE = 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM = 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY = 10;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int Setting node type, used only within settings nav 80 */
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER = 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
82 /** @var string|int The identifier for the node, used to retrieve the node */
84 /** @var string The text to use for the node */
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self::TYPE_UNKNOWN;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self::NODETYPE_LEAF;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
132 * Constructs a new navigation_node
134 * @param array|string $properties Either an array of properties or a string to use
135 * as the text for the node
137 public function __construct($properties) {
138 if (is_array($properties)) {
139 // Check the array for each property that we allow to set at construction.
140 // text - The main content for the node
141 // shorttext - A short text if required for the node
142 // icon - The icon to display for the node
143 // type - The type of the node
144 // key - The key to use to identify the node
145 // parent - A reference to the nodes parent
146 // action - The action to attribute to this node, usually a URL to link to
147 if (array_key_exists('text', $properties)) {
148 $this->text = $properties['text'];
150 if (array_key_exists('shorttext', $properties)) {
151 $this->shorttext = $properties['shorttext'];
153 if (!array_key_exists('icon', $properties)) {
154 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
156 $this->icon = $properties['icon'];
157 if ($this->icon instanceof pix_icon) {
158 if (empty($this->icon->attributes['class'])) {
159 $this->icon->attributes['class'] = 'navicon';
161 $this->icon->attributes['class'] .= ' navicon';
164 if (array_key_exists('type', $properties)) {
165 $this->type = $properties['type'];
167 $this->type = self::TYPE_CUSTOM;
169 if (array_key_exists('key', $properties)) {
170 $this->key = $properties['key'];
172 if (array_key_exists('parent', $properties)) {
173 $this->parent = $properties['parent'];
175 // This needs to happen last because of the check_if_active call that occurs
176 if (array_key_exists('action', $properties)) {
177 $this->action = $properties['action'];
178 if (is_string($this->action)) {
179 $this->action = new moodle_url($this->action);
181 if (self::$autofindactive) {
182 $this->check_if_active();
185 } else if (is_string($properties)) {
186 $this->text = $properties;
188 if ($this->text === null) {
189 throw new coding_exception('You must set the text for the node when you create it.');
191 // Default the title to the text
192 $this->title = $this->text;
193 // Instantiate a new navigation node collection for this nodes children
194 $this->children = new navigation_node_collection();
198 * Checks if this node is the active node.
200 * This is determined by comparing the action for the node against the
201 * defined URL for the page. A match will see this node marked as active.
203 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
206 public function check_if_active($strength=URL_MATCH_EXACT) {
207 global $FULLME, $PAGE;
208 // Set fullmeurl if it hasn't already been set
209 if (self::$fullmeurl == null) {
210 if ($PAGE->has_set_url()) {
211 self::override_active_url(new moodle_url($PAGE->url));
213 self::override_active_url(new moodle_url($FULLME));
217 // Compare the action of this node against the fullmeurl
218 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
219 $this->make_active();
226 * This sets the URL that the URL of new nodes get compared to when locating
229 * The active node is the node that matches the URL set here. By default this
230 * is either $PAGE->url or if that hasn't been set $FULLME.
232 * @param moodle_url $url The url to use for the fullmeurl.
234 public static function override_active_url(moodle_url $url) {
235 // Clone the URL, in case the calling script changes their URL later.
236 self::$fullmeurl = new moodle_url($url);
240 * Adds a navigation node as a child of this node.
242 * @param string $text
243 * @param moodle_url|action_link $action
245 * @param string $shorttext
246 * @param string|int $key
247 * @param pix_icon $icon
248 * @return navigation_node
250 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
251 // First convert the nodetype for this node to a branch as it will now have children
252 if ($this->nodetype !== self::NODETYPE_BRANCH) {
253 $this->nodetype = self::NODETYPE_BRANCH;
255 // Properties array used when creating the new navigation node
260 // Set the action if one was provided
261 if ($action!==null) {
262 $itemarray['action'] = $action;
264 // Set the shorttext if one was provided
265 if ($shorttext!==null) {
266 $itemarray['shorttext'] = $shorttext;
268 // Set the icon if one was provided
270 $itemarray['icon'] = $icon;
272 // Default the key to the number of children if not provided
274 $key = $this->children->count();
277 $itemarray['key'] = $key;
278 // Set the parent to this node
279 $itemarray['parent'] = $this;
280 // Add the child using the navigation_node_collections add method
281 $node = $this->children->add(new navigation_node($itemarray));
282 // If the node is a category node or the user is logged in and its a course
283 // then mark this node as a branch (makes it expandable by AJAX)
284 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
285 $node->nodetype = self::NODETYPE_BRANCH;
287 // If this node is hidden mark it's children as hidden also
289 $node->hidden = true;
291 // Return the node (reference returned by $this->children->add()
296 * Searches for a node of the given type with the given key.
298 * This searches this node plus all of its children, and their children....
299 * If you know the node you are looking for is a child of this node then please
300 * use the get method instead.
302 * @param int|string $key The key of the node we are looking for
303 * @param int $type One of navigation_node::TYPE_*
304 * @return navigation_node|false
306 public function find($key, $type) {
307 return $this->children->find($key, $type);
311 * Get ths child of this node that has the given key + (optional) type.
313 * If you are looking for a node and want to search all children + thier children
314 * then please use the find method instead.
316 * @param int|string $key The key of the node we are looking for
317 * @param int $type One of navigation_node::TYPE_*
318 * @return navigation_node|false
320 public function get($key, $type=null) {
321 return $this->children->get($key, $type);
329 public function remove() {
330 return $this->parent->children->remove($this->key, $this->type);
334 * Checks if this node has or could have any children
336 * @return bool Returns true if it has children or could have (by AJAX expansion)
338 public function has_children() {
339 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
343 * Marks this node as active and forces it open.
345 * Important: If you are here because you need to mark a node active to get
346 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
347 * You can use it to specify a different URL to match the active navigation node on
348 * rather than having to locate and manually mark a node active.
350 public function make_active() {
351 $this->isactive = true;
352 $this->add_class('active_tree_node');
354 if ($this->parent !== null) {
355 $this->parent->make_inactive();
360 * Marks a node as inactive and recusised back to the base of the tree
361 * doing the same to all parents.
363 public function make_inactive() {
364 $this->isactive = false;
365 $this->remove_class('active_tree_node');
366 if ($this->parent !== null) {
367 $this->parent->make_inactive();
372 * Forces this node to be open and at the same time forces open all
373 * parents until the root node.
377 public function force_open() {
378 $this->forceopen = true;
379 if ($this->parent !== null) {
380 $this->parent->force_open();
385 * Adds a CSS class to this node.
387 * @param string $class
390 public function add_class($class) {
391 if (!in_array($class, $this->classes)) {
392 $this->classes[] = $class;
398 * Removes a CSS class from this node.
400 * @param string $class
401 * @return bool True if the class was successfully removed.
403 public function remove_class($class) {
404 if (in_array($class, $this->classes)) {
405 $key = array_search($class,$this->classes);
407 unset($this->classes[$key]);
415 * Sets the title for this node and forces Moodle to utilise it.
416 * @param string $title
418 public function title($title) {
419 $this->title = $title;
420 $this->forcetitle = true;
424 * Resets the page specific information on this node if it is being unserialised.
426 public function __wakeup(){
427 $this->forceopen = false;
428 $this->isactive = false;
429 $this->remove_class('active_tree_node');
433 * Checks if this node or any of its children contain the active node.
439 public function contains_active_node() {
440 if ($this->isactive) {
443 foreach ($this->children as $child) {
444 if ($child->isactive || $child->contains_active_node()) {
453 * Finds the active node.
455 * Searches this nodes children plus all of the children for the active node
456 * and returns it if found.
460 * @return navigation_node|false
462 public function find_active_node() {
463 if ($this->isactive) {
466 foreach ($this->children as &$child) {
467 $outcome = $child->find_active_node();
468 if ($outcome !== false) {
477 * Searches all children for the best matching active node
478 * @return navigation_node|false
480 public function search_for_active_node() {
481 if ($this->check_if_active(URL_MATCH_BASE)) {
484 foreach ($this->children as &$child) {
485 $outcome = $child->search_for_active_node();
486 if ($outcome !== false) {
495 * Gets the content for this node.
497 * @param bool $shorttext If true shorttext is used rather than the normal text
500 public function get_content($shorttext=false) {
501 if ($shorttext && $this->shorttext!==null) {
502 return format_string($this->shorttext);
504 return format_string($this->text);
509 * Gets the title to use for this node.
513 public function get_title() {
514 if ($this->forcetitle || $this->action != null){
522 * Gets the CSS class to add to this node to describe its type
526 public function get_css_type() {
527 if (array_key_exists($this->type, $this->namedtypes)) {
528 return 'type_'.$this->namedtypes[$this->type];
530 return 'type_unknown';
534 * Finds all nodes that are expandable by AJAX
536 * @param array $expandable An array by reference to populate with expandable nodes.
538 public function find_expandable(array &$expandable) {
539 foreach ($this->children as &$child) {
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, 'key' => $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 = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $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 // We always load the frontpage course to ensure it is available without
957 // JavaScript enabled.
958 $frontpagecourse = $this->load_course($SITE);
959 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
961 $canviewcourseprofile = true;
963 // Next load context specific content into the navigation
964 switch ($this->page->context->contextlevel) {
965 case CONTEXT_SYSTEM :
966 // This has already been loaded we just need to map the variable
967 $coursenode = $frontpagecourse;
969 case CONTEXT_COURSECAT :
970 // This has already been loaded we just need to map the variable
971 $coursenode = $frontpagecourse;
972 $this->load_all_categories($this->page->context->instanceid);
975 case CONTEXT_COURSE :
976 // Load the course associated with the page into the navigation
977 $course = $this->page->course;
978 $coursenode = $this->load_course($course);
980 // If the course wasn't added then don't try going any further.
982 $canviewcourseprofile = false;
986 // If the user is not enrolled then we only want to show the
987 // course node and not populate it.
988 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
989 // Not enrolled, can't view, and hasn't switched roles
991 if (!can_access_course($coursecontext)) {
992 $coursenode->make_active();
993 $canviewcourseprofile = false;
996 // Add the essentials such as reports etc...
997 $this->add_course_essentials($coursenode, $course);
998 if ($this->format_display_course_content($course->format)) {
999 // Load the course sections
1000 $sections = $this->load_course_sections($course, $coursenode);
1002 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1003 $coursenode->make_active();
1006 case CONTEXT_MODULE :
1007 $course = $this->page->course;
1008 $cm = $this->page->cm;
1009 // Load the course associated with the page into the navigation
1010 $coursenode = $this->load_course($course);
1012 // If the user is not enrolled then we only want to show the
1013 // course node and not populate it.
1014 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1015 if (!can_access_course($coursecontext)) {
1017 $coursenode->make_active();
1019 $canviewcourseprofile = false;
1023 $this->add_course_essentials($coursenode, $course);
1024 // Load the course sections into the page
1025 $sections = $this->load_course_sections($course, $coursenode);
1026 if ($course->id !== SITEID) {
1027 // Find the section for the $CM associated with the page and collect
1028 // its section number.
1029 foreach ($sections as $section) {
1030 if ($section->id == $cm->section) {
1031 $cm->sectionnumber = $section->section;
1036 // Load all of the section activities for the section the cm belongs to.
1037 if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1038 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1040 $activities = array();
1041 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1042 // "stealth" activity from unavailable section
1043 $activities[$cm->id] = $activity;
1047 $activities = array();
1048 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1050 if (!empty($activities[$cm->id])) {
1051 // Finally load the cm specific navigaton information
1052 $this->load_activity($cm, $course, $activities[$cm->id]);
1053 // Check if we have an active ndoe
1054 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1055 // And make the activity node active.
1056 $activities[$cm->id]->make_active();
1059 //TODO: something is wrong, what to do? (Skodak)
1063 $course = $this->page->course;
1064 if ($course->id != SITEID) {
1065 // Load the course associated with the user into the navigation
1066 $coursenode = $this->load_course($course);
1067 // If the user is not enrolled then we only want to show the
1068 // course node and not populate it.
1069 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1070 if (!can_access_course($coursecontext)) {
1071 $coursenode->make_active();
1072 $canviewcourseprofile = false;
1075 $this->add_course_essentials($coursenode, $course);
1076 $sections = $this->load_course_sections($course, $coursenode);
1082 if (!empty($CFG->navcourselimit)) {
1083 $limit = $CFG->navcourselimit;
1085 if ($showcategories) {
1086 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1087 foreach ($categories as &$category) {
1088 if ($category->children->count() >= $limit) {
1089 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1090 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1093 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1094 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1097 // Load for the current user
1098 $this->load_for_user();
1099 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1100 $this->load_for_user(null, true);
1102 // Load each extending user into the navigation.
1103 foreach ($this->extendforuser as $user) {
1104 if ($user->id !== $USER->id) {
1105 $this->load_for_user($user);
1109 // Give the local plugins a chance to include some navigation if they want.
1110 foreach (get_list_of_plugins('local') as $plugin) {
1111 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1114 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1115 $function = $plugin.'_extends_navigation';
1116 if (function_exists($function)) {
1121 // Remove any empty root nodes
1122 foreach ($this->rootnodes as $node) {
1123 // Dont remove the home node
1124 if ($node->key !== 'home' && !$node->has_children()) {
1129 if (!$this->contains_active_node()) {
1130 $this->search_for_active_node();
1133 // If the user is not logged in modify the navigation structure as detailed
1134 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1135 if (!isloggedin()) {
1136 $activities = clone($this->rootnodes['site']->children);
1137 $this->rootnodes['site']->remove();
1138 $children = clone($this->children);
1139 $this->children = new navigation_node_collection();
1140 foreach ($activities as $child) {
1141 $this->children->add($child);
1143 foreach ($children as $child) {
1144 $this->children->add($child);
1150 * Checks the course format to see whether it wants the navigation to load
1151 * additional information for the course.
1153 * This function utilises a callback that can exist within the course format lib.php file
1154 * The callback should be a function called:
1155 * callback_{formatname}_display_content()
1156 * It doesn't get any arguments and should return true if additional content is
1157 * desired. If the callback doesn't exist we assume additional content is wanted.
1159 * @param string $format The course format
1162 protected function format_display_course_content($format) {
1164 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1165 if (file_exists($formatlib)) {
1166 require_once($formatlib);
1167 $displayfunc = 'callback_'.$format.'_display_content';
1168 if (function_exists($displayfunc) && !$displayfunc()) {
1169 return $displayfunc();
1176 * Loads of the the courses in Moodle into the navigation.
1178 * @param string|array $categoryids Either a string or array of category ids to load courses for
1179 * @return array An array of navigation_node
1181 protected function load_all_courses($categoryids=null) {
1182 global $CFG, $DB, $USER;
1184 if ($categoryids !== null) {
1185 if (is_array($categoryids)) {
1186 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1189 $params = array($categoryids);
1191 array_unshift($params, SITEID);
1192 $select = ' AND c.category '.$select;
1194 $params = array(SITEID);
1198 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1199 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1202 LEFT JOIN {course_categories} cat ON cat.id=c.category
1203 WHERE c.id <> ?$select
1204 ORDER BY c.sortorder ASC";
1206 if (!empty($CFG->navcourselimit)) {
1207 $limit = $CFG->navcourselimit;
1209 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1211 $coursenodes = array();
1212 foreach ($courses as $course) {
1213 context_instance_preload($course);
1214 $coursenodes[$course->id] = $this->add_course($course);
1216 return $coursenodes;
1220 * Loads all categories (top level or if an id is specified for that category)
1222 * @param int $categoryid
1225 protected function load_all_categories($categoryid=null) {
1227 if ($categoryid == null) {
1228 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1230 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1231 $wantedids = explode('/', trim($category->path, '/'));
1232 list($select, $params) = $DB->get_in_or_equal($wantedids);
1233 $select = 'id '.$select.' OR parent '.$select;
1234 $params = array_merge($params, $params);
1235 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1237 $structured = array();
1238 $categoriestoload = array();
1239 foreach ($categories as $category) {
1240 if ($category->parent == '0') {
1241 $structured[$category->id] = array('category'=>$category, 'children'=>array());
1243 if ($category->parent == $categoryid) {
1244 $categoriestoload[] = $category->id;
1247 $id = $category->parent;
1248 while ($id != '0') {
1250 if (!array_key_exists($id, $categories)) {
1251 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST);
1253 $id = $categories[$id]->parent;
1255 $parents = array_reverse($parents);
1256 $parentref = &$structured[array_shift($parents)];
1257 foreach ($parents as $parent) {
1258 if (!array_key_exists($parent, $parentref['children'])) {
1259 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1261 $parentref = &$parentref['children'][$parent];
1263 if (!array_key_exists($category->id, $parentref['children'])) {
1264 $parentref['children'][$category->id] = array('category'=>$category, 'children'=>array());
1269 foreach ($structured as $category) {
1270 $this->add_category($category, $this->rootnodes['courses']);
1273 if ($categoryid !== null && count($wantedids)) {
1274 foreach ($wantedids as $catid) {
1275 $this->load_all_courses($catid);
1281 * Adds a structured category to the navigation in the correct order/place
1283 * @param object $cat
1284 * @param navigation_node $parent
1286 protected function add_category($cat, navigation_node $parent) {
1287 $categorynode = $parent->get($cat['category']->id, navigation_node::TYPE_CATEGORY);
1288 if (!$categorynode) {
1289 $category = $cat['category'];
1290 $url = new moodle_url('/course/category.php', array('id'=>$category->id));
1291 $categorynode = $parent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id);
1292 if (empty($category->visible)) {
1293 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1294 $categorynode->hidden = true;
1296 $categorynode->display = false;
1300 foreach ($cat['children'] as $child) {
1301 $this->add_category($child, $categorynode);
1306 * Loads the given course into the navigation
1308 * @param stdClass $course
1309 * @return navigation_node
1311 protected function load_course(stdClass $course) {
1312 if ($course->id == SITEID) {
1313 $coursenode = $this->rootnodes['site'];
1314 } else if (array_key_exists($course->id, $this->mycourses)) {
1315 if (!isset($this->mycourses[$course->id]->coursenode)) {
1316 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
1318 $coursenode = $this->mycourses[$course->id]->coursenode;
1320 $coursenode = $this->add_course($course);
1326 * Loads all of the courses section into the navigation.
1328 * This function utilisies a callback that can be implemented within the course
1329 * formats lib.php file to customise the navigation that is generated at this
1330 * point for the course.
1332 * By default (if not defined) the method {@see load_generic_course_sections} is
1335 * @param stdClass $course Database record for the course
1336 * @param navigation_node $coursenode The course node within the navigation
1337 * @return array Array of navigation nodes for the section with key = section id
1339 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1341 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1342 $structurefunc = 'callback_'.$course->format.'_load_content';
1343 if (function_exists($structurefunc)) {
1344 return $structurefunc($this, $course, $coursenode);
1345 } else if (file_exists($structurefile)) {
1346 require_once $structurefile;
1347 if (function_exists($structurefunc)) {
1348 return $structurefunc($this, $course, $coursenode);
1350 return $this->load_generic_course_sections($course, $coursenode);
1353 return $this->load_generic_course_sections($course, $coursenode);
1358 * Generically loads the course sections into the course's navigation.
1360 * @param stdClass $course
1361 * @param navigation_node $coursenode
1362 * @param string $name The string that identifies each section. e.g Topic, or Week
1363 * @param string $activeparam The url used to identify the active section
1364 * @return array An array of course section nodes
1366 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1367 global $CFG, $DB, $USER;
1369 require_once($CFG->dirroot.'/course/lib.php');
1371 if (!$this->cache->cached('modinfo'.$course->id)) {
1372 $this->cache->set('modinfo'.$course->id, get_fast_modinfo($course));
1374 $modinfo = $this->cache->{'modinfo'.$course->id};
1376 if (!$this->cache->cached('coursesections'.$course->id)) {
1377 $this->cache->set('coursesections'.$course->id, array_slice(get_all_sections($course->id), 0, $course->numsections+1, true));
1379 $sections = $this->cache->{'coursesections'.$course->id};
1381 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1383 if (isloggedin() && !isguestuser()) {
1384 $activesection = $DB->get_field("course_display", "display", array("userid"=>$USER->id, "course"=>$course->id));
1386 $activesection = null;
1389 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1390 $namingfunctionexists = (function_exists($namingfunction));
1392 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1393 if (function_exists($activeparamfunction)) {
1394 $activeparam = $activeparamfunction();
1396 $activeparam = 'section';
1398 $navigationsections = array();
1399 foreach ($sections as $sectionid=>$section) {
1400 $section = clone($section);
1401 if ($course->id == SITEID) {
1402 $this->load_section_activities($coursenode, $section->section, $modinfo);
1404 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1407 if ($namingfunctionexists) {
1408 $sectionname = $namingfunction($course, $section, $sections);
1410 $sectionname = get_string('section').' '.$section->section;
1412 //$url = new moodle_url('/course/view.php', array('id'=>$course->id));
1414 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1415 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1416 $sectionnode->hidden = (!$section->visible);
1417 if ($this->page->context->contextlevel != CONTEXT_MODULE && ($sectionnode->isactive || ($activesection != null && $section->section == $activesection))) {
1418 $sectionnode->force_open();
1419 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1421 $section->sectionnode = $sectionnode;
1422 $navigationsections[$sectionid] = $section;
1425 return $navigationsections;
1428 * Loads all of the activities for a section into the navigation structure.
1430 * @param navigation_node $sectionnode
1431 * @param int $sectionnumber
1432 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1433 * @return array Array of activity nodes
1435 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1436 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1440 $activities = array();
1442 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1443 $cm = $modinfo->cms[$cmid];
1444 if (!$cm->uservisible) {
1448 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1450 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1452 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1453 $activitynode = $sectionnode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1454 $activitynode->title(get_string('modulename', $cm->modname));
1455 $activitynode->hidden = (!$cm->visible);
1456 if ($cm->modname == 'label') {
1457 $activitynode->display = false;
1458 } else if ($this->module_extends_navigation($cm->modname)) {
1459 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1461 $activities[$cmid] = $activitynode;
1467 * Loads a stealth module from unavailable section
1468 * @param navigation_node $coursenode
1469 * @param stdClass $modinfo
1470 * @return navigation_node or null if not accessible
1472 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1473 if (empty($modinfo->cms[$this->page->cm->id])) {
1476 $cm = $modinfo->cms[$this->page->cm->id];
1477 if (!$cm->uservisible) {
1481 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1483 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1485 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1486 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1487 $activitynode->title(get_string('modulename', $cm->modname));
1488 $activitynode->hidden = (!$cm->visible);
1489 if ($cm->modname == 'label') {
1490 $activitynode->display = false;
1491 } else if ($this->module_extends_navigation($cm->modname)) {
1492 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1494 return $activitynode;
1497 * Loads the navigation structure for the given activity into the activities node.
1499 * This method utilises a callback within the modules lib.php file to load the
1500 * content specific to activity given.
1502 * The callback is a method: {modulename}_extend_navigation()
1504 * * {@see forum_extend_navigation()}
1505 * * {@see workshop_extend_navigation()}
1507 * @param stdClass $cm
1508 * @param stdClass $course
1509 * @param navigation_node $activity
1512 protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1515 $activity->make_active();
1516 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1517 $function = $cm->modname.'_extend_navigation';
1519 if (file_exists($file)) {
1520 require_once($file);
1521 if (function_exists($function)) {
1522 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1523 $function($activity, $course, $activtyrecord, $cm);
1527 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1531 * Loads user specific information into the navigation in the appopriate place.
1533 * If no user is provided the current user is assumed.
1535 * @param stdClass $user
1538 protected function load_for_user($user=null, $forceforcontext=false) {
1539 global $DB, $CFG, $USER;
1541 if ($user === null) {
1542 // We can't require login here but if the user isn't logged in we don't
1543 // want to show anything
1544 if (!isloggedin() || isguestuser()) {
1548 } else if (!is_object($user)) {
1549 // If the user is not an object then get them from the database
1550 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1553 $iscurrentuser = ($user->id == $USER->id);
1555 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1557 // Get the course set against the page, by default this will be the site
1558 $course = $this->page->course;
1559 $baseargs = array('id'=>$user->id);
1560 if ($course->id !== SITEID && (!$iscurrentuser || $forceforcontext)) {
1561 if (array_key_exists($course->id, $this->mycourses)) {
1562 $coursenode = $this->mycourses[$course->id]->coursenode;
1564 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1566 $coursenode = $this->load_course($course);
1569 $baseargs['course'] = $course->id;
1570 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1571 $issitecourse = false;
1573 // Load all categories and get the context for the system
1574 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1575 $issitecourse = true;
1578 // Create a node to add user information under.
1579 if ($iscurrentuser && !$forceforcontext) {
1580 // If it's the current user the information will go under the profile root node
1581 $usernode = $this->rootnodes['myprofile'];
1583 if (!$issitecourse) {
1584 // Not the current user so add it to the participants node for the current course
1585 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1586 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1588 // This is the site so add a users node to the root branch
1589 $usersnode = $this->rootnodes['users'];
1590 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1591 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1594 // We should NEVER get here, if the course hasn't been populated
1595 // with a participants node then the navigaiton either wasn't generated
1596 // for it (you are missing a require_login or set_context call) or
1597 // you don't have access.... in the interests of no leaking informatin
1598 // we simply quit...
1601 // Add a branch for the current user
1602 $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);
1604 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1605 $usernode->make_active();
1609 // If the user is the current user or has permission to view the details of the requested
1610 // user than add a view profile link.
1611 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1612 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1613 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1615 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1619 // Add nodes for forum posts and discussions if the user can view either or both
1620 // There are no capability checks here as the content of the page is based
1621 // purely on the forums the current user has access too.
1622 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1623 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1624 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1627 if (!empty($CFG->bloglevel)) {
1628 require_once($CFG->dirroot.'/blog/lib.php');
1629 // Get all options for the user
1630 $options = blog_get_options_for_user($user);
1631 if (count($options) > 0) {
1632 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1633 foreach ($options as $option) {
1634 $blogs->add($option['string'], $option['link']);
1639 if (!empty($CFG->messaging)) {
1640 $messageargs = null;
1641 if ($USER->id!=$user->id) {
1642 $messageargs = array('id'=>$user->id);
1644 $url = new moodle_url('/message/index.php',$messageargs);
1645 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
1648 // TODO: Private file capability check
1649 if ($iscurrentuser) {
1650 $url = new moodle_url('/user/files.php');
1651 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
1654 // Add a node to view the users notes if permitted
1655 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1656 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1657 if ($coursecontext->instanceid) {
1658 $url->param('course', $coursecontext->instanceid);
1660 $usernode->add(get_string('notes', 'notes'), $url);
1663 // Add a reports tab and then add reports the the user has permission to see.
1664 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1666 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext));
1668 $reporttab = $usernode->add(get_string('activityreports'));
1669 $reportargs = array('user'=>$user->id);
1670 if (!empty($course->id)) {
1671 $reportargs['id'] = $course->id;
1673 $reportargs['id'] = SITEID;
1675 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1676 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1677 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1680 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1681 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1684 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1685 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1688 if (!empty($CFG->enablestats)) {
1689 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1690 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1694 $gradeaccess = false;
1695 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1696 //ok - can view all course grades
1697 $gradeaccess = true;
1698 } else if ($course->showgrades) {
1699 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1700 //ok - can view own grades
1701 $gradeaccess = true;
1702 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1703 // ok - can view grades of this user - parent most probably
1704 $gradeaccess = true;
1705 } else if ($anyreport) {
1706 // ok - can view grades of this user - parent most probably
1707 $gradeaccess = true;
1711 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1714 // Check the number of nodes in the report node... if there are none remove
1716 if (count($reporttab->children)===0) {
1717 $usernode->remove_child($reporttab);
1721 // If the user is the current user add the repositories for the current user
1722 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
1723 if ($iscurrentuser) {
1724 require_once($CFG->dirroot . '/repository/lib.php');
1725 $editabletypes = repository::get_editable_types($usercontext);
1726 if (!empty($editabletypes)) {
1727 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1729 } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
1731 // Add view grade report is permitted
1732 $reports = get_plugin_list('gradereport');
1733 arsort($reports); // user is last, we want to test it first
1735 $userscourses = enrol_get_users_courses($user->id);
1736 $userscoursesnode = $usernode->add(get_string('courses'));
1738 foreach ($userscourses as $usercourse) {
1739 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
1740 $usercoursenode = $userscoursesnode->add($usercourse->shortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
1742 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
1743 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
1744 foreach ($reports as $plugin => $plugindir) {
1745 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
1746 //stop when the first visible plugin is found
1747 $gradeavailable = true;
1753 if ($gradeavailable) {
1754 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
1755 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
1758 // Add a node to view the users notes if permitted
1759 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
1760 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
1761 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
1764 if (can_access_course(get_context_instance(CONTEXT_COURSE, $usercourse->id), $user->id)) {
1765 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
1768 $outlinetreport = ($anyreport || has_capability('coursereport/outline:view', $usercoursecontext));
1769 $logtodayreport = ($anyreport || has_capability('coursereport/log:viewtoday', $usercoursecontext));
1770 $logreport = ($anyreport || has_capability('coursereport/log:view', $usercoursecontext));
1771 $statsreport = ($anyreport || has_capability('coursereport/stats:view', $usercoursecontext));
1772 if ($outlinetreport || $logtodayreport || $logreport || $statsreport) {
1773 $reporttab = $usercoursenode->add(get_string('activityreports'));
1774 $reportargs = array('user'=>$user->id, 'id'=>$usercourse->id);
1775 if ($outlinetreport) {
1776 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1777 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1780 if ($logtodayreport) {
1781 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1785 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1788 if (!empty($CFG->enablestats) && $statsreport) {
1789 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1798 * This method simply checks to see if a given module can extend the navigation.
1800 * @param string $modname
1803 protected function module_extends_navigation($modname) {
1805 if ($this->cache->cached($modname.'_extends_navigation')) {
1806 return $this->cache->{$modname.'_extends_navigation'};
1808 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1809 $function = $modname.'_extend_navigation';
1810 if (function_exists($function)) {
1811 $this->cache->{$modname.'_extends_navigation'} = true;
1813 } else if (file_exists($file)) {
1814 require_once($file);
1815 if (function_exists($function)) {
1816 $this->cache->{$modname.'_extends_navigation'} = true;
1820 $this->cache->{$modname.'_extends_navigation'} = false;
1824 * Extends the navigation for the given user.
1826 * @param stdClass $user A user from the database
1828 public function extend_for_user($user) {
1829 $this->extendforuser[] = $user;
1833 * Returns all of the users the navigation is being extended for
1837 public function get_extending_users() {
1838 return $this->extendforuser;
1841 * Adds the given course to the navigation structure.
1843 * @param stdClass $course
1844 * @return navigation_node
1846 public function add_course(stdClass $course, $forcegeneric = false) {
1848 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1849 if ($course->id !== SITEID && !$canviewhidden && !$course->visible) {
1853 $issite = ($course->id == SITEID);
1854 $ismycourse = (array_key_exists($course->id, $this->mycourses) && !$forcegeneric);
1855 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories));
1856 $shortname = $course->shortname;
1861 $shortname = get_string('sitepages');
1862 } else if ($ismycourse) {
1863 $parent = $this->rootnodes['mycourses'];
1864 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1866 $parent = $this->rootnodes['courses'];
1867 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1870 if ($displaycategories) {
1871 // We need to load the category structure for this course
1872 $categoryfound = false;
1873 if (!empty($course->categorypath)) {
1874 $categories = explode('/', trim($course->categorypath, '/'));
1875 $category = $parent;
1876 while ($category && $categoryid = array_shift($categories)) {
1877 $category = $category->get($categoryid, self::TYPE_CATEGORY);
1879 if ($category instanceof navigation_node) {
1880 $parent = $category;
1881 $categoryfound = true;
1883 if (!$categoryfound && $forcegeneric) {
1884 $this->load_all_categories($course->category);
1885 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1886 $parent = $category;
1887 $categoryfound = true;
1890 } else if (!empty($course->category)) {
1891 $this->load_all_categories($course->category);
1892 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1893 $parent = $category;
1894 $categoryfound = true;
1896 if (!$categoryfound && !$forcegeneric) {
1897 $this->load_all_categories($course->category);
1898 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1899 $parent = $category;
1900 $categoryfound = true;
1906 // We found the course... we can return it now :)
1907 if ($coursenode = $parent->get($course->id, self::TYPE_COURSE)) {
1911 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
1912 $coursenode->nodetype = self::NODETYPE_BRANCH;
1913 $coursenode->hidden = (!$course->visible);
1914 $coursenode->title($course->fullname);
1915 $this->addedcourses[$course->id] = &$coursenode;
1916 if ($ismycourse && !empty($CFG->navshowallcourses)) {
1917 // We need to add this course to the general courses node as well as the
1918 // my courses node, rerun the function with the kill param
1919 $genericcourse = $this->add_course($course, true);
1920 if ($genericcourse->isactive) {
1921 $genericcourse->make_inactive();
1922 $genericcourse->collapse = true;
1923 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
1924 $parent = $genericcourse->parent;
1925 while ($parent && $parent->type == self::TYPE_CATEGORY) {
1926 $parent->collapse = true;
1927 $parent = $parent->parent;
1935 * Adds essential course nodes to the navigation for the given course.
1937 * This method adds nodes such as reports, blogs and participants
1939 * @param navigation_node $coursenode
1940 * @param stdClass $course
1943 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1946 if ($course->id == SITEID) {
1947 return $this->add_front_page_course_essentials($coursenode, $course);
1950 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1955 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1956 require_once($CFG->dirroot.'/blog/lib.php');
1957 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1958 $currentgroup = groups_get_course_group($course, true);
1959 if ($course->id == SITEID) {
1961 } else if ($course->id && !$currentgroup) {
1962 $filterselect = $course->id;
1964 $filterselect = $currentgroup;
1966 $filterselect = clean_param($filterselect, PARAM_INT);
1967 if ($CFG->bloglevel >= 3) {
1968 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1969 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1971 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1972 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1974 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
1975 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1978 // View course reports
1979 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1980 $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', ''));
1981 $coursereports = get_plugin_list('coursereport');
1982 foreach ($coursereports as $report=>$dir) {
1983 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1984 if (file_exists($libfile)) {
1985 require_once($libfile);
1986 $reportfunction = $report.'_report_extend_navigation';
1987 if (function_exists($report.'_report_extend_navigation')) {
1988 $reportfunction($reportnav, $course, $this->page->context);
1996 * This generates the the structure of the course that won't be generated when
1997 * the modules and sections are added.
1999 * Things such as the reports branch, the participants branch, blogs... get
2000 * added to the course node by this method.
2002 * @param navigation_node $coursenode
2003 * @param stdClass $course
2004 * @return bool True for successfull generation
2006 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2009 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2013 // Hidden node that we use to determine if the front page navigation is loaded.
2014 // This required as there are not other guaranteed nodes that may be loaded.
2015 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2018 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2019 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2025 if (has_capability('moodle/blog:view', $this->page->context)) {
2026 require_once($CFG->dirroot.'/blog/lib.php');
2027 if (blog_is_enabled_for_user()) {
2028 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2029 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
2034 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2035 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2039 if (!empty($CFG->usetags) && isloggedin()) {
2040 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2044 // View course reports
2045 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2046 $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', ''));
2047 $coursereports = get_plugin_list('coursereport');
2048 foreach ($coursereports as $report=>$dir) {
2049 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2050 if (file_exists($libfile)) {
2051 require_once($libfile);
2052 $reportfunction = $report.'_report_extend_navigation';
2053 if (function_exists($report.'_report_extend_navigation')) {
2054 $reportfunction($reportnav, $course, $this->page->context);
2063 * Clears the navigation cache
2065 public function clear_cache() {
2066 $this->cache->clear();
2070 * Sets an expansion limit for the navigation
2072 * The expansion limit is used to prevent the display of content that has a type
2073 * greater than the provided $type.
2075 * Can be used to ensure things such as activities or activity content don't get
2076 * shown on the navigation.
2077 * They are still generated in order to ensure the navbar still makes sense.
2079 * @param int $type One of navigation_node::TYPE_*
2082 public function set_expansion_limit($type) {
2083 $nodes = $this->find_all_of_type($type);
2084 foreach ($nodes as &$node) {
2085 // We need to generate the full site node
2086 if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2089 foreach ($node->children as &$child) {
2090 // We still want to show course reports and participants containers
2091 // or there will be navigation missing.
2092 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2095 $child->display = false;
2101 * Attempts to get the navigation with the given key from this nodes children.
2103 * This function only looks at this nodes children, it does NOT look recursivily.
2104 * If the node can't be found then false is returned.
2106 * If you need to search recursivily then use the {@see find()} method.
2108 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2109 * may be of more use to you.
2111 * @param string|int $key The key of the node you wish to receive.
2112 * @param int $type One of navigation_node::TYPE_*
2113 * @return navigation_node|false
2115 public function get($key, $type = null) {
2116 if (!$this->initialised) {
2117 $this->initialise();
2119 return parent::get($key, $type);
2123 * Searches this nodes children and thier children to find a navigation node
2124 * with the matching key and type.
2126 * This method is recursive and searches children so until either a node is
2127 * found of there are no more nodes to search.
2129 * If you know that the node being searched for is a child of this node
2130 * then use the {@see get()} method instead.
2132 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2133 * may be of more use to you.
2135 * @param string|int $key The key of the node you wish to receive.
2136 * @param int $type One of navigation_node::TYPE_*
2137 * @return navigation_node|false
2139 public function find($key, $type) {
2140 if (!$this->initialised) {
2141 $this->initialise();
2143 return parent::find($key, $type);
2148 * The limited global navigation class used for the AJAX extension of the global
2151 * The primary methods that are used in the global navigation class have been overriden
2152 * to ensure that only the relevant branch is generated at the root of the tree.
2153 * This can be done because AJAX is only used when the backwards structure for the
2154 * requested branch exists.
2155 * This has been done only because it shortens the amounts of information that is generated
2156 * which of course will speed up the response time.. because no one likes laggy AJAX.
2158 * @package moodlecore
2159 * @subpackage navigation
2160 * @copyright 2009 Sam Hemelryk
2161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2163 class global_navigation_for_ajax extends global_navigation {
2165 protected $branchtype;
2166 protected $instanceid;
2169 protected $expandable = array();
2172 * Constructs the navigation for use in AJAX request
2174 public function __construct($page, $branchtype, $id) {
2175 $this->page = $page;
2176 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2177 $this->children = new navigation_node_collection();
2178 $this->branchtype = $branchtype;
2179 $this->instanceid = $id;
2180 $this->initialise();
2183 * Initialise the navigation given the type and id for the branch to expand.
2185 * @return array The expandable nodes
2187 public function initialise() {
2188 global $CFG, $DB, $SITE;
2190 if ($this->initialised || during_initial_install()) {
2191 return $this->expandable;
2193 $this->initialised = true;
2195 $this->rootnodes = array();
2196 $this->rootnodes['site'] = $this->add_course($SITE);
2197 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2199 // Branchtype will be one of navigation_node::TYPE_*
2200 switch ($this->branchtype) {
2201 case self::TYPE_CATEGORY :
2202 $this->load_all_categories($this->instanceid);
2204 if (!empty($CFG->navcourselimit)) {
2205 $limit = (int)$CFG->navcourselimit;
2207 $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
2208 foreach ($courses as $course) {
2209 $this->add_course($course);
2212 case self::TYPE_COURSE :
2213 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2214 require_course_login($course);
2215 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2216 $coursenode = $this->add_course($course);
2217 $this->add_course_essentials($coursenode, $course);
2218 if ($this->format_display_course_content($course->format)) {
2219 $this->load_course_sections($course, $coursenode);
2222 case self::TYPE_SECTION :
2223 $sql = 'SELECT c.*, cs.section AS sectionnumber
2225 LEFT JOIN {course_sections} cs ON cs.course = c.id
2227 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2228 require_course_login($course);
2229 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2230 $coursenode = $this->add_course($course);
2231 $this->add_course_essentials($coursenode, $course);
2232 $sections = $this->load_course_sections($course, $coursenode);
2233 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
2235 case self::TYPE_ACTIVITY :
2236 $cm = get_coursemodule_from_id(false, $this->instanceid, 0, false, MUST_EXIST);
2237 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2238 require_course_login($course, true, $cm);
2239 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2240 $coursenode = $this->load_course($course);
2241 $sections = $this->load_course_sections($course, $coursenode);
2242 foreach ($sections as $section) {
2243 if ($section->id == $cm->section) {
2244 $cm->sectionnumber = $section->section;
2248 if ($course->id == SITEID) {
2249 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2251 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
2252 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2256 throw new Exception('Unknown type');
2257 return $this->expandable;
2260 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2261 $this->load_for_user(null, true);
2264 $this->find_expandable($this->expandable);
2265 return $this->expandable;
2269 * Returns an array of expandable nodes
2272 public function get_expandable() {
2273 return $this->expandable;
2280 * This class is used to manage the navbar, which is initialised from the navigation
2281 * object held by PAGE
2283 * @package moodlecore
2284 * @subpackage navigation
2285 * @copyright 2009 Sam Hemelryk
2286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2288 class navbar extends navigation_node {
2290 protected $initialised = false;
2292 protected $keys = array();
2293 /** @var null|string */
2294 protected $content = null;
2295 /** @var moodle_page object */
2298 protected $ignoreactive = false;
2300 protected $duringinstall = false;
2302 protected $hasitems = false;
2306 public $children = array();
2308 public $includesettingsbase = false;
2310 * The almighty constructor
2312 * @param moodle_page $page
2314 public function __construct(moodle_page $page) {
2316 if (during_initial_install()) {
2317 $this->duringinstall = true;
2320 $this->page = $page;
2321 $this->text = get_string('home');
2322 $this->shorttext = get_string('home');
2323 $this->action = new moodle_url($CFG->wwwroot);
2324 $this->nodetype = self::NODETYPE_BRANCH;
2325 $this->type = self::TYPE_SYSTEM;
2329 * Quick check to see if the navbar will have items in.
2331 * @return bool Returns true if the navbar will have items, false otherwise
2333 public function has_items() {
2334 if ($this->duringinstall) {
2336 } else if ($this->hasitems !== false) {
2339 $this->page->navigation->initialise($this->page);
2341 $activenodefound = ($this->page->navigation->contains_active_node() ||
2342 $this->page->settingsnav->contains_active_node());
2344 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2345 $this->hasitems = $outcome;
2350 * Turn on/off ignore active
2352 * @param bool $setting
2354 public function ignore_active($setting=true) {
2355 $this->ignoreactive = ($setting);
2357 public function get($key, $type = null) {
2358 foreach ($this->children as &$child) {
2359 if ($child->key === $key && ($type == null || $type == $child->type)) {
2366 * Returns an array of navigation_node's that make up the navbar.
2370 public function get_items() {
2372 // Make sure that navigation is initialised
2373 if (!$this->has_items()) {
2376 if ($this->items !== null) {
2377 return $this->items;
2380 if (count($this->children) > 0) {
2381 // Add the custom children
2382 $items = array_reverse($this->children);
2385 $navigationactivenode = $this->page->navigation->find_active_node();
2386 $settingsactivenode = $this->page->settingsnav->find_active_node();
2388 // Check if navigation contains the active node
2389 if (!$this->ignoreactive) {
2391 if ($navigationactivenode && $settingsactivenode) {
2392 // Parse a combined navigation tree
2393 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2394 if (!$settingsactivenode->mainnavonly) {
2395 $items[] = $settingsactivenode;
2397 $settingsactivenode = $settingsactivenode->parent;
2399 if (!$this->includesettingsbase) {
2400 // Removes the first node from the settings (root node) from the list
2403 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2404 if (!$navigationactivenode->mainnavonly) {
2405 $items[] = $navigationactivenode;
2407 $navigationactivenode = $navigationactivenode->parent;
2409 } else if ($navigationactivenode) {
2410 // Parse the navigation tree to get the active node
2411 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2412 if (!$navigationactivenode->mainnavonly) {
2413 $items[] = $navigationactivenode;
2415 $navigationactivenode = $navigationactivenode->parent;
2417 } else if ($settingsactivenode) {
2418 // Parse the settings navigation to get the active node
2419 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2420 if (!$settingsactivenode->mainnavonly) {
2421 $items[] = $settingsactivenode;
2423 $settingsactivenode = $settingsactivenode->parent;
2428 $items[] = new navigation_node(array(
2429 'text'=>$this->page->navigation->text,
2430 'shorttext'=>$this->page->navigation->shorttext,
2431 'key'=>$this->page->navigation->key,
2432 'action'=>$this->page->navigation->action
2435 $this->items = array_reverse($items);
2436 return $this->items;
2440 * Add a new navigation_node to the navbar, overrides parent::add
2442 * This function overrides {@link navigation_node::add()} so that we can change
2443 * the way nodes get added to allow us to simply call add and have the node added to the
2446 * @param string $text
2447 * @param string|moodle_url $action
2449 * @param string|int $key
2450 * @param string $shorttext
2451 * @param string $icon
2452 * @return navigation_node
2454 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2455 if ($this->content !== null) {
2456 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2459 // Properties array used when creating the new navigation node
2464 // Set the action if one was provided
2465 if ($action!==null) {
2466 $itemarray['action'] = $action;
2468 // Set the shorttext if one was provided
2469 if ($shorttext!==null) {
2470 $itemarray['shorttext'] = $shorttext;
2472 // Set the icon if one was provided
2474 $itemarray['icon'] = $icon;
2476 // Default the key to the number of children if not provided
2477 if ($key === null) {
2478 $key = count($this->children);
2481 $itemarray['key'] = $key;
2482 // Set the parent to this node
2483 $itemarray['parent'] = $this;
2484 // Add the child using the navigation_node_collections add method
2485 $this->children[] = new navigation_node($itemarray);
2491 * Class used to manage the settings option for the current page
2493 * This class is used to manage the settings options in a tree format (recursively)
2494 * and was created initially for use with the settings blocks.
2496 * @package moodlecore
2497 * @subpackage navigation
2498 * @copyright 2009 Sam Hemelryk
2499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2501 class settings_navigation extends navigation_node {
2502 /** @var stdClass */
2504 /** @var navigation_cache */
2506 /** @var moodle_page */
2509 protected $adminsection;
2511 protected $initialised = false;
2513 protected $userstoextendfor = array();
2516 * Sets up the object with basic settings and preparse it for use
2518 * @param moodle_page $page
2520 public function __construct(moodle_page &$page) {
2521 if (during_initial_install()) {
2524 $this->page = $page;
2525 // Initialise the main navigation. It is most important that this is done
2526 // before we try anything
2527 $this->page->navigation->initialise();
2528 // Initialise the navigation cache
2529 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2530 $this->children = new navigation_node_collection();
2533 * Initialise the settings navigation based on the current context
2535 * This function initialises the settings navigation tree for a given context
2536 * by calling supporting functions to generate major parts of the tree.
2539 public function initialise() {
2542 if (during_initial_install()) {
2544 } else if ($this->initialised) {
2547 $this->id = 'settingsnav';
2548 $this->context = $this->page->context;
2550 $context = $this->context;
2551 if ($context->contextlevel == CONTEXT_BLOCK) {
2552 $this->load_block_settings();
2553 $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));
2556 switch ($context->contextlevel) {
2557 case CONTEXT_SYSTEM:
2558 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2559 $this->load_front_page_settings(($context->id == $this->context->id));
2562 case CONTEXT_COURSECAT:
2563 $this->load_category_settings();
2565 case CONTEXT_COURSE:
2566 if ($this->page->course->id != SITEID) {
2567 $this->load_course_settings(($context->id == $this->context->id));
2569 $this->load_front_page_settings(($context->id == $this->context->id));
2572 case CONTEXT_MODULE:
2573 $this->load_module_settings();
2574 $this->load_course_settings();
2577 if ($this->page->course->id != SITEID) {
2578 $this->load_course_settings();
2583 $settings = $this->load_user_settings($this->page->course->id);
2584 $admin = $this->load_administration_settings();
2586 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2587 $admin->force_open();
2588 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2589 $settings->force_open();
2592 // Check if the user is currently logged in as another user
2593 if (session_is_loggedinas()) {
2594 // Get the actual user, we need this so we can display an informative return link
2595 $realuser = session_get_realuser();
2596 // Add the informative return to original user link
2597 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2598 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2601 // Make sure the first child doesnt have proceed with hr set to true
2603 foreach ($this->children as $key=>$node) {
2604 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2608 $this->initialised = true;
2611 * Override the parent function so that we can add preceeding hr's and set a
2612 * root node class against all first level element
2614 * It does this by first calling the parent's add method {@link navigation_node::add()}
2615 * and then proceeds to use the key to set class and hr
2617 * @param string $text
2618 * @param sting|moodle_url $url
2619 * @param string $shorttext
2620 * @param string|int $key
2622 * @param string $icon
2623 * @return navigation_node
2625 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2626 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2627 $node->add_class('root_node');
2632 * This function allows the user to add something to the start of the settings
2633 * navigation, which means it will be at the top of the settings navigation block
2635 * @param string $text
2636 * @param sting|moodle_url $url
2637 * @param string $shorttext
2638 * @param string|int $key
2640 * @param string $icon
2641 * @return navigation_node
2643 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2644 $children = $this->children;
2645 $childrenclass = get_class($children);
2646 $this->children = new $childrenclass;
2647 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2648 foreach ($children as $child) {
2649 $this->children->add($child);
2654 * Load the site administration tree
2656 * This function loads the site administration tree by using the lib/adminlib library functions
2658 * @param navigation_node $referencebranch A reference to a branch in the settings
2660 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2661 * tree and start at the beginning
2662 * @return mixed A key to access the admin tree by
2664 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2667 // Check if we are just starting to generate this navigation.
2668 if ($referencebranch === null) {
2670 // Require the admin lib then get an admin structure
2671 if (!function_exists('admin_get_root')) {
2672 require_once($CFG->dirroot.'/lib/adminlib.php');
2674 $adminroot = admin_get_root(false, false);
2675 // This is the active section identifier
2676 $this->adminsection = $this->page->url->param('section');
2678 // Disable the navigation from automatically finding the active node
2679 navigation_node::$autofindactive = false;
2680 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2681 foreach ($adminroot->children as $adminbranch) {
2682 $this->load_administration_settings($referencebranch, $adminbranch);
2684 navigation_node::$autofindactive = true;
2686 // Use the admin structure to locate the active page
2687 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2688 $currentnode = $this;
2689 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2690 $currentnode = $currentnode->get($pathkey);
2693 $currentnode->make_active();
2696 $this->scan_for_active_node($referencebranch);
2698 return $referencebranch;
2699 } else if ($adminbranch->check_access()) {
2700 // We have a reference branch that we can access and is not hidden `hurrah`
2701 // Now we need to display it and any children it may have
2704 if ($adminbranch instanceof admin_settingpage) {
2705 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2706 } else if ($adminbranch instanceof admin_externalpage) {
2707 $url = $adminbranch->url;
2711 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2713 if ($adminbranch->is_hidden()) {
2714 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2715 $reference->add_class('hidden');
2717 $reference->display = false;
2721 // Check if we are generating the admin notifications and whether notificiations exist
2722 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2723 $reference->add_class('criticalnotification');
2725 // Check if this branch has children
2726 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2727 foreach ($adminbranch->children as $branch) {
2728 // Generate the child branches as well now using this branch as the reference
2729 $this->load_administration_settings($reference, $branch);
2732 $reference->icon = new pix_icon('i/settings', '');
2738 * This function recursivily scans nodes until it finds the active node or there
2739 * are no more nodes.
2740 * @param navigation_node $node
2742 protected function scan_for_active_node(navigation_node $node) {
2743 if (!$node->check_if_active() && $node->children->count()>0) {
2744 foreach ($node->children as &$child) {
2745 $this->scan_for_active_node($child);
2751 * Gets a navigation node given an array of keys that represent the path to
2754 * @param array $path
2755 * @return navigation_node|false
2757 protected function get_by_path(array $path) {
2758 $node = $this->get(array_shift($path));
2759 foreach ($path as $key) {
2766 * Generate the list of modules for the given course.
2768 * The array of resources and activities that can be added to a course is then
2769 * stored in the cache so that we can access it for anywhere.
2770 * It saves us generating it all the time
2773 * // To get resources:
2774 * $this->cache->{'course'.$courseid.'resources'}
2775 * // To get activities:
2776 * $this->cache->{'course'.$courseid.'activities'}
2779 * @param stdClass $course The course to get modules for
2781 protected function get_course_modules($course) {
2783 $mods = $modnames = $modnamesplural = $modnamesused = array();
2784 // This function is included when we include course/lib.php at the top
2786 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2787 $resources = array();
2788 $activities = array();
2789 foreach($modnames as $modname=>$modnamestr) {
2790 if (!course_allowed_module($course, $modname)) {
2794 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2795 if (!file_exists($libfile)) {
2798 include_once($libfile);
2799 $gettypesfunc = $modname.'_get_types';
2800 if (function_exists($gettypesfunc)) {
2801 $types = $gettypesfunc();
2802 foreach($types as $type) {
2803 if (!isset($type->modclass) || !isset($type->typestr)) {
2804 debugging('Incorrect activity type in '.$modname);
2807 if ($type->modclass == MOD_CLASS_RESOURCE) {
2808 $resources[html_entity_decode($type->type)] = $type->typestr;
2810 $activities[html_entity_decode($type->type)] = $type->typestr;
2814 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2815 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2816 $resources[$modname] = $modnamestr;
2818 // all other archetypes are considered activity
2819 $activities[$modname] = $modnamestr;
2823 $this->cache->{'course'.$course->id.'resources'} = $resources;
2824 $this->cache->{'course'.$course->id.'activities'} = $activities;
2828 * This function loads the course settings that are available for the user
2830 * @param bool $forceopen If set to true the course node will be forced open
2831 * @return navigation_node|false
2833 protected function load_course_settings($forceopen = false) {
2834 global $CFG, $USER, $SESSION, $OUTPUT;
2836 $course = $this->page->course;
2837 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2839 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
2841 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2843 $coursenode->force_open();
2846 if (has_capability('moodle/course:update', $coursecontext)) {
2847 // Add the turn on/off settings
2848 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2849 if ($this->page->user_is_editing()) {
2850 $url->param('edit', 'off');
2851 $editstring = get_string('turneditingoff');
2853 $url->param('edit', 'on');
2854 $editstring = get_string('turneditingon');
2856 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2858 if ($this->page->user_is_editing()) {
2859 // Removed as per MDL-22732
2860 // $this->add_course_editing_links($course);
2863 // Add the course settings link
2864 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2865 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2867 // Add the course completion settings link
2868 if ($CFG->enablecompletion && $course->enablecompletion) {
2869 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2870 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2875 enrol_add_course_navigation($coursenode, $course);
2878 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2879 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2880 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2883 // Add view grade report is permitted
2884 $reportavailable = false;
2885 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2886 $reportavailable = true;
2887 } else if (!empty($course->showgrades)) {
2888 $reports = get_plugin_list('gradereport');
2889 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2890 arsort($reports); // user is last, we want to test it first
2891 foreach ($reports as $plugin => $plugindir) {
2892 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2893 //stop when the first visible plugin is found
2894 $reportavailable = true;
2900 if ($reportavailable) {
2901 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2902 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2905 // Add outcome if permitted
2906 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2907 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2908 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
2911 // Backup this course
2912 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2913 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2914 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
2917 // Restore to this course
2918 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2919 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
2920 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
2923 // Import data from other courses
2924 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2925 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
2926 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
2929 // Publish course on a hub
2930 if (has_capability('moodle/course:publish', $coursecontext)) {
2931 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2932 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
2935 // Reset this course
2936 if (has_capability('moodle/course:reset', $coursecontext)) {
2937 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2938 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2942 require_once($CFG->dirroot.'/question/editlib.php');
2943 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
2945 // Repository Instances
2946 require_once($CFG->dirroot.'/repository/lib.php');
2947 $editabletypes = repository::get_editable_types($coursecontext);
2948 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2949 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id));
2950 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
2954 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
2955 // hidden in new courses and courses where legacy files were turned off
2956 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
2957 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
2962 $assumedrole = $this->in_alternative_role();
2963 if ($assumedrole!==false) {
2964 $roles[0] = get_string('switchrolereturn');
2966 if (has_capability('moodle/role:switchroles', $coursecontext)) {
2967 $availableroles = get_switchable_roles($coursecontext);
2968 if (is_array($availableroles)) {
2969 foreach ($availableroles as $key=>$role) {
2970 if ($assumedrole===(int)$key) {
2973 $roles[$key] = $role;
2977 if (is_array($roles) && count($roles)>0) {
2978 $switchroles = $this->add(get_string('switchroleto'));
2979 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2980 $switchroles->force_open();
2982 $returnurl = $this->page->url;
2983 $returnurl->param('sesskey', sesskey());
2984 $SESSION->returnurl = serialize($returnurl);
2985 foreach ($roles as $key=>$name) {
2986 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2987 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
2990 // Return we are done
2995 * Adds branches and links to the settings navigation to add course activities
2998 * @param stdClass $course
3000 protected function add_course_editing_links($course) {
3003 require_once($CFG->dirroot.'/course/lib.php');
3005 // Add `add` resources|activities branches
3006 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3007 if (file_exists($structurefile)) {
3008 require_once($structurefile);
3009 $requestkey = call_user_func('callback_'.$course->format.'_request_key');
3010 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3012 $requestkey = get_string('section');
3013 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3016 $sections = get_all_sections($course->id);
3018 $addresource = $this->add(get_string('addresource'));
3019 $addactivity = $this->add(get_string('addactivity'));
3020 if ($formatidentifier!==0) {
3021 $addresource->force_open();
3022 $addactivity->force_open();
3025 if (!$this->cache->cached('course'.$course->id.'resources')) {
3026 $this->get_course_modules($course);
3028 $resources = $this->cache->{'course'.$course->id.'resources'};
3029 $activities = $this->cache->{'course'.$course->id.'activities'};
3031 $textlib = textlib_get_instance();
3033 foreach ($sections as $section) {
3034 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
3037 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $requestkey=>$section->section));
3038 if ($section->section == 0) {
3039 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3040 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3042 $sectionname = get_section_name($course, $section);
3043 $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING);
3044 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING);
3046 foreach ($resources as $value=>$resource) {
3047 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3048 $pos = strpos($value, '&type=');
3050 $url->param('add', $textlib->substr($value, 0,$pos));
3051 $url->param('type', $textlib->substr($value, $pos+6));
3053 $url->param('add', $value);
3055 $sectionresources->add($resource, $url, self::TYPE_SETTING);
3058 foreach ($activities as $activityname=>$activity) {
3059 if ($activity==='--') {
3063 if (strpos($activity, '--')===0) {
3064 $subbranch = $sectionactivities->add(trim($activity, '-'));
3067 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3068 $pos = strpos($activityname, '&type=');
3070 $url->param('add', $textlib->substr($activityname, 0,$pos));
3071 $url->param('type', $textlib->substr($activityname, $pos+6));
3073 $url->param('add', $activityname);
3075 if ($subbranch !== false) {
3076 $subbranch->add($activity, $url, self::TYPE_SETTING);
3078 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3085 * This function calls the module function to inject module settings into the
3086 * settings navigation tree.
3088 * This only gets called if there is a corrosponding function in the modules
3091 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3093 * @return navigation_node|false
3095 protected function load_module_settings() {
3098 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3099 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3100 $this->page->set_cm($cm, $this->page->course);
3103 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3104 if (file_exists($file)) {
3105 require_once($file);
3108 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3109 $modulenode->force_open();
3111 // Settings for the module
3112 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3113 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3114 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING);
3116 // Assign local roles
3117 if (count(get_assignable_roles($this->page->cm->context))>0) {
3118 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3119 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
3122 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3123 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3124 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3126 // Check role permissions
3127 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3128 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3129 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3132 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3133 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3134 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
3137 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
3138 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
3139 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING);
3142 // Add a backup link
3143 $featuresfunc = $this->page->activityname.'_supports';
3144 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3145 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3146 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
3149 // Restore this activity
3150 $featuresfunc = $this->page->activityname.'_supports';
3151 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3152 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3153 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING);
3156 $function = $this->page->activityname.'_extend_settings_navigation';
3157 if (!function_exists($function)) {
3161 $function($this, $modulenode);
3163 // Remove the module node if there are no children
3164 if (empty($modulenode->children)) {
3165 $modulenode->remove();
3172 * Loads the user settings block of the settings nav
3174 * This function is simply works out the userid and whether we need to load
3175 * just the current users profile settings, or the current user and the user the
3176 * current user is viewing.
3178 * This function has some very ugly code to work out the user, if anyone has
3179 * any bright ideas please feel free to intervene.
3181 * @param int $courseid The course id of the current course
3182 * @return navigation_node|false
3184 protected function load_user_settings($courseid=SITEID) {
3185 global $USER, $FULLME, $CFG;
3187 if (isguestuser() || !isloggedin()) {
3191 $navusers = $this->page->navigation->get_extending_users();
3193 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3195 foreach ($this->userstoextendfor as $userid) {
3196 if ($userid == $USER->id) {
3199 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3200 if (is_null($usernode)) {
3204 foreach ($navusers as $user) {
3205 if ($user->id == $USER->id) {
3208 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3209 if (is_null($usernode)) {
3213 $this->generate_user_settings($courseid, $USER->id);
3215 $usernode = $this->generate_user_settings($courseid, $USER->id);
3221 * Extends the settings navigation for the given user.
3223 * Note: This method gets called automatically if you call
3224 * $PAGE->navigation->extend_for_user($userid)
3226 * @param int $userid
3228 public function extend_for_user($userid) {
3231 if (!in_array($userid, $this->userstoextendfor)) {
3232 $this->userstoextendfor[] = $userid;
3233 if ($this->initialised) {
3234 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3235 $children = array();
3236 foreach ($this->children as $child) {
3237 $children[] = $child;
3239 array_unshift($children, array_pop($children));
3240 $this->children = new navigation_node_collection();
3241 foreach ($children as $child) {
3242 $this->children->add($child);
3249 * This function gets called by {@link load_user_settings()} and actually works out
3250 * what can be shown/done
3252 * @param int $courseid The current course' id
3253 * @param int $userid The user id to load for
3254 * @param string $gstitle The string to pass to get_string for the branch title
3255 * @return navigation_node|false
3257 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3258 global $DB, $CFG, $USER, $SITE;
3260 if ($courseid != SITEID) {
3261 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3262 $course = $this->page->course;
3264 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
3270 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3271 $systemcontext = get_system_context();
3272 $currentuser = ($USER->id == $userid);
3276 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3278 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
3281 // Check that the user can view the profile
3282 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3283 if ($course->id==SITEID) {
3284 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3285 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3289 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !can_access_course($coursecontext, $user->id)) {
3292 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3293 // If groups are in use, make sure we can see that group
3299 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3302 if ($gstitle != 'usercurrentsettings') {
3306 // Add a user setting branch
3307 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3308 $usersetting->id = 'usersettings';
3309 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3310 // Automatically start by making it active
3311 $usersetting->make_active();
3314 // Check if the user has been deleted
3315 if ($user->deleted) {
3316 if (!has_capability('moodle/user:update', $coursecontext)) {
3317 // We can't edit the user so just show the user deleted message
3318 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3320 // We can edit the user so show the user deleted message and link it to the profile
3321 if ($course->id == SITEID) {
3322 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));