MDL-20636 fix most of the remaining codechecker issues in mod/quiz and lib/questionli...
[moodle.git] / lib / navigationlib.php
blob1e4be90292143938017f31fc542669be02d9feb7
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
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
22 * @since 2.0
23 * @package core
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
36 /**
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
45 * @package moodlecore
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node implements renderable {
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF = 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH = 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN = null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE = 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM = 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY = 10;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE = 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION = 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY = 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE = 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM = 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING = 70;
75 /** @var int Setting node type, used only within settings nav 80 */
76 const TYPE_USER = 80;
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER = 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
81 public $id = null;
82 /** @var string|int The identifier for the node, used to retrieve the node */
83 public $key = null;
84 /** @var string The text to use for the node */
85 public $text = null;
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
89 public $title = null;
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
95 public $icon = null;
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self::TYPE_UNKNOWN;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self::NODETYPE_LEAF;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
124 /** @var array */
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
132 * Constructs a new navigation_node
134 * @param array|string $properties Either an array of properties or a string to use
135 * as the text for the node
137 public function __construct($properties) {
138 if (is_array($properties)) {
139 // Check the array for each property that we allow to set at construction.
140 // text - The main content for the node
141 // shorttext - A short text if required for the node
142 // icon - The icon to display for the node
143 // type - The type of the node
144 // key - The key to use to identify the node
145 // parent - A reference to the nodes parent
146 // action - The action to attribute to this node, usually a URL to link to
147 if (array_key_exists('text', $properties)) {
148 $this->text = $properties['text'];
150 if (array_key_exists('shorttext', $properties)) {
151 $this->shorttext = $properties['shorttext'];
153 if (!array_key_exists('icon', $properties)) {
154 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
156 $this->icon = $properties['icon'];
157 if ($this->icon instanceof pix_icon) {
158 if (empty($this->icon->attributes['class'])) {
159 $this->icon->attributes['class'] = 'navicon';
160 } else {
161 $this->icon->attributes['class'] .= ' navicon';
164 if (array_key_exists('type', $properties)) {
165 $this->type = $properties['type'];
166 } else {
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
204 * @return bool
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));
212 } else {
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();
220 return true;
222 return false;
226 * This sets the URL that the URL of new nodes get compared to when locating
227 * the active node.
229 * The active node is the node that matches the URL set here. By default this
230 * is either $PAGE->url or if that hasn't been set $FULLME.
232 * @param moodle_url $url The url to use for the fullmeurl.
234 public static function override_active_url(moodle_url $url) {
235 // Clone the URL, in case the calling script changes their URL later.
236 self::$fullmeurl = new moodle_url($url);
240 * Adds a navigation node as a child of this node.
242 * @param string $text
243 * @param moodle_url|action_link $action
244 * @param int $type
245 * @param string $shorttext
246 * @param string|int $key
247 * @param pix_icon $icon
248 * @return navigation_node
250 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
251 // First convert the nodetype for this node to a branch as it will now have children
252 if ($this->nodetype !== self::NODETYPE_BRANCH) {
253 $this->nodetype = self::NODETYPE_BRANCH;
255 // Properties array used when creating the new navigation node
256 $itemarray = array(
257 'text' => $text,
258 'type' => $type
260 // Set the action if one was provided
261 if ($action!==null) {
262 $itemarray['action'] = $action;
264 // Set the shorttext if one was provided
265 if ($shorttext!==null) {
266 $itemarray['shorttext'] = $shorttext;
268 // Set the icon if one was provided
269 if ($icon!==null) {
270 $itemarray['icon'] = $icon;
272 // Default the key to the number of children if not provided
273 if ($key === null) {
274 $key = $this->children->count();
276 // Set the key
277 $itemarray['key'] = $key;
278 // Set the parent to this node
279 $itemarray['parent'] = $this;
280 // Add the child using the navigation_node_collections add method
281 $node = $this->children->add(new navigation_node($itemarray));
282 // If the node is a category node or the user is logged in and its a course
283 // then mark this node as a branch (makes it expandable by AJAX)
284 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
285 $node->nodetype = self::NODETYPE_BRANCH;
287 // If this node is hidden mark it's children as hidden also
288 if ($this->hidden) {
289 $node->hidden = true;
291 // Return the node (reference returned by $this->children->add()
292 return $node;
296 * Searches for a node of the given type with the given key.
298 * This searches this node plus all of its children, and their children....
299 * If you know the node you are looking for is a child of this node then please
300 * use the get method instead.
302 * @param int|string $key The key of the node we are looking for
303 * @param int $type One of navigation_node::TYPE_*
304 * @return navigation_node|false
306 public function find($key, $type) {
307 return $this->children->find($key, $type);
311 * Get ths child of this node that has the given key + (optional) type.
313 * If you are looking for a node and want to search all children + thier children
314 * then please use the find method instead.
316 * @param int|string $key The key of the node we are looking for
317 * @param int $type One of navigation_node::TYPE_*
318 * @return navigation_node|false
320 public function get($key, $type=null) {
321 return $this->children->get($key, $type);
325 * Removes this node.
327 * @return bool
329 public function remove() {
330 return $this->parent->children->remove($this->key, $this->type);
334 * Checks if this node has or could have any children
336 * @return bool Returns true if it has children or could have (by AJAX expansion)
338 public function has_children() {
339 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
343 * Marks this node as active and forces it open.
345 * Important: If you are here because you need to mark a node active to get
346 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
347 * You can use it to specify a different URL to match the active navigation node on
348 * rather than having to locate and manually mark a node active.
350 public function make_active() {
351 $this->isactive = true;
352 $this->add_class('active_tree_node');
353 $this->force_open();
354 if ($this->parent !== null) {
355 $this->parent->make_inactive();
360 * Marks a node as inactive and recusised back to the base of the tree
361 * doing the same to all parents.
363 public function make_inactive() {
364 $this->isactive = false;
365 $this->remove_class('active_tree_node');
366 if ($this->parent !== null) {
367 $this->parent->make_inactive();
372 * Forces this node to be open and at the same time forces open all
373 * parents until the root node.
375 * Recursive.
377 public function force_open() {
378 $this->forceopen = true;
379 if ($this->parent !== null) {
380 $this->parent->force_open();
385 * Adds a CSS class to this node.
387 * @param string $class
388 * @return bool
390 public function add_class($class) {
391 if (!in_array($class, $this->classes)) {
392 $this->classes[] = $class;
394 return true;
398 * Removes a CSS class from this node.
400 * @param string $class
401 * @return bool True if the class was successfully removed.
403 public function remove_class($class) {
404 if (in_array($class, $this->classes)) {
405 $key = array_search($class,$this->classes);
406 if ($key!==false) {
407 unset($this->classes[$key]);
408 return true;
411 return false;
415 * Sets the title for this node and forces Moodle to utilise it.
416 * @param string $title
418 public function title($title) {
419 $this->title = $title;
420 $this->forcetitle = true;
424 * Resets the page specific information on this node if it is being unserialised.
426 public function __wakeup(){
427 $this->forceopen = false;
428 $this->isactive = false;
429 $this->remove_class('active_tree_node');
433 * Checks if this node or any of its children contain the active node.
435 * Recursive.
437 * @return bool
439 public function contains_active_node() {
440 if ($this->isactive) {
441 return true;
442 } else {
443 foreach ($this->children as $child) {
444 if ($child->isactive || $child->contains_active_node()) {
445 return true;
449 return false;
453 * Finds the active node.
455 * Searches this nodes children plus all of the children for the active node
456 * and returns it if found.
458 * Recursive.
460 * @return navigation_node|false
462 public function find_active_node() {
463 if ($this->isactive) {
464 return $this;
465 } else {
466 foreach ($this->children as &$child) {
467 $outcome = $child->find_active_node();
468 if ($outcome !== false) {
469 return $outcome;
473 return false;
477 * Searches all children for the best matching active node
478 * @return navigation_node|false
480 public function search_for_active_node() {
481 if ($this->check_if_active(URL_MATCH_BASE)) {
482 return $this;
483 } else {
484 foreach ($this->children as &$child) {
485 $outcome = $child->search_for_active_node();
486 if ($outcome !== false) {
487 return $outcome;
491 return false;
495 * Gets the content for this node.
497 * @param bool $shorttext If true shorttext is used rather than the normal text
498 * @return string
500 public function get_content($shorttext=false) {
501 if ($shorttext && $this->shorttext!==null) {
502 return format_string($this->shorttext);
503 } else {
504 return format_string($this->text);
509 * Gets the title to use for this node.
511 * @return string
513 public function get_title() {
514 if ($this->forcetitle || $this->action != null){
515 return $this->title;
516 } else {
517 return '';
522 * Gets the CSS class to add to this node to describe its type
524 * @return string
526 public function get_css_type() {
527 if (array_key_exists($this->type, $this->namedtypes)) {
528 return 'type_'.$this->namedtypes[$this->type];
530 return 'type_unknown';
534 * Finds all nodes that are expandable by AJAX
536 * @param array $expandable An array by reference to populate with expandable nodes.
538 public function find_expandable(array &$expandable) {
539 foreach ($this->children as &$child) {
540 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count() == 0 && $child->display) {
541 $child->id = 'expandable_branch_'.(count($expandable)+1);
542 $this->add_class('canexpand');
543 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
545 $child->find_expandable($expandable);
550 * Finds all nodes of a given type (recursive)
552 * @param int $type On of navigation_node::TYPE_*
553 * @return array
555 public function find_all_of_type($type) {
556 $nodes = $this->children->type($type);
557 foreach ($this->children as &$node) {
558 $childnodes = $node->find_all_of_type($type);
559 $nodes = array_merge($nodes, $childnodes);
561 return $nodes;
565 * Removes this node if it is empty
567 public function trim_if_empty() {
568 if ($this->children->count() == 0) {
569 $this->remove();
574 * Creates a tab representation of this nodes children that can be used
575 * with print_tabs to produce the tabs on a page.
577 * call_user_func_array('print_tabs', $node->get_tabs_array());
579 * @param array $inactive
580 * @param bool $return
581 * @return array Array (tabs, selected, inactive, activated, return)
583 public function get_tabs_array(array $inactive=array(), $return=false) {
584 $tabs = array();
585 $rows = array();
586 $selected = null;
587 $activated = array();
588 foreach ($this->children as $node) {
589 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
590 if ($node->contains_active_node()) {
591 if ($node->children->count() > 0) {
592 $activated[] = $node->key;
593 foreach ($node->children as $child) {
594 if ($child->contains_active_node()) {
595 $selected = $child->key;
597 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
599 } else {
600 $selected = $node->key;
604 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
609 * Navigation node collection
611 * This class is responsible for managing a collection of navigation nodes.
612 * It is required because a node's unique identifier is a combination of both its
613 * key and its type.
615 * Originally an array was used with a string key that was a combination of the two
616 * however it was decided that a better solution would be to use a class that
617 * implements the standard IteratorAggregate interface.
619 * @package moodlecore
620 * @subpackage navigation
621 * @copyright 2010 Sam Hemelryk
622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
624 class navigation_node_collection implements IteratorAggregate {
626 * A multidimensional array to where the first key is the type and the second
627 * key is the nodes key.
628 * @var array
630 protected $collection = array();
632 * An array that contains references to nodes in the same order they were added.
633 * This is maintained as a progressive array.
634 * @var array
636 protected $orderedcollection = array();
638 * A reference to the last node that was added to the collection
639 * @var navigation_node
641 protected $last = null;
643 * The total number of items added to this array.
644 * @var int
646 protected $count = 0;
648 * Adds a navigation node to the collection
650 * @param navigation_node $node
651 * @return navigation_node
653 public function add(navigation_node $node) {
654 global $CFG;
655 $key = $node->key;
656 $type = $node->type;
657 // First check we have a 2nd dimension for this type
658 if (!array_key_exists($type, $this->orderedcollection)) {
659 $this->orderedcollection[$type] = array();
661 // Check for a collision and report if debugging is turned on
662 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
663 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
665 // Add the node to the appropriate place in the ordered structure.
666 $this->orderedcollection[$type][$key] = $node;
667 // Add a reference to the node to the progressive collection.
668 $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
669 // Update the last property to a reference to this new node.
670 $this->last = &$this->orderedcollection[$type][$key];
671 $this->count++;
672 // Return the reference to the now added node
673 return $this->last;
677 * Fetches a node from this collection.
679 * @param string|int $key The key of the node we want to find.
680 * @param int $type One of navigation_node::TYPE_*.
681 * @return navigation_node|null
683 public function get($key, $type=null) {
684 if ($type !== null) {
685 // If the type is known then we can simply check and fetch
686 if (!empty($this->orderedcollection[$type][$key])) {
687 return $this->orderedcollection[$type][$key];
689 } else {
690 // Because we don't know the type we look in the progressive array
691 foreach ($this->collection as $node) {
692 if ($node->key === $key) {
693 return $node;
697 return false;
700 * Searches for a node with matching key and type.
702 * This function searches both the nodes in this collection and all of
703 * the nodes in each collection belonging to the nodes in this collection.
705 * Recursive.
707 * @param string|int $key The key of the node we want to find.
708 * @param int $type One of navigation_node::TYPE_*.
709 * @return navigation_node|null
711 public function find($key, $type=null) {
712 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
713 return $this->orderedcollection[$type][$key];
714 } else {
715 $nodes = $this->getIterator();
716 // Search immediate children first
717 foreach ($nodes as &$node) {
718 if ($node->key === $key && ($type === null || $type === $node->type)) {
719 return $node;
722 // Now search each childs children
723 foreach ($nodes as &$node) {
724 $result = $node->children->find($key, $type);
725 if ($result !== false) {
726 return $result;
730 return false;
734 * Fetches the last node that was added to this collection
736 * @return navigation_node
738 public function last() {
739 return $this->last;
742 * Fetches all nodes of a given type from this collection
744 public function type($type) {
745 if (!array_key_exists($type, $this->orderedcollection)) {
746 $this->orderedcollection[$type] = array();
748 return $this->orderedcollection[$type];
751 * Removes the node with the given key and type from the collection
753 * @param string|int $key
754 * @param int $type
755 * @return bool
757 public function remove($key, $type=null) {
758 $child = $this->get($key, $type);
759 if ($child !== false) {
760 foreach ($this->collection as $colkey => $node) {
761 if ($node->key == $key && $node->type == $type) {
762 unset($this->collection[$colkey]);
763 break;
766 unset($this->orderedcollection[$child->type][$child->key]);
767 $this->count--;
768 return true;
770 return false;
774 * Gets the number of nodes in this collection
775 * @return int
777 public function count() {
778 return count($this->collection);
781 * Gets an array iterator for the collection.
783 * This is required by the IteratorAggregator interface and is used by routines
784 * such as the foreach loop.
786 * @return ArrayIterator
788 public function getIterator() {
789 return new ArrayIterator($this->collection);
794 * The global navigation class used for... the global navigation
796 * This class is used by PAGE to store the global navigation for the site
797 * and is then used by the settings nav and navbar to save on processing and DB calls
799 * See
800 * <ul>
801 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
802 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
803 * </ul>
805 * @package moodlecore
806 * @subpackage navigation
807 * @copyright 2009 Sam Hemelryk
808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
810 class global_navigation extends navigation_node {
812 * The Moodle page this navigation object belongs to.
813 * @var moodle_page
815 protected $page;
816 /** @var bool */
817 protected $initialised = false;
818 /** @var array */
819 protected $mycourses = array();
820 /** @var array */
821 protected $rootnodes = array();
822 /** @var bool */
823 protected $showemptysections = false;
824 /** @var array */
825 protected $extendforuser = array();
826 /** @var navigation_cache */
827 protected $cache;
828 /** @var array */
829 protected $addedcourses = array();
830 /** @var int */
831 protected $expansionlimit = 0;
832 /** @var int */
833 protected $useridtouseforparentchecks = 0;
836 * Constructs a new global navigation
838 * @param moodle_page $page The page this navigation object belongs to
840 public function __construct(moodle_page $page) {
841 global $CFG, $SITE, $USER;
843 if (during_initial_install()) {
844 return;
847 if (get_home_page() == HOMEPAGE_SITE) {
848 // We are using the site home for the root element
849 $properties = array(
850 'key' => 'home',
851 'type' => navigation_node::TYPE_SYSTEM,
852 'text' => get_string('home'),
853 'action' => new moodle_url('/')
855 } else {
856 // We are using the users my moodle for the root element
857 $properties = array(
858 'key' => 'myhome',
859 'type' => navigation_node::TYPE_SYSTEM,
860 'text' => get_string('myhome'),
861 'action' => new moodle_url('/my/')
865 // Use the parents consturctor.... good good reuse
866 parent::__construct($properties);
868 // Initalise and set defaults
869 $this->page = $page;
870 $this->forceopen = true;
871 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
873 // Check if we need to clear the cache
874 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
875 if ($regenerate === 'navigation') {
876 $this->cache->clear();
881 * Mutator to set userid to allow parent to see child's profile
882 * page navigation. See MDL-25805 for initial issue. Linked to it
883 * is an issue explaining why this is a REALLY UGLY HACK thats not
884 * for you to use!
886 * @param int $userid userid of profile page that parent wants to navigate around.
888 public function set_userid_for_parent_checks($userid) {
889 $this->useridtouseforparentchecks = $userid;
894 * Initialises the navigation object.
896 * This causes the navigation object to look at the current state of the page
897 * that it is associated with and then load the appropriate content.
899 * This should only occur the first time that the navigation structure is utilised
900 * which will normally be either when the navbar is called to be displayed or
901 * when a block makes use of it.
903 * @return bool
905 public function initialise() {
906 global $CFG, $SITE, $USER, $DB;
907 // Check if it has alread been initialised
908 if ($this->initialised || during_initial_install()) {
909 return true;
911 $this->initialised = true;
913 // Set up the five base root nodes. These are nodes where we will put our
914 // content and are as follows:
915 // site: Navigation for the front page.
916 // myprofile: User profile information goes here.
917 // mycourses: The users courses get added here.
918 // courses: Additional courses are added here.
919 // users: Other users information loaded here.
920 $this->rootnodes = array();
921 if (get_home_page() == HOMEPAGE_SITE) {
922 // The home element should be my moodle because the root element is the site
923 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
924 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
926 } else {
927 // The home element should be the site because the root node is my moodle
928 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
929 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
930 // We need to stop automatic redirection
931 $this->rootnodes['home']->action->param('redirect', '0');
934 $this->rootnodes['site'] = $this->add_course($SITE);
935 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
936 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
937 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
938 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
940 // Fetch all of the users courses.
941 $limit = 20;
942 if (!empty($CFG->navcourselimit)) {
943 $limit = $CFG->navcourselimit;
946 if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') == 1) {
947 // There is only one category so we don't want to show categories
948 $CFG->navshowcategories = false;
951 $this->mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
952 $showallcourses = (count($this->mycourses) == 0 || !empty($CFG->navshowallcourses));
953 $showcategories = ($showallcourses && !empty($CFG->navshowcategories));
955 // Check if any courses were returned.
956 if (count($this->mycourses) > 0) {
957 // Add all of the users courses to the navigation
958 foreach ($this->mycourses as &$course) {
959 $course->coursenode = $this->add_course($course);
963 if ($showcategories) {
964 // Load all categories (ensures we get the base categories)
965 $this->load_all_categories();
966 } else if ($showallcourses) {
967 // Load all courses
968 $this->load_all_courses();
971 // We always load the frontpage course to ensure it is available without
972 // JavaScript enabled.
973 $frontpagecourse = $this->load_course($SITE);
974 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
976 $canviewcourseprofile = true;
978 // Next load context specific content into the navigation
979 switch ($this->page->context->contextlevel) {
980 case CONTEXT_SYSTEM :
981 // This has already been loaded we just need to map the variable
982 $coursenode = $frontpagecourse;
983 break;
984 case CONTEXT_COURSECAT :
985 // This has already been loaded we just need to map the variable
986 $coursenode = $frontpagecourse;
987 $this->load_all_categories($this->page->context->instanceid);
988 break;
989 case CONTEXT_BLOCK :
990 case CONTEXT_COURSE :
991 // Load the course associated with the page into the navigation
992 $course = $this->page->course;
993 $coursenode = $this->load_course($course);
995 // If the course wasn't added then don't try going any further.
996 if (!$coursenode) {
997 $canviewcourseprofile = false;
998 break;
1001 // If the user is not enrolled then we only want to show the
1002 // course node and not populate it.
1003 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1005 // Not enrolled, can't view, and hasn't switched roles
1006 if (!can_access_course($coursecontext)) {
1007 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1008 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1009 $isparent = false;
1010 if ($this->useridtouseforparentchecks) {
1011 $currentuser = ($this->useridtouseforparentchecks == $USER->id);
1012 if (!$currentuser) {
1013 $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST);
1014 if ($DB->record_exists('role_assignments', array('userid'=>$USER->id, 'contextid'=>$usercontext->id))
1015 and has_capability('moodle/user:viewdetails', $usercontext)) {
1016 $isparent = true;
1021 if (!$isparent) {
1022 $coursenode->make_active();
1023 $canviewcourseprofile = false;
1024 break;
1027 // Add the essentials such as reports etc...
1028 $this->add_course_essentials($coursenode, $course);
1029 if ($this->format_display_course_content($course->format)) {
1030 // Load the course sections
1031 $sections = $this->load_course_sections($course, $coursenode);
1033 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1034 $coursenode->make_active();
1036 break;
1037 case CONTEXT_MODULE :
1038 $course = $this->page->course;
1039 $cm = $this->page->cm;
1040 // Load the course associated with the page into the navigation
1041 $coursenode = $this->load_course($course);
1043 // If the user is not enrolled then we only want to show the
1044 // course node and not populate it.
1045 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1046 if (!can_access_course($coursecontext)) {
1047 if ($coursenode) {
1048 $coursenode->make_active();
1050 $canviewcourseprofile = false;
1051 break;
1054 $this->add_course_essentials($coursenode, $course);
1055 // Load the course sections into the page
1056 $sections = $this->load_course_sections($course, $coursenode);
1057 if ($course->id != SITEID) {
1058 // Find the section for the $CM associated with the page and collect
1059 // its section number.
1060 if (isset($cm->sectionnum)) {
1061 $cm->sectionnumber = $cm->sectionnum;
1062 } else {
1063 foreach ($sections as $section) {
1064 if ($section->id == $cm->section) {
1065 $cm->sectionnumber = $section->section;
1066 break;
1071 // Load all of the section activities for the section the cm belongs to.
1072 if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1073 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1074 } else {
1075 $activities = array();
1076 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1077 // "stealth" activity from unavailable section
1078 $activities[$cm->id] = $activity;
1081 } else {
1082 $activities = array();
1083 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1085 if (!empty($activities[$cm->id])) {
1086 // Finally load the cm specific navigaton information
1087 $this->load_activity($cm, $course, $activities[$cm->id]);
1088 // Check if we have an active ndoe
1089 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1090 // And make the activity node active.
1091 $activities[$cm->id]->make_active();
1093 } else {
1094 //TODO: something is wrong, what to do? (Skodak)
1096 break;
1097 case CONTEXT_USER :
1098 $course = $this->page->course;
1099 if ($course->id != SITEID) {
1100 // Load the course associated with the user into the navigation
1101 $coursenode = $this->load_course($course);
1102 // If the user is not enrolled then we only want to show the
1103 // course node and not populate it.
1104 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1105 if (!can_access_course($coursecontext)) {
1106 $coursenode->make_active();
1107 $canviewcourseprofile = false;
1108 break;
1110 $this->add_course_essentials($coursenode, $course);
1111 $sections = $this->load_course_sections($course, $coursenode);
1113 break;
1116 $limit = 20;
1117 if (!empty($CFG->navcourselimit)) {
1118 $limit = $CFG->navcourselimit;
1120 if ($showcategories) {
1121 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1122 foreach ($categories as &$category) {
1123 if ($category->children->count() >= $limit) {
1124 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1125 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1128 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1129 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1132 // Load for the current user
1133 $this->load_for_user();
1134 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1135 $this->load_for_user(null, true);
1137 // Load each extending user into the navigation.
1138 foreach ($this->extendforuser as $user) {
1139 if ($user->id != $USER->id) {
1140 $this->load_for_user($user);
1144 // Give the local plugins a chance to include some navigation if they want.
1145 foreach (get_list_of_plugins('local') as $plugin) {
1146 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1147 continue;
1149 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1150 $function = $plugin.'_extends_navigation';
1151 if (function_exists($function)) {
1152 $function($this);
1156 // Remove any empty root nodes
1157 foreach ($this->rootnodes as $node) {
1158 // Dont remove the home node
1159 if ($node->key !== 'home' && !$node->has_children()) {
1160 $node->remove();
1164 if (!$this->contains_active_node()) {
1165 $this->search_for_active_node();
1168 // If the user is not logged in modify the navigation structure as detailed
1169 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1170 if (!isloggedin()) {
1171 $activities = clone($this->rootnodes['site']->children);
1172 $this->rootnodes['site']->remove();
1173 $children = clone($this->children);
1174 $this->children = new navigation_node_collection();
1175 foreach ($activities as $child) {
1176 $this->children->add($child);
1178 foreach ($children as $child) {
1179 $this->children->add($child);
1182 return true;
1185 * Checks the course format to see whether it wants the navigation to load
1186 * additional information for the course.
1188 * This function utilises a callback that can exist within the course format lib.php file
1189 * The callback should be a function called:
1190 * callback_{formatname}_display_content()
1191 * It doesn't get any arguments and should return true if additional content is
1192 * desired. If the callback doesn't exist we assume additional content is wanted.
1194 * @param string $format The course format
1195 * @return bool
1197 protected function format_display_course_content($format) {
1198 global $CFG;
1199 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1200 if (file_exists($formatlib)) {
1201 require_once($formatlib);
1202 $displayfunc = 'callback_'.$format.'_display_content';
1203 if (function_exists($displayfunc) && !$displayfunc()) {
1204 return $displayfunc();
1207 return true;
1211 * Loads of the the courses in Moodle into the navigation.
1213 * @param string|array $categoryids Either a string or array of category ids to load courses for
1214 * @return array An array of navigation_node
1216 protected function load_all_courses($categoryids=null) {
1217 global $CFG, $DB, $USER;
1219 if ($categoryids !== null) {
1220 if (is_array($categoryids)) {
1221 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1222 } else {
1223 $select = '= ?';
1224 $params = array($categoryids);
1226 array_unshift($params, SITEID);
1227 $select = ' AND c.category '.$select;
1228 } else {
1229 $params = array(SITEID);
1230 $select = '';
1233 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1234 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1235 FROM {course} c
1236 $ccjoin
1237 LEFT JOIN {course_categories} cat ON cat.id=c.category
1238 WHERE c.id <> ?$select
1239 ORDER BY c.sortorder ASC";
1240 $limit = 20;
1241 if (!empty($CFG->navcourselimit)) {
1242 $limit = $CFG->navcourselimit;
1244 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1246 $coursenodes = array();
1247 foreach ($courses as $course) {
1248 context_instance_preload($course);
1249 $coursenodes[$course->id] = $this->add_course($course);
1251 return $coursenodes;
1255 * Loads all categories (top level or if an id is specified for that category)
1257 * @param int $categoryid
1258 * @return void
1260 protected function load_all_categories($categoryid=null) {
1261 global $DB;
1262 if ($categoryid == null) {
1263 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1264 } else {
1265 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1266 $wantedids = explode('/', trim($category->path, '/'));
1267 list($select, $params) = $DB->get_in_or_equal($wantedids);
1268 $select = 'id '.$select.' OR parent '.$select;
1269 $params = array_merge($params, $params);
1270 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1272 $structured = array();
1273 $categoriestoload = array();
1274 foreach ($categories as $category) {
1275 if ($category->parent == '0') {
1276 $structured[$category->id] = array('category'=>$category, 'children'=>array());
1277 } else {
1278 if ($category->parent == $categoryid) {
1279 $categoriestoload[] = $category->id;
1281 $parents = array();
1282 $id = $category->parent;
1283 while ($id != '0') {
1284 $parents[] = $id;
1285 if (!array_key_exists($id, $categories)) {
1286 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST);
1288 $id = $categories[$id]->parent;
1290 $parents = array_reverse($parents);
1291 $parentref = &$structured[array_shift($parents)];
1292 foreach ($parents as $parent) {
1293 if (!array_key_exists($parent, $parentref['children'])) {
1294 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1296 $parentref = &$parentref['children'][$parent];
1298 if (!array_key_exists($category->id, $parentref['children'])) {
1299 $parentref['children'][$category->id] = array('category'=>$category, 'children'=>array());
1304 foreach ($structured as $category) {
1305 $this->add_category($category, $this->rootnodes['courses']);
1308 if ($categoryid !== null && count($wantedids)) {
1309 foreach ($wantedids as $catid) {
1310 $this->load_all_courses($catid);
1316 * Adds a structured category to the navigation in the correct order/place
1318 * @param object $cat
1319 * @param navigation_node $parent
1321 protected function add_category($cat, navigation_node $parent) {
1322 $categorynode = $parent->get($cat['category']->id, navigation_node::TYPE_CATEGORY);
1323 if (!$categorynode) {
1324 $category = $cat['category'];
1325 $url = new moodle_url('/course/category.php', array('id'=>$category->id));
1326 $categorynode = $parent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id);
1327 if (empty($category->visible)) {
1328 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1329 $categorynode->hidden = true;
1330 } else {
1331 $categorynode->display = false;
1335 foreach ($cat['children'] as $child) {
1336 $this->add_category($child, $categorynode);
1341 * Loads the given course into the navigation
1343 * @param stdClass $course
1344 * @return navigation_node
1346 protected function load_course(stdClass $course) {
1347 if ($course->id == SITEID) {
1348 $coursenode = $this->rootnodes['site'];
1349 } else if (array_key_exists($course->id, $this->mycourses)) {
1350 if (!isset($this->mycourses[$course->id]->coursenode)) {
1351 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
1353 $coursenode = $this->mycourses[$course->id]->coursenode;
1354 } else {
1355 $coursenode = $this->add_course($course);
1357 return $coursenode;
1361 * Loads all of the courses section into the navigation.
1363 * This function utilisies a callback that can be implemented within the course
1364 * formats lib.php file to customise the navigation that is generated at this
1365 * point for the course.
1367 * By default (if not defined) the method {@see load_generic_course_sections} is
1368 * called instead.
1370 * @param stdClass $course Database record for the course
1371 * @param navigation_node $coursenode The course node within the navigation
1372 * @return array Array of navigation nodes for the section with key = section id
1374 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1375 global $CFG;
1376 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1377 $structurefunc = 'callback_'.$course->format.'_load_content';
1378 if (function_exists($structurefunc)) {
1379 return $structurefunc($this, $course, $coursenode);
1380 } else if (file_exists($structurefile)) {
1381 require_once $structurefile;
1382 if (function_exists($structurefunc)) {
1383 return $structurefunc($this, $course, $coursenode);
1384 } else {
1385 return $this->load_generic_course_sections($course, $coursenode);
1387 } else {
1388 return $this->load_generic_course_sections($course, $coursenode);
1393 * Generically loads the course sections into the course's navigation.
1395 * @param stdClass $course
1396 * @param navigation_node $coursenode
1397 * @param string $name The string that identifies each section. e.g Topic, or Week
1398 * @param string $activeparam The url used to identify the active section
1399 * @return array An array of course section nodes
1401 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1402 global $CFG, $DB, $USER;
1404 require_once($CFG->dirroot.'/course/lib.php');
1406 if (!$this->cache->cached('modinfo'.$course->id)) {
1407 $this->cache->set('modinfo'.$course->id, get_fast_modinfo($course));
1409 $modinfo = $this->cache->{'modinfo'.$course->id};
1411 if (!$this->cache->cached('coursesections'.$course->id)) {
1412 $this->cache->set('coursesections'.$course->id, array_slice(get_all_sections($course->id), 0, $course->numsections+1, true));
1414 $sections = $this->cache->{'coursesections'.$course->id};
1416 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1418 $activesection = course_get_display($course->id);
1420 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1421 $namingfunctionexists = (function_exists($namingfunction));
1423 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1424 if (function_exists($activeparamfunction)) {
1425 $activeparam = $activeparamfunction();
1426 } else {
1427 $activeparam = 'section';
1429 $navigationsections = array();
1430 foreach ($sections as $sectionid=>$section) {
1431 $section = clone($section);
1432 if ($course->id == SITEID) {
1433 $this->load_section_activities($coursenode, $section->section, $modinfo);
1434 } else {
1435 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1436 continue;
1438 if ($namingfunctionexists) {
1439 $sectionname = $namingfunction($course, $section, $sections);
1440 } else {
1441 $sectionname = get_string('section').' '.$section->section;
1443 //$url = new moodle_url('/course/view.php', array('id'=>$course->id));
1444 $url = null;
1445 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1446 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1447 $sectionnode->hidden = (!$section->visible);
1448 if ($this->page->context->contextlevel != CONTEXT_MODULE && ($sectionnode->isactive || ($activesection && $section->section == $activesection))) {
1449 $sectionnode->force_open();
1450 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1452 $section->sectionnode = $sectionnode;
1453 $navigationsections[$sectionid] = $section;
1456 return $navigationsections;
1459 * Loads all of the activities for a section into the navigation structure.
1461 * @param navigation_node $sectionnode
1462 * @param int $sectionnumber
1463 * @param course_modinfo $modinfo Object returned from {@see get_fast_modinfo()}
1464 * @return array Array of activity nodes
1466 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, course_modinfo $modinfo) {
1467 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1468 return true;
1471 $activities = array();
1473 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1474 $cm = $modinfo->cms[$cmid];
1475 if (!$cm->uservisible) {
1476 continue;
1478 if ($cm->icon) {
1479 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1480 } else {
1481 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1483 $url = $cm->get_url();
1484 $activitynode = $sectionnode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1485 $activitynode->title(get_string('modulename', $cm->modname));
1486 $activitynode->hidden = (!$cm->visible);
1487 if (!$url) {
1488 // Do not show activities that don't have links!
1489 $activitynode->display = false;
1490 } else if ($this->module_extends_navigation($cm->modname)) {
1491 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1493 $activities[$cmid] = $activitynode;
1496 return $activities;
1499 * Loads a stealth module from unavailable section
1500 * @param navigation_node $coursenode
1501 * @param stdClass $modinfo
1502 * @return navigation_node or null if not accessible
1504 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1505 if (empty($modinfo->cms[$this->page->cm->id])) {
1506 return null;
1508 $cm = $modinfo->cms[$this->page->cm->id];
1509 if (!$cm->uservisible) {
1510 return null;
1512 if ($cm->icon) {
1513 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1514 } else {
1515 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1517 $url = $cm->get_url();
1518 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1519 $activitynode->title(get_string('modulename', $cm->modname));
1520 $activitynode->hidden = (!$cm->visible);
1521 if (!$url) {
1522 // Don't show activities that don't have links!
1523 $activitynode->display = false;
1524 } else if ($this->module_extends_navigation($cm->modname)) {
1525 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1527 return $activitynode;
1530 * Loads the navigation structure for the given activity into the activities node.
1532 * This method utilises a callback within the modules lib.php file to load the
1533 * content specific to activity given.
1535 * The callback is a method: {modulename}_extend_navigation()
1536 * Examples:
1537 * * {@see forum_extend_navigation()}
1538 * * {@see workshop_extend_navigation()}
1540 * @param cm_info|stdClass $cm
1541 * @param stdClass $course
1542 * @param navigation_node $activity
1543 * @return bool
1545 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
1546 global $CFG, $DB;
1548 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1549 if (!($cm instanceof cm_info)) {
1550 $modinfo = get_fast_modinfo($course);
1551 $cm = $modinfo->get_cm($cm->id);
1554 $activity->make_active();
1555 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1556 $function = $cm->modname.'_extend_navigation';
1558 if (file_exists($file)) {
1559 require_once($file);
1560 if (function_exists($function)) {
1561 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1562 $function($activity, $course, $activtyrecord, $cm);
1563 return true;
1566 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1567 return false;
1570 * Loads user specific information into the navigation in the appopriate place.
1572 * If no user is provided the current user is assumed.
1574 * @param stdClass $user
1575 * @return bool
1577 protected function load_for_user($user=null, $forceforcontext=false) {
1578 global $DB, $CFG, $USER;
1580 if ($user === null) {
1581 // We can't require login here but if the user isn't logged in we don't
1582 // want to show anything
1583 if (!isloggedin() || isguestuser()) {
1584 return false;
1586 $user = $USER;
1587 } else if (!is_object($user)) {
1588 // If the user is not an object then get them from the database
1589 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1592 $iscurrentuser = ($user->id == $USER->id);
1594 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1596 // Get the course set against the page, by default this will be the site
1597 $course = $this->page->course;
1598 $baseargs = array('id'=>$user->id);
1599 if ($course->id != SITEID && (!$iscurrentuser || $forceforcontext)) {
1600 if (array_key_exists($course->id, $this->mycourses)) {
1601 $coursenode = $this->mycourses[$course->id]->coursenode;
1602 } else {
1603 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1604 if (!$coursenode) {
1605 $coursenode = $this->load_course($course);
1608 $baseargs['course'] = $course->id;
1609 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1610 $issitecourse = false;
1611 } else {
1612 // Load all categories and get the context for the system
1613 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1614 $issitecourse = true;
1617 // Create a node to add user information under.
1618 if ($iscurrentuser && !$forceforcontext) {
1619 // If it's the current user the information will go under the profile root node
1620 $usernode = $this->rootnodes['myprofile'];
1621 } else {
1622 if (!$issitecourse) {
1623 // Not the current user so add it to the participants node for the current course
1624 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1625 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1626 } else {
1627 // This is the site so add a users node to the root branch
1628 $usersnode = $this->rootnodes['users'];
1629 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1630 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1632 if (!$usersnode) {
1633 // We should NEVER get here, if the course hasn't been populated
1634 // with a participants node then the navigaiton either wasn't generated
1635 // for it (you are missing a require_login or set_context call) or
1636 // you don't have access.... in the interests of no leaking informatin
1637 // we simply quit...
1638 return false;
1640 // Add a branch for the current user
1641 $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);
1643 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1644 $usernode->make_active();
1648 // If the user is the current user or has permission to view the details of the requested
1649 // user than add a view profile link.
1650 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1651 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1652 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1653 } else {
1654 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1658 // Add nodes for forum posts and discussions if the user can view either or both
1659 // There are no capability checks here as the content of the page is based
1660 // purely on the forums the current user has access too.
1661 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1662 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1663 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1665 // Add blog nodes
1666 if (!empty($CFG->bloglevel)) {
1667 require_once($CFG->dirroot.'/blog/lib.php');
1668 // Get all options for the user
1669 $options = blog_get_options_for_user($user);
1670 if (count($options) > 0) {
1671 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1672 foreach ($options as $option) {
1673 $blogs->add($option['string'], $option['link']);
1678 if (!empty($CFG->messaging)) {
1679 $messageargs = null;
1680 if ($USER->id!=$user->id) {
1681 $messageargs = array('id'=>$user->id);
1683 $url = new moodle_url('/message/index.php',$messageargs);
1684 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
1687 $context = get_context_instance(CONTEXT_USER, $USER->id);
1688 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
1689 $url = new moodle_url('/user/files.php');
1690 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
1693 // Add a node to view the users notes if permitted
1694 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1695 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1696 if ($coursecontext->instanceid) {
1697 $url->param('course', $coursecontext->instanceid);
1699 $usernode->add(get_string('notes', 'notes'), $url);
1702 // Add a reports tab and then add reports the the user has permission to see.
1703 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1705 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext));
1706 if ($viewreports) {
1707 $reporttab = $usernode->add(get_string('activityreports'));
1708 $reportargs = array('user'=>$user->id);
1709 if (!empty($course->id)) {
1710 $reportargs['id'] = $course->id;
1711 } else {
1712 $reportargs['id'] = SITEID;
1714 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1715 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1716 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1719 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1720 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1723 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1724 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1727 if (!empty($CFG->enablestats)) {
1728 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1729 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1733 $gradeaccess = false;
1734 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1735 //ok - can view all course grades
1736 $gradeaccess = true;
1737 } else if ($course->showgrades) {
1738 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1739 //ok - can view own grades
1740 $gradeaccess = true;
1741 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1742 // ok - can view grades of this user - parent most probably
1743 $gradeaccess = true;
1744 } else if ($anyreport) {
1745 // ok - can view grades of this user - parent most probably
1746 $gradeaccess = true;
1749 if ($gradeaccess) {
1750 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1753 // Check the number of nodes in the report node... if there are none remove
1754 // the node
1755 if (count($reporttab->children)===0) {
1756 $usernode->remove_child($reporttab);
1760 // If the user is the current user add the repositories for the current user
1761 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
1762 if ($iscurrentuser) {
1763 require_once($CFG->dirroot . '/repository/lib.php');
1764 $editabletypes = repository::get_editable_types($usercontext);
1765 if (!empty($editabletypes)) {
1766 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1768 } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
1770 // Add view grade report is permitted
1771 $reports = get_plugin_list('gradereport');
1772 arsort($reports); // user is last, we want to test it first
1774 $userscourses = enrol_get_users_courses($user->id);
1775 $userscoursesnode = $usernode->add(get_string('courses'));
1777 foreach ($userscourses as $usercourse) {
1778 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
1779 $usercoursenode = $userscoursesnode->add($usercourse->shortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
1781 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
1782 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
1783 foreach ($reports as $plugin => $plugindir) {
1784 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
1785 //stop when the first visible plugin is found
1786 $gradeavailable = true;
1787 break;
1792 if ($gradeavailable) {
1793 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
1794 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
1797 // Add a node to view the users notes if permitted
1798 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
1799 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
1800 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
1803 if (can_access_course(get_context_instance(CONTEXT_COURSE, $usercourse->id), $user->id)) {
1804 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
1807 $outlinetreport = ($anyreport || has_capability('coursereport/outline:view', $usercoursecontext));
1808 $logtodayreport = ($anyreport || has_capability('coursereport/log:viewtoday', $usercoursecontext));
1809 $logreport = ($anyreport || has_capability('coursereport/log:view', $usercoursecontext));
1810 $statsreport = ($anyreport || has_capability('coursereport/stats:view', $usercoursecontext));
1811 if ($outlinetreport || $logtodayreport || $logreport || $statsreport) {
1812 $reporttab = $usercoursenode->add(get_string('activityreports'));
1813 $reportargs = array('user'=>$user->id, 'id'=>$usercourse->id);
1814 if ($outlinetreport) {
1815 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1816 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1819 if ($logtodayreport) {
1820 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1823 if ($logreport) {
1824 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1827 if (!empty($CFG->enablestats) && $statsreport) {
1828 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1833 return true;
1837 * This method simply checks to see if a given module can extend the navigation.
1839 * @param string $modname
1840 * @return bool
1842 protected function module_extends_navigation($modname) {
1843 global $CFG;
1844 if ($this->cache->cached($modname.'_extends_navigation')) {
1845 return $this->cache->{$modname.'_extends_navigation'};
1847 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1848 $function = $modname.'_extend_navigation';
1849 if (function_exists($function)) {
1850 $this->cache->{$modname.'_extends_navigation'} = true;
1851 return true;
1852 } else if (file_exists($file)) {
1853 require_once($file);
1854 if (function_exists($function)) {
1855 $this->cache->{$modname.'_extends_navigation'} = true;
1856 return true;
1859 $this->cache->{$modname.'_extends_navigation'} = false;
1860 return false;
1863 * Extends the navigation for the given user.
1865 * @param stdClass $user A user from the database
1867 public function extend_for_user($user) {
1868 $this->extendforuser[] = $user;
1872 * Returns all of the users the navigation is being extended for
1874 * @return array
1876 public function get_extending_users() {
1877 return $this->extendforuser;
1880 * Adds the given course to the navigation structure.
1882 * @param stdClass $course
1883 * @return navigation_node
1885 public function add_course(stdClass $course, $forcegeneric = false) {
1886 global $CFG;
1888 if ($course->id != SITEID) {
1889 if (!$course->visible) {
1890 if (is_role_switched($course->id)) {
1891 // user has to be able to access course in order to switch, let's skip the visibility test here
1892 } else if (!has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
1893 return false;
1898 $issite = ($course->id == SITEID);
1899 $ismycourse = (array_key_exists($course->id, $this->mycourses) && !$forcegeneric);
1900 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories));
1901 $shortname = $course->shortname;
1903 if ($issite) {
1904 $parent = $this;
1905 $url = null;
1906 $shortname = get_string('sitepages');
1907 } else if ($ismycourse) {
1908 $parent = $this->rootnodes['mycourses'];
1909 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1910 } else {
1911 $parent = $this->rootnodes['courses'];
1912 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1915 if ($displaycategories) {
1916 // We need to load the category structure for this course
1917 $categoryfound = false;
1918 if (!empty($course->categorypath)) {
1919 $categories = explode('/', trim($course->categorypath, '/'));
1920 $category = $parent;
1921 while ($category && $categoryid = array_shift($categories)) {
1922 $category = $category->get($categoryid, self::TYPE_CATEGORY);
1924 if ($category instanceof navigation_node) {
1925 $parent = $category;
1926 $categoryfound = true;
1928 if (!$categoryfound && $forcegeneric) {
1929 $this->load_all_categories($course->category);
1930 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1931 $parent = $category;
1932 $categoryfound = true;
1935 } else if (!empty($course->category)) {
1936 $this->load_all_categories($course->category);
1937 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1938 $parent = $category;
1939 $categoryfound = true;
1941 if (!$categoryfound && !$forcegeneric) {
1942 $this->load_all_categories($course->category);
1943 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1944 $parent = $category;
1945 $categoryfound = true;
1951 // We found the course... we can return it now :)
1952 if ($coursenode = $parent->get($course->id, self::TYPE_COURSE)) {
1953 return $coursenode;
1956 $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
1957 $coursenode->nodetype = self::NODETYPE_BRANCH;
1958 $coursenode->hidden = (!$course->visible);
1959 $coursenode->title($course->fullname);
1960 $this->addedcourses[$course->id] = &$coursenode;
1961 if ($ismycourse && !empty($CFG->navshowallcourses)) {
1962 // We need to add this course to the general courses node as well as the
1963 // my courses node, rerun the function with the kill param
1964 $genericcourse = $this->add_course($course, true);
1965 if ($genericcourse->isactive) {
1966 $genericcourse->make_inactive();
1967 $genericcourse->collapse = true;
1968 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
1969 $parent = $genericcourse->parent;
1970 while ($parent && $parent->type == self::TYPE_CATEGORY) {
1971 $parent->collapse = true;
1972 $parent = $parent->parent;
1977 return $coursenode;
1980 * Adds essential course nodes to the navigation for the given course.
1982 * This method adds nodes such as reports, blogs and participants
1984 * @param navigation_node $coursenode
1985 * @param stdClass $course
1986 * @return bool
1988 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1989 global $CFG;
1991 if ($course->id == SITEID) {
1992 return $this->add_front_page_course_essentials($coursenode, $course);
1995 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1996 return true;
1999 //Participants
2000 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2001 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2002 $currentgroup = groups_get_course_group($course, true);
2003 if ($course->id == SITEID) {
2004 $filterselect = '';
2005 } else if ($course->id && !$currentgroup) {
2006 $filterselect = $course->id;
2007 } else {
2008 $filterselect = $currentgroup;
2010 $filterselect = clean_param($filterselect, PARAM_INT);
2011 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2012 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2013 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2014 $participants->add(get_string('blogs','blog'), $blogsurls->out());
2016 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2017 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2019 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2020 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2023 // View course reports
2024 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2025 $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', ''));
2026 $coursereports = get_plugin_list('coursereport');
2027 foreach ($coursereports as $report=>$dir) {
2028 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2029 if (file_exists($libfile)) {
2030 require_once($libfile);
2031 $reportfunction = $report.'_report_extend_navigation';
2032 if (function_exists($report.'_report_extend_navigation')) {
2033 $reportfunction($reportnav, $course, $this->page->context);
2038 return true;
2041 * This generates the the structure of the course that won't be generated when
2042 * the modules and sections are added.
2044 * Things such as the reports branch, the participants branch, blogs... get
2045 * added to the course node by this method.
2047 * @param navigation_node $coursenode
2048 * @param stdClass $course
2049 * @return bool True for successfull generation
2051 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2052 global $CFG;
2054 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2055 return true;
2058 // Hidden node that we use to determine if the front page navigation is loaded.
2059 // This required as there are not other guaranteed nodes that may be loaded.
2060 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2062 //Participants
2063 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2064 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2067 $filterselect = 0;
2069 // Blogs
2070 if (!empty($CFG->bloglevel)
2071 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2072 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2073 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2074 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
2077 // Notes
2078 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2079 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2082 // Tags
2083 if (!empty($CFG->usetags) && isloggedin()) {
2084 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2088 // View course reports
2089 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2090 $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', ''));
2091 $coursereports = get_plugin_list('coursereport');
2092 foreach ($coursereports as $report=>$dir) {
2093 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2094 if (file_exists($libfile)) {
2095 require_once($libfile);
2096 $reportfunction = $report.'_report_extend_navigation';
2097 if (function_exists($report.'_report_extend_navigation')) {
2098 $reportfunction($reportnav, $course, $this->page->context);
2103 return true;
2107 * Clears the navigation cache
2109 public function clear_cache() {
2110 $this->cache->clear();
2114 * Sets an expansion limit for the navigation
2116 * The expansion limit is used to prevent the display of content that has a type
2117 * greater than the provided $type.
2119 * Can be used to ensure things such as activities or activity content don't get
2120 * shown on the navigation.
2121 * They are still generated in order to ensure the navbar still makes sense.
2123 * @param int $type One of navigation_node::TYPE_*
2124 * @return <type>
2126 public function set_expansion_limit($type) {
2127 $nodes = $this->find_all_of_type($type);
2128 foreach ($nodes as &$node) {
2129 // We need to generate the full site node
2130 if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2131 continue;
2133 foreach ($node->children as &$child) {
2134 // We still want to show course reports and participants containers
2135 // or there will be navigation missing.
2136 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2137 continue;
2139 $child->display = false;
2142 return true;
2145 * Attempts to get the navigation with the given key from this nodes children.
2147 * This function only looks at this nodes children, it does NOT look recursivily.
2148 * If the node can't be found then false is returned.
2150 * If you need to search recursivily then use the {@see find()} method.
2152 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2153 * may be of more use to you.
2155 * @param string|int $key The key of the node you wish to receive.
2156 * @param int $type One of navigation_node::TYPE_*
2157 * @return navigation_node|false
2159 public function get($key, $type = null) {
2160 if (!$this->initialised) {
2161 $this->initialise();
2163 return parent::get($key, $type);
2167 * Searches this nodes children and thier children to find a navigation node
2168 * with the matching key and type.
2170 * This method is recursive and searches children so until either a node is
2171 * found of there are no more nodes to search.
2173 * If you know that the node being searched for is a child of this node
2174 * then use the {@see get()} method instead.
2176 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2177 * may be of more use to you.
2179 * @param string|int $key The key of the node you wish to receive.
2180 * @param int $type One of navigation_node::TYPE_*
2181 * @return navigation_node|false
2183 public function find($key, $type) {
2184 if (!$this->initialised) {
2185 $this->initialise();
2187 return parent::find($key, $type);
2192 * The limited global navigation class used for the AJAX extension of the global
2193 * navigation class.
2195 * The primary methods that are used in the global navigation class have been overriden
2196 * to ensure that only the relevant branch is generated at the root of the tree.
2197 * This can be done because AJAX is only used when the backwards structure for the
2198 * requested branch exists.
2199 * This has been done only because it shortens the amounts of information that is generated
2200 * which of course will speed up the response time.. because no one likes laggy AJAX.
2202 * @package moodlecore
2203 * @subpackage navigation
2204 * @copyright 2009 Sam Hemelryk
2205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2207 class global_navigation_for_ajax extends global_navigation {
2209 protected $branchtype;
2210 protected $instanceid;
2212 /** @var array */
2213 protected $expandable = array();
2216 * Constructs the navigation for use in AJAX request
2218 public function __construct($page, $branchtype, $id) {
2219 $this->page = $page;
2220 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2221 $this->children = new navigation_node_collection();
2222 $this->branchtype = $branchtype;
2223 $this->instanceid = $id;
2224 $this->initialise();
2227 * Initialise the navigation given the type and id for the branch to expand.
2229 * @return array The expandable nodes
2231 public function initialise() {
2232 global $CFG, $DB, $SITE;
2234 if ($this->initialised || during_initial_install()) {
2235 return $this->expandable;
2237 $this->initialised = true;
2239 $this->rootnodes = array();
2240 $this->rootnodes['site'] = $this->add_course($SITE);
2241 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2243 // Branchtype will be one of navigation_node::TYPE_*
2244 switch ($this->branchtype) {
2245 case self::TYPE_CATEGORY :
2246 $this->load_all_categories($this->instanceid);
2247 $limit = 20;
2248 if (!empty($CFG->navcourselimit)) {
2249 $limit = (int)$CFG->navcourselimit;
2251 $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
2252 foreach ($courses as $course) {
2253 $this->add_course($course);
2255 break;
2256 case self::TYPE_COURSE :
2257 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2258 require_course_login($course);
2259 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2260 $coursenode = $this->add_course($course);
2261 $this->add_course_essentials($coursenode, $course);
2262 if ($this->format_display_course_content($course->format)) {
2263 $this->load_course_sections($course, $coursenode);
2265 break;
2266 case self::TYPE_SECTION :
2267 $sql = 'SELECT c.*, cs.section AS sectionnumber
2268 FROM {course} c
2269 LEFT JOIN {course_sections} cs ON cs.course = c.id
2270 WHERE cs.id = ?';
2271 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2272 require_course_login($course);
2273 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2274 $coursenode = $this->add_course($course);
2275 $this->add_course_essentials($coursenode, $course);
2276 $sections = $this->load_course_sections($course, $coursenode);
2277 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
2278 break;
2279 case self::TYPE_ACTIVITY :
2280 $sql = "SELECT c.*
2281 FROM {course} c
2282 JOIN {course_modules} cm ON cm.course = c.id
2283 WHERE cm.id = :cmid";
2284 $params = array('cmid' => $this->instanceid);
2285 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2286 $modinfo = get_fast_modinfo($course);
2287 $cm = $modinfo->get_cm($this->instanceid);
2288 require_course_login($course, true, $cm);
2289 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2290 $coursenode = $this->load_course($course);
2291 if ($course->id == SITEID) {
2292 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2293 } else {
2294 $sections = $this->load_course_sections($course, $coursenode);
2295 $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, get_fast_modinfo($course));
2296 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2298 break;
2299 default:
2300 throw new Exception('Unknown type');
2301 return $this->expandable;
2304 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2305 $this->load_for_user(null, true);
2308 $this->find_expandable($this->expandable);
2309 return $this->expandable;
2313 * Returns an array of expandable nodes
2314 * @return array
2316 public function get_expandable() {
2317 return $this->expandable;
2322 * Navbar class
2324 * This class is used to manage the navbar, which is initialised from the navigation
2325 * object held by PAGE
2327 * @package moodlecore
2328 * @subpackage navigation
2329 * @copyright 2009 Sam Hemelryk
2330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2332 class navbar extends navigation_node {
2333 /** @var bool */
2334 protected $initialised = false;
2335 /** @var mixed */
2336 protected $keys = array();
2337 /** @var null|string */
2338 protected $content = null;
2339 /** @var moodle_page object */
2340 protected $page;
2341 /** @var bool */
2342 protected $ignoreactive = false;
2343 /** @var bool */
2344 protected $duringinstall = false;
2345 /** @var bool */
2346 protected $hasitems = false;
2347 /** @var array */
2348 protected $items;
2349 /** @var array */
2350 public $children = array();
2351 /** @var bool */
2352 public $includesettingsbase = false;
2354 * The almighty constructor
2356 * @param moodle_page $page
2358 public function __construct(moodle_page $page) {
2359 global $CFG;
2360 if (during_initial_install()) {
2361 $this->duringinstall = true;
2362 return false;
2364 $this->page = $page;
2365 $this->text = get_string('home');
2366 $this->shorttext = get_string('home');
2367 $this->action = new moodle_url($CFG->wwwroot);
2368 $this->nodetype = self::NODETYPE_BRANCH;
2369 $this->type = self::TYPE_SYSTEM;
2373 * Quick check to see if the navbar will have items in.
2375 * @return bool Returns true if the navbar will have items, false otherwise
2377 public function has_items() {
2378 if ($this->duringinstall) {
2379 return false;
2380 } else if ($this->hasitems !== false) {
2381 return true;
2383 $this->page->navigation->initialise($this->page);
2385 $activenodefound = ($this->page->navigation->contains_active_node() ||
2386 $this->page->settingsnav->contains_active_node());
2388 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2389 $this->hasitems = $outcome;
2390 return $outcome;
2394 * Turn on/off ignore active
2396 * @param bool $setting
2398 public function ignore_active($setting=true) {
2399 $this->ignoreactive = ($setting);
2401 public function get($key, $type = null) {
2402 foreach ($this->children as &$child) {
2403 if ($child->key === $key && ($type == null || $type == $child->type)) {
2404 return $child;
2407 return false;
2410 * Returns an array of navigation_node's that make up the navbar.
2412 * @return array
2414 public function get_items() {
2415 $items = array();
2416 // Make sure that navigation is initialised
2417 if (!$this->has_items()) {
2418 return $items;
2420 if ($this->items !== null) {
2421 return $this->items;
2424 if (count($this->children) > 0) {
2425 // Add the custom children
2426 $items = array_reverse($this->children);
2429 $navigationactivenode = $this->page->navigation->find_active_node();
2430 $settingsactivenode = $this->page->settingsnav->find_active_node();
2432 // Check if navigation contains the active node
2433 if (!$this->ignoreactive) {
2435 if ($navigationactivenode && $settingsactivenode) {
2436 // Parse a combined navigation tree
2437 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2438 if (!$settingsactivenode->mainnavonly) {
2439 $items[] = $settingsactivenode;
2441 $settingsactivenode = $settingsactivenode->parent;
2443 if (!$this->includesettingsbase) {
2444 // Removes the first node from the settings (root node) from the list
2445 array_pop($items);
2447 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2448 if (!$navigationactivenode->mainnavonly) {
2449 $items[] = $navigationactivenode;
2451 $navigationactivenode = $navigationactivenode->parent;
2453 } else if ($navigationactivenode) {
2454 // Parse the navigation tree to get the active node
2455 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2456 if (!$navigationactivenode->mainnavonly) {
2457 $items[] = $navigationactivenode;
2459 $navigationactivenode = $navigationactivenode->parent;
2461 } else if ($settingsactivenode) {
2462 // Parse the settings navigation to get the active node
2463 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2464 if (!$settingsactivenode->mainnavonly) {
2465 $items[] = $settingsactivenode;
2467 $settingsactivenode = $settingsactivenode->parent;
2472 $items[] = new navigation_node(array(
2473 'text'=>$this->page->navigation->text,
2474 'shorttext'=>$this->page->navigation->shorttext,
2475 'key'=>$this->page->navigation->key,
2476 'action'=>$this->page->navigation->action
2479 $this->items = array_reverse($items);
2480 return $this->items;
2484 * Add a new navigation_node to the navbar, overrides parent::add
2486 * This function overrides {@link navigation_node::add()} so that we can change
2487 * the way nodes get added to allow us to simply call add and have the node added to the
2488 * end of the navbar
2490 * @param string $text
2491 * @param string|moodle_url $action
2492 * @param int $type
2493 * @param string|int $key
2494 * @param string $shorttext
2495 * @param string $icon
2496 * @return navigation_node
2498 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2499 if ($this->content !== null) {
2500 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2503 // Properties array used when creating the new navigation node
2504 $itemarray = array(
2505 'text' => $text,
2506 'type' => $type
2508 // Set the action if one was provided
2509 if ($action!==null) {
2510 $itemarray['action'] = $action;
2512 // Set the shorttext if one was provided
2513 if ($shorttext!==null) {
2514 $itemarray['shorttext'] = $shorttext;
2516 // Set the icon if one was provided
2517 if ($icon!==null) {
2518 $itemarray['icon'] = $icon;
2520 // Default the key to the number of children if not provided
2521 if ($key === null) {
2522 $key = count($this->children);
2524 // Set the key
2525 $itemarray['key'] = $key;
2526 // Set the parent to this node
2527 $itemarray['parent'] = $this;
2528 // Add the child using the navigation_node_collections add method
2529 $this->children[] = new navigation_node($itemarray);
2530 return $this;
2535 * Class used to manage the settings option for the current page
2537 * This class is used to manage the settings options in a tree format (recursively)
2538 * and was created initially for use with the settings blocks.
2540 * @package moodlecore
2541 * @subpackage navigation
2542 * @copyright 2009 Sam Hemelryk
2543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2545 class settings_navigation extends navigation_node {
2546 /** @var stdClass */
2547 protected $context;
2548 /** @var navigation_cache */
2549 protected $cache;
2550 /** @var moodle_page */
2551 protected $page;
2552 /** @var string */
2553 protected $adminsection;
2554 /** @var bool */
2555 protected $initialised = false;
2556 /** @var array */
2557 protected $userstoextendfor = array();
2560 * Sets up the object with basic settings and preparse it for use
2562 * @param moodle_page $page
2564 public function __construct(moodle_page &$page) {
2565 if (during_initial_install()) {
2566 return false;
2568 $this->page = $page;
2569 // Initialise the main navigation. It is most important that this is done
2570 // before we try anything
2571 $this->page->navigation->initialise();
2572 // Initialise the navigation cache
2573 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2574 $this->children = new navigation_node_collection();
2577 * Initialise the settings navigation based on the current context
2579 * This function initialises the settings navigation tree for a given context
2580 * by calling supporting functions to generate major parts of the tree.
2583 public function initialise() {
2584 global $DB, $SESSION;
2586 if (during_initial_install()) {
2587 return false;
2588 } else if ($this->initialised) {
2589 return true;
2591 $this->id = 'settingsnav';
2592 $this->context = $this->page->context;
2594 $context = $this->context;
2595 if ($context->contextlevel == CONTEXT_BLOCK) {
2596 $this->load_block_settings();
2597 $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));
2600 switch ($context->contextlevel) {
2601 case CONTEXT_SYSTEM:
2602 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2603 $this->load_front_page_settings(($context->id == $this->context->id));
2605 break;
2606 case CONTEXT_COURSECAT:
2607 $this->load_category_settings();
2608 break;
2609 case CONTEXT_COURSE:
2610 if ($this->page->course->id != SITEID) {
2611 $this->load_course_settings(($context->id == $this->context->id));
2612 } else {
2613 $this->load_front_page_settings(($context->id == $this->context->id));
2615 break;
2616 case CONTEXT_MODULE:
2617 $this->load_module_settings();
2618 $this->load_course_settings();
2619 break;
2620 case CONTEXT_USER:
2621 if ($this->page->course->id != SITEID) {
2622 $this->load_course_settings();
2624 break;
2627 $settings = $this->load_user_settings($this->page->course->id);
2629 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
2630 $admin = $this->load_administration_settings();
2631 $SESSION->load_navigation_admin = ($admin->has_children());
2632 } else {
2633 $admin = false;
2636 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2637 $admin->force_open();
2638 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2639 $settings->force_open();
2642 // Check if the user is currently logged in as another user
2643 if (session_is_loggedinas()) {
2644 // Get the actual user, we need this so we can display an informative return link
2645 $realuser = session_get_realuser();
2646 // Add the informative return to original user link
2647 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2648 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2651 foreach ($this->children as $key=>$node) {
2652 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2653 $node->remove();
2656 $this->initialised = true;
2659 * Override the parent function so that we can add preceeding hr's and set a
2660 * root node class against all first level element
2662 * It does this by first calling the parent's add method {@link navigation_node::add()}
2663 * and then proceeds to use the key to set class and hr
2665 * @param string $text
2666 * @param sting|moodle_url $url
2667 * @param string $shorttext
2668 * @param string|int $key
2669 * @param int $type
2670 * @param string $icon
2671 * @return navigation_node
2673 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2674 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2675 $node->add_class('root_node');
2676 return $node;
2680 * This function allows the user to add something to the start of the settings
2681 * navigation, which means it will be at the top of the settings navigation block
2683 * @param string $text
2684 * @param sting|moodle_url $url
2685 * @param string $shorttext
2686 * @param string|int $key
2687 * @param int $type
2688 * @param string $icon
2689 * @return navigation_node
2691 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2692 $children = $this->children;
2693 $childrenclass = get_class($children);
2694 $this->children = new $childrenclass;
2695 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2696 foreach ($children as $child) {
2697 $this->children->add($child);
2699 return $node;
2702 * Load the site administration tree
2704 * This function loads the site administration tree by using the lib/adminlib library functions
2706 * @param navigation_node $referencebranch A reference to a branch in the settings
2707 * navigation tree
2708 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2709 * tree and start at the beginning
2710 * @return mixed A key to access the admin tree by
2712 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2713 global $CFG;
2715 // Check if we are just starting to generate this navigation.
2716 if ($referencebranch === null) {
2718 // Require the admin lib then get an admin structure
2719 if (!function_exists('admin_get_root')) {
2720 require_once($CFG->dirroot.'/lib/adminlib.php');
2722 $adminroot = admin_get_root(false, false);
2723 // This is the active section identifier
2724 $this->adminsection = $this->page->url->param('section');
2726 // Disable the navigation from automatically finding the active node
2727 navigation_node::$autofindactive = false;
2728 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2729 foreach ($adminroot->children as $adminbranch) {
2730 $this->load_administration_settings($referencebranch, $adminbranch);
2732 navigation_node::$autofindactive = true;
2734 // Use the admin structure to locate the active page
2735 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2736 $currentnode = $this;
2737 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2738 $currentnode = $currentnode->get($pathkey);
2740 if ($currentnode) {
2741 $currentnode->make_active();
2743 } else {
2744 $this->scan_for_active_node($referencebranch);
2746 return $referencebranch;
2747 } else if ($adminbranch->check_access()) {
2748 // We have a reference branch that we can access and is not hidden `hurrah`
2749 // Now we need to display it and any children it may have
2750 $url = null;
2751 $icon = null;
2752 if ($adminbranch instanceof admin_settingpage) {
2753 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2754 } else if ($adminbranch instanceof admin_externalpage) {
2755 $url = $adminbranch->url;
2758 // Add the branch
2759 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2761 if ($adminbranch->is_hidden()) {
2762 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2763 $reference->add_class('hidden');
2764 } else {
2765 $reference->display = false;
2769 // Check if we are generating the admin notifications and whether notificiations exist
2770 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2771 $reference->add_class('criticalnotification');
2773 // Check if this branch has children
2774 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2775 foreach ($adminbranch->children as $branch) {
2776 // Generate the child branches as well now using this branch as the reference
2777 $this->load_administration_settings($reference, $branch);
2779 } else {
2780 $reference->icon = new pix_icon('i/settings', '');
2786 * This function recursivily scans nodes until it finds the active node or there
2787 * are no more nodes.
2788 * @param navigation_node $node
2790 protected function scan_for_active_node(navigation_node $node) {
2791 if (!$node->check_if_active() && $node->children->count()>0) {
2792 foreach ($node->children as &$child) {
2793 $this->scan_for_active_node($child);
2799 * Gets a navigation node given an array of keys that represent the path to
2800 * the desired node.
2802 * @param array $path
2803 * @return navigation_node|false
2805 protected function get_by_path(array $path) {
2806 $node = $this->get(array_shift($path));
2807 foreach ($path as $key) {
2808 $node->get($key);
2810 return $node;
2814 * Generate the list of modules for the given course.
2816 * The array of resources and activities that can be added to a course is then
2817 * stored in the cache so that we can access it for anywhere.
2818 * It saves us generating it all the time
2820 * <code php>
2821 * // To get resources:
2822 * $this->cache->{'course'.$courseid.'resources'}
2823 * // To get activities:
2824 * $this->cache->{'course'.$courseid.'activities'}
2825 * </code>
2827 * @param stdClass $course The course to get modules for
2829 protected function get_course_modules($course) {
2830 global $CFG;
2831 $mods = $modnames = $modnamesplural = $modnamesused = array();
2832 // This function is included when we include course/lib.php at the top
2833 // of this file
2834 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2835 $resources = array();
2836 $activities = array();
2837 foreach($modnames as $modname=>$modnamestr) {
2838 if (!course_allowed_module($course, $modname)) {
2839 continue;
2842 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2843 if (!file_exists($libfile)) {
2844 continue;
2846 include_once($libfile);
2847 $gettypesfunc = $modname.'_get_types';
2848 if (function_exists($gettypesfunc)) {
2849 $types = $gettypesfunc();
2850 foreach($types as $type) {
2851 if (!isset($type->modclass) || !isset($type->typestr)) {
2852 debugging('Incorrect activity type in '.$modname);
2853 continue;
2855 if ($type->modclass == MOD_CLASS_RESOURCE) {
2856 $resources[html_entity_decode($type->type)] = $type->typestr;
2857 } else {
2858 $activities[html_entity_decode($type->type)] = $type->typestr;
2861 } else {
2862 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2863 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2864 $resources[$modname] = $modnamestr;
2865 } else {
2866 // all other archetypes are considered activity
2867 $activities[$modname] = $modnamestr;
2871 $this->cache->{'course'.$course->id.'resources'} = $resources;
2872 $this->cache->{'course'.$course->id.'activities'} = $activities;
2876 * This function loads the course settings that are available for the user
2878 * @param bool $forceopen If set to true the course node will be forced open
2879 * @return navigation_node|false
2881 protected function load_course_settings($forceopen = false) {
2882 global $CFG, $USER, $SESSION, $OUTPUT;
2884 $course = $this->page->course;
2885 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2887 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
2889 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2890 if ($forceopen) {
2891 $coursenode->force_open();
2894 if (has_capability('moodle/course:update', $coursecontext)) {
2895 // Add the turn on/off settings
2896 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2897 if ($this->page->user_is_editing()) {
2898 $url->param('edit', 'off');
2899 $editstring = get_string('turneditingoff');
2900 } else {
2901 $url->param('edit', 'on');
2902 $editstring = get_string('turneditingon');
2904 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2906 if ($this->page->user_is_editing()) {
2907 // Removed as per MDL-22732
2908 // $this->add_course_editing_links($course);
2911 // Add the course settings link
2912 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2913 $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2915 // Add the course completion settings link
2916 if ($CFG->enablecompletion && $course->enablecompletion) {
2917 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2918 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2922 // add enrol nodes
2923 enrol_add_course_navigation($coursenode, $course);
2925 // Manage filters
2926 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2927 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2928 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2931 // Add view grade report is permitted
2932 $reportavailable = false;
2933 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2934 $reportavailable = true;
2935 } else if (!empty($course->showgrades)) {
2936 $reports = get_plugin_list('gradereport');
2937 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2938 arsort($reports); // user is last, we want to test it first
2939 foreach ($reports as $plugin => $plugindir) {
2940 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2941 //stop when the first visible plugin is found
2942 $reportavailable = true;
2943 break;
2948 if ($reportavailable) {
2949 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2950 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
2953 // Add outcome if permitted
2954 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2955 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2956 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
2959 // Backup this course
2960 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2961 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2962 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
2965 // Restore to this course
2966 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2967 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
2968 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
2971 // Import data from other courses
2972 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2973 $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
2974 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
2977 // Publish course on a hub
2978 if (has_capability('moodle/course:publish', $coursecontext)) {
2979 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2980 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
2983 // Reset this course
2984 if (has_capability('moodle/course:reset', $coursecontext)) {
2985 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2986 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2989 // Questions
2990 require_once($CFG->dirroot.'/question/editlib.php');
2991 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
2993 // Repository Instances
2994 require_once($CFG->dirroot.'/repository/lib.php');
2995 $editabletypes = repository::get_editable_types($coursecontext);
2996 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2997 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id));
2998 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3001 // Manage files
3002 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3003 // hidden in new courses and courses where legacy files were turned off
3004 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3005 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3008 // Switch roles
3009 $roles = array();
3010 $assumedrole = $this->in_alternative_role();
3011 if ($assumedrole!==false) {
3012 $roles[0] = get_string('switchrolereturn');
3014 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3015 $availableroles = get_switchable_roles($coursecontext);
3016 if (is_array($availableroles)) {
3017 foreach ($availableroles as $key=>$role) {
3018 if ($assumedrole == (int)$key) {
3019 continue;
3021 $roles[$key] = $role;
3025 if (is_array($roles) && count($roles)>0) {
3026 $switchroles = $this->add(get_string('switchroleto'));
3027 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3028 $switchroles->force_open();
3030 $returnurl = $this->page->url;
3031 $returnurl->param('sesskey', sesskey());
3032 $SESSION->returnurl = serialize($returnurl);
3033 foreach ($roles as $key=>$name) {
3034 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
3035 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
3038 // Return we are done
3039 return $coursenode;
3043 * Adds branches and links to the settings navigation to add course activities
3044 * and resources.
3046 * @param stdClass $course
3048 protected function add_course_editing_links($course) {
3049 global $CFG;
3051 require_once($CFG->dirroot.'/course/lib.php');
3053 // Add `add` resources|activities branches
3054 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3055 if (file_exists($structurefile)) {
3056 require_once($structurefile);
3057 $requestkey = call_user_func('callback_'.$course->format.'_request_key');
3058 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3059 } else {
3060 $requestkey = get_string('section');
3061 $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3064 $sections = get_all_sections($course->id);
3066 $addresource = $this->add(get_string('addresource'));
3067 $addactivity = $this->add(get_string('addactivity'));
3068 if ($formatidentifier!==0) {
3069 $addresource->force_open();
3070 $addactivity->force_open();
3073 if (!$this->cache->cached('course'.$course->id.'resources')) {
3074 $this->get_course_modules($course);
3076 $resources = $this->cache->{'course'.$course->id.'resources'};
3077 $activities = $this->cache->{'course'.$course->id.'activities'};
3079 $textlib = textlib_get_instance();
3081 foreach ($sections as $section) {
3082 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
3083 continue;
3085 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $requestkey=>$section->section));
3086 if ($section->section == 0) {
3087 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3088 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3089 } else {
3090 $sectionname = get_section_name($course, $section);
3091 $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING);
3092 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING);
3094 foreach ($resources as $value=>$resource) {
3095 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3096 $pos = strpos($value, '&type=');
3097 if ($pos!==false) {
3098 $url->param('add', $textlib->substr($value, 0,$pos));
3099 $url->param('type', $textlib->substr($value, $pos+6));
3100 } else {
3101 $url->param('add', $value);
3103 $sectionresources->add($resource, $url, self::TYPE_SETTING);
3105 $subbranch = false;
3106 foreach ($activities as $activityname=>$activity) {
3107 if ($activity==='--') {
3108 $subbranch = false;
3109 continue;
3111 if (strpos($activity, '--')===0) {
3112 $subbranch = $sectionactivities->add(trim($activity, '-'));
3113 continue;
3115 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3116 $pos = strpos($activityname, '&type=');
3117 if ($pos!==false) {
3118 $url->param('add', $textlib->substr($activityname, 0,$pos));
3119 $url->param('type', $textlib->substr($activityname, $pos+6));
3120 } else {
3121 $url->param('add', $activityname);
3123 if ($subbranch !== false) {
3124 $subbranch->add($activity, $url, self::TYPE_SETTING);
3125 } else {
3126 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3133 * This function calls the module function to inject module settings into the
3134 * settings navigation tree.
3136 * This only gets called if there is a corrosponding function in the modules
3137 * lib file.
3139 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3141 * @return navigation_node|false
3143 protected function load_module_settings() {
3144 global $CFG;
3146 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3147 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3148 $this->page->set_cm($cm, $this->page->course);
3151 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3152 if (file_exists($file)) {
3153 require_once($file);
3156 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3157 $modulenode->force_open();
3159 // Settings for the module
3160 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3161 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3162 $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING);
3164 // Assign local roles
3165 if (count(get_assignable_roles($this->page->cm->context))>0) {
3166 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3167 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
3169 // Override roles
3170 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3171 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3172 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3174 // Check role permissions
3175 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3176 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3177 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3179 // Manage filters
3180 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3181 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3182 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
3185 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
3186 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
3187 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING);
3190 // Add a backup link
3191 $featuresfunc = $this->page->activityname.'_supports';
3192 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3193 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3194 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
3197 // Restore this activity
3198 $featuresfunc = $this->page->activityname.'_supports';
3199 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3200 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3201 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING);
3204 $function = $this->page->activityname.'_extend_settings_navigation';
3205 if (!function_exists($function)) {
3206 return $modulenode;
3209 $function($this, $modulenode);
3211 // Remove the module node if there are no children
3212 if (empty($modulenode->children)) {
3213 $modulenode->remove();
3216 return $modulenode;
3220 * Loads the user settings block of the settings nav
3222 * This function is simply works out the userid and whether we need to load
3223 * just the current users profile settings, or the current user and the user the
3224 * current user is viewing.
3226 * This function has some very ugly code to work out the user, if anyone has
3227 * any bright ideas please feel free to intervene.
3229 * @param int $courseid The course id of the current course
3230 * @return navigation_node|false
3232 protected function load_user_settings($courseid=SITEID) {
3233 global $USER, $FULLME, $CFG;
3235 if (isguestuser() || !isloggedin()) {
3236 return false;
3239 $navusers = $this->page->navigation->get_extending_users();
3241 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3242 $usernode = null;
3243 foreach ($this->userstoextendfor as $userid) {
3244 if ($userid == $USER->id) {
3245 continue;
3247 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3248 if (is_null($usernode)) {
3249 $usernode = $node;
3252 foreach ($navusers as $user) {
3253 if ($user->id == $USER->id) {
3254 continue;
3256 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3257 if (is_null($usernode)) {
3258 $usernode = $node;
3261 $this->generate_user_settings($courseid, $USER->id);
3262 } else {
3263 $usernode = $this->generate_user_settings($courseid, $USER->id);
3265 return $usernode;
3269 * Extends the settings navigation for the given user.
3271 * Note: This method gets called automatically if you call
3272 * $PAGE->navigation->extend_for_user($userid)
3274 * @param int $userid
3276 public function extend_for_user($userid) {
3277 global $CFG;
3279 if (!in_array($userid, $this->userstoextendfor)) {
3280 $this->userstoextendfor[] = $userid;
3281 if ($this->initialised) {
3282 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3283 $children = array();
3284 foreach ($this->children as $child) {
3285 $children[] = $child;
3287 array_unshift($children, array_pop($children));
3288 $this->children = new navigation_node_collection();
3289 foreach ($children as $child) {
3290 $this->children->add($child);
3297 * This function gets called by {@link load_user_settings()} and actually works out
3298 * what can be shown/done
3300 * @param int $courseid The current course' id
3301 * @param int $userid The user id to load for
3302 * @param string $gstitle The string to pass to get_string for the branch title
3303 * @return navigation_node|false
3305 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3306 global $DB, $CFG, $USER, $SITE;
3308 if ($courseid != SITEID) {
3309 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3310 $course = $this->page->course;
3311 } else {
3312 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
3314 } else {
3315 $course = $SITE;
3318 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3319 $systemcontext = get_system_context();
3320 $currentuser = ($USER->id == $userid);
3322 if ($currentuser) {
3323 $user = $USER;
3324 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3325 } else {
3326 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
3327 return false;
3329 // Check that the user can view the profile
3330 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3331 if ($course->id==SITEID) {
3332 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3333 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3334 return false;
3336 } else {
3337 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !can_access_course($coursecontext, $user->id)) {
3338 return false;
3340 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3341 // If groups are in use, make sure we can see that group
3342 return false;
3347 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3349 $key = $gstitle;
3350 if ($gstitle != 'usercurrentsettings') {
3351 $key .= $userid;
3354 // Add a user setting branch
3355 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3356 $usersetting->id = 'usersettings';
3357 if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3358 // Automatically start by making it active
3359 $usersetting->make_active();
3362 // Check if the user has been deleted
3363 if ($user->deleted) {
3364 if (!has_capability('moodle/user:update', $coursecontext)) {
3365 // We can't edit the user so just show the user deleted message
3366 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3367 } else {
3368 // We can edit the user so show the user deleted message and link it to the profile
3369 if ($course->id == SITEID) {
3370 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3371 } else {
3372 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3374 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3376 return true;
3379 // Add the profile edit link
3380 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3381 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3382 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3383 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3384 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3385 if (!empty($user->auth)) {
3386 $userauth = get_auth_plugin($user->auth);
3387 if ($userauth->can_edit_profile()) {
3388 $url = $userauth->edit_profile_url();
3389 if (empty($url)) {
3390 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3392 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3398 // Change password link
3399 if (!empty($user->auth)) {
3400 $userauth = get_auth_plugin($user->auth);
3401 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3402 $passwordchangeurl = $userauth->change_password_url();
3403 if (empty($passwordchangeurl)) {
3404 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3406 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3410 // View the roles settings
3411 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3412 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3414 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3415 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3417 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3419 if (!empty($assignableroles)) {
3420 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3421 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3424 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3425 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3426 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3429 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3430 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3433 // Portfolio
3434 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3435 require_once($CFG->libdir . '/portfoliolib.php');
3436 if (portfolio_instances(true, false)) {
3437 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3439 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3440 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3442 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3443 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3447 $enablemanagetokens = false;
3448 if (!empty($CFG->enablerssfeeds)) {
3449 $enablemanagetokens = true;
3450 } else if (!is_siteadmin($USER->id)
3451 && !empty($CFG->enablewebservices)
3452 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3453 $enablemanagetokens = true;
3455 // Security keys
3456 if ($currentuser && $enablemanagetokens) {
3457 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3458 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3461 // Repository
3462 if (!$currentuser) {
3463 require_once($CFG->dirroot . '/repository/lib.php');
3464 $editabletypes = repository::get_editable_types($usercontext);
3465 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
3466 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3467 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3471 // Messaging
3472 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
3473 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3474 // Hide the node if messaging disabled
3475 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING)->display = !empty($CFG->messaging);
3478 // Blogs
3479 if ($currentuser && !empty($CFG->bloglevel)) {
3480 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3481 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3482 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
3483 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3484 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3488 // Login as ...
3489 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3490 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3491 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3494 return $usersetting;
3498 * Loads block specific settings in the navigation
3500 * @return navigation_node
3502 protected function load_block_settings() {
3503 global $CFG;
3505 $blocknode = $this->add(print_context_name($this->context));
3506 $blocknode->force_open();
3508 // Assign local roles
3509 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3510 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3512 // Override roles
3513 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3514 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3515 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3517 // Check role permissions
3518 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3519 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3520 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3523 return $blocknode;
3527 * Loads category specific settings in the navigation
3529 * @return navigation_node
3531 protected function load_category_settings() {
3532 global $CFG;
3534 $categorynode = $this->add(print_context_name($this->context));
3535 $categorynode->force_open();
3537 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
3538 $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
3539 if ($this->page->user_is_editing()) {
3540 $url->param('categoryedit', '0');
3541 $editstring = get_string('turneditingoff');
3542 } else {
3543 $url->param('categoryedit', '1');
3544 $editstring = get_string('turneditingon');
3546 $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3549 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
3550 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
3551 $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
3553 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
3554 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
3557 // Assign local roles
3558 if (has_capability('moodle/role:assign', $this->context)) {
3559 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3560 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
3563 // Override roles
3564 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3565 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3566 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
3568 // Check role permissions
3569 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3570 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3571 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
3574 // Cohorts
3575 if (has_capability('moodle/cohort:manage', $this->context) or has_capability('moodle/cohort:view', $this->context)) {
3576 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', array('contextid' => $this->context->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', ''));
3579 // Manage filters
3580 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
3581 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
3582 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
3585 return $categorynode;
3589 * Determine whether the user is assuming another role
3591 * This function checks to see if the user is assuming another role by means of
3592 * role switching. In doing this we compare each RSW key (context path) against
3593 * the current context path. This ensures that we can provide the switching
3594 * options against both the course and any page shown under the course.
3596 * @return bool|int The role(int) if the user is in another role, false otherwise
3598 protected function in_alternative_role() {
3599 global $USER;
3600 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
3601 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
3602 return $USER->access['rsw'][$this->page->context->path];
3604 foreach ($USER->access['rsw'] as $key=>$role) {
3605 if (strpos($this->context->path,$key)===0) {
3606 return $role;
3610 return false;
3614 * This function loads all of the front page settings into the settings navigation.
3615 * This function is called when the user is on the front page, or $COURSE==$SITE
3616 * @return navigation_node
3618 protected function load_front_page_settings($forceopen = false) {
3619 global $SITE, $CFG;
3621 $course = clone($SITE);
3622 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3624 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
3625 if ($forceopen) {
3626 $frontpage->force_open();
3628 $frontpage->id = 'frontpagesettings';
3630 if (has_capability('moodle/course:update', $coursecontext)) {
3632 // Add the turn on/off settings
3633 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
3634 if ($this->page->user_is_editing()) {
3635 $url->param('edit', 'off');
3636 $editstring = get_string('turneditingoff');
3637 } else {
3638 $url->param('edit', 'on');
3639 $editstring = get_string('turneditingon');
3641 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3643 // Add the course settings link
3644 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
3645 $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3648 // add enrol nodes
3649 enrol_add_course_navigation($frontpage, $course);
3651 // Manage filters
3652 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3653 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3654 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3657 // Backup this course
3658 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3659 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3660 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
3663 // Restore to this course
3664 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3665 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3666 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
3669 // Manage questions
3670 $questioncaps = array('moodle/question:add',
3671 'moodle/question:editmine',
3672 'moodle/question:editall',
3673 'moodle/question:viewmine',
3674 'moodle/question:viewall',
3675 'moodle/question:movemine',
3676 'moodle/question:moveall');
3677 if (has_any_capability($questioncaps, $this->context)) {
3678 $questionlink = $CFG->wwwroot.'/question/edit.php';
3679 } else if (has_capability('moodle/question:managecategory', $this->context)) {
3680 $questionlink = $CFG->wwwroot.'/question/category.php';
3682 if (isset($questionlink)) {
3683 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
3684 $frontpage->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
3687 // Manage files
3688 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
3689 //hiden in new installs
3690 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
3691 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
3693 return $frontpage;
3697 * This function marks the cache as volatile so it is cleared during shutdown
3699 public function clear_cache() {
3700 $this->cache->volatile();
3705 * Simple class used to output a navigation branch in XML
3707 * @package moodlecore
3708 * @subpackage navigation
3709 * @copyright 2009 Sam Hemelryk
3710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3712 class navigation_json {
3713 /** @var array */
3714 protected $nodetype = array('node','branch');
3715 /** @var array */
3716 protected $expandable = array();
3718 * Turns a branch and all of its children into XML
3720 * @param navigation_node $branch
3721 * @return string XML string
3723 public function convert($branch) {
3724 $xml = $this->convert_child($branch);
3725 return $xml;
3728 * Set the expandable items in the array so that we have enough information
3729 * to attach AJAX events
3730 * @param array $expandable
3732 public function set_expandable($expandable) {
3733 foreach ($expandable as $node) {
3734 $this->expandable[$node['key'].':'.$node['type']] = $node;
3738 * Recusively converts a child node and its children to XML for output
3740 * @param navigation_node $child The child to convert
3741 * @param int $depth Pointlessly used to track the depth of the XML structure
3742 * @return string JSON
3744 protected function convert_child($child, $depth=1) {
3745 global $OUTPUT;
3747 if (!$child->display) {
3748 return '';
3750 $attributes = array();
3751 $attributes['id'] = $child->id;
3752 $attributes['name'] = $child->text;
3753 $attributes['type'] = $child->type;
3754 $attributes['key'] = $child->key;
3755 $attributes['class'] = $child->get_css_type();
3757 if ($child->icon instanceof pix_icon) {
3758 $attributes['icon'] = array(
3759 'component' => $child->icon->component,
3760 'pix' => $child->icon->pix,
3762 foreach ($child->icon->attributes as $key=>$value) {
3763 if ($key == 'class') {
3764 $attributes['icon']['classes'] = explode(' ', $value);
3765 } else if (!array_key_exists($key, $attributes['icon'])) {
3766 $attributes['icon'][$key] = $value;
3770 } else if (!empty($child->icon)) {
3771 $attributes['icon'] = (string)$child->icon;
3774 if ($child->forcetitle || $child->title !== $child->text) {
3775 $attributes['title'] = htmlentities($child->title);
3777 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
3778 $attributes['expandable'] = $child->key;
3779 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
3782 if (count($child->classes)>0) {
3783 $attributes['class'] .= ' '.join(' ',$child->classes);
3785 if (is_string($child->action)) {
3786 $attributes['link'] = $child->action;
3787 } else if ($child->action instanceof moodle_url) {
3788 $attributes['link'] = $child->action->out();
3790 $attributes['hidden'] = ($child->hidden);
3791 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
3793 if (count($child->children)>0) {
3794 $attributes['children'] = array();
3795 foreach ($child->children as $subchild) {
3796 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
3800 if ($depth > 1) {
3801 return $attributes;
3802 } else {
3803 return json_encode($attributes);
3809 * The cache class used by global navigation and settings navigation to cache bits
3810 * and bobs that are used during their generation.
3812 * It is basically an easy access point to session with a bit of smarts to make
3813 * sure that the information that is cached is valid still.
3815 * Example use:
3816 * <code php>
3817 * if (!$cache->viewdiscussion()) {
3818 * // Code to do stuff and produce cachable content
3819 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3821 * $content = $cache->viewdiscussion;
3822 * </code>
3824 * @package moodlecore
3825 * @subpackage navigation
3826 * @copyright 2009 Sam Hemelryk
3827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3829 class navigation_cache {
3830 /** @var int */
3831 protected $creation;
3832 /** @var array */
3833 protected $session;
3834 /** @var string */
3835 protected $area;
3836 /** @var int */
3837 protected $timeout;
3838 /** @var stdClass */
3839 protected $currentcontext;
3840 /** @var int */
3841 const CACHETIME = 0;
3842 /** @var int */
3843 const CACHEUSERID = 1;
3844 /** @var int */
3845 const CACHEVALUE = 2;
3846 /** @var null|array An array of navigation cache areas to expire on shutdown */
3847 public static $volatilecaches;
3850 * Contructor for the cache. Requires two arguments
3852 * @param string $area The string to use to segregate this particular cache
3853 * it can either be unique to start a fresh cache or if you want
3854 * to share a cache then make it the string used in the original
3855 * cache
3856 * @param int $timeout The number of seconds to time the information out after
3858 public function __construct($area, $timeout=60) {
3859 global $SESSION;
3860 $this->creation = time();
3861 $this->area = $area;
3863 if (!isset($SESSION->navcache)) {
3864 $SESSION->navcache = new stdClass;
3867 if (!isset($SESSION->navcache->{$area})) {
3868 $SESSION->navcache->{$area} = array();
3870 $this->session = &$SESSION->navcache->{$area};
3871 $this->timeout = time()-$timeout;
3872 if (rand(0,10)===0) {
3873 $this->garbage_collection();
3878 * Magic Method to retrieve something by simply calling using = cache->key
3880 * @param mixed $key The identifier for the information you want out again
3881 * @return void|mixed Either void or what ever was put in
3883 public function __get($key) {
3884 if (!$this->cached($key)) {
3885 return;
3887 $information = $this->session[$key][self::CACHEVALUE];
3888 return unserialize($information);
3892 * Magic method that simply uses {@link set();} to store something in the cache
3894 * @param string|int $key
3895 * @param mixed $information
3897 public function __set($key, $information) {
3898 $this->set($key, $information);
3902 * Sets some information against the cache (session) for later retrieval
3904 * @param string|int $key
3905 * @param mixed $information
3907 public function set($key, $information) {
3908 global $USER;
3909 $information = serialize($information);
3910 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
3913 * Check the existence of the identifier in the cache
3915 * @param string|int $key
3916 * @return bool
3918 public function cached($key) {
3919 global $USER;
3920 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) {
3921 return false;
3923 return true;
3926 * Compare something to it's equivilant in the cache
3928 * @param string $key
3929 * @param mixed $value
3930 * @param bool $serialise Whether to serialise the value before comparison
3931 * this should only be set to false if the value is already
3932 * serialised
3933 * @return bool If the value is the same false if it is not set or doesn't match
3935 public function compare($key, $value, $serialise=true) {
3936 if ($this->cached($key)) {
3937 if ($serialise) {
3938 $value = serialize($value);
3940 if ($this->session[$key][self::CACHEVALUE] === $value) {
3941 return true;
3944 return false;
3947 * Wipes the entire cache, good to force regeneration
3949 public function clear() {
3950 $this->session = array();
3953 * Checks all cache entries and removes any that have expired, good ole cleanup
3955 protected function garbage_collection() {
3956 foreach ($this->session as $key=>$cachedinfo) {
3957 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
3958 unset($this->session[$key]);
3964 * Marks the cache as being volatile (likely to change)
3966 * Any caches marked as volatile will be destroyed at the on shutdown by
3967 * {@link navigation_node::destroy_volatile_caches()} which is registered
3968 * as a shutdown function if any caches are marked as volatile.
3970 * @param bool $setting True to destroy the cache false not too
3972 public function volatile($setting = true) {
3973 if (self::$volatilecaches===null) {
3974 self::$volatilecaches = array();
3975 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
3978 if ($setting) {
3979 self::$volatilecaches[$this->area] = $this->area;
3980 } else if (array_key_exists($this->area, self::$volatilecaches)) {
3981 unset(self::$volatilecaches[$this->area]);
3986 * Destroys all caches marked as volatile
3988 * This function is static and works in conjunction with the static volatilecaches
3989 * property of navigation cache.
3990 * Because this function is static it manually resets the cached areas back to an
3991 * empty array.
3993 public static function destroy_volatile_caches() {
3994 global $SESSION;
3995 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
3996 foreach (self::$volatilecaches as $area) {
3997 $SESSION->navcache->{$area} = array();
3999 } else {
4000 $SESSION->navcache = new stdClass;