3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 if (!function_exists('get_all_sections')) {
30 /** Include course lib for its functions */
31 require_once($CFG->dirroot.'/course/lib.php');
35 * The name that will be used to separate the navigation cache within SESSION
37 define('NAVIGATION_CACHE_NAME', 'navigation');
40 * This class is used to represent a node in a navigation tree
42 * This class is used to represent a node in a navigation tree within Moodle,
43 * the tree could be one of global navigation, settings navigation, or the navbar.
44 * Each node can be one of two types either a Leaf (default) or a branch.
45 * When a node is first created it is created as a leaf, when/if children are added
46 * the node then becomes a branch.
49 * @subpackage navigation
50 * @copyright 2009 Sam Hemelryk
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class navigation_node implements renderable {
54 /** @var int Used to identify this node a leaf (default) 0 */
55 const NODETYPE_LEAF = 0;
56 /** @var int Used to identify this node a branch, happens with children 1 */
57 const NODETYPE_BRANCH = 1;
58 /** @var null Unknown node type null */
59 const TYPE_UNKNOWN = null;
60 /** @var int System node type 0 */
61 const TYPE_ROOTNODE = 0;
62 /** @var int System node type 1 */
63 const TYPE_SYSTEM = 1;
64 /** @var int Category node type 10 */
65 const TYPE_CATEGORY = 10;
66 /** @var int Course node type 20 */
67 const TYPE_COURSE = 20;
68 /** @var int Course Structure node type 30 */
69 const TYPE_SECTION = 30;
70 /** @var int Activity node type, e.g. Forum, Quiz 40 */
71 const TYPE_ACTIVITY = 40;
72 /** @var int Resource node type, e.g. Link to a file, or label 50 */
73 const TYPE_RESOURCE = 50;
74 /** @var int A custom node type, default when adding without specifing type 60 */
75 const TYPE_CUSTOM = 60;
76 /** @var int Setting node type, used only within settings nav 70 */
77 const TYPE_SETTING = 70;
78 /** @var int Setting node type, used only within settings nav 80 */
80 /** @var int Setting node type, used for containers of no importance 90 */
81 const TYPE_CONTAINER = 90;
83 /** @var int Parameter to aid the coder in tracking [optional] */
85 /** @var string|int The identifier for the node, used to retrieve the node */
87 /** @var string The text to use for the node */
89 /** @var string Short text to use if requested [optional] */
90 public $shorttext = null;
91 /** @var string The title attribute for an action if one is defined */
93 /** @var string A string that can be used to build a help button */
94 public $helpbutton = null;
95 /** @var moodle_url|action_link|null An action for the node (link) */
96 public $action = null;
97 /** @var pix_icon The path to an icon to use for this node */
99 /** @var int See TYPE_* constants defined for this class */
100 public $type = self::TYPE_UNKNOWN;
101 /** @var int See NODETYPE_* constants defined for this class */
102 public $nodetype = self::NODETYPE_LEAF;
103 /** @var bool If set to true the node will be collapsed by default */
104 public $collapse = false;
105 /** @var bool If set to true the node will be expanded by default */
106 public $forceopen = false;
107 /** @var array An array of CSS classes for the node */
108 public $classes = array();
109 /** @var navigation_node_collection An array of child nodes */
110 public $children = array();
111 /** @var bool If set to true the node will be recognised as active */
112 public $isactive = false;
113 /** @var bool If set to true the node will be dimmed */
114 public $hidden = false;
115 /** @var bool If set to false the node will not be displayed */
116 public $display = true;
117 /** @var bool If set to true then an HR will be printed before the node */
118 public $preceedwithhr = false;
119 /** @var bool If set to true the the navigation bar should ignore this node */
120 public $mainnavonly = false;
121 /** @var bool If set to true a title will be added to the action no matter what */
122 public $forcetitle = false;
123 /** @var navigation_node A reference to the node parent */
124 public $parent = null;
126 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
127 /** @var moodle_url */
128 protected static $fullmeurl = null;
129 /** @var bool toogles auto matching of active node */
130 public static $autofindactive = true;
133 * Constructs a new navigation_node
135 * @param array|string $properties Either an array of properties or a string to use
136 * as the text for the node
138 public function __construct($properties) {
139 if (is_array($properties)) {
140 // Check the array for each property that we allow to set at construction.
141 // text - The main content for the node
142 // shorttext - A short text if required for the node
143 // icon - The icon to display for the node
144 // type - The type of the node
145 // key - The key to use to identify the node
146 // parent - A reference to the nodes parent
147 // action - The action to attribute to this node, usually a URL to link to
148 if (array_key_exists('text', $properties)) {
149 $this->text = $properties['text'];
151 if (array_key_exists('shorttext', $properties)) {
152 $this->shorttext = $properties['shorttext'];
154 if (array_key_exists('icon', $properties)) {
155 $this->icon = $properties['icon'];
156 if ($this->icon instanceof pix_icon) {
157 if (empty($this->icon->attributes['class'])) {
158 $this->icon->attributes['class'] = 'navicon';
160 $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 * Overrides the fullmeurl variable providing
228 * @param moodle_url $url The url to use for the fullmeurl.
230 public static function override_active_url(moodle_url $url) {
231 self::$fullmeurl = $url;
235 * Adds a navigation node as a child of this node.
237 * @param string $text
238 * @param moodle_url|action_link $action
240 * @param string $shorttext
241 * @param string|int $key
242 * @param pix_icon $icon
243 * @return navigation_node
245 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
246 // First convert the nodetype for this node to a branch as it will now have children
247 if ($this->nodetype !== self::NODETYPE_BRANCH) {
248 $this->nodetype = self::NODETYPE_BRANCH;
250 // Properties array used when creating the new navigation node
255 // Set the action if one was provided
256 if ($action!==null) {
257 $itemarray['action'] = $action;
259 // Set the shorttext if one was provided
260 if ($shorttext!==null) {
261 $itemarray['shorttext'] = $shorttext;
263 // Set the icon if one was provided
265 $itemarray['icon'] = $icon;
267 // Default the key to the number of children if not provided
269 $key = $this->children->count();
272 $itemarray['key'] = $key;
273 // Set the parent to this node
274 $itemarray['parent'] = $this;
275 // Add the child using the navigation_node_collections add method
276 $node = $this->children->add(new navigation_node($itemarray));
277 // If the node is a category node or the user is logged in and its a course
278 // then mark this node as a branch (makes it expandable by AJAX)
279 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
280 $node->nodetype = self::NODETYPE_BRANCH;
282 // If this node is hidden mark it's children as hidden also
284 $node->hidden = true;
286 // Return the node (reference returned by $this->children->add()
291 * Searches for a node of the given type with the given key.
293 * This searches this node plus all of its children, and their children....
294 * If you know the node you are looking for is a child of this node then please
295 * use the get method instead.
297 * @param int|string $key The key of the node we are looking for
298 * @param int $type One of navigation_node::TYPE_*
299 * @return navigation_node|false
301 public function find($key, $type) {
302 return $this->children->find($key, $type);
306 * Get ths child of this node that has the given key + (optional) type.
308 * If you are looking for a node and want to search all children + thier children
309 * then please use the find method instead.
311 * @param int|string $key The key of the node we are looking for
312 * @param int $type One of navigation_node::TYPE_*
313 * @return navigation_node|false
315 public function get($key, $type=null) {
316 return $this->children->get($key, $type);
324 public function remove() {
325 return $this->parent->children->remove($this->key, $this->type);
329 * Checks if this node has or could have any children
331 * @return bool Returns true if it has children or could have (by AJAX expansion)
333 public function has_children() {
334 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
338 * Marks this node as active and forces it open.
340 public function make_active() {
341 $this->isactive = true;
342 $this->add_class('active_tree_node');
344 if ($this->parent !== null) {
345 $this->parent->make_inactive();
350 * Marks a node as inactive and recusised back to the base of the tree
351 * doing the same to all parents.
353 public function make_inactive() {
354 $this->isactive = false;
355 $this->remove_class('active_tree_node');
356 if ($this->parent !== null) {
357 $this->parent->make_inactive();
362 * Forces this node to be open and at the same time forces open all
363 * parents until the root node.
367 public function force_open() {
368 $this->forceopen = true;
369 if ($this->parent !== null) {
370 $this->parent->force_open();
375 * Adds a CSS class to this node.
377 * @param string $class
380 public function add_class($class) {
381 if (!in_array($class, $this->classes)) {
382 $this->classes[] = $class;
388 * Removes a CSS class from this node.
390 * @param string $class
391 * @return bool True if the class was successfully removed.
393 public function remove_class($class) {
394 if (in_array($class, $this->classes)) {
395 $key = array_search($class,$this->classes);
397 unset($this->classes[$key]);
405 * Sets the title for this node and forces Moodle to utilise it.
406 * @param string $title
408 public function title($title) {
409 $this->title = $title;
410 $this->forcetitle = true;
414 * Resets the page specific information on this node if it is being unserialised.
416 public function __wakeup(){
417 $this->forceopen = false;
418 $this->isactive = false;
419 $this->remove_class('active_tree_node');
423 * Checks if this node or any of its children contain the active node.
429 public function contains_active_node() {
430 if ($this->isactive) {
433 foreach ($this->children as $child) {
434 if ($child->isactive || $child->contains_active_node()) {
443 * Finds the active node.
445 * Searches this nodes children plus all of the children for the active node
446 * and returns it if found.
450 * @return navigation_node|false
452 public function find_active_node() {
453 if ($this->isactive) {
456 foreach ($this->children as &$child) {
457 $outcome = $child->find_active_node();
458 if ($outcome !== false) {
467 * Gets the content for this node.
469 * @param bool $shorttext If true shorttext is used rather than the normal text
472 public function get_content($shorttext=false) {
473 if ($shorttext && $this->shorttext!==null) {
474 return format_string($this->shorttext);
476 return format_string($this->text);
481 * Gets the title to use for this node.
485 public function get_title() {
486 if ($this->forcetitle || ($this->shorttext!==null && $this->title !== $this->shorttext) || $this->title !== $this->text) {
494 * Gets the CSS class to add to this node to describe its type
498 public function get_css_type() {
499 if (array_key_exists($this->type, $this->namedtypes)) {
500 return 'type_'.$this->namedtypes[$this->type];
502 return 'type_unknown';
506 * Finds all nodes that are expandable by AJAX
508 * @param array $expandable An array by reference to populate with expandable nodes.
510 public function find_expandable(array &$expandable) {
514 foreach ($this->children as &$child) {
515 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count()==0 && $child->display) {
516 $child->id = 'expandable_branch_'.(count($expandable)+1);
517 $this->add_class('canexpand');
518 $expandable[] = array('id'=>$child->id,'branchid'=>$child->key,'type'=>$child->type);
520 $child->find_expandable($expandable);
524 public function find_all_of_type($type) {
525 $nodes = $this->children->type($type);
526 foreach ($this->children as &$node) {
527 $childnodes = $node->find_all_of_type($type);
528 $nodes = array_merge($nodes, $childnodes);
535 * Navigation node collection
537 * This class is responsible for managing a collection of navigation nodes.
538 * It is required because a node's unique identifier is a combination of both its
541 * Originally an array was used with a string key that was a combination of the two
542 * however it was decided that a better solution would be to use a class that
543 * implements the standard IteratorAggregate interface.
545 * @package moodlecore
546 * @subpackage navigation
547 * @copyright 2010 Sam Hemelryk
548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550 class navigation_node_collection implements IteratorAggregate {
552 * A multidimensional array to where the first key is the type and the second
553 * key is the nodes key.
556 protected $collection = array();
558 * An array that contains references to nodes in the same order they were added.
559 * This is maintained as a progressive array.
562 protected $orderedcollection = array();
564 * A reference to the last node that was added to the collection
565 * @var navigation_node
567 protected $last = null;
569 * The total number of items added to this array.
572 protected $count = 0;
574 * Adds a navigation node to the collection
576 * @param navigation_node $node
577 * @return navigation_node
579 public function add(navigation_node $node) {
583 // First check we have a 2nd dimension for this type
584 if (!array_key_exists($type, $this->orderedcollection)) {
585 $this->orderedcollection[$type] = array();
587 // Check for a collision and report if debugging is turned on
588 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
589 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
591 // Add the node to the appropriate place in the ordered structure.
592 $this->orderedcollection[$type][$key] = $node;
593 // Add a reference to the node to the progressive collection.
594 $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
595 // Update the last property to a reference to this new node.
596 $this->last = &$this->orderedcollection[$type][$key];
598 // Return the reference to the now added node
603 * Fetches a node from this collection.
605 * @param string|int $key The key of the node we want to find.
606 * @param int $type One of navigation_node::TYPE_*.
607 * @return navigation_node|null
609 public function get($key, $type=null) {
610 if ($type !== null) {
611 // If the type is known then we can simply check and fetch
612 if (!empty($this->orderedcollection[$type][$key])) {
613 return $this->orderedcollection[$type][$key];
616 // Because we don't know the type we look in the progressive array
617 foreach ($this->collection as $node) {
618 if ($node->key === $key) {
626 * Searches for a node with matching key and type.
628 * This function searches both the nodes in this collection and all of
629 * the nodes in each collection belonging to the nodes in this collection.
633 * @param string|int $key The key of the node we want to find.
634 * @param int $type One of navigation_node::TYPE_*.
635 * @return navigation_node|null
637 public function find($key, $type=null) {
638 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
639 return $this->orderedcollection[$type][$key];
641 $nodes = $this->getIterator();
642 // Search immediate children first
643 foreach ($nodes as &$node) {
644 if ($node->key == $key && ($type == null || $type === $node->type)) {
648 // Now search each childs children
649 foreach ($nodes as &$node) {
650 $result = $node->children->find($key, $type);
651 if ($result !== false) {
660 * Fetches the last node that was added to this collection
662 * @return navigation_node
664 public function last() {
668 * Fetches all nodes of a given type from this collection
670 public function type($type) {
671 if (!array_key_exists($type, $this->orderedcollection)) {
672 $this->orderedcollection[$type] = array();
674 return $this->orderedcollection[$type];
677 * Removes the node with the given key and type from the collection
679 * @param string|int $key
683 public function remove($key, $type=null) {
684 $child = $this->get($key, $type);
685 if ($child !== false) {
686 foreach ($this->collection as $colkey => $node) {
687 if ($node->key == $key && $node->type == $type) {
688 unset($this->collection[$colkey]);
692 unset($this->orderedcollection[$child->type][$child->key]);
700 * Gets the number of nodes in this collection
703 public function count() {
704 return count($this->collection);
707 * Gets an array iterator for the collection.
709 * This is required by the IteratorAggregator interface and is used by routines
710 * such as the foreach loop.
712 * @return ArrayIterator
714 public function getIterator() {
715 return new ArrayIterator($this->collection);
720 * The global navigation class used for... the global navigation
722 * This class is used by PAGE to store the global navigation for the site
723 * and is then used by the settings nav and navbar to save on processing and DB calls
727 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
728 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
731 * @package moodlecore
732 * @subpackage navigation
733 * @copyright 2009 Sam Hemelryk
734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
736 class global_navigation extends navigation_node {
738 * The Moodle page this navigation object belongs to.
743 protected $initialised = false;
745 protected $mycourses = array();
747 protected $rootnodes = array();
749 protected $showemptysections = false;
751 protected $extendforuser = array();
752 /** @var navigation_cache */
755 protected $addedcourses = array();
757 protected $expansionlimit = 0;
760 * Constructs a new global navigation
762 * @param moodle_page $page The page this navigation object belongs to
764 public function __construct(moodle_page $page) {
767 if (during_initial_install()) {
771 // Use the parents consturctor.... good good reuse
774 'type' => navigation_node::TYPE_SYSTEM,
775 'text' => get_string('myhome'),
776 'action' => new moodle_url('/my/')
778 parent::__construct($properties);
780 // Initalise and set defaults
782 $this->forceopen = true;
783 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
785 // Check if we need to clear the cache
786 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
787 if ($regenerate === 'navigation') {
788 $this->cache->clear();
793 * Initialises the navigation object.
795 * This causes the navigation object to look at the current state of the page
796 * that it is associated with and then load the appropriate content.
798 * This should only occur the first time that the navigation structure is utilised
799 * which will normally be either when the navbar is called to be displayed or
800 * when a block makes use of it.
804 public function initialise() {
806 // Check if it has alread been initialised
807 if ($this->initialised || during_initial_install()) {
811 // Set up the five base root nodes. These are nodes where we will put our
812 // content and are as follows:
813 // site: Navigation for the front page.
814 // myprofile: User profile information goes here.
815 // mycourses: The users courses get added here.
816 // courses: Additional courses are added here.
817 // users: Other users information loaded here.
818 $this->rootnodes = array();
819 $this->rootnodes['site'] = $this->add_course($SITE);
820 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
821 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
822 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
823 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
825 // Fetch all of the users courses.
826 $this->mycourses = get_my_courses($USER->id);
827 // Check if any courses were returned.
828 if (count($this->mycourses) > 0) {
829 // Add all of the users courses to the navigation
830 foreach ($this->mycourses as &$course) {
831 $course->coursenode = $this->add_course($course);
834 // The user had no specific courses! they could be no logged in, guest
835 // or admin so load all courses instead.
836 $this->load_all_courses();
839 // Next load context specific content into the navigation
840 switch ($this->page->context->contextlevel) {
841 case CONTEXT_SYSTEM :
842 case CONTEXT_COURSECAT :
843 // Load the front page course navigation
844 $this->load_course($SITE);
847 case CONTEXT_COURSE :
848 // Load the course associated with the page into the navigation
849 $course = $this->page->course;
850 $coursenode = $this->load_course($course);
852 $coursenode->make_active();
853 // Add the essentials such as reports etc...
854 $this->add_course_essentials($coursenode, $course);
855 if ($this->format_display_course_content($course->format)) {
856 // Load the course sections
857 $sections = $this->load_course_sections($course, $coursenode);
860 case CONTEXT_MODULE :
861 $course = $this->page->course;
862 $cm = $this->page->cm;
863 // Load the course associated with the page into the navigation
864 $coursenode = $this->load_course($course);
865 $this->add_course_essentials($coursenode, $course);
866 // Load the course sections into the page
867 $sections = $this->load_course_sections($course, $coursenode);
868 if ($course->id !== SITEID) {
869 // Find the section for the $CM associated with the page and collect
870 // its section number.
871 foreach ($sections as $section) {
872 if ($section->id == $cm->section) {
873 $cm->sectionnumber = $section->section;
878 // Load all of the section activities for the section the cm belongs to.
879 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
880 // Finally load the cm specific navigaton information
882 $activities = array();
883 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
885 $this->load_activity($cm, $course, $activities[$cm->id]);
886 // And make the activity node active.
887 $activities[$cm->id]->make_active();
890 $course = $this->page->course;
891 if ($course->id != SITEID) {
892 // Load the course associated with the user into the navigation
893 $coursenode = $this->load_course($course);
894 $this->add_course_essentials($coursenode, $course);
895 $sections = $this->load_course_sections($course, $coursenode);
900 // Load for the current user
901 $this->load_for_user();
902 // Load each extending user into the navigation.
903 foreach ($this->extendforuser as $user) {
904 if ($user->id !== $USER->id) {
905 $this->load_for_user($user);
909 // Remove any empty root nodes
910 foreach ($this->rootnodes as $node) {
911 if (!$node->has_children()) {
916 // If the user is not logged in modify the navigation structure as detailed
917 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
919 $activities = clone($this->rootnodes['site']->children);
920 $this->rootnodes['site']->remove();
921 $children = clone($this->children);
922 $this->children = new navigation_node_collection();
923 foreach ($activities as $child) {
924 $this->children->add($child);
926 foreach ($children as $child) {
927 $this->children->add($child);
929 $this->action = new moodle_url('/');
932 $this->initialised = true;
936 * Checks the course format to see whether it wants the navigation to load
937 * additional information for the course.
939 * This function utilises a callback that can exist within the course format lib.php file
940 * The callback should be a function called:
941 * callback_{formatname}_display_content()
942 * It doesn't get any arguments and should return true if additional content is
943 * desired. If the callback doesn't exist we assume additional content is wanted.
945 * @param string $format The course format
948 protected function format_display_course_content($format) {
950 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
951 if (file_exists($formatlib)) {
952 require_once($formatlib);
953 $displayfunc = 'callback_'.$format.'_display_content';
954 if (function_exists($displayfunc) && !$displayfunc()) {
955 return $displayfunc();
962 * Loads of the the courses in Moodle into the navigation.
964 * @return array An array of navigation_node
966 protected function load_all_courses() {
968 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
969 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
972 LEFT JOIN {course_categories} cat ON cat.id=c.category
973 WHERE c.id != :siteid
974 ORDER BY c.sortorder ASC";
975 $courses = $DB->get_records_sql($sql, array('siteid'=>SITEID));
976 $coursenodes = array();
977 foreach ($courses as $course) {
978 context_instance_preload($course);
979 $coursenodes[$course->id] = $this->add_course($course);
985 * Loads the given course into the navigation
987 * @param stdClass $course
988 * @return navigation_node
990 protected function load_course(stdClass $course) {
991 if ($course->id == SITEID) {
992 $coursenode = $this->rootnodes['site'];
993 } else if (array_key_exists($course->id, $this->mycourses)) {
994 if (!isset($this->mycourses[$course->id]->coursenode)) {
995 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
997 $coursenode = $this->mycourses[$course->id]->coursenode;
999 $coursenode = $this->add_course($course);
1005 * Loads all of the courses section into the navigation.
1007 * This function utilisies a callback that can be implemented within the course
1008 * formats lib.php file to customise the navigation that is generated at this
1009 * point for the course.
1011 * By default (if not defined) the method {@see load_generic_course_sections} is
1014 * @param stdClass $course Database record for the course
1015 * @param navigation_node $coursenode The course node within the navigation
1016 * @return array Array of navigation nodes for the section with key = section id
1018 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1020 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1021 $structurefunc = 'callback_'.$course->format.'_load_content';
1022 if (function_exists($structurefunc)) {
1023 return $structurefunc($this, $course, $coursenode);
1024 } else if (file_exists($structurefile)) {
1025 require_once $structurefile;
1026 if (function_exists($structurefunc)) {
1027 return $structurefunc($this, $course, $coursenode);
1029 return $this->load_generic_course_sections($course, $coursenode, get_string('topic'), 'topic');
1032 return $this->load_generic_course_sections($course, $coursenode, get_string('topic'), 'topic');
1037 * Generically loads the course sections into the course's navigation.
1039 * @param stdClass $course
1040 * @param navigation_node $coursenode
1041 * @param string $name The string that identifies each section. e.g Topic, or Week
1042 * @param string $activeparam The url used to identify the active section
1043 * @return array An array of course section nodes
1045 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $name, $activeparam) {
1046 $modinfo = get_fast_modinfo($course);
1047 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1048 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1050 $strgeneral = get_string('general');
1051 foreach ($sections as &$section) {
1052 if ($course->id == SITEID) {
1053 $this->load_section_activities($coursenode, $section->section, $modinfo);
1055 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1058 if ($section->section == 0) {
1059 $sectionname = $strgeneral;
1061 $sectionname = $name.' '.$section->section;
1063 $url = new moodle_url('/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1064 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1065 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1066 $sectionnode->hidden = (!$section->visible);
1067 if ($sectionnode->isactive) {
1068 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1070 $section->sectionnode = $sectionnode;
1076 * Loads all of the activities for a section into the navigation structure.
1078 * @param navigation_node $sectionnode
1079 * @param int $sectionnumber
1080 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1081 * @return array Array of activity nodes
1083 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1084 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1088 $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page->context);
1090 $activities = array();
1092 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1093 $cm = $modinfo->cms[$cmid];
1094 if (!$viewhiddenactivities && !$cm->visible) {
1098 $icon = new pix_icon($cm->icon, '', $cm->iconcomponent);
1100 $icon = new pix_icon('icon', '', $cm->modname);
1102 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1103 $activitynode = $sectionnode->add($cm->name, $url, navigation_node::TYPE_ACTIVITY, $cm->name, $cm->id, $icon);
1104 $activitynode->title(get_string('modulename', $cm->modname));
1105 $activitynode->hidden = (!$cm->visible);
1106 if ($this->module_extends_navigation($cm->modname)) {
1107 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1109 $activities[$cmid] = $activitynode;
1115 * Loads the navigation structure for the given activity into the activities node.
1117 * This method utilises a callback within the modules lib.php file to load the
1118 * content specific to activity given.
1120 * The callback is a method: {modulename}_extend_navigation()
1122 * * {@see forum_extend_navigation()}
1123 * * {@see workshop_extend_navigation()}
1125 * @param stdClass $cm
1126 * @param stdClass $course
1127 * @param navigation_node $activity
1130 protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1133 $activity->make_active();
1134 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1135 $function = $cm->modname.'_extend_navigation';
1137 if (file_exists($file)) {
1138 require_once($file);
1139 if (function_exists($function)) {
1140 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1141 $function($activity, $course, $activtyrecord, $cm);
1145 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1149 * Loads user specific information into the navigation in the appopriate place.
1151 * If no user is provided the current user is assumed.
1153 * @param stdClass $user
1156 protected function load_for_user($user=null) {
1157 global $DB, $CFG, $USER;
1159 $iscurrentuser = false;
1160 if ($user === null) {
1161 // We can't require login here but if the user isn't logged in we don't
1162 // want to show anything
1163 if (!isloggedin()) {
1167 $iscurrentuser = true;
1168 } else if (!is_object($user)) {
1169 // If the user is not an object then get them from the database
1170 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1172 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1174 // Get the course set against the page, by default this will be the site
1175 $course = $this->page->course;
1176 $baseargs = array('id'=>$user->id);
1177 if ($course->id !== SITEID) {
1178 if (array_key_exists($course->id, $this->mycourses)) {
1179 $coursenode = $this->mycourses[$course->id]->coursenode;
1181 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1183 $coursenode = $this->load_course($course);
1186 $baseargs['course'] = $course->id;
1187 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1188 $issitecourse = false;
1190 // Load all categories and get the context for the system
1191 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1192 $issitecourse = true;
1195 // Create a node to add user information under.
1196 if ($iscurrentuser) {
1197 // If it's the current user the information will go under the profile root node
1198 $usernode = $this->rootnodes['myprofile'];
1200 if (!$issitecourse) {
1201 // Not the current user so add it to the participants node for the current course
1202 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1204 // This is the site so add a users node to the root branch
1205 $usersnode = $this->rootnodes['users'];
1206 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1208 // Add a branch for the current user
1209 $usernode = $usersnode->add(fullname($user, true));
1212 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1213 $usernode->force_open();
1216 // If the user is the current user or has permission to view the details of the requested
1217 // user than add a view profile link.
1218 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1219 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1222 // Add nodes for forum posts and discussions if the user can view either or both
1223 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1224 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
1225 if ($canviewposts || $canviewdiscussions) {
1226 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1227 if ($canviewposts) {
1228 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1230 if ($canviewdiscussions) {
1231 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1235 // Add a node to view the users notes if permitted
1236 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1237 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1238 if ($coursecontext->instanceid) {
1239 $url->param('course', $coursecontext->instanceid);
1241 $usernode->add(get_string('notes', 'notes'), $url);
1244 // Add a reports tab and then add reports the the user has permission to see.
1245 $reporttab = $usernode->add(get_string('activityreports'));
1246 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1247 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser));
1248 $reportargs = array('user'=>$user->id);
1249 if (!empty($course->id)) {
1250 $reportargs['id'] = $course->id;
1252 $reportargs['id'] = SITEID;
1254 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1255 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1256 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1259 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1260 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1263 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1264 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1267 if (!empty($CFG->enablestats)) {
1268 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1269 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1273 $gradeaccess = false;
1274 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1275 //ok - can view all course grades
1276 $gradeaccess = true;
1277 } else if ($course->showgrades) {
1278 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1279 //ok - can view own grades
1280 $gradeaccess = true;
1281 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1282 // ok - can view grades of this user - parent most probably
1283 $gradeaccess = true;
1284 } else if ($anyreport) {
1285 // ok - can view grades of this user - parent most probably
1286 $gradeaccess = true;
1290 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1293 // Check the number of nodes in the report node... if there are none remove
1295 if (count($reporttab->children)===0) {
1296 $usernode->remove_child($reporttab);
1299 // If the user is the current user add the repositories for the current user
1300 if ($iscurrentuser) {
1301 require_once($CFG->dirroot . '/repository/lib.php');
1302 $editabletypes = repository::get_editable_types($usercontext);
1303 if (!empty($editabletypes)) {
1304 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1311 * This method simply checks to see if a given module can extend the navigation.
1313 * @param string $modname
1316 protected function module_extends_navigation($modname) {
1318 if ($this->cache->cached($modname.'_extends_navigation')) {
1319 return $this->cache->{$modname.'_extends_navigation'};
1321 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1322 $function = $modname.'_extend_navigation';
1323 if (function_exists($function)) {
1324 $this->cache->{$modname.'_extends_navigation'} = true;
1326 } else if (file_exists($file)) {
1327 require_once($file);
1328 if (function_exists($function)) {
1329 $this->cache->{$modname.'_extends_navigation'} = true;
1333 $this->cache->{$modname.'_extends_navigation'} = false;
1337 * Extends the navigation for the given user.
1339 * @param stdClass $user A user from the database
1341 public function extend_for_user($user) {
1342 $this->extendforuser[] = $user;
1345 * Adds the given course to the navigation structure.
1347 * @param stdClass $course
1348 * @return navigation_node
1350 public function add_course(stdClass $course) {
1351 if (array_key_exists($course->id, $this->addedcourses)) {
1352 return $this->addedcourses[$course->id];
1355 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1356 if ($course->id !== SITEID && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1360 if ($course->id == SITEID) {
1362 $url = new moodle_url('/');
1363 } else if (array_key_exists($course->id, $this->mycourses)) {
1364 $parent = $this->rootnodes['mycourses'];
1365 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1367 $parent = $this->rootnodes['courses'];
1368 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1370 $coursenode = $parent->add($course->fullname, $url, self::TYPE_COURSE, $course->shortname, $course->id);
1371 $coursenode->nodetype = self::NODETYPE_BRANCH;
1372 $coursenode->hidden = (!$course->visible);
1373 $this->addedcourses[$course->id] = &$coursenode;
1377 * Adds essential course nodes to the navigation for the given course.
1379 * This method adds nodes such as reports, blogs and participants
1381 * @param navigation_node $coursenode
1382 * @param stdClass $course
1385 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1388 if ($course->id === SITEID) {
1389 return $this->add_front_page_course_essentials($coursenode, $course);
1392 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1397 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1398 require_once($CFG->dirroot.'/blog/lib.php');
1399 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1400 $currentgroup = groups_get_course_group($course, true);
1401 if ($course->id == SITEID) {
1403 } else if ($course->id && !$currentgroup) {
1404 $filterselect = $course->id;
1406 $filterselect = $currentgroup;
1408 $filterselect = clean_param($filterselect, PARAM_INT);
1409 if ($CFG->bloglevel >= 3) {
1410 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1411 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1413 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1414 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1416 } else if (count($this->extendforuser) > 0) {
1417 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1420 // View course reports
1421 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1422 $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', ''));
1423 $coursereports = get_plugin_list('coursereport');
1424 foreach ($coursereports as $report=>$dir) {
1425 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1426 if (file_exists($libfile)) {
1427 require_once($libfile);
1428 $reportfunction = $report.'_report_extend_navigation';
1429 if (function_exists($report.'_report_extend_navigation')) {
1430 $reportfunction($reportnav, $course, $this->page->context);
1438 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1441 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1446 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1447 require_once($CFG->dirroot.'/blog/lib.php');
1448 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1451 $currentgroup = groups_get_course_group($course, true);
1452 if ($course->id == SITEID) {
1454 } else if ($course->id && !$currentgroup) {
1455 $filterselect = $course->id;
1457 $filterselect = $currentgroup;
1459 $filterselect = clean_param($filterselect, PARAM_INT);
1460 if ($CFG->bloglevel >= 3) {
1461 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1462 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1464 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1465 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1467 if (!empty($CFG->usetags)) {
1468 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
1472 // View course reports
1473 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1474 $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', ''));
1475 $coursereports = get_plugin_list('coursereport');
1476 foreach ($coursereports as $report=>$dir) {
1477 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1478 if (file_exists($libfile)) {
1479 require_once($libfile);
1480 $reportfunction = $report.'_report_extend_navigation';
1481 if (function_exists($report.'_report_extend_navigation')) {
1482 $reportfunction($reportnav, $course, $this->page->context);
1491 * Clears the navigation cache
1493 public function clear_cache() {
1494 $this->cache->clear();
1497 public function set_expansion_limit($type) {
1498 $nodes = $this->find_all_of_type($type);
1499 foreach ($nodes as &$node) {
1500 foreach ($node->children as &$child) {
1501 $child->display = false;
1509 * The limited global navigation class used for the AJAX extension of the global
1512 * The primary methods that are used in the global navigation class have been overriden
1513 * to ensure that only the relevant branch is generated at the root of the tree.
1514 * This can be done because AJAX is only used when the backwards structure for the
1515 * requested branch exists.
1516 * This has been done only because it shortens the amounts of information that is generated
1517 * which of course will speed up the response time.. because no one likes laggy AJAX.
1519 * @package moodlecore
1520 * @subpackage navigation
1521 * @copyright 2009 Sam Hemelryk
1522 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1524 class global_navigation_for_ajax extends global_navigation {
1527 protected $expandable = array();
1530 * Constructs the navigation for use in AJAX request
1532 public function __construct() {
1534 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1535 $this->children = new navigation_node_collection();
1536 $this->rootnodes = array();
1537 //$this->rootnodes['site'] = $this->add_course($SITE);
1538 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1541 * Initialise the navigation given the type and id for the branch to expand.
1543 * @param int $branchtype One of navigation_node::TYPE_*
1545 * @return array The expandable nodes
1547 public function initialise($branchtype, $id) {
1550 if ($this->initialised || during_initial_install()) {
1551 return $this->expandable;
1554 // Branchtype will be one of navigation_node::TYPE_*
1555 switch ($branchtype) {
1556 case self::TYPE_COURSE :
1557 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
1558 require_course_login($course);
1559 $this->page = $PAGE;
1560 $coursenode = $this->add_course($course);
1561 $this->add_course_essentials($coursenode, $course);
1562 if ($this->format_display_course_content($course->format)) {
1563 $this->load_course_sections($course, $coursenode);
1566 case self::TYPE_SECTION :
1567 $sql = 'SELECT c.*, cs.section AS sectionnumber
1569 LEFT JOIN {course_sections} cs ON cs.course = c.id
1571 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
1572 require_course_login($course);
1573 $this->page = $PAGE;
1574 $coursenode = $this->add_course($course);
1575 $this->add_course_essentials($coursenode, $course);
1576 $sections = $this->load_course_sections($course, $coursenode);
1577 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
1579 case self::TYPE_ACTIVITY :
1580 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
1581 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1582 require_course_login($course, true, $cm);
1583 $this->page = $PAGE;
1584 $coursenode = $this->load_course($course);
1585 $sections = $this->load_course_sections($course, $coursenode);
1586 foreach ($sections as $section) {
1587 if ($section->id == $cm->section) {
1588 $cm->sectionnumber = $section->section;
1592 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1593 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
1596 throw new Exception('Unknown type');
1597 return $this->expandable;
1600 $this->find_expandable($this->expandable);
1601 return $this->expandable;
1608 * This class is used to manage the navbar, which is initialised from the navigation
1609 * object held by PAGE
1611 * @package moodlecore
1612 * @subpackage navigation
1613 * @copyright 2009 Sam Hemelryk
1614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1616 class navbar extends navigation_node {
1618 protected $initialised = false;
1620 protected $keys = array();
1621 /** @var null|string */
1622 protected $content = null;
1623 /** @var moodle_page object */
1626 protected $ignoreactive = false;
1628 protected $duringinstall = false;
1630 protected $hasitems = false;
1634 public $children = array();
1636 * The almighty constructor
1638 * @param moodle_page $page
1640 public function __construct(moodle_page $page) {
1642 if (during_initial_install()) {
1643 $this->duringinstall = true;
1646 $this->page = $page;
1647 $this->text = get_string('home');
1648 $this->shorttext = get_string('home');
1649 $this->action = new moodle_url($CFG->wwwroot);
1650 $this->nodetype = self::NODETYPE_BRANCH;
1651 $this->type = self::TYPE_SYSTEM;
1655 * Quick check to see if the navbar will have items in.
1657 * @return bool Returns true if the navbar will have items, false otherwise
1659 public function has_items() {
1660 if ($this->duringinstall) {
1662 } else if ($this->hasitems !== false) {
1665 $this->page->navigation->initialise($this->page);
1667 $activenodefound = ($this->page->navigation->contains_active_node() ||
1668 $this->page->settingsnav->contains_active_node());
1670 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
1671 $this->hasitems = $outcome;
1676 * Turn on/off ignore active
1678 * @param bool $setting
1680 public function ignore_active($setting=true) {
1681 $this->ignoreactive = ($setting);
1683 public function get($key, $type = null) {
1684 foreach ($this->children as &$child) {
1685 if ($child->key === $key && ($type == null || $type == $child->type)) {
1692 * Returns an array of navigation_node's that make up the navbar.
1696 public function get_items() {
1698 // Make sure that navigation is initialised
1699 if (!$this->has_items()) {
1702 if ($this->items !== null) {
1703 return $this->items;
1706 if (count($this->children) > 0) {
1707 // Add the custom children
1708 $items = array_reverse($this->children);
1711 $navigationactivenode = $this->page->navigation->find_active_node();
1712 $settingsactivenode = $this->page->settingsnav->find_active_node();
1714 // Check if navigation contains the active node
1715 if (!$this->ignoreactive) {
1717 if ($navigationactivenode && $settingsactivenode) {
1718 // Parse a combined navigation tree
1719 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1720 if (!$settingsactivenode->mainnavonly) {
1721 $items[] = $settingsactivenode;
1723 $settingsactivenode = $settingsactivenode->parent;
1725 // Removes the first node from the settings (root node) from the list
1727 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1728 if (!$navigationactivenode->mainnavonly) {
1729 $items[] = $navigationactivenode;
1731 $navigationactivenode = $navigationactivenode->parent;
1733 } else if ($navigationactivenode) {
1734 // Parse the navigation tree to get the active node
1735 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1736 if (!$navigationactivenode->mainnavonly) {
1737 $items[] = $navigationactivenode;
1739 $navigationactivenode = $navigationactivenode->parent;
1741 } else if ($settingsactivenode) {
1742 // Parse the settings navigation to get the active node
1743 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1744 if (!$settingsactivenode->mainnavonly) {
1745 $items[] = $settingsactivenode;
1747 $settingsactivenode = $settingsactivenode->parent;
1752 $items[] = new navigation_node(array(
1753 'text'=>$this->page->navigation->text,
1754 'shorttext'=>$this->page->navigation->shorttext,
1755 'key'=>$this->page->navigation->key,
1756 'action'=>$this->page->navigation->action
1759 $this->items = array_reverse($items);
1760 return $this->items;
1764 * Add a new navigation_node to the navbar, overrides parent::add
1766 * This function overrides {@link navigation_node::add()} so that we can change
1767 * the way nodes get added to allow us to simply call add and have the node added to the
1770 * @param string $text
1771 * @param string|moodle_url $action
1773 * @param string|int $key
1774 * @param string $shorttext
1775 * @param string $icon
1776 * @return navigation_node
1778 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
1779 if ($this->content !== null) {
1780 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
1783 // Properties array used when creating the new navigation node
1788 // Set the action if one was provided
1789 if ($action!==null) {
1790 $itemarray['action'] = $action;
1792 // Set the shorttext if one was provided
1793 if ($shorttext!==null) {
1794 $itemarray['shorttext'] = $shorttext;
1796 // Set the icon if one was provided
1798 $itemarray['icon'] = $icon;
1800 // Default the key to the number of children if not provided
1801 if ($key === null) {
1802 $key = count($this->children);
1805 $itemarray['key'] = $key;
1806 // Set the parent to this node
1807 $itemarray['parent'] = $this;
1808 // Add the child using the navigation_node_collections add method
1809 $this->children[] = new navigation_node($itemarray);
1815 * Class used to manage the settings option for the current page
1817 * This class is used to manage the settings options in a tree format (recursively)
1818 * and was created initially for use with the settings blocks.
1820 * @package moodlecore
1821 * @subpackage navigation
1822 * @copyright 2009 Sam Hemelryk
1823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1825 class settings_navigation extends navigation_node {
1826 /** @var stdClass */
1828 /** @var navigation_cache */
1830 /** @var moodle_page */
1833 protected $adminsection;
1835 * Sets up the object with basic settings and preparse it for use
1837 * @param moodle_page $page
1839 public function __construct(moodle_page &$page) {
1840 if (during_initial_install()) {
1843 $this->page = $page;
1844 // Initialise the main navigation. It is most important that this is done
1845 // before we try anything
1846 $this->page->navigation->initialise();
1847 // Initialise the navigation cache
1848 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1849 $this->children = new navigation_node_collection();
1852 * Initialise the settings navigation based on the current context
1854 * This function initialises the settings navigation tree for a given context
1855 * by calling supporting functions to generate major parts of the tree.
1858 public function initialise() {
1861 if (during_initial_install()) {
1864 $this->id = 'settingsnav';
1865 $this->context = $this->page->context;
1867 $context = $this->context;
1868 if ($context->contextlevel == CONTEXT_BLOCK) {
1869 $this->load_block_settings();
1870 $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));
1873 switch ($context->contextlevel) {
1874 case CONTEXT_SYSTEM:
1875 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
1876 $this->load_front_page_settings(($context->id == $this->context->id));
1879 case CONTEXT_COURSECAT:
1880 $this->load_category_settings();
1882 case CONTEXT_COURSE:
1883 if ($this->page->course->id != SITEID) {
1884 $this->load_course_settings(($context->id == $this->context->id));
1886 $this->load_front_page_settings(($context->id == $this->context->id));
1889 case CONTEXT_MODULE:
1890 $this->load_module_settings();
1891 $this->load_course_settings();
1894 if ($this->page->course->id != SITEID) {
1895 $this->load_course_settings();
1900 $settings = $this->load_user_settings($this->page->course->id);
1901 $admin = $this->load_administration_settings();
1903 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
1904 $admin->force_open();
1905 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
1906 $settings->force_open();
1909 // Check if the user is currently logged in as another user
1910 if (session_is_loggedinas()) {
1911 // Get the actual user, we need this so we can display an informative return link
1912 $realuser = session_get_realuser();
1913 // Add the informative return to original user link
1914 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
1915 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
1918 // Make sure the first child doesnt have proceed with hr set to true
1920 foreach ($this->children as $key=>$node) {
1921 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
1927 * Override the parent function so that we can add preceeding hr's and set a
1928 * root node class against all first level element
1930 * It does this by first calling the parent's add method {@link navigation_node::add()}
1931 * and then proceeds to use the key to set class and hr
1933 * @param string $text
1934 * @param sting|moodle_url $url
1935 * @param string $shorttext
1936 * @param string|int $key
1938 * @param string $icon
1939 * @return navigation_node
1941 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
1942 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
1943 $node->add_class('root_node');
1948 * This function allows the user to add something to the start of the settings
1949 * navigation, which means it will be at the top of the settings navigation block
1951 * @param string $text
1952 * @param sting|moodle_url $url
1953 * @param string $shorttext
1954 * @param string|int $key
1956 * @param string $icon
1957 * @return navigation_node
1959 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
1960 $children = $this->children;
1961 $this->children = new get_class($children);
1962 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
1963 foreach ($children as $child) {
1964 $this->children->add($child);
1969 * Load the site administration tree
1971 * This function loads the site administration tree by using the lib/adminlib library functions
1973 * @param navigation_node $referencebranch A reference to a branch in the settings
1975 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
1976 * tree and start at the beginning
1977 * @return mixed A key to access the admin tree by
1979 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
1982 // Check if we are just starting to generate this navigation.
1983 if ($referencebranch === null) {
1985 // Require the admin lib then get an admin structure
1986 if (!function_exists('admin_get_root')) {
1987 require_once($CFG->dirroot.'/lib/adminlib.php');
1989 $adminroot = admin_get_root(false, false);
1990 // This is the active section identifier
1991 $this->adminsection = $this->page->url->param('section');
1993 // Disable the navigation from automatically finding the active node
1994 navigation_node::$autofindactive = false;
1995 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
1996 foreach ($adminroot->children as $adminbranch) {
1997 $this->load_administration_settings($referencebranch, $adminbranch);
1999 navigation_node::$autofindactive = true;
2001 // Use the admin structure to locate the active page
2002 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2003 $currentnode = $this;
2004 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2005 $currentnode = $currentnode->get($pathkey);
2008 $currentnode->make_active();
2011 return $referencebranch;
2012 } else if ($adminbranch->check_access()) {
2013 // We have a reference branch that we can access and is not hidden `hurrah`
2014 // Now we need to display it and any children it may have
2017 if ($adminbranch instanceof admin_settingpage) {
2018 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2019 } else if ($adminbranch instanceof admin_externalpage) {
2020 $url = $adminbranch->url;
2024 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2026 if ($adminbranch->is_hidden()) {
2027 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2028 $reference->add_class('hidden');
2030 $reference->display = false;
2034 // Check if we are generating the admin notifications and whether notificiations exist
2035 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2036 $reference->add_class('criticalnotification');
2038 // Check if this branch has children
2039 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2040 foreach ($adminbranch->children as $branch) {
2041 // Generate the child branches as well now using this branch as the reference
2042 $this->load_administration_settings($reference, $branch);
2045 $reference->icon = new pix_icon('i/settings', '');
2051 * Gets a navigation node given an array of keys that represent the path to
2054 * @param array $path
2055 * @return navigation_node|false
2057 protected function get_by_path(array $path) {
2058 $node = $this->get(array_shift($path));
2059 foreach ($path as $key) {
2066 * Generate the list of modules for the given course.
2068 * The array of resources and activities that can be added to a course is then
2069 * stored in the cache so that we can access it for anywhere.
2070 * It saves us generating it all the time
2073 * // To get resources:
2074 * $this->cache->{'course'.$courseid.'resources'}
2075 * // To get activities:
2076 * $this->cache->{'course'.$courseid.'activities'}
2079 * @param stdClass $course The course to get modules for
2081 protected function get_course_modules($course) {
2083 $mods = $modnames = $modnamesplural = $modnamesused = array();
2084 // This function is included when we include course/lib.php at the top
2086 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2087 $resources = array();
2088 $activities = array();
2089 foreach($modnames as $modname=>$modnamestr) {
2090 if (!course_allowed_module($course, $modname)) {
2094 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2095 if (!file_exists($libfile)) {
2098 include_once($libfile);
2099 $gettypesfunc = $modname.'_get_types';
2100 if (function_exists($gettypesfunc)) {
2101 $types = $gettypesfunc();
2102 foreach($types as $type) {
2103 if (!isset($type->modclass) || !isset($type->typestr)) {
2104 debugging('Incorrect activity type in '.$modname);
2107 if ($type->modclass == MOD_CLASS_RESOURCE) {
2108 $resources[html_entity_decode($type->type)] = $type->typestr;
2110 $activities[html_entity_decode($type->type)] = $type->typestr;
2114 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2115 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2116 $resources[$modname] = $modnamestr;
2118 // all other archetypes are considered activity
2119 $activities[$modname] = $modnamestr;
2123 $this->cache->{'course'.$course->id.'resources'} = $resources;
2124 $this->cache->{'course'.$course->id.'activities'} = $activities;
2128 * This function loads the course settings that are available for the user
2130 * @param bool $forceopen If set to true the course node will be forced open
2131 * @return navigation_node|false
2133 protected function load_course_settings($forceopen = false) {
2134 global $CFG, $USER, $SESSION, $OUTPUT;
2136 $course = $this->page->course;
2137 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2138 if (!$this->cache->cached('canviewcourse'.$course->id)) {
2139 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
2141 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2145 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2147 $coursenode->force_open();
2150 if (has_capability('moodle/course:update', $coursecontext)) {
2151 // Add the turn on/off settings
2152 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2153 if ($this->page->user_is_editing()) {
2154 $url->param('edit', 'off');
2155 $editstring = get_string('turneditingoff');
2157 $url->param('edit', 'on');
2158 $editstring = get_string('turneditingon');
2160 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2162 if ($this->page->user_is_editing()) {
2163 // Add `add` resources|activities branches
2164 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2165 if (file_exists($structurefile)) {
2166 require_once($structurefile);
2167 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2168 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2170 $formatstring = get_string('topic');
2171 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2173 if (!$this->cache->cached('coursesections'.$course->id)) {
2174 $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
2176 $sections = $this->cache->{'coursesections'.$course->id};
2178 $addresource = $this->add(get_string('addresource'));
2179 $addactivity = $this->add(get_string('addactivity'));
2180 if ($formatidentifier!==0) {
2181 $addresource->force_open();
2182 $addactivity->force_open();
2185 if (!$this->cache->cached('course'.$course->id.'resources')) {
2186 $this->get_course_modules($course);
2188 $resources = $this->cache->{'course'.$course->id.'resources'};
2189 $activities = $this->cache->{'course'.$course->id.'activities'};
2191 $textlib = textlib_get_instance();
2193 foreach ($sections as $section) {
2194 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2197 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
2198 if ($section->section == 0) {
2199 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2200 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2202 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2203 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2205 foreach ($resources as $value=>$resource) {
2206 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2207 $pos = strpos($value, '&type=');
2209 $url->param('add', $textlib->substr($value, 0,$pos));
2210 $url->param('type', $textlib->substr($value, $pos+6));
2212 $url->param('add', $value);
2214 $sectionresources->add($resource, $url, self::TYPE_SETTING);
2217 foreach ($activities as $activityname=>$activity) {
2218 if ($activity==='--') {
2222 if (strpos($activity, '--')===0) {
2223 $subbranch = $sectionresources->add(trim($activity, '-'));
2226 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2227 $pos = strpos($activityname, '&type=');
2229 $url->param('add', $textlib->substr($activityname, 0,$pos));
2230 $url->param('type', $textlib->substr($activityname, $pos+6));
2232 $url->param('add', $activityname);
2234 if ($subbranch !== false) {
2235 $subbranch->add($activity, $url, self::TYPE_SETTING);
2237 $sectionresources->add($activity, $url, self::TYPE_SETTING);
2243 // Add the course settings link
2244 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2245 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2248 if (has_capability('moodle/role:assign', $coursecontext)) {
2249 // Add assign or override roles if allowed
2250 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
2251 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2253 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2254 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
2255 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2257 // Check role permissions
2258 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2259 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
2260 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2263 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2264 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2265 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2269 // Add view grade report is permitted
2270 $reportavailable = false;
2271 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2272 $reportavailable = true;
2273 } else if (!empty($course->showgrades)) {
2274 $reports = get_plugin_list('gradereport');
2275 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2276 arsort($reports); // user is last, we want to test it first
2277 foreach ($reports as $plugin => $plugindir) {
2278 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2279 //stop when the first visible plugin is found
2280 $reportavailable = true;
2286 if ($reportavailable) {
2287 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2288 $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2291 // Add outcome if permitted
2292 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2293 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2294 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/outcomes', ''));
2297 // Add meta course links
2298 if ($course->metacourse) {
2299 if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
2300 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
2301 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2302 } else if (has_capability('moodle/role:assign', $coursecontext)) {
2303 $roleassign = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2304 $roleassign->hidden = true;
2308 // Manage groups in this course
2309 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
2310 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
2311 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/group', ''));
2314 // Backup this course
2315 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2316 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2317 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2320 // Restore to this course
2321 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2322 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2323 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2326 // Import data from other courses
2327 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2328 $url = new moodle_url('/course/import.php', array('id'=>$course->id));
2329 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2332 // Reset this course
2333 if (has_capability('moodle/course:reset', $coursecontext)) {
2334 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2335 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2339 $questioncaps = array('moodle/question:add',
2340 'moodle/question:editmine',
2341 'moodle/question:editall',
2342 'moodle/question:viewmine',
2343 'moodle/question:viewall',
2344 'moodle/question:movemine',
2345 'moodle/question:moveall');
2346 if (has_any_capability($questioncaps, $this->context)) {
2347 $questionlink = $CFG->wwwroot.'/question/edit.php';
2348 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2349 $questionlink = $CFG->wwwroot.'/question/category.php';
2351 if (isset($questionlink)) {
2352 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
2353 $coursenode->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
2356 // Repository Instances
2357 require_once($CFG->dirroot.'/repository/lib.php');
2358 $editabletypes = repository::get_editable_types($this->context);
2359 if (has_capability('moodle/course:update', $this->context) && !empty($editabletypes)) {
2360 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$this->context->id));
2361 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
2365 if (has_capability('moodle/course:managefiles', $this->context)) {
2366 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
2367 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
2371 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2372 require_once($CFG->dirroot.'/enrol/authorize/const.php');
2373 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
2374 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2375 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2376 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2378 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
2379 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2385 if (empty($course->metacourse) && ($course->id!==SITEID)) {
2386 if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2387 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
2388 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2389 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2392 } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2393 // inspector, manager, etc. - do not show anything
2395 // access because otherwise they would not get into this course at all
2396 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2397 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2403 $assumedrole = $this->in_alternative_role();
2404 if ($assumedrole!==false) {
2405 $roles[0] = get_string('switchrolereturn');
2407 if (has_capability('moodle/role:switchroles', $this->context)) {
2408 $availableroles = get_switchable_roles($this->context);
2409 if (is_array($availableroles)) {
2410 foreach ($availableroles as $key=>$role) {
2411 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2414 $roles[$key] = $role;
2418 if (is_array($roles) && count($roles)>0) {
2419 $switchroles = $this->add(get_string('switchroleto'));
2420 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2421 $switchroles->force_open();
2423 $returnurl = $this->page->url;
2424 $returnurl->param('sesskey', sesskey());
2425 $SESSION->returnurl = serialize($returnurl);
2426 foreach ($roles as $key=>$name) {
2427 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2428 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
2431 // Return we are done
2436 * This function calls the module function to inject module settings into the
2437 * settings navigation tree.
2439 * This only gets called if there is a corrosponding function in the modules
2442 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2444 * @return navigation_node|false
2446 protected function load_module_settings() {
2449 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
2450 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
2451 $this->page->set_cm($cm, $this->page->course);
2454 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2455 $modulenode->force_open();
2457 // Settings for the module
2458 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2459 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2460 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2462 // Assign local roles
2463 if (count(get_assignable_roles($this->page->cm->context))>0) {
2464 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2465 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2468 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2469 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2470 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2472 // Check role permissions
2473 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2474 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2475 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2478 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2479 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2480 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2483 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2484 $function = $this->page->activityname.'_extend_settings_navigation';
2486 if (file_exists($file)) {
2487 require_once($file);
2489 if (!function_exists($function)) {
2493 $function($this, $modulenode);
2495 // Remove the module node if there are no children
2496 if (empty($modulenode->children)) {
2497 $modulenode->remove();
2504 * Loads the user settings block of the settings nav
2506 * This function is simply works out the userid and whether we need to load
2507 * just the current users profile settings, or the current user and the user the
2508 * current user is viewing.
2510 * This function has some very ugly code to work out the user, if anyone has
2511 * any bright ideas please feel free to intervene.
2513 * @param int $courseid The course id of the current course
2514 * @return navigation_node|false
2516 protected function load_user_settings($courseid=SITEID) {
2517 global $USER, $FULLME, $CFG;
2519 if (isguestuser() || !isloggedin()) {
2523 // This is terribly ugly code, but I couldn't see a better way around it
2524 // we need to pick up the user id, it can be the current user or someone else
2525 // and the key depends on the current location
2526 // Default to look at id
2528 if (strpos($FULLME,'/blog/') || strpos($FULLME, $CFG->admin.'/roles/')) {
2529 // And blog and roles just do thier own thing using `userid`
2530 $userkey = 'userid';
2531 } else if ($this->context->contextlevel >= CONTEXT_COURSECAT && strpos($FULLME, '/message/')===false && strpos($FULLME, '/mod/forum/user')===false && strpos($FULLME, '/user/editadvanced')===false) {
2532 // If we have a course context and we are not in message or forum
2533 // Message and forum both pick the user up from `id`
2537 $userid = optional_param($userkey, $USER->id, PARAM_INT);
2538 if ($userid!=$USER->id) {
2539 $usernode = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
2540 $this->generate_user_settings($courseid, $USER->id);
2542 $usernode = $this->generate_user_settings($courseid, $USER->id);
2548 * This function gets called by {@link load_user_settings()} and actually works out
2549 * what can be shown/done
2551 * @param int $courseid The current course' id
2552 * @param int $userid The user id to load for
2553 * @param string $gstitle The string to pass to get_string for the branch title
2554 * @return navigation_node|false
2556 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
2557 global $DB, $CFG, $USER, $SITE;
2559 if ($courseid != SITEID) {
2560 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
2561 $course = $this->page->course;
2563 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
2569 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
2570 $systemcontext = get_system_context();
2571 $currentuser = ($USER->id == $userid);
2575 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2577 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
2580 // Check that the user can view the profile
2581 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2582 if ($course->id==SITEID) {
2583 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
2584 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
2588 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
2591 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
2592 // If groups are in use, make sure we can see that group
2598 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
2600 // Add a user setting branch
2601 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname));
2602 $usersetting->id = 'usersettings';
2604 // Check if the user has been deleted
2605 if ($user->deleted) {
2606 if (!has_capability('moodle/user:update', $coursecontext)) {
2607 // We can't edit the user so just show the user deleted message
2608 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
2610 // We can edit the user so show the user deleted message and link it to the profile
2611 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
2612 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
2617 // Add the profile edit link
2618 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
2619 if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
2620 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
2621 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
2622 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
2623 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
2624 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
2628 // Change password link
2629 if (!empty($user->auth)) {
2630 $userauth = get_auth_plugin($user->auth);
2631 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
2632 $passwordchangeurl = $userauth->change_password_url();
2633 if (!$passwordchangeurl) {
2634 if (empty($CFG->loginhttps)) {
2635 $wwwroot = $CFG->wwwroot;
2637 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2639 $passwordchangeurl = new moodle_url('/login/change_password.php');
2641 $urlbits = explode($passwordchangeurl. '?', 1);
2642 $passwordchangeurl = new moodle_url($urlbits[0]);
2643 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
2644 foreach ($matches as $pair) {
2645 $fullmeurl->param($pair[1],$pair[2]);
2649 $passwordchangeurl->param('id', $course->id);
2650 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
2654 // View the roles settings
2655 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
2656 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
2658 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
2659 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
2661 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
2663 if (!empty($assignableroles)) {
2664 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2665 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
2668 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
2669 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2670 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2673 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2674 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2678 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
2679 require_once($CFG->libdir . '/portfoliolib.php');
2680 if (portfolio_instances(true, false)) {
2681 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
2682 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
2683 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
2688 if ($currentuser && !is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $systemcontext)) {
2689 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
2690 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
2694 if (!$currentuser) {
2695 require_once($CFG->dirroot . '/repository/lib.php');
2696 $editabletypes = repository::get_editable_types($usercontext);
2697 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
2698 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
2699 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
2704 if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
2705 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
2706 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
2709 return $usersetting;
2713 * Loads block specific settings in the navigation
2715 * @return navigation_node
2717 protected function load_block_settings() {
2720 $blocknode = $this->add(print_context_name($this->context));
2721 $blocknode->force_open();
2723 // Assign local roles
2724 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2725 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2728 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2729 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2730 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2732 // Check role permissions
2733 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2734 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2735 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2742 * Loads category specific settings in the navigation
2744 * @return navigation_node
2746 protected function load_category_settings() {
2749 $categorynode = $this->add(print_context_name($this->context));
2750 $categorynode->force_open();
2752 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
2753 $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid)));
2754 $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid)));
2757 // Assign local roles
2758 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2759 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2762 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2763 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2764 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2766 // Check role permissions
2767 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2768 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2769 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2772 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
2773 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
2774 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2777 return $categorynode;
2781 * Determine whether the user is assuming another role
2783 * This function checks to see if the user is assuming another role by means of
2784 * role switching. In doing this we compare each RSW key (context path) against
2785 * the current context path. This ensures that we can provide the switching
2786 * options against both the course and any page shown under the course.
2788 * @return bool|int The role(int) if the user is in another role, false otherwise
2790 protected function in_alternative_role() {
2792 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
2793 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
2794 return $USER->access['rsw'][$this->page->context->path];
2796 foreach ($USER->access['rsw'] as $key=>$role) {
2797 if (strpos($this->context->path,$key)===0) {
2806 * This function loads all of the front page settings into the settings navigation.
2807 * This function is called when the user is on the front page, or $COURSE==$SITE
2808 * @return navigation_node
2810 protected function load_front_page_settings($forceopen = false) {
2813 $course = clone($SITE);
2814 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
2816 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
2818 $frontpage->force_open();
2820 $frontpage->id = 'frontpagesettings';
2822 if (has_capability('moodle/course:update', $coursecontext)) {
2824 // Add the turn on/off settings
2825 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2826 if ($this->page->user_is_editing()) {
2827 $url->param('edit', 'off');
2828 $editstring = get_string('turneditingoff');
2830 $url->param('edit', 'on');
2831 $editstring = get_string('turneditingon');
2833 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2835 // Add the course settings link
2836 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
2837 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2841 if (has_capability('moodle/site:viewparticipants', $coursecontext)) {
2842 $url = new moodle_url('/user/index.php', array('contextid'=>$coursecontext->id));
2843 $frontpage->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/users', ''));
2847 if (has_capability('moodle/role:assign', $coursecontext)) {
2848 // Add assign or override roles if allowed
2849 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
2850 $frontpage->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2852 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2853 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
2854 $frontpage->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2856 // Check role permissions
2857 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2858 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
2859 $frontpage->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2862 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2863 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2864 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2868 // Backup this course
2869 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2870 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2871 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2874 // Restore to this course
2875 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2876 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2877 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2881 $questioncaps = array('moodle/question:add',
2882 'moodle/question:editmine',
2883 'moodle/question:editall',
2884 'moodle/question:viewmine',
2885 'moodle/question:viewall',
2886 'moodle/question:movemine',
2887 'moodle/question:moveall');
2888 if (has_any_capability($questioncaps, $this->context)) {
2889 $questionlink = $CFG->wwwroot.'/question/edit.php';
2890 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2891 $questionlink = $CFG->wwwroot.'/question/category.php';
2893 if (isset($questionlink)) {
2894 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
2895 $frontpage->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
2899 if (has_capability('moodle/course:managefiles', $this->context)) {
2900 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
2901 $frontpage->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
2907 * This function marks the cache as volatile so it is cleared during shutdown
2909 public function clear_cache() {
2910 $this->cache->volatile();
2915 * Simple class used to output a navigation branch in XML
2917 * @package moodlecore
2918 * @subpackage navigation
2919 * @copyright 2009 Sam Hemelryk
2920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2922 class navigation_json {
2924 protected $nodetype = array('node','branch');
2926 protected $expandable = array();
2928 * Turns a branch and all of its children into XML
2930 * @param navigation_node $branch
2931 * @return string XML string
2933 public function convert($branch) {
2934 $xml = $this->convert_child($branch);
2938 * Set the expandable items in the array so that we have enough information
2939 * to attach AJAX events
2940 * @param array $expandable
2942 public function set_expandable($expandable) {
2943 foreach ($expandable as $node) {
2944 $this->expandable[(string)$node['branchid']] = $node;
2948 * Recusively converts a child node and its children to XML for output
2950 * @param navigation_node $child The child to convert
2951 * @param int $depth Pointlessly used to track the depth of the XML structure
2952 * @return string JSON
2954 protected function convert_child($child, $depth=1) {
2957 if (!$child->display) {
2960 $attributes = array();
2961 $attributes['id'] = $child->id;
2962 $attributes['name'] = $child->text;
2963 $attributes['type'] = $child->type;
2964 $attributes['key'] = $child->key;
2965 $attributes['class'] = $child->get_css_type();
2967 if ($child->icon instanceof pix_icon) {
2968 $attributes['icon'] = array(
2969 'component' => $child->icon->component,
2970 'pix' => $child->icon->pix,
2972 foreach ($child->icon->attributes as $key=>$value) {
2973 if ($key == 'class') {
2974 $attributes['icon']['classes'] = explode(' ', $value);
2975 } else if (!array_key_exists($key, $attributes['icon'])) {
2976 $attributes['icon'][$key] = $value;
2980 } else if (!empty($child->icon)) {
2981 $attributes['icon'] = (string)$child->icon;
2984 if ($child->forcetitle || $child->title !== $child->text) {
2985 $attributes['title'] = htmlentities($child->title);
2987 if (array_key_exists((string)$child->key, $this->expandable)) {
2988 $attributes['expandable'] = $child->key;
2989 $child->add_class($this->expandable[$child->key]['id']);
2992 if (count($child->classes)>0) {
2993 $attributes['class'] .= ' '.join(' ',$child->classes);
2995 if (is_string($child->action)) {
2996 $attributes['link'] = $child->action;
2997 } else if ($child->action instanceof moodle_url) {
2998 $attributes['link'] = $child->action->out();
3000 $attributes['hidden'] = ($child->hidden);
3001 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
3003 if (count($child->children)>0) {
3004 $attributes['children'] = array();
3005 foreach ($child->children as $subchild) {
3006 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
3013 return json_encode($attributes);
3019 * The cache class used by global navigation and settings navigation to cache bits
3020 * and bobs that are used during their generation.
3022 * It is basically an easy access point to session with a bit of smarts to make
3023 * sure that the information that is cached is valid still.
3027 * if (!$cache->viewdiscussion()) {
3028 * // Code to do stuff and produce cachable content
3029 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3031 * $content = $cache->viewdiscussion;
3034 * @package moodlecore
3035 * @subpackage navigation
3036 * @copyright 2009 Sam Hemelryk
3037 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3039 class navigation_cache {
3041 protected $creation;
3048 /** @var stdClass */
3049 protected $currentcontext;
3051 const CACHETIME = 0;
3053 const CACHEUSERID = 1;
3055 const CACHEVALUE = 2;
3056 /** @var null|array An array of navigation cache areas to expire on shutdown */
3057 public static $volatilecaches;
3060 * Contructor for the cache. Requires two arguments
3062 * @param string $area The string to use to segregate this particular cache
3063 * it can either be unique to start a fresh cache or if you want
3064 * to share a cache then make it the string used in the original
3066 * @param int $timeout The number of seconds to time the information out after
3068 public function __construct($area, $timeout=60) {
3070 $this->creation = time();
3071 $this->area = $area;
3073 if (!isset($SESSION->navcache)) {
3074 $SESSION->navcache = new stdClass;
3077 if (!isset($SESSION->navcache->{$area})) {
3078 $SESSION->navcache->{$area} = array();
3080 $this->session = &$SESSION->navcache->{$area};
3081 $this->timeout = time()-$timeout;
3082 if (rand(0,10)===0) {
3083 $this->garbage_collection();
3088 * Magic Method to retrieve something by simply calling using = cache->key
3090 * @param mixed $key The identifier for the information you want out again
3091 * @return void|mixed Either void or what ever was put in
3093 public function __get($key) {
3094 if (!$this->cached($key)) {
3097 $information = $this->session[$key][self::CACHEVALUE];
3098 return unserialize($information);
3102 * Magic method that simply uses {@link set();} to store something in the cache
3104 * @param string|int $key
3105 * @param mixed $information
3107 public function __set($key, $information) {
3108 $this->set($key, $information);
3112 * Sets some information against the cache (session) for later retrieval
3114 * @param string|int $key
3115 * @param mixed $information
3117 public function set($key, $information) {
3119 $information = serialize($information);
3120 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
3123 * Check the existence of the identifier in the cache
3125 * @param string|int $key
3128 public function cached($key) {
3130 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
3136 * Compare something to it's equivilant in the cache
3138 * @param string $key
3139 * @param mixed $value
3140 * @param bool $serialise Whether to serialise the value before comparison
3141 * this should only be set to false if the value is already
3143 * @return bool If the value is the same false if it is not set or doesn't match
3145 public function compare($key, $value, $serialise=true) {
3146 if ($this->cached($key)) {
3148 $value = serialize($value);
3150 if ($this->session[$key][self::CACHEVALUE] === $value) {
3157 * Wipes the entire cache, good to force regeneration
3159 public function clear() {
3160 $this->session = array();
3163 * Checks all cache entries and removes any that have expired, good ole cleanup
3165 protected function garbage_collection() {
3166 foreach ($this->session as $key=>$cachedinfo) {
3167 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
3168 unset($this->session[$key]);
3174 * Marks the cache as being volatile (likely to change)
3176 * Any caches marked as volatile will be destroyed at the on shutdown by
3177 * {@link navigation_node::destroy_volatile_caches()} which is registered
3178 * as a shutdown function if any caches are marked as volatile.
3180 * @param bool $setting True to destroy the cache false not too
3182 public function volatile($setting = true) {
3183 if (self::$volatilecaches===null) {
3184 self::$volatilecaches = array();
3185 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
3189 self::$volatilecaches[$this->area] = $this->area;
3190 } else if (array_key_exists($this->area, self::$volatilecaches)) {
3191 unset(self::$volatilecaches[$this->area]);
3196 * Destroys all caches marked as volatile
3198 * This function is static and works in conjunction with the static volatilecaches
3199 * property of navigation cache.
3200 * Because this function is static it manually resets the cached areas back to an
3203 public static function destroy_volatile_caches() {
3205 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
3206 foreach (self::$volatilecaches as $area) {
3207 $SESSION->navcache->{$area} = array();