3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node
implements renderable
{
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF
= 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH
= 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN
= null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE
= 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM
= 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY
= 10;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE
= 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION
= 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY
= 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE
= 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM
= 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING
= 70;
75 /** @var int Setting node type, used only within settings nav 80 */
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER
= 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
82 /** @var string|int The identifier for the node, used to retrieve the node */
84 /** @var string The text to use for the node */
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self
::TYPE_UNKNOWN
;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self
::NODETYPE_LEAF
;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
130 /** @var mixed If set to an int, that section will be included even if it has no activities */
131 public $includesectionnum = false;
134 * Constructs a new navigation_node
136 * @param array|string $properties Either an array of properties or a string to use
137 * as the text for the node
139 public function __construct($properties) {
140 if (is_array($properties)) {
141 // Check the array for each property that we allow to set at construction.
142 // text - The main content for the node
143 // shorttext - A short text if required for the node
144 // icon - The icon to display for the node
145 // type - The type of the node
146 // key - The key to use to identify the node
147 // parent - A reference to the nodes parent
148 // action - The action to attribute to this node, usually a URL to link to
149 if (array_key_exists('text', $properties)) {
150 $this->text
= $properties['text'];
152 if (array_key_exists('shorttext', $properties)) {
153 $this->shorttext
= $properties['shorttext'];
155 if (!array_key_exists('icon', $properties)) {
156 $properties['icon'] = new pix_icon('i/navigationitem', '');
158 $this->icon
= $properties['icon'];
159 if ($this->icon
instanceof pix_icon
) {
160 if (empty($this->icon
->attributes
['class'])) {
161 $this->icon
->attributes
['class'] = 'navicon';
163 $this->icon
->attributes
['class'] .= ' navicon';
166 if (array_key_exists('type', $properties)) {
167 $this->type
= $properties['type'];
169 $this->type
= self
::TYPE_CUSTOM
;
171 if (array_key_exists('key', $properties)) {
172 $this->key
= $properties['key'];
174 // This needs to happen last because of the check_if_active call that occurs
175 if (array_key_exists('action', $properties)) {
176 $this->action
= $properties['action'];
177 if (is_string($this->action
)) {
178 $this->action
= new moodle_url($this->action
);
180 if (self
::$autofindactive) {
181 $this->check_if_active();
184 if (array_key_exists('parent', $properties)) {
185 $this->set_parent($properties['parent']);
187 } else if (is_string($properties)) {
188 $this->text
= $properties;
190 if ($this->text
=== null) {
191 throw new coding_exception('You must set the text for the node when you create it.');
193 // Default the title to the text
194 $this->title
= $this->text
;
195 // Instantiate a new navigation node collection for this nodes children
196 $this->children
= new navigation_node_collection();
200 * Checks if this node is the active node.
202 * This is determined by comparing the action for the node against the
203 * defined URL for the page. A match will see this node marked as active.
205 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
208 public function check_if_active($strength=URL_MATCH_EXACT
) {
209 global $FULLME, $PAGE;
210 // Set fullmeurl if it hasn't already been set
211 if (self
::$fullmeurl == null) {
212 if ($PAGE->has_set_url()) {
213 self
::override_active_url(new moodle_url($PAGE->url
));
215 self
::override_active_url(new moodle_url($FULLME));
219 // Compare the action of this node against the fullmeurl
220 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
221 $this->make_active();
228 * This sets the URL that the URL of new nodes get compared to when locating
231 * The active node is the node that matches the URL set here. By default this
232 * is either $PAGE->url or if that hasn't been set $FULLME.
234 * @param moodle_url $url The url to use for the fullmeurl.
236 public static function override_active_url(moodle_url
$url) {
237 // Clone the URL, in case the calling script changes their URL later.
238 self
::$fullmeurl = new moodle_url($url);
242 * Creates a navigation node, ready to add it as a child using add_node
243 * function. (The created node needs to be added before you can use it.)
244 * @param string $text
245 * @param moodle_url|action_link $action
247 * @param string $shorttext
248 * @param string|int $key
249 * @param pix_icon $icon
250 * @return navigation_node
252 public static function create($text, $action=null, $type=self
::TYPE_CUSTOM
,
253 $shorttext=null, $key=null, pix_icon
$icon=null) {
254 // Properties array used when creating the new navigation node
259 // Set the action if one was provided
260 if ($action!==null) {
261 $itemarray['action'] = $action;
263 // Set the shorttext if one was provided
264 if ($shorttext!==null) {
265 $itemarray['shorttext'] = $shorttext;
267 // Set the icon if one was provided
269 $itemarray['icon'] = $icon;
272 $itemarray['key'] = $key;
273 // Construct and return
274 return new navigation_node($itemarray);
278 * Adds a navigation node as a child of this node.
280 * @param string $text
281 * @param moodle_url|action_link $action
283 * @param string $shorttext
284 * @param string|int $key
285 * @param pix_icon $icon
286 * @return navigation_node
288 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
290 $childnode = self
::create($text, $action, $type, $shorttext, $key, $icon);
292 // Add the child to end and return
293 return $this->add_node($childnode);
297 * Adds a navigation node as a child of this one, given a $node object
298 * created using the create function.
299 * @param navigation_node $childnode Node to add
300 * @param int|string $key The key of a node to add this before. If not
301 * specified, adds at end of list
302 * @return navigation_node The added node
304 public function add_node(navigation_node
$childnode, $beforekey=null) {
305 // First convert the nodetype for this node to a branch as it will now have children
306 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
307 $this->nodetype
= self
::NODETYPE_BRANCH
;
309 // Set the parent to this node
310 $childnode->set_parent($this);
312 // Default the key to the number of children if not provided
313 if ($childnode->key
=== null) {
314 $childnode->key
= $this->children
->count();
317 // Add the child using the navigation_node_collections add method
318 $node = $this->children
->add($childnode, $beforekey);
320 // If added node is a category node or the user is logged in and it's a course
321 // then mark added node as a branch (makes it expandable by AJAX)
322 $type = $childnode->type
;
323 if (($type==self
::TYPE_CATEGORY
) ||
(isloggedin() && $type==self
::TYPE_COURSE
)) {
324 $node->nodetype
= self
::NODETYPE_BRANCH
;
326 // If this node is hidden mark it's children as hidden also
328 $node->hidden
= true;
330 // Return added node (reference returned by $this->children->add()
335 * Return a list of all the keys of all the child nodes.
336 * @return array the keys.
338 public function get_children_key_list() {
339 return $this->children
->get_key_list();
343 * Searches for a node of the given type with the given key.
345 * This searches this node plus all of its children, and their children....
346 * If you know the node you are looking for is a child of this node then please
347 * use the get method instead.
349 * @param int|string $key The key of the node we are looking for
350 * @param int $type One of navigation_node::TYPE_*
351 * @return navigation_node|false
353 public function find($key, $type) {
354 return $this->children
->find($key, $type);
358 * Get ths child of this node that has the given key + (optional) type.
360 * If you are looking for a node and want to search all children + thier children
361 * then please use the find method instead.
363 * @param int|string $key The key of the node we are looking for
364 * @param int $type One of navigation_node::TYPE_*
365 * @return navigation_node|false
367 public function get($key, $type=null) {
368 return $this->children
->get($key, $type);
376 public function remove() {
377 return $this->parent
->children
->remove($this->key
, $this->type
);
381 * Checks if this node has or could have any children
383 * @return bool Returns true if it has children or could have (by AJAX expansion)
385 public function has_children() {
386 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0);
390 * Marks this node as active and forces it open.
392 * Important: If you are here because you need to mark a node active to get
393 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
394 * You can use it to specify a different URL to match the active navigation node on
395 * rather than having to locate and manually mark a node active.
397 public function make_active() {
398 $this->isactive
= true;
399 $this->add_class('active_tree_node');
401 if ($this->parent
!== null) {
402 $this->parent
->make_inactive();
407 * Marks a node as inactive and recusised back to the base of the tree
408 * doing the same to all parents.
410 public function make_inactive() {
411 $this->isactive
= false;
412 $this->remove_class('active_tree_node');
413 if ($this->parent
!== null) {
414 $this->parent
->make_inactive();
419 * Forces this node to be open and at the same time forces open all
420 * parents until the root node.
424 public function force_open() {
425 $this->forceopen
= true;
426 if ($this->parent
!== null) {
427 $this->parent
->force_open();
432 * Adds a CSS class to this node.
434 * @param string $class
437 public function add_class($class) {
438 if (!in_array($class, $this->classes
)) {
439 $this->classes
[] = $class;
445 * Removes a CSS class from this node.
447 * @param string $class
448 * @return bool True if the class was successfully removed.
450 public function remove_class($class) {
451 if (in_array($class, $this->classes
)) {
452 $key = array_search($class,$this->classes
);
454 unset($this->classes
[$key]);
462 * Sets the title for this node and forces Moodle to utilise it.
463 * @param string $title
465 public function title($title) {
466 $this->title
= $title;
467 $this->forcetitle
= true;
471 * Resets the page specific information on this node if it is being unserialised.
473 public function __wakeup(){
474 $this->forceopen
= false;
475 $this->isactive
= false;
476 $this->remove_class('active_tree_node');
480 * Checks if this node or any of its children contain the active node.
486 public function contains_active_node() {
487 if ($this->isactive
) {
490 foreach ($this->children
as $child) {
491 if ($child->isactive ||
$child->contains_active_node()) {
500 * Finds the active node.
502 * Searches this nodes children plus all of the children for the active node
503 * and returns it if found.
507 * @return navigation_node|false
509 public function find_active_node() {
510 if ($this->isactive
) {
513 foreach ($this->children
as &$child) {
514 $outcome = $child->find_active_node();
515 if ($outcome !== false) {
524 * Searches all children for the best matching active node
525 * @return navigation_node|false
527 public function search_for_active_node() {
528 if ($this->check_if_active(URL_MATCH_BASE
)) {
531 foreach ($this->children
as &$child) {
532 $outcome = $child->search_for_active_node();
533 if ($outcome !== false) {
542 * Gets the content for this node.
544 * @param bool $shorttext If true shorttext is used rather than the normal text
547 public function get_content($shorttext=false) {
548 if ($shorttext && $this->shorttext
!==null) {
549 return format_string($this->shorttext
);
551 return format_string($this->text
);
556 * Gets the title to use for this node.
560 public function get_title() {
561 if ($this->forcetitle ||
$this->action
!= null){
569 * Gets the CSS class to add to this node to describe its type
573 public function get_css_type() {
574 if (array_key_exists($this->type
, $this->namedtypes
)) {
575 return 'type_'.$this->namedtypes
[$this->type
];
577 return 'type_unknown';
581 * Finds all nodes that are expandable by AJAX
583 * @param array $expandable An array by reference to populate with expandable nodes.
585 public function find_expandable(array &$expandable) {
586 foreach ($this->children
as &$child) {
587 if ($child->nodetype
== self
::NODETYPE_BRANCH
&& $child->children
->count() == 0 && $child->display
) {
588 $child->id
= 'expandable_branch_'.(count($expandable)+
1);
589 $this->add_class('canexpand');
590 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
592 $child->find_expandable($expandable);
597 * Finds all nodes of a given type (recursive)
599 * @param int $type On of navigation_node::TYPE_*
602 public function find_all_of_type($type) {
603 $nodes = $this->children
->type($type);
604 foreach ($this->children
as &$node) {
605 $childnodes = $node->find_all_of_type($type);
606 $nodes = array_merge($nodes, $childnodes);
612 * Removes this node if it is empty
614 public function trim_if_empty() {
615 if ($this->children
->count() == 0) {
621 * Creates a tab representation of this nodes children that can be used
622 * with print_tabs to produce the tabs on a page.
624 * call_user_func_array('print_tabs', $node->get_tabs_array());
626 * @param array $inactive
627 * @param bool $return
628 * @return array Array (tabs, selected, inactive, activated, return)
630 public function get_tabs_array(array $inactive=array(), $return=false) {
634 $activated = array();
635 foreach ($this->children
as $node) {
636 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
637 if ($node->contains_active_node()) {
638 if ($node->children
->count() > 0) {
639 $activated[] = $node->key
;
640 foreach ($node->children
as $child) {
641 if ($child->contains_active_node()) {
642 $selected = $child->key
;
644 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
647 $selected = $node->key
;
651 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
655 * Sets the parent for this node and if this node is active ensures that the tree is properly
658 * @param navigation_node $parent
660 public function set_parent(navigation_node
$parent) {
661 // Set the parent (thats the easy part)
662 $this->parent
= $parent;
663 // Check if this node is active (this is checked during construction)
664 if ($this->isactive
) {
665 // Force all of the parent nodes open so you can see this node
666 $this->parent
->force_open();
667 // Make all parents inactive so that its clear where we are.
668 $this->parent
->make_inactive();
674 * Navigation node collection
676 * This class is responsible for managing a collection of navigation nodes.
677 * It is required because a node's unique identifier is a combination of both its
680 * Originally an array was used with a string key that was a combination of the two
681 * however it was decided that a better solution would be to use a class that
682 * implements the standard IteratorAggregate interface.
684 * @package moodlecore
685 * @subpackage navigation
686 * @copyright 2010 Sam Hemelryk
687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
689 class navigation_node_collection
implements IteratorAggregate
{
691 * A multidimensional array to where the first key is the type and the second
692 * key is the nodes key.
695 protected $collection = array();
697 * An array that contains references to nodes in the same order they were added.
698 * This is maintained as a progressive array.
701 protected $orderedcollection = array();
703 * A reference to the last node that was added to the collection
704 * @var navigation_node
706 protected $last = null;
708 * The total number of items added to this array.
711 protected $count = 0;
714 * Adds a navigation node to the collection
716 * @param navigation_node $node Node to add
717 * @param string $beforekey If specified, adds before a node with this key,
718 * otherwise adds at end
719 * @return navigation_node Added node
721 public function add(navigation_node
$node, $beforekey=null) {
726 // First check we have a 2nd dimension for this type
727 if (!array_key_exists($type, $this->orderedcollection
)) {
728 $this->orderedcollection
[$type] = array();
730 // Check for a collision and report if debugging is turned on
731 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
732 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
735 // Find the key to add before
736 $newindex = $this->count
;
738 if ($beforekey !== null) {
739 foreach ($this->collection
as $index => $othernode) {
740 if ($othernode->key
=== $beforekey) {
746 if ($newindex === $this->count
) {
747 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
748 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
752 // Add the node to the appropriate place in the by-type structure (which
753 // is not ordered, despite the variable name)
754 $this->orderedcollection
[$type][$key] = $node;
756 // Update existing references in the ordered collection (which is the
757 // one that isn't called 'ordered') to shuffle them along if required
758 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
759 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
762 // Add a reference to the node to the progressive collection.
763 $this->collection
[$newindex] = &$this->orderedcollection
[$type][$key];
764 // Update the last property to a reference to this new node.
765 $this->last
= &$this->orderedcollection
[$type][$key];
767 // Reorder the array by index if needed
769 ksort($this->collection
);
772 // Return the reference to the now added node
777 * Return a list of all the keys of all the nodes.
778 * @return array the keys.
780 public function get_key_list() {
782 foreach ($this->collection
as $node) {
783 $keys[] = $node->key
;
789 * Fetches a node from this collection.
791 * @param string|int $key The key of the node we want to find.
792 * @param int $type One of navigation_node::TYPE_*.
793 * @return navigation_node|null
795 public function get($key, $type=null) {
796 if ($type !== null) {
797 // If the type is known then we can simply check and fetch
798 if (!empty($this->orderedcollection
[$type][$key])) {
799 return $this->orderedcollection
[$type][$key];
802 // Because we don't know the type we look in the progressive array
803 foreach ($this->collection
as $node) {
804 if ($node->key
=== $key) {
813 * Searches for a node with matching key and type.
815 * This function searches both the nodes in this collection and all of
816 * the nodes in each collection belonging to the nodes in this collection.
820 * @param string|int $key The key of the node we want to find.
821 * @param int $type One of navigation_node::TYPE_*.
822 * @return navigation_node|null
824 public function find($key, $type=null) {
825 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
826 return $this->orderedcollection
[$type][$key];
828 $nodes = $this->getIterator();
829 // Search immediate children first
830 foreach ($nodes as &$node) {
831 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
835 // Now search each childs children
836 foreach ($nodes as &$node) {
837 $result = $node->children
->find($key, $type);
838 if ($result !== false) {
847 * Fetches the last node that was added to this collection
849 * @return navigation_node
851 public function last() {
856 * Fetches all nodes of a given type from this collection
858 public function type($type) {
859 if (!array_key_exists($type, $this->orderedcollection
)) {
860 $this->orderedcollection
[$type] = array();
862 return $this->orderedcollection
[$type];
865 * Removes the node with the given key and type from the collection
867 * @param string|int $key
871 public function remove($key, $type=null) {
872 $child = $this->get($key, $type);
873 if ($child !== false) {
874 foreach ($this->collection
as $colkey => $node) {
875 if ($node->key
== $key && $node->type
== $type) {
876 unset($this->collection
[$colkey]);
880 unset($this->orderedcollection
[$child->type
][$child->key
]);
888 * Gets the number of nodes in this collection
890 * This option uses an internal count rather than counting the actual options to avoid
891 * a performance hit through the count function.
895 public function count() {
899 * Gets an array iterator for the collection.
901 * This is required by the IteratorAggregator interface and is used by routines
902 * such as the foreach loop.
904 * @return ArrayIterator
906 public function getIterator() {
907 return new ArrayIterator($this->collection
);
912 * The global navigation class used for... the global navigation
914 * This class is used by PAGE to store the global navigation for the site
915 * and is then used by the settings nav and navbar to save on processing and DB calls
919 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
920 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
923 * @package moodlecore
924 * @subpackage navigation
925 * @copyright 2009 Sam Hemelryk
926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
928 class global_navigation
extends navigation_node
{
930 * The Moodle page this navigation object belongs to.
935 protected $initialised = false;
937 protected $mycourses = array();
939 protected $rootnodes = array();
941 protected $showemptysections = false;
943 protected $showcategories = null;
945 protected $extendforuser = array();
946 /** @var navigation_cache */
949 protected $addedcourses = array();
951 protected $addedcategories = array();
953 protected $expansionlimit = 0;
955 protected $useridtouseforparentchecks = 0;
958 * Constructs a new global navigation
960 * @param moodle_page $page The page this navigation object belongs to
962 public function __construct(moodle_page
$page) {
963 global $CFG, $SITE, $USER;
965 if (during_initial_install()) {
969 if (get_home_page() == HOMEPAGE_SITE
) {
970 // We are using the site home for the root element
973 'type' => navigation_node
::TYPE_SYSTEM
,
974 'text' => get_string('home'),
975 'action' => new moodle_url('/')
978 // We are using the users my moodle for the root element
981 'type' => navigation_node
::TYPE_SYSTEM
,
982 'text' => get_string('myhome'),
983 'action' => new moodle_url('/my/')
987 // Use the parents consturctor.... good good reuse
988 parent
::__construct($properties);
990 // Initalise and set defaults
992 $this->forceopen
= true;
993 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
997 * Mutator to set userid to allow parent to see child's profile
998 * page navigation. See MDL-25805 for initial issue. Linked to it
999 * is an issue explaining why this is a REALLY UGLY HACK thats not
1002 * @param int $userid userid of profile page that parent wants to navigate around.
1004 public function set_userid_for_parent_checks($userid) {
1005 $this->useridtouseforparentchecks
= $userid;
1010 * Initialises the navigation object.
1012 * This causes the navigation object to look at the current state of the page
1013 * that it is associated with and then load the appropriate content.
1015 * This should only occur the first time that the navigation structure is utilised
1016 * which will normally be either when the navbar is called to be displayed or
1017 * when a block makes use of it.
1021 public function initialise() {
1022 global $CFG, $SITE, $USER, $DB;
1023 // Check if it has alread been initialised
1024 if ($this->initialised ||
during_initial_install()) {
1027 $this->initialised
= true;
1029 // Set up the five base root nodes. These are nodes where we will put our
1030 // content and are as follows:
1031 // site: Navigation for the front page.
1032 // myprofile: User profile information goes here.
1033 // mycourses: The users courses get added here.
1034 // courses: Additional courses are added here.
1035 // users: Other users information loaded here.
1036 $this->rootnodes
= array();
1037 if (get_home_page() == HOMEPAGE_SITE
) {
1038 // The home element should be my moodle because the root element is the site
1039 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1040 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_SETTING
, null, 'home');
1043 // The home element should be the site because the root node is my moodle
1044 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self
::TYPE_SETTING
, null, 'home');
1045 if (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_MY
)) {
1046 // We need to stop automatic redirection
1047 $this->rootnodes
['home']->action
->param('redirect', '0');
1050 $this->rootnodes
['site'] = $this->add_course($SITE);
1051 $this->rootnodes
['myprofile'] = $this->add(get_string('myprofile'), null, self
::TYPE_USER
, null, 'myprofile');
1052 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses');
1053 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
1054 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1056 // Fetch all of the users courses.
1058 if (!empty($CFG->navcourselimit
)) {
1059 $limit = $CFG->navcourselimit
;
1062 $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
1063 $showallcourses = (count($mycourses) == 0 ||
!empty($CFG->navshowallcourses
));
1064 // When checking if we are to show categories there is an additional override.
1065 // If the user is viewing a category then we will load it regardless of settings.
1066 // to ensure that the navigation is consistent.
1067 $showcategories = $this->page
->context
->contextlevel
== CONTEXT_COURSECAT ||
($showallcourses && $this->show_categories());
1068 $issite = ($this->page
->course
->id
== SITEID
);
1069 $ismycourse = (array_key_exists($this->page
->course
->id
, $mycourses));
1071 // Check if any courses were returned.
1072 if (count($mycourses) > 0) {
1073 // Add all of the users courses to the navigation
1074 foreach ($mycourses as $course) {
1075 $course->coursenode
= $this->add_course($course, false, true);
1079 if ($showallcourses) {
1081 $this->load_all_courses();
1084 // We always load the frontpage course to ensure it is available without
1085 // JavaScript enabled.
1086 $frontpagecourse = $this->load_course($SITE);
1087 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
1088 $this->load_course_sections($SITE, $frontpagecourse);
1090 $canviewcourseprofile = true;
1092 // Next load context specific content into the navigation
1093 switch ($this->page
->context
->contextlevel
) {
1094 case CONTEXT_SYSTEM
:
1095 // This has already been loaded we just need to map the variable
1096 $coursenode = $frontpagecourse;
1097 $this->load_all_categories(null, $showcategories);
1099 case CONTEXT_COURSECAT
:
1100 // This has already been loaded we just need to map the variable
1101 $coursenode = $frontpagecourse;
1102 $this->load_all_categories($this->page
->context
->instanceid
, $showcategories);
1103 if (array_key_exists($this->page
->context
->instanceid
, $this->addedcategories
)) {
1104 $this->addedcategories
[$this->page
->context
->instanceid
]->make_active();
1107 case CONTEXT_BLOCK
:
1108 case CONTEXT_COURSE
:
1110 // If it is the front page course, or a block on it then
1111 // everything has already been loaded.
1114 // Load the course associated with the page into the navigation
1115 $course = $this->page
->course
;
1116 if ($showcategories && !$ismycourse) {
1117 $this->load_all_categories($course->category
, $showcategories);
1119 $coursenode = $this->load_course($course);
1121 // If the course wasn't added then don't try going any further.
1123 $canviewcourseprofile = false;
1127 // If the user is not enrolled then we only want to show the
1128 // course node and not populate it.
1130 // Not enrolled, can't view, and hasn't switched roles
1131 if (!can_access_course($course)) {
1132 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1133 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1135 if ($this->useridtouseforparentchecks
) {
1136 if ($this->useridtouseforparentchecks
!= $USER->id
) {
1137 $usercontext = get_context_instance(CONTEXT_USER
, $this->useridtouseforparentchecks
, MUST_EXIST
);
1138 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))
1139 and has_capability('moodle/user:viewdetails', $usercontext)) {
1146 $coursenode->make_active();
1147 $canviewcourseprofile = false;
1151 // Add the essentials such as reports etc...
1152 $this->add_course_essentials($coursenode, $course);
1153 if ($this->format_display_course_content($course->format
)) {
1154 // Load the course sections
1155 $sections = $this->load_course_sections($course, $coursenode);
1157 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1158 $coursenode->make_active();
1161 case CONTEXT_MODULE
:
1163 // If this is the site course then most information will have
1164 // already been loaded.
1165 // However we need to check if there is more content that can
1166 // yet be loaded for the specific module instance.
1167 $activitynode = $this->rootnodes
['site']->get($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1168 if ($activitynode) {
1169 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1174 $course = $this->page
->course
;
1175 $cm = $this->page
->cm
;
1177 if ($showcategories && !$ismycourse) {
1178 $this->load_all_categories($course->category
, $showcategories);
1181 // Load the course associated with the page into the navigation
1182 $coursenode = $this->load_course($course);
1184 // If the course wasn't added then don't try going any further.
1186 $canviewcourseprofile = false;
1190 // If the user is not enrolled then we only want to show the
1191 // course node and not populate it.
1192 if (!can_access_course($course)) {
1193 $coursenode->make_active();
1194 $canviewcourseprofile = false;
1198 $this->add_course_essentials($coursenode, $course);
1200 // Get section number from $cm (if provided) - we need this
1201 // before loading sections in order to tell it to load this section
1202 // even if it would not normally display (=> it contains only
1203 // a label, which we are now editing)
1204 $sectionnum = isset($cm->sectionnum
) ?
$cm->sectionnum
: 0;
1206 // This value has to be stored in a member variable because
1207 // otherwise we would have to pass it through a public API
1208 // to course formats and they would need to change their
1209 // functions to pass it along again...
1210 $this->includesectionnum
= $sectionnum;
1212 $this->includesectionnum
= false;
1215 // Load the course sections into the page
1216 $sections = $this->load_course_sections($course, $coursenode);
1217 if ($course->id
!= SITEID
) {
1218 // Find the section for the $CM associated with the page and collect
1219 // its section number.
1221 $cm->sectionnumber
= $sectionnum;
1223 foreach ($sections as $section) {
1224 if ($section->id
== $cm->section
) {
1225 $cm->sectionnumber
= $section->section
;
1231 // Load all of the section activities for the section the cm belongs to.
1232 if (isset($cm->sectionnumber
) and !empty($sections[$cm->sectionnumber
])) {
1233 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1234 $activities = $this->load_section_activities($sections[$cm->sectionnumber
]->sectionnode
, $cm->sectionnumber
, $activityarray);
1236 $activities = array();
1237 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1238 // "stealth" activity from unavailable section
1239 $activities[$cm->id
] = $activity;
1243 $activities = array();
1244 $activities[$cm->id
] = $coursenode->get($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1246 if (!empty($activities[$cm->id
])) {
1247 // Finally load the cm specific navigaton information
1248 $this->load_activity($cm, $course, $activities[$cm->id
]);
1249 // Check if we have an active ndoe
1250 if (!$activities[$cm->id
]->contains_active_node() && !$activities[$cm->id
]->search_for_active_node()) {
1251 // And make the activity node active.
1252 $activities[$cm->id
]->make_active();
1255 //TODO: something is wrong, what to do? (Skodak)
1260 // The users profile information etc is already loaded
1261 // for the front page.
1264 $course = $this->page
->course
;
1265 if ($showcategories && !$ismycourse) {
1266 $this->load_all_categories($course->category
, $showcategories);
1268 // Load the course associated with the user into the navigation
1269 $coursenode = $this->load_course($course);
1271 // If the course wasn't added then don't try going any further.
1273 $canviewcourseprofile = false;
1277 // If the user is not enrolled then we only want to show the
1278 // course node and not populate it.
1279 if (!can_access_course($course)) {
1280 $coursenode->make_active();
1281 $canviewcourseprofile = false;
1284 $this->add_course_essentials($coursenode, $course);
1285 $sections = $this->load_course_sections($course, $coursenode);
1290 if (!empty($CFG->navcourselimit
)) {
1291 $limit = $CFG->navcourselimit
;
1293 if ($showcategories) {
1294 $categories = $this->find_all_of_type(self
::TYPE_CATEGORY
);
1295 foreach ($categories as &$category) {
1296 if ($category->children
->count() >= $limit) {
1297 $url = new moodle_url('/course/category.php', array('id'=>$category->key
));
1298 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1301 } else if ($this->rootnodes
['courses']->children
->count() >= $limit) {
1302 $this->rootnodes
['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self
::TYPE_SETTING
);
1305 // Load for the current user
1306 $this->load_for_user();
1307 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
&& $canviewcourseprofile) {
1308 $this->load_for_user(null, true);
1310 // Load each extending user into the navigation.
1311 foreach ($this->extendforuser
as $user) {
1312 if ($user->id
!= $USER->id
) {
1313 $this->load_for_user($user);
1317 // Give the local plugins a chance to include some navigation if they want.
1318 foreach (get_list_of_plugins('local') as $plugin) {
1319 if (!file_exists($CFG->dirroot
.'/local/'.$plugin.'/lib.php')) {
1322 require_once($CFG->dirroot
.'/local/'.$plugin.'/lib.php');
1323 $function = $plugin.'_extends_navigation';
1324 if (function_exists($function)) {
1329 // Remove any empty root nodes
1330 foreach ($this->rootnodes
as $node) {
1331 // Dont remove the home node
1332 if ($node->key
!== 'home' && !$node->has_children()) {
1337 if (!$this->contains_active_node()) {
1338 $this->search_for_active_node();
1341 // If the user is not logged in modify the navigation structure as detailed
1342 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1343 if (!isloggedin()) {
1344 $activities = clone($this->rootnodes
['site']->children
);
1345 $this->rootnodes
['site']->remove();
1346 $children = clone($this->children
);
1347 $this->children
= new navigation_node_collection();
1348 foreach ($activities as $child) {
1349 $this->children
->add($child);
1351 foreach ($children as $child) {
1352 $this->children
->add($child);
1359 * Returns true is courses should be shown within categories on the navigation.
1363 protected function show_categories() {
1365 if ($this->showcategories
=== null) {
1366 $show = $this->page
->context
->contextlevel
== CONTEXT_COURSECAT
;
1367 $show = $show ||
(!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1);
1368 $this->showcategories
= $show;
1370 return $this->showcategories
;
1374 * Checks the course format to see whether it wants the navigation to load
1375 * additional information for the course.
1377 * This function utilises a callback that can exist within the course format lib.php file
1378 * The callback should be a function called:
1379 * callback_{formatname}_display_content()
1380 * It doesn't get any arguments and should return true if additional content is
1381 * desired. If the callback doesn't exist we assume additional content is wanted.
1383 * @param string $format The course format
1386 protected function format_display_course_content($format) {
1388 $formatlib = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
1389 if (file_exists($formatlib)) {
1390 require_once($formatlib);
1391 $displayfunc = 'callback_'.$format.'_display_content';
1392 if (function_exists($displayfunc) && !$displayfunc()) {
1393 return $displayfunc();
1400 * Loads of the the courses in Moodle into the navigation.
1402 * @global moodle_database $DB
1403 * @param string|array $categoryids Either a string or array of category ids to load courses for
1404 * @return array An array of navigation_node
1406 protected function load_all_courses($categoryids=null) {
1407 global $CFG, $DB, $USER;
1409 if ($categoryids !== null) {
1410 if (is_array($categoryids)) {
1411 list ($categoryselect, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'catid');
1413 $categoryselect = '= :categoryid';
1414 $params = array('categoryid', $categoryids);
1416 $params['siteid'] = SITEID
;
1417 $categoryselect = ' AND c.category '.$categoryselect;
1419 $params = array('siteid' => SITEID
);
1420 $categoryselect = '';
1423 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1424 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
) +
array(SITEID
), SQL_PARAMS_NAMED
, 'lcourse', false);
1425 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category, cat.path AS categorypath $ccselect
1428 LEFT JOIN {course_categories} cat ON cat.id=c.category
1429 WHERE c.id {$courseids} {$categoryselect}
1430 ORDER BY c.sortorder ASC";
1432 if (!empty($CFG->navcourselimit
)) {
1433 $limit = $CFG->navcourselimit
;
1435 $courses = $DB->get_records_sql($sql, $params +
$courseparams, 0, $limit);
1437 $coursenodes = array();
1438 foreach ($courses as $course) {
1439 context_instance_preload($course);
1440 $coursenodes[$course->id
] = $this->add_course($course);
1442 return $coursenodes;
1446 * Loads all categories (top level or if an id is specified for that category)
1448 * @param int $categoryid The category id to load or null/0 to load all base level categories
1449 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1450 * as the requested category and any parent categories.
1453 protected function load_all_categories($categoryid = null, $showbasecategories = false) {
1456 // Check if this category has already been loaded
1457 if ($categoryid !== null && array_key_exists($categoryid, $this->addedcategories
) && $this->addedcategories
[$categoryid]->children
->count() > 0) {
1458 return $this->addedcategories
[$categoryid];
1461 $coursestoload = array();
1462 if (empty($categoryid)) { // can be 0
1463 // We are going to load all of the first level categories (categories without parents)
1464 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder ASC, id ASC');
1465 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1466 // The category itself has been loaded already so we just need to ensure its subcategories
1468 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories
), SQL_PARAMS_NAMED
, 'parent', false);
1469 if ($showbasecategories) {
1470 // We need to include categories with parent = 0 as well
1472 FROM {course_categories} cc
1473 WHERE (parent = :categoryid OR parent = 0) AND
1475 ORDER BY depth DESC, sortorder ASC, id ASC";
1478 FROM {course_categories} cc
1479 WHERE parent = :categoryid AND
1481 ORDER BY depth DESC, sortorder ASC, id ASC";
1483 $params['categoryid'] = $categoryid;
1484 $categories = $DB->get_records_sql($sql, $params);
1485 if (count($categories) == 0) {
1486 // There are no further categories that require loading.
1490 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1491 // and load this category plus all its parents and subcategories
1492 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1493 $coursestoload = explode('/', trim($category->path
, '/'));
1494 list($select, $params) = $DB->get_in_or_equal($coursestoload);
1495 $select = 'id '.$select.' OR parent '.$select;
1496 if ($showbasecategories) {
1497 $select .= ' OR parent = 0';
1499 $params = array_merge($params, $params);
1500 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1503 // Now we have an array of categories we need to add them to the navigation.
1504 while (!empty($categories)) {
1505 $category = reset($categories);
1506 if (array_key_exists($category->id
, $this->addedcategories
)) {
1508 } else if ($category->parent
== '0') {
1509 $this->add_category($category, $this->rootnodes
['courses']);
1510 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1511 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1513 // This category isn't in the navigation and niether is it's parent (yet).
1514 // We need to go through the category path and add all of its components in order.
1515 $path = explode('/', trim($category->path
, '/'));
1516 foreach ($path as $catid) {
1517 if (!array_key_exists($catid, $this->addedcategories
)) {
1518 // This category isn't in the navigation yet so add it.
1519 $subcategory = $categories[$catid];
1520 if ($subcategory->parent
== '0') {
1521 // Yay we have a root category - this likely means we will now be able
1522 // to add categories without problems.
1523 $this->add_category($subcategory, $this->rootnodes
['courses']);
1524 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
1525 // The parent is in the category (as we'd expect) so add it now.
1526 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
1527 // Remove the category from the categories array.
1528 unset($categories[$catid]);
1530 // We should never ever arrive here - if we have then there is a bigger
1532 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1537 // Remove the category from the categories array now that we know it has been added.
1538 unset($categories[$category->id
]);
1540 // Check if there are any categories to load.
1541 if (count($coursestoload) > 0) {
1542 $this->load_all_courses($coursestoload);
1547 * Adds a structured category to the navigation in the correct order/place
1549 * @param stdClass $category
1550 * @param navigation_node $parent
1552 protected function add_category(stdClass
$category, navigation_node
$parent) {
1553 if (array_key_exists($category->id
, $this->addedcategories
)) {
1556 $url = new moodle_url('/course/category.php', array('id' => $category->id
));
1557 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
1558 $categoryname = format_string($category->name
, true, array('context' => $context));
1559 $categorynode = $parent->add($categoryname, $url, self
::TYPE_CATEGORY
, $categoryname, $category->id
);
1560 if (empty($category->visible
)) {
1561 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1562 $categorynode->hidden
= true;
1564 $categorynode->display
= false;
1567 $this->addedcategories
[$category->id
] = &$categorynode;
1571 * Loads the given course into the navigation
1573 * @param stdClass $course
1574 * @return navigation_node
1576 protected function load_course(stdClass
$course) {
1577 if ($course->id
== SITEID
) {
1578 return $this->rootnodes
['site'];
1579 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
1580 return $this->addedcourses
[$course->id
];
1582 return $this->add_course($course);
1587 * Loads all of the courses section into the navigation.
1589 * This function utilisies a callback that can be implemented within the course
1590 * formats lib.php file to customise the navigation that is generated at this
1591 * point for the course.
1593 * By default (if not defined) the method {@see load_generic_course_sections} is
1596 * @param stdClass $course Database record for the course
1597 * @param navigation_node $coursenode The course node within the navigation
1598 * @return array Array of navigation nodes for the section with key = section id
1600 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode) {
1602 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
1603 $structurefunc = 'callback_'.$course->format
.'_load_content';
1604 if (function_exists($structurefunc)) {
1605 return $structurefunc($this, $course, $coursenode);
1606 } else if (file_exists($structurefile)) {
1607 require_once $structurefile;
1608 if (function_exists($structurefunc)) {
1609 return $structurefunc($this, $course, $coursenode);
1611 return $this->load_generic_course_sections($course, $coursenode);
1614 return $this->load_generic_course_sections($course, $coursenode);
1619 * Generates an array of sections and an array of activities for the given course.
1621 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1623 * @param stdClass $course
1624 * @return array Array($sections, $activities)
1626 protected function generate_sections_and_activities(stdClass
$course) {
1628 require_once($CFG->dirroot
.'/course/lib.php');
1630 $modinfo = get_fast_modinfo($course);
1632 $sections = array_slice(get_all_sections($course->id
), 0, $course->numsections+
1, true);
1633 $activities = array();
1635 foreach ($sections as $key => $section) {
1636 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1637 $sections[$key] = clone($section);
1638 unset($sections[$key]->summary
);
1639 $sections[$key]->hasactivites
= false;
1640 if (!array_key_exists($section->section
, $modinfo->sections
)) {
1643 foreach ($modinfo->sections
[$section->section
] as $cmid) {
1644 $cm = $modinfo->cms
[$cmid];
1645 if (!$cm->uservisible
) {
1648 $activity = new stdClass
;
1649 $activity->id
= $cm->id
;
1650 $activity->course
= $course->id
;
1651 $activity->section
= $section->section
;
1652 $activity->name
= $cm->name
;
1653 $activity->icon
= $cm->icon
;
1654 $activity->iconcomponent
= $cm->iconcomponent
;
1655 $activity->hidden
= (!$cm->visible
);
1656 $activity->modname
= $cm->modname
;
1657 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1658 $activity->onclick
= $cm->get_on_click();
1659 $url = $cm->get_url();
1661 $activity->url
= null;
1662 $activity->display
= false;
1664 $activity->url
= $cm->get_url()->out();
1665 $activity->display
= true;
1666 if (self
::module_extends_navigation($cm->modname
)) {
1667 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1670 $activities[$cmid] = $activity;
1671 if ($activity->display
) {
1672 $sections[$key]->hasactivites
= true;
1677 return array($sections, $activities);
1681 * Generically loads the course sections into the course's navigation.
1683 * @param stdClass $course
1684 * @param navigation_node $coursenode
1685 * @param string $courseformat The course format
1686 * @return array An array of course section nodes
1688 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode, $courseformat='unknown') {
1689 global $CFG, $DB, $USER;
1690 require_once($CFG->dirroot
.'/course/lib.php');
1692 list($sections, $activities) = $this->generate_sections_and_activities($course);
1694 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1695 $namingfunctionexists = (function_exists($namingfunction));
1697 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page
->context
);
1699 $urlfunction = 'callback_'.$courseformat.'_get_section_url';
1700 if (empty($CFG->navlinkcoursesections
) ||
!function_exists($urlfunction)) {
1701 $urlfunction = null;
1704 $keyfunction = 'callback_'.$courseformat.'_request_key';
1705 $key = course_get_display($course->id
);
1706 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT
== '0' && function_exists($keyfunction) && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1707 $key = optional_param($keyfunction(), $key, PARAM_INT
);
1710 $navigationsections = array();
1711 foreach ($sections as $sectionid => $section) {
1712 $section = clone($section);
1713 if ($course->id
== SITEID
) {
1714 $this->load_section_activities($coursenode, $section->section
, $activities);
1716 if ((!$viewhiddensections && !$section->visible
) ||
(!$this->showemptysections
&&
1717 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
1720 if ($namingfunctionexists) {
1721 $sectionname = $namingfunction($course, $section, $sections);
1723 $sectionname = get_string('section').' '.$section->section
;
1727 if (!empty($urlfunction)) {
1728 $url = $urlfunction($course->id
, $section->section
);
1730 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
, null, $section->id
);
1731 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1732 $sectionnode->hidden
= (!$section->visible
);
1733 if ($key != '0' && $section->section
!= '0' && $section->section
== $key && $this->page
->context
->contextlevel
!= CONTEXT_MODULE
&& $section->hasactivites
) {
1734 $sectionnode->make_active();
1735 $this->load_section_activities($sectionnode, $section->section
, $activities);
1737 $section->sectionnode
= $sectionnode;
1738 $navigationsections[$sectionid] = $section;
1741 return $navigationsections;
1744 * Loads all of the activities for a section into the navigation structure.
1746 * @todo 2.2 - $activities should always be an array and we should no longer check for it being a
1747 * course_modinfo object
1749 * @param navigation_node $sectionnode
1750 * @param int $sectionnumber
1751 * @param course_modinfo $modinfo Object returned from {@see get_fast_modinfo()}
1752 * @return array Array of activity nodes
1754 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, $activities) {
1755 // A static counter for JS function naming
1756 static $legacyonclickcounter = 0;
1758 if ($activities instanceof course_modinfo
) {
1759 debugging('global_navigation::load_section_activities argument 3 should now recieve an array of activites. See that method for an example.', DEBUG_DEVELOPER
);
1760 list($sections, $activities) = $this->generate_sections_and_activities($activities->course
);
1763 $activitynodes = array();
1764 foreach ($activities as $activity) {
1765 if ($activity->section
!= $sectionnumber) {
1768 if ($activity->icon
) {
1769 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
1771 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
1774 // Prepare the default name and url for the node
1775 $activityname = format_string($activity->name
, true, array('context' => get_context_instance(CONTEXT_MODULE
, $activity->id
)));
1776 $action = new moodle_url($activity->url
);
1778 // Check if the onclick property is set (puke!)
1779 if (!empty($activity->onclick
)) {
1780 // Increment the counter so that we have a unique number.
1781 $legacyonclickcounter++
;
1782 // Generate the function name we will use
1783 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1784 $propogrationhandler = '';
1785 // Check if we need to cancel propogation. Remember inline onclick
1786 // events would return false if they wanted to prevent propogation and the
1788 if (strpos($activity->onclick
, 'return false')) {
1789 $propogrationhandler = 'e.halt();';
1791 // Decode the onclick - it has already been encoded for display (puke)
1792 $onclick = htmlspecialchars_decode($activity->onclick
);
1793 // Build the JS function the click event will call
1794 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1795 $this->page
->requires
->js_init_code($jscode);
1796 // Override the default url with the new action link
1797 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1800 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
1801 $activitynode->title(get_string('modulename', $activity->modname
));
1802 $activitynode->hidden
= $activity->hidden
;
1803 $activitynode->display
= $activity->display
;
1804 $activitynode->nodetype
= $activity->nodetype
;
1805 $activitynodes[$activity->id
] = $activitynode;
1808 return $activitynodes;
1811 * Loads a stealth module from unavailable section
1812 * @param navigation_node $coursenode
1813 * @param stdClass $modinfo
1814 * @return navigation_node or null if not accessible
1816 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
1817 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
1820 $cm = $modinfo->cms
[$this->page
->cm
->id
];
1821 if (!$cm->uservisible
) {
1825 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
1827 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
1829 $url = $cm->get_url();
1830 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
1831 $activitynode->title(get_string('modulename', $cm->modname
));
1832 $activitynode->hidden
= (!$cm->visible
);
1834 // Don't show activities that don't have links!
1835 $activitynode->display
= false;
1836 } else if (self
::module_extends_navigation($cm->modname
)) {
1837 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1839 return $activitynode;
1842 * Loads the navigation structure for the given activity into the activities node.
1844 * This method utilises a callback within the modules lib.php file to load the
1845 * content specific to activity given.
1847 * The callback is a method: {modulename}_extend_navigation()
1849 * * {@see forum_extend_navigation()}
1850 * * {@see workshop_extend_navigation()}
1852 * @param cm_info|stdClass $cm
1853 * @param stdClass $course
1854 * @param navigation_node $activity
1857 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
1860 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1861 if (!($cm instanceof cm_info
)) {
1862 $modinfo = get_fast_modinfo($course);
1863 $cm = $modinfo->get_cm($cm->id
);
1866 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1867 $activity->make_active();
1868 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
1869 $function = $cm->modname
.'_extend_navigation';
1871 if (file_exists($file)) {
1872 require_once($file);
1873 if (function_exists($function)) {
1874 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
1875 $function($activity, $course, $activtyrecord, $cm);
1879 // Allow the active advanced grading method plugin to append module navigation
1880 $featuresfunc = $cm->modname
.'_supports';
1881 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
1882 require_once($CFG->dirroot
.'/grade/grading/lib.php');
1883 $gradingman = get_grading_manager($cm->context
, $cm->modname
);
1884 $gradingman->extend_navigation($this, $activity);
1887 return $activity->has_children();
1890 * Loads user specific information into the navigation in the appropriate place.
1892 * If no user is provided the current user is assumed.
1894 * @param stdClass $user
1895 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
1898 protected function load_for_user($user=null, $forceforcontext=false) {
1899 global $DB, $CFG, $USER;
1901 if ($user === null) {
1902 // We can't require login here but if the user isn't logged in we don't
1903 // want to show anything
1904 if (!isloggedin() ||
isguestuser()) {
1908 } else if (!is_object($user)) {
1909 // If the user is not an object then get them from the database
1910 list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER
, 'ctx');
1911 $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
1912 $user = $DB->get_record_sql($sql, array('userid' => (int)$user), MUST_EXIST
);
1913 context_instance_preload($user);
1916 $iscurrentuser = ($user->id
== $USER->id
);
1918 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
1920 // Get the course set against the page, by default this will be the site
1921 $course = $this->page
->course
;
1922 $baseargs = array('id'=>$user->id
);
1923 if ($course->id
!= SITEID
&& (!$iscurrentuser ||
$forceforcontext)) {
1924 $coursenode = $this->load_course($course);
1925 $baseargs['course'] = $course->id
;
1926 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1927 $issitecourse = false;
1929 // Load all categories and get the context for the system
1930 $coursecontext = get_context_instance(CONTEXT_SYSTEM
);
1931 $issitecourse = true;
1934 // Create a node to add user information under.
1935 if ($iscurrentuser && !$forceforcontext) {
1936 // If it's the current user the information will go under the profile root node
1937 $usernode = $this->rootnodes
['myprofile'];
1938 $course = get_site();
1939 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1940 $issitecourse = true;
1942 if (!$issitecourse) {
1943 // Not the current user so add it to the participants node for the current course
1944 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
1945 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1947 // This is the site so add a users node to the root branch
1948 $usersnode = $this->rootnodes
['users'];
1949 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
1950 $usersnode->action
= new moodle_url('/user/index.php', array('id'=>$course->id
));
1952 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1955 // We should NEVER get here, if the course hasn't been populated
1956 // with a participants node then the navigaiton either wasn't generated
1957 // for it (you are missing a require_login or set_context call) or
1958 // you don't have access.... in the interests of no leaking informatin
1959 // we simply quit...
1962 // Add a branch for the current user
1963 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
1964 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, $user->id
);
1966 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
1967 $usernode->make_active();
1971 // If the user is the current user or has permission to view the details of the requested
1972 // user than add a view profile link.
1973 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
1974 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
1975 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1977 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1981 if (!empty($CFG->navadduserpostslinks
)) {
1982 // Add nodes for forum posts and discussions if the user can view either or both
1983 // There are no capability checks here as the content of the page is based
1984 // purely on the forums the current user has access too.
1985 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1986 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1987 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1991 if (!empty($CFG->bloglevel
)) {
1992 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
1993 require_once($CFG->dirroot
.'/blog/lib.php');
1994 // Get all options for the user
1995 $options = blog_get_options_for_user($user);
1996 $this->cache
->set('userblogoptions'.$user->id
, $options);
1998 $options = $this->cache
->{'userblogoptions'.$user->id
};
2001 if (count($options) > 0) {
2002 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2003 foreach ($options as $type => $option) {
2004 if ($type == "rss") {
2005 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
2007 $blogs->add($option['string'], $option['link']);
2013 if (!empty($CFG->messaging
)) {
2014 $messageargs = null;
2015 if ($USER->id
!=$user->id
) {
2016 $messageargs = array('id'=>$user->id
);
2018 $url = new moodle_url('/message/index.php',$messageargs);
2019 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2022 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
2023 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2024 $url = new moodle_url('/user/filesedit.php');
2025 $usernode->add(get_string('myfiles'), $url, self
::TYPE_SETTING
);
2028 // Add a node to view the users notes if permitted
2029 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2030 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
));
2031 if ($coursecontext->instanceid
) {
2032 $url->param('course', $coursecontext->instanceid
);
2034 $usernode->add(get_string('notes', 'notes'), $url);
2038 $reporttab = $usernode->add(get_string('activityreports'));
2039 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2040 foreach ($reports as $reportfunction) {
2041 $reportfunction($reporttab, $user, $course);
2043 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2044 if ($anyreport ||
($course->showreports
&& $iscurrentuser && $forceforcontext)) {
2045 // Add grade hardcoded grade report if necessary
2046 $gradeaccess = false;
2047 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2048 //ok - can view all course grades
2049 $gradeaccess = true;
2050 } else if ($course->showgrades
) {
2051 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2052 //ok - can view own grades
2053 $gradeaccess = true;
2054 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2055 // ok - can view grades of this user - parent most probably
2056 $gradeaccess = true;
2057 } else if ($anyreport) {
2058 // ok - can view grades of this user - parent most probably
2059 $gradeaccess = true;
2063 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id
, 'user'=>$usercontext->instanceid
)));
2066 // Check the number of nodes in the report node... if there are none remove the node
2067 $reporttab->trim_if_empty();
2069 // If the user is the current user add the repositories for the current user
2070 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2071 if ($iscurrentuser) {
2072 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
2073 require_once($CFG->dirroot
. '/repository/lib.php');
2074 $editabletypes = repository
::get_editable_types($usercontext);
2075 $haseditabletypes = !empty($editabletypes);
2076 unset($editabletypes);
2077 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
2079 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
2081 if ($haseditabletypes) {
2082 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id
)));
2084 } else if ($course->id
== SITEID
&& has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2086 // Add view grade report is permitted
2087 $reports = get_plugin_list('gradereport');
2088 arsort($reports); // user is last, we want to test it first
2090 $userscourses = enrol_get_users_courses($user->id
);
2091 $userscoursesnode = $usernode->add(get_string('courses'));
2093 foreach ($userscourses as $usercourse) {
2094 $usercoursecontext = get_context_instance(CONTEXT_COURSE
, $usercourse->id
);
2095 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2096 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$usercourse->id
)), self
::TYPE_CONTAINER
);
2098 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2099 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2100 foreach ($reports as $plugin => $plugindir) {
2101 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2102 //stop when the first visible plugin is found
2103 $gradeavailable = true;
2109 if ($gradeavailable) {
2110 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id
));
2111 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/grades', ''));
2114 // Add a node to view the users notes if permitted
2115 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2116 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
, 'course'=>$usercourse->id
));
2117 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2120 if (can_access_course($usercourse, $user->id
)) {
2121 $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', ''));
2124 $reporttab = $usercoursenode->add(get_string('activityreports'));
2126 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2127 foreach ($reports as $reportfunction) {
2128 $reportfunction($reporttab, $user, $usercourse);
2131 $reporttab->trim_if_empty();
2138 * This method simply checks to see if a given module can extend the navigation.
2140 * TODO: A shared caching solution should be used to save details on what extends navigation
2142 * @param string $modname
2145 protected static function module_extends_navigation($modname) {
2147 static $extendingmodules = array();
2148 if (!array_key_exists($modname, $extendingmodules)) {
2149 $extendingmodules[$modname] = false;
2150 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2151 if (file_exists($file)) {
2152 $function = $modname.'_extend_navigation';
2153 require_once($file);
2154 $extendingmodules[$modname] = (function_exists($function));
2157 return $extendingmodules[$modname];
2160 * Extends the navigation for the given user.
2162 * @param stdClass $user A user from the database
2164 public function extend_for_user($user) {
2165 $this->extendforuser
[] = $user;
2169 * Returns all of the users the navigation is being extended for
2173 public function get_extending_users() {
2174 return $this->extendforuser
;
2177 * Adds the given course to the navigation structure.
2179 * @param stdClass $course
2180 * @return navigation_node
2182 public function add_course(stdClass
$course, $forcegeneric = false, $ismycourse = false) {
2185 // We found the course... we can return it now :)
2186 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2187 return $this->addedcourses
[$course->id
];
2190 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2192 if ($course->id
!= SITEID
&& !$course->visible
) {
2193 if (is_role_switched($course->id
)) {
2194 // user has to be able to access course in order to switch, let's skip the visibility test here
2195 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2200 $issite = ($course->id
== SITEID
);
2201 $ismycourse = ($ismycourse && !$forcegeneric);
2202 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2207 if (empty($CFG->usesitenameforsitepages
)) {
2208 $shortname = get_string('sitepages');
2210 } else if ($ismycourse) {
2211 $parent = $this->rootnodes
['mycourses'];
2212 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2214 $parent = $this->rootnodes
['courses'];
2215 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2218 if (!$ismycourse && !$issite && !empty($course->category
)) {
2219 if ($this->show_categories()) {
2220 // We need to load the category structure for this course
2221 $this->load_all_categories($course->category
);
2223 if (array_key_exists($course->category
, $this->addedcategories
)) {
2224 $parent = $this->addedcategories
[$course->category
];
2225 // This could lead to the course being created so we should check whether it is the case again
2226 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2227 return $this->addedcourses
[$course->id
];
2232 $coursenode = $parent->add($shortname, $url, self
::TYPE_COURSE
, $shortname, $course->id
);
2233 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2234 $coursenode->hidden
= (!$course->visible
);
2235 $coursenode->title(format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
))));
2236 if (!$forcegeneric) {
2237 $this->addedcourses
[$course->id
] = &$coursenode;
2239 if ($ismycourse && !empty($CFG->navshowallcourses
)) {
2240 // We need to add this course to the general courses node as well as the
2241 // my courses node, rerun the function with the kill param
2242 $genericcourse = $this->add_course($course, true);
2243 if ($genericcourse->isactive
) {
2244 $genericcourse->make_inactive();
2245 $genericcourse->collapse
= true;
2246 if ($genericcourse->parent
&& $genericcourse->parent
->type
== self
::TYPE_CATEGORY
) {
2247 $parent = $genericcourse->parent
;
2248 while ($parent && $parent->type
== self
::TYPE_CATEGORY
) {
2249 $parent->collapse
= true;
2250 $parent = $parent->parent
;
2259 * Adds essential course nodes to the navigation for the given course.
2261 * This method adds nodes such as reports, blogs and participants
2263 * @param navigation_node $coursenode
2264 * @param stdClass $course
2267 public function add_course_essentials($coursenode, stdClass
$course) {
2270 if ($course->id
== SITEID
) {
2271 return $this->add_front_page_course_essentials($coursenode, $course);
2274 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2279 if (has_capability('moodle/course:viewparticipants', $this->page
->context
)) {
2280 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2281 $currentgroup = groups_get_course_group($course, true);
2282 if ($course->id
== SITEID
) {
2284 } else if ($course->id
&& !$currentgroup) {
2285 $filterselect = $course->id
;
2287 $filterselect = $currentgroup;
2289 $filterselect = clean_param($filterselect, PARAM_INT
);
2290 if (($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2291 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2292 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2293 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2295 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2296 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id
)));
2298 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2299 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2302 // View course reports
2303 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2304 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2305 $coursereports = get_plugin_list('coursereport'); // deprecated
2306 foreach ($coursereports as $report=>$dir) {
2307 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2308 if (file_exists($libfile)) {
2309 require_once($libfile);
2310 $reportfunction = $report.'_report_extend_navigation';
2311 if (function_exists($report.'_report_extend_navigation')) {
2312 $reportfunction($reportnav, $course, $this->page
->context
);
2317 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2318 foreach ($reports as $reportfunction) {
2319 $reportfunction($reportnav, $course, $this->page
->context
);
2325 * This generates the the structure of the course that won't be generated when
2326 * the modules and sections are added.
2328 * Things such as the reports branch, the participants branch, blogs... get
2329 * added to the course node by this method.
2331 * @param navigation_node $coursenode
2332 * @param stdClass $course
2333 * @return bool True for successfull generation
2335 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2338 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2342 // Hidden node that we use to determine if the front page navigation is loaded.
2343 // This required as there are not other guaranteed nodes that may be loaded.
2344 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2347 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2348 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
2354 if (!empty($CFG->bloglevel
)
2355 and ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2356 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2357 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2358 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2362 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2363 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2367 if (!empty($CFG->usetags
) && isloggedin()) {
2368 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2373 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2374 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self
::TYPE_CUSTOM
, null, 'calendar');
2377 // View course reports
2378 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2379 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2380 $coursereports = get_plugin_list('coursereport'); // deprecated
2381 foreach ($coursereports as $report=>$dir) {
2382 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2383 if (file_exists($libfile)) {
2384 require_once($libfile);
2385 $reportfunction = $report.'_report_extend_navigation';
2386 if (function_exists($report.'_report_extend_navigation')) {
2387 $reportfunction($reportnav, $course, $this->page
->context
);
2392 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2393 foreach ($reports as $reportfunction) {
2394 $reportfunction($reportnav, $course, $this->page
->context
);
2401 * Clears the navigation cache
2403 public function clear_cache() {
2404 $this->cache
->clear();
2408 * Sets an expansion limit for the navigation
2410 * The expansion limit is used to prevent the display of content that has a type
2411 * greater than the provided $type.
2413 * Can be used to ensure things such as activities or activity content don't get
2414 * shown on the navigation.
2415 * They are still generated in order to ensure the navbar still makes sense.
2417 * @param int $type One of navigation_node::TYPE_*
2420 public function set_expansion_limit($type) {
2421 $nodes = $this->find_all_of_type($type);
2422 foreach ($nodes as &$node) {
2423 // We need to generate the full site node
2424 if ($type == self
::TYPE_COURSE
&& $node->key
== SITEID
) {
2427 foreach ($node->children
as &$child) {
2428 // We still want to show course reports and participants containers
2429 // or there will be navigation missing.
2430 if ($type == self
::TYPE_COURSE
&& $child->type
=== self
::TYPE_CONTAINER
) {
2433 $child->display
= false;
2439 * Attempts to get the navigation with the given key from this nodes children.
2441 * This function only looks at this nodes children, it does NOT look recursivily.
2442 * If the node can't be found then false is returned.
2444 * If you need to search recursivily then use the {@see find()} method.
2446 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2447 * may be of more use to you.
2449 * @param string|int $key The key of the node you wish to receive.
2450 * @param int $type One of navigation_node::TYPE_*
2451 * @return navigation_node|false
2453 public function get($key, $type = null) {
2454 if (!$this->initialised
) {
2455 $this->initialise();
2457 return parent
::get($key, $type);
2461 * Searches this nodes children and thier children to find a navigation node
2462 * with the matching key and type.
2464 * This method is recursive and searches children so until either a node is
2465 * found of there are no more nodes to search.
2467 * If you know that the node being searched for is a child of this node
2468 * then use the {@see get()} method instead.
2470 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2471 * may be of more use to you.
2473 * @param string|int $key The key of the node you wish to receive.
2474 * @param int $type One of navigation_node::TYPE_*
2475 * @return navigation_node|false
2477 public function find($key, $type) {
2478 if (!$this->initialised
) {
2479 $this->initialise();
2481 return parent
::find($key, $type);
2486 * The limited global navigation class used for the AJAX extension of the global
2489 * The primary methods that are used in the global navigation class have been overriden
2490 * to ensure that only the relevant branch is generated at the root of the tree.
2491 * This can be done because AJAX is only used when the backwards structure for the
2492 * requested branch exists.
2493 * This has been done only because it shortens the amounts of information that is generated
2494 * which of course will speed up the response time.. because no one likes laggy AJAX.
2496 * @package moodlecore
2497 * @subpackage navigation
2498 * @copyright 2009 Sam Hemelryk
2499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2501 class global_navigation_for_ajax
extends global_navigation
{
2503 protected $branchtype;
2504 protected $instanceid;
2507 protected $expandable = array();
2510 * Constructs the navigation for use in AJAX request
2512 public function __construct($page, $branchtype, $id) {
2513 $this->page
= $page;
2514 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2515 $this->children
= new navigation_node_collection();
2516 $this->branchtype
= $branchtype;
2517 $this->instanceid
= $id;
2518 $this->initialise();
2521 * Initialise the navigation given the type and id for the branch to expand.
2523 * @return array The expandable nodes
2525 public function initialise() {
2526 global $CFG, $DB, $SITE;
2528 if ($this->initialised ||
during_initial_install()) {
2529 return $this->expandable
;
2531 $this->initialised
= true;
2533 $this->rootnodes
= array();
2534 $this->rootnodes
['site'] = $this->add_course($SITE);
2535 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
2537 // Branchtype will be one of navigation_node::TYPE_*
2538 switch ($this->branchtype
) {
2539 case self
::TYPE_CATEGORY
:
2540 $this->load_all_categories($this->instanceid
);
2542 if (!empty($CFG->navcourselimit
)) {
2543 $limit = (int)$CFG->navcourselimit
;
2545 $courses = $DB->get_records('course', array('category' => $this->instanceid
), 'sortorder','*', 0, $limit);
2546 foreach ($courses as $course) {
2547 $this->add_course($course);
2550 case self
::TYPE_COURSE
:
2551 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
2552 require_course_login($course, true, null, false, true);
2553 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2554 $coursenode = $this->add_course($course);
2555 $this->add_course_essentials($coursenode, $course);
2556 if ($this->format_display_course_content($course->format
)) {
2557 $this->load_course_sections($course, $coursenode);
2560 case self
::TYPE_SECTION
:
2561 $sql = 'SELECT c.*, cs.section AS sectionnumber
2563 LEFT JOIN {course_sections} cs ON cs.course = c.id
2565 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
2566 require_course_login($course, true, null, false, true);
2567 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2568 $coursenode = $this->add_course($course);
2569 $this->add_course_essentials($coursenode, $course);
2570 $sections = $this->load_course_sections($course, $coursenode);
2571 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2572 $this->load_section_activities($sections[$course->sectionnumber
]->sectionnode
, $course->sectionnumber
, $activities);
2574 case self
::TYPE_ACTIVITY
:
2577 JOIN {course_modules} cm ON cm.course = c.id
2578 WHERE cm.id = :cmid";
2579 $params = array('cmid' => $this->instanceid
);
2580 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
2581 $modinfo = get_fast_modinfo($course);
2582 $cm = $modinfo->get_cm($this->instanceid
);
2583 require_course_login($course, true, $cm, false, true);
2584 $this->page
->set_context(get_context_instance(CONTEXT_MODULE
, $cm->id
));
2585 $coursenode = $this->load_course($course);
2586 if ($course->id
== SITEID
) {
2587 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
));
2589 $sections = $this->load_course_sections($course, $coursenode);
2590 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2591 $activities = $this->load_section_activities($sections[$cm->sectionnum
]->sectionnode
, $cm->sectionnum
, $activities);
2592 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id
]);
2596 throw new Exception('Unknown type');
2597 return $this->expandable
;
2600 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
) {
2601 $this->load_for_user(null, true);
2604 $this->find_expandable($this->expandable
);
2605 return $this->expandable
;
2609 * Returns an array of expandable nodes
2612 public function get_expandable() {
2613 return $this->expandable
;
2620 * This class is used to manage the navbar, which is initialised from the navigation
2621 * object held by PAGE
2623 * @package moodlecore
2624 * @subpackage navigation
2625 * @copyright 2009 Sam Hemelryk
2626 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2628 class navbar
extends navigation_node
{
2630 protected $initialised = false;
2632 protected $keys = array();
2633 /** @var null|string */
2634 protected $content = null;
2635 /** @var moodle_page object */
2638 protected $ignoreactive = false;
2640 protected $duringinstall = false;
2642 protected $hasitems = false;
2646 public $children = array();
2648 public $includesettingsbase = false;
2650 * The almighty constructor
2652 * @param moodle_page $page
2654 public function __construct(moodle_page
$page) {
2656 if (during_initial_install()) {
2657 $this->duringinstall
= true;
2660 $this->page
= $page;
2661 $this->text
= get_string('home');
2662 $this->shorttext
= get_string('home');
2663 $this->action
= new moodle_url($CFG->wwwroot
);
2664 $this->nodetype
= self
::NODETYPE_BRANCH
;
2665 $this->type
= self
::TYPE_SYSTEM
;
2669 * Quick check to see if the navbar will have items in.
2671 * @return bool Returns true if the navbar will have items, false otherwise
2673 public function has_items() {
2674 if ($this->duringinstall
) {
2676 } else if ($this->hasitems
!== false) {
2679 $this->page
->navigation
->initialise($this->page
);
2681 $activenodefound = ($this->page
->navigation
->contains_active_node() ||
2682 $this->page
->settingsnav
->contains_active_node());
2684 $outcome = (count($this->children
)>0 ||
(!$this->ignoreactive
&& $activenodefound));
2685 $this->hasitems
= $outcome;
2690 * Turn on/off ignore active
2692 * @param bool $setting
2694 public function ignore_active($setting=true) {
2695 $this->ignoreactive
= ($setting);
2697 public function get($key, $type = null) {
2698 foreach ($this->children
as &$child) {
2699 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
2706 * Returns an array of navigation_node's that make up the navbar.
2710 public function get_items() {
2712 // Make sure that navigation is initialised
2713 if (!$this->has_items()) {
2716 if ($this->items
!== null) {
2717 return $this->items
;
2720 if (count($this->children
) > 0) {
2721 // Add the custom children
2722 $items = array_reverse($this->children
);
2725 $navigationactivenode = $this->page
->navigation
->find_active_node();
2726 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
2728 // Check if navigation contains the active node
2729 if (!$this->ignoreactive
) {
2731 if ($navigationactivenode && $settingsactivenode) {
2732 // Parse a combined navigation tree
2733 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
2734 if (!$settingsactivenode->mainnavonly
) {
2735 $items[] = $settingsactivenode;
2737 $settingsactivenode = $settingsactivenode->parent
;
2739 if (!$this->includesettingsbase
) {
2740 // Removes the first node from the settings (root node) from the list
2743 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
2744 if (!$navigationactivenode->mainnavonly
) {
2745 $items[] = $navigationactivenode;
2747 $navigationactivenode = $navigationactivenode->parent
;
2749 } else if ($navigationactivenode) {
2750 // Parse the navigation tree to get the active node
2751 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
2752 if (!$navigationactivenode->mainnavonly
) {
2753 $items[] = $navigationactivenode;
2755 $navigationactivenode = $navigationactivenode->parent
;
2757 } else if ($settingsactivenode) {
2758 // Parse the settings navigation to get the active node
2759 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
2760 if (!$settingsactivenode->mainnavonly
) {
2761 $items[] = $settingsactivenode;
2763 $settingsactivenode = $settingsactivenode->parent
;
2768 $items[] = new navigation_node(array(
2769 'text'=>$this->page
->navigation
->text
,
2770 'shorttext'=>$this->page
->navigation
->shorttext
,
2771 'key'=>$this->page
->navigation
->key
,
2772 'action'=>$this->page
->navigation
->action
2775 $this->items
= array_reverse($items);
2776 return $this->items
;
2780 * Add a new navigation_node to the navbar, overrides parent::add
2782 * This function overrides {@link navigation_node::add()} so that we can change
2783 * the way nodes get added to allow us to simply call add and have the node added to the
2786 * @param string $text
2787 * @param string|moodle_url $action
2789 * @param string|int $key
2790 * @param string $shorttext
2791 * @param string $icon
2792 * @return navigation_node
2794 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
2795 if ($this->content
!== null) {
2796 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
2799 // Properties array used when creating the new navigation node
2804 // Set the action if one was provided
2805 if ($action!==null) {
2806 $itemarray['action'] = $action;
2808 // Set the shorttext if one was provided
2809 if ($shorttext!==null) {
2810 $itemarray['shorttext'] = $shorttext;
2812 // Set the icon if one was provided
2814 $itemarray['icon'] = $icon;
2816 // Default the key to the number of children if not provided
2817 if ($key === null) {
2818 $key = count($this->children
);
2821 $itemarray['key'] = $key;
2822 // Set the parent to this node
2823 $itemarray['parent'] = $this;
2824 // Add the child using the navigation_node_collections add method
2825 $this->children
[] = new navigation_node($itemarray);
2831 * Class used to manage the settings option for the current page
2833 * This class is used to manage the settings options in a tree format (recursively)
2834 * and was created initially for use with the settings blocks.
2836 * @package moodlecore
2837 * @subpackage navigation
2838 * @copyright 2009 Sam Hemelryk
2839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2841 class settings_navigation
extends navigation_node
{
2842 /** @var stdClass */
2844 /** @var moodle_page */
2847 protected $adminsection;
2849 protected $initialised = false;
2851 protected $userstoextendfor = array();
2852 /** @var navigation_cache **/
2856 * Sets up the object with basic settings and preparse it for use
2858 * @param moodle_page $page
2860 public function __construct(moodle_page
&$page) {
2861 if (during_initial_install()) {
2864 $this->page
= $page;
2865 // Initialise the main navigation. It is most important that this is done
2866 // before we try anything
2867 $this->page
->navigation
->initialise();
2868 // Initialise the navigation cache
2869 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2870 $this->children
= new navigation_node_collection();
2873 * Initialise the settings navigation based on the current context
2875 * This function initialises the settings navigation tree for a given context
2876 * by calling supporting functions to generate major parts of the tree.
2879 public function initialise() {
2880 global $DB, $SESSION;
2882 if (during_initial_install()) {
2884 } else if ($this->initialised
) {
2887 $this->id
= 'settingsnav';
2888 $this->context
= $this->page
->context
;
2890 $context = $this->context
;
2891 if ($context->contextlevel
== CONTEXT_BLOCK
) {
2892 $this->load_block_settings();
2893 $context = $context->get_parent_context();
2896 switch ($context->contextlevel
) {
2897 case CONTEXT_SYSTEM
:
2898 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2899 $this->load_front_page_settings(($context->id
== $this->context
->id
));
2902 case CONTEXT_COURSECAT
:
2903 $this->load_category_settings();
2905 case CONTEXT_COURSE
:
2906 if ($this->page
->course
->id
!= SITEID
) {
2907 $this->load_course_settings(($context->id
== $this->context
->id
));
2909 $this->load_front_page_settings(($context->id
== $this->context
->id
));
2912 case CONTEXT_MODULE
:
2913 $this->load_module_settings();
2914 $this->load_course_settings();
2917 if ($this->page
->course
->id
!= SITEID
) {
2918 $this->load_course_settings();
2923 $settings = $this->load_user_settings($this->page
->course
->id
);
2925 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') ||
$SESSION->load_navigation_admin
)) {
2926 $admin = $this->load_administration_settings();
2927 $SESSION->load_navigation_admin
= ($admin->has_children());
2932 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $admin) {
2933 $admin->force_open();
2934 } else if ($context->contextlevel
== CONTEXT_USER
&& $settings) {
2935 $settings->force_open();
2938 // Check if the user is currently logged in as another user
2939 if (session_is_loggedinas()) {
2940 // Get the actual user, we need this so we can display an informative return link
2941 $realuser = session_get_realuser();
2942 // Add the informative return to original user link
2943 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page
->course
->id
, 'return'=>1,'sesskey'=>sesskey()));
2944 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self
::TYPE_SETTING
, null, null, new pix_icon('t/left', ''));
2947 foreach ($this->children
as $key=>$node) {
2948 if ($node->nodetype
!= self
::NODETYPE_BRANCH ||
$node->children
->count()===0) {
2952 $this->initialised
= true;
2955 * Override the parent function so that we can add preceeding hr's and set a
2956 * root node class against all first level element
2958 * It does this by first calling the parent's add method {@link navigation_node::add()}
2959 * and then proceeds to use the key to set class and hr
2961 * @param string $text
2962 * @param sting|moodle_url $url
2963 * @param string $shorttext
2964 * @param string|int $key
2966 * @param string $icon
2967 * @return navigation_node
2969 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
2970 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
2971 $node->add_class('root_node');
2976 * This function allows the user to add something to the start of the settings
2977 * navigation, which means it will be at the top of the settings navigation block
2979 * @param string $text
2980 * @param sting|moodle_url $url
2981 * @param string $shorttext
2982 * @param string|int $key
2984 * @param string $icon
2985 * @return navigation_node
2987 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
2988 $children = $this->children
;
2989 $childrenclass = get_class($children);
2990 $this->children
= new $childrenclass;
2991 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2992 foreach ($children as $child) {
2993 $this->children
->add($child);
2998 * Load the site administration tree
3000 * This function loads the site administration tree by using the lib/adminlib library functions
3002 * @param navigation_node $referencebranch A reference to a branch in the settings
3004 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3005 * tree and start at the beginning
3006 * @return mixed A key to access the admin tree by
3008 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
3011 // Check if we are just starting to generate this navigation.
3012 if ($referencebranch === null) {
3014 // Require the admin lib then get an admin structure
3015 if (!function_exists('admin_get_root')) {
3016 require_once($CFG->dirroot
.'/lib/adminlib.php');
3018 $adminroot = admin_get_root(false, false);
3019 // This is the active section identifier
3020 $this->adminsection
= $this->page
->url
->param('section');
3022 // Disable the navigation from automatically finding the active node
3023 navigation_node
::$autofindactive = false;
3024 $referencebranch = $this->add(get_string('administrationsite'), null, self
::TYPE_SETTING
, null, 'root');
3025 foreach ($adminroot->children
as $adminbranch) {
3026 $this->load_administration_settings($referencebranch, $adminbranch);
3028 navigation_node
::$autofindactive = true;
3030 // Use the admin structure to locate the active page
3031 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
3032 $currentnode = $this;
3033 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
3034 $currentnode = $currentnode->get($pathkey);
3037 $currentnode->make_active();
3040 $this->scan_for_active_node($referencebranch);
3042 return $referencebranch;
3043 } else if ($adminbranch->check_access()) {
3044 // We have a reference branch that we can access and is not hidden `hurrah`
3045 // Now we need to display it and any children it may have
3048 if ($adminbranch instanceof admin_settingpage
) {
3049 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name
));
3050 } else if ($adminbranch instanceof admin_externalpage
) {
3051 $url = $adminbranch->url
;
3055 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
3057 if ($adminbranch->is_hidden()) {
3058 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
3059 $reference->add_class('hidden');
3061 $reference->display
= false;
3065 // Check if we are generating the admin notifications and whether notificiations exist
3066 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
3067 $reference->add_class('criticalnotification');
3069 // Check if this branch has children
3070 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
3071 foreach ($adminbranch->children
as $branch) {
3072 // Generate the child branches as well now using this branch as the reference
3073 $this->load_administration_settings($reference, $branch);
3076 $reference->icon
= new pix_icon('i/settings', '');
3082 * This function recursivily scans nodes until it finds the active node or there
3083 * are no more nodes.
3084 * @param navigation_node $node
3086 protected function scan_for_active_node(navigation_node
$node) {
3087 if (!$node->check_if_active() && $node->children
->count()>0) {
3088 foreach ($node->children
as &$child) {
3089 $this->scan_for_active_node($child);
3095 * Gets a navigation node given an array of keys that represent the path to
3098 * @param array $path
3099 * @return navigation_node|false
3101 protected function get_by_path(array $path) {
3102 $node = $this->get(array_shift($path));
3103 foreach ($path as $key) {
3110 * Generate the list of modules for the given course.
3112 * @param stdClass $course The course to get modules for
3114 protected function get_course_modules($course) {
3116 $mods = $modnames = $modnamesplural = $modnamesused = array();
3117 // This function is included when we include course/lib.php at the top
3119 get_all_mods($course->id
, $mods, $modnames, $modnamesplural, $modnamesused);
3120 $resources = array();
3121 $activities = array();
3122 foreach($modnames as $modname=>$modnamestr) {
3123 if (!course_allowed_module($course, $modname)) {
3127 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3128 if (!file_exists($libfile)) {
3131 include_once($libfile);
3132 $gettypesfunc = $modname.'_get_types';
3133 if (function_exists($gettypesfunc)) {
3134 $types = $gettypesfunc();
3135 foreach($types as $type) {
3136 if (!isset($type->modclass
) ||
!isset($type->typestr
)) {
3137 debugging('Incorrect activity type in '.$modname);
3140 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
3141 $resources[html_entity_decode($type->type
)] = $type->typestr
;
3143 $activities[html_entity_decode($type->type
)] = $type->typestr
;
3147 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
3148 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
3149 $resources[$modname] = $modnamestr;
3151 // all other archetypes are considered activity
3152 $activities[$modname] = $modnamestr;
3156 return array($resources, $activities);
3160 * This function loads the course settings that are available for the user
3162 * @param bool $forceopen If set to true the course node will be forced open
3163 * @return navigation_node|false
3165 protected function load_course_settings($forceopen = false) {
3168 $course = $this->page
->course
;
3169 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
3171 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3173 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
3175 $coursenode->force_open();
3178 if (has_capability('moodle/course:update', $coursecontext)) {
3179 // Add the turn on/off settings
3180 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
3181 if ($this->page
->user_is_editing()) {
3182 $url->param('edit', 'off');
3183 $editstring = get_string('turneditingoff');
3185 $url->param('edit', 'on');
3186 $editstring = get_string('turneditingon');
3188 $coursenode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3190 if ($this->page
->user_is_editing()) {
3191 // Removed as per MDL-22732
3192 // $this->add_course_editing_links($course);
3195 // Add the course settings link
3196 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
3197 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3199 // Add the course completion settings link
3200 if ($CFG->enablecompletion
&& $course->enablecompletion
) {
3201 $url = new moodle_url('/course/completion.php', array('id'=>$course->id
));
3202 $coursenode->add(get_string('completion', 'completion'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3207 enrol_add_course_navigation($coursenode, $course);
3210 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3211 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
3212 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
3215 // Add view grade report is permitted
3216 $reportavailable = false;
3217 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3218 $reportavailable = true;
3219 } else if (!empty($course->showgrades
)) {
3220 $reports = get_plugin_list('gradereport');
3221 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3222 arsort($reports); // user is last, we want to test it first
3223 foreach ($reports as $plugin => $plugindir) {
3224 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3225 //stop when the first visible plugin is found
3226 $reportavailable = true;
3232 if ($reportavailable) {
3233 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
3234 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, 'grades', new pix_icon('i/grades', ''));
3237 // Add outcome if permitted
3238 if (!empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $coursecontext)) {
3239 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
3240 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
3243 // Backup this course
3244 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3245 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
3246 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
3249 // Restore to this course
3250 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3251 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
3252 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
3255 // Import data from other courses
3256 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3257 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
3258 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/restore', ''));
3261 // Publish course on a hub
3262 if (has_capability('moodle/course:publish', $coursecontext)) {
3263 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
3264 $coursenode->add(get_string('publish'), $url, self
::TYPE_SETTING
, null, 'publish', new pix_icon('i/publish', ''));
3267 // Reset this course
3268 if (has_capability('moodle/course:reset', $coursecontext)) {
3269 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
3270 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/return', ''));
3274 require_once($CFG->libdir
. '/questionlib.php');
3275 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3277 if (has_capability('moodle/course:update', $coursecontext)) {
3278 // Repository Instances
3279 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
3280 require_once($CFG->dirroot
. '/repository/lib.php');
3281 $editabletypes = repository
::get_editable_types($coursecontext);
3282 $haseditabletypes = !empty($editabletypes);
3283 unset($editabletypes);
3284 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
3286 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
3288 if ($haseditabletypes) {
3289 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
3290 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
3295 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3296 // hidden in new courses and courses where legacy files were turned off
3297 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
3298 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/files', ''));
3303 $assumedrole = $this->in_alternative_role();
3304 if ($assumedrole !== false) {
3305 $roles[0] = get_string('switchrolereturn');
3307 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3308 $availableroles = get_switchable_roles($coursecontext);
3309 if (is_array($availableroles)) {
3310 foreach ($availableroles as $key=>$role) {
3311 if ($assumedrole == (int)$key) {
3314 $roles[$key] = $role;
3318 if (is_array($roles) && count($roles)>0) {
3319 $switchroles = $this->add(get_string('switchroleto'));
3320 if ((count($roles)==1 && array_key_exists(0, $roles))||
$assumedrole!==false) {
3321 $switchroles->force_open();
3323 $returnurl = $this->page
->url
;
3324 $returnurl->param('sesskey', sesskey());
3325 foreach ($roles as $key => $name) {
3326 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3327 $switchroles->add($name, $url, self
::TYPE_SETTING
, null, $key, new pix_icon('i/roles', ''));
3330 // Return we are done
3335 * Adds branches and links to the settings navigation to add course activities
3338 * @param stdClass $course
3340 protected function add_course_editing_links($course) {
3343 require_once($CFG->dirroot
.'/course/lib.php');
3345 // Add `add` resources|activities branches
3346 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3347 if (file_exists($structurefile)) {
3348 require_once($structurefile);
3349 $requestkey = call_user_func('callback_'.$course->format
.'_request_key');
3350 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3352 $requestkey = get_string('section');
3353 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3356 $sections = get_all_sections($course->id
);
3358 $addresource = $this->add(get_string('addresource'));
3359 $addactivity = $this->add(get_string('addactivity'));
3360 if ($formatidentifier!==0) {
3361 $addresource->force_open();
3362 $addactivity->force_open();
3365 $this->get_course_modules($course);
3367 $textlib = textlib_get_instance();
3369 foreach ($sections as $section) {
3370 if ($formatidentifier !== 0 && $section->section
!= $formatidentifier) {
3373 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id
, $requestkey=>$section->section
));
3374 if ($section->section
== 0) {
3375 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3376 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3378 $sectionname = get_section_name($course, $section);
3379 $sectionresources = $addresource->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3380 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3382 foreach ($resources as $value=>$resource) {
3383 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3384 $pos = strpos($value, '&type=');
3386 $url->param('add', $textlib->substr($value, 0,$pos));
3387 $url->param('type', $textlib->substr($value, $pos+
6));
3389 $url->param('add', $value);
3391 $sectionresources->add($resource, $url, self
::TYPE_SETTING
);
3394 foreach ($activities as $activityname=>$activity) {
3395 if ($activity==='--') {
3399 if (strpos($activity, '--')===0) {
3400 $subbranch = $sectionactivities->add(trim($activity, '-'));
3403 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3404 $pos = strpos($activityname, '&type=');
3406 $url->param('add', $textlib->substr($activityname, 0,$pos));
3407 $url->param('type', $textlib->substr($activityname, $pos+
6));
3409 $url->param('add', $activityname);
3411 if ($subbranch !== false) {
3412 $subbranch->add($activity, $url, self
::TYPE_SETTING
);
3414 $sectionactivities->add($activity, $url, self
::TYPE_SETTING
);
3421 * This function calls the module function to inject module settings into the
3422 * settings navigation tree.
3424 * This only gets called if there is a corrosponding function in the modules
3427 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3429 * @return navigation_node|false
3431 protected function load_module_settings() {
3434 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
3435 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
3436 $this->page
->set_cm($cm, $this->page
->course
);
3439 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
3440 if (file_exists($file)) {
3441 require_once($file);
3444 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
));
3445 $modulenode->force_open();
3447 // Settings for the module
3448 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
3449 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => true, 'sesskey' => sesskey()));
3450 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
3452 // Assign local roles
3453 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
3454 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
3455 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
3458 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
3459 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
3460 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
3462 // Check role permissions
3463 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
3464 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
3465 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
3468 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
3469 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
3470 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
3473 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3474 foreach ($reports as $reportfunction) {
3475 $reportfunction($modulenode, $this->page
->cm
);
3477 // Add a backup link
3478 $featuresfunc = $this->page
->activityname
.'_supports';
3479 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
3480 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
3481 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
3484 // Restore this activity
3485 $featuresfunc = $this->page
->activityname
.'_supports';
3486 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
3487 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
3488 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
3491 // Allow the active advanced grading method plugin to append its settings
3492 $featuresfunc = $this->page
->activityname
.'_supports';
3493 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
3494 require_once($CFG->dirroot
.'/grade/grading/lib.php');
3495 $gradingman = get_grading_manager($this->page
->cm
->context
, $this->page
->activityname
);
3496 $gradingman->extend_settings_navigation($this, $modulenode);
3499 $function = $this->page
->activityname
.'_extend_settings_navigation';
3500 if (!function_exists($function)) {
3504 $function($this, $modulenode);
3506 // Remove the module node if there are no children
3507 if (empty($modulenode->children
)) {
3508 $modulenode->remove();
3515 * Loads the user settings block of the settings nav
3517 * This function is simply works out the userid and whether we need to load
3518 * just the current users profile settings, or the current user and the user the
3519 * current user is viewing.
3521 * This function has some very ugly code to work out the user, if anyone has
3522 * any bright ideas please feel free to intervene.
3524 * @param int $courseid The course id of the current course
3525 * @return navigation_node|false
3527 protected function load_user_settings($courseid=SITEID
) {
3528 global $USER, $FULLME, $CFG;
3530 if (isguestuser() ||
!isloggedin()) {
3534 $navusers = $this->page
->navigation
->get_extending_users();
3536 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
3538 foreach ($this->userstoextendfor
as $userid) {
3539 if ($userid == $USER->id
) {
3542 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3543 if (is_null($usernode)) {
3547 foreach ($navusers as $user) {
3548 if ($user->id
== $USER->id
) {
3551 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
3552 if (is_null($usernode)) {
3556 $this->generate_user_settings($courseid, $USER->id
);
3558 $usernode = $this->generate_user_settings($courseid, $USER->id
);
3564 * Extends the settings navigation for the given user.
3566 * Note: This method gets called automatically if you call
3567 * $PAGE->navigation->extend_for_user($userid)
3569 * @param int $userid
3571 public function extend_for_user($userid) {
3574 if (!in_array($userid, $this->userstoextendfor
)) {
3575 $this->userstoextendfor
[] = $userid;
3576 if ($this->initialised
) {
3577 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
3578 $children = array();
3579 foreach ($this->children
as $child) {
3580 $children[] = $child;
3582 array_unshift($children, array_pop($children));
3583 $this->children
= new navigation_node_collection();
3584 foreach ($children as $child) {
3585 $this->children
->add($child);
3592 * This function gets called by {@link load_user_settings()} and actually works out
3593 * what can be shown/done
3595 * @global moodle_database $DB
3596 * @param int $courseid The current course' id
3597 * @param int $userid The user id to load for
3598 * @param string $gstitle The string to pass to get_string for the branch title
3599 * @return navigation_node|false
3601 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3602 global $DB, $CFG, $USER, $SITE;
3604 if ($courseid != SITEID
) {
3605 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
3606 $course = $this->page
->course
;
3608 list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
3609 $sql = "SELECT c.* $select FROM {course} c $join WHERE c.id = :courseid";
3610 $course = $DB->get_record_sql($sql, array('courseid' => $courseid), MUST_EXIST
);
3611 context_instance_preload($course);
3617 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3618 $systemcontext = get_system_context();
3619 $currentuser = ($USER->id
== $userid);
3623 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3626 list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER
, 'ctx');
3627 $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
3628 $user = $DB->get_record_sql($sql, array('userid' => $userid), IGNORE_MISSING
);
3632 context_instance_preload($user);
3634 // Check that the user can view the profile
3635 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3636 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3638 if ($course->id
== SITEID
) {
3639 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
3640 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3644 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3645 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3646 if ((!$canviewusercourse && !$canviewuser) ||
!can_access_course($course, $user->id
)) {
3649 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
) {
3650 // If groups are in use, make sure we can see that group
3656 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
3659 if ($gstitle != 'usercurrentsettings') {
3663 // Add a user setting branch
3664 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self
::TYPE_CONTAINER
, null, $key);
3665 $usersetting->id
= 'usersettings';
3666 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $this->page
->context
->instanceid
== $user->id
) {
3667 // Automatically start by making it active
3668 $usersetting->make_active();
3671 // Check if the user has been deleted
3672 if ($user->deleted
) {
3673 if (!has_capability('moodle/user:update', $coursecontext)) {
3674 // We can't edit the user so just show the user deleted message
3675 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
3677 // We can edit the user so show the user deleted message and link it to the profile
3678 if ($course->id
== SITEID
) {
3679 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
3681 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
3683 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
3688 $userauthplugin = false;
3689 if (!empty($user->auth
)) {
3690 $userauthplugin = get_auth_plugin($user->auth
);
3693 // Add the profile edit link
3694 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3695 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3696 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
3697 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
3698 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3699 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3700 $url = $userauthplugin->edit_profile_url();
3702 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
3704 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
3709 // Change password link
3710 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3711 $passwordchangeurl = $userauthplugin->change_password_url();
3712 if (empty($passwordchangeurl)) {
3713 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
3715 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
);
3718 // View the roles settings
3719 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3720 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
3722 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
3723 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
3725 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
3727 if (!empty($assignableroles)) {
3728 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3729 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
3732 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
3733 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3734 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3737 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3738 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3742 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
3743 require_once($CFG->libdir
. '/portfoliolib.php');
3744 if (portfolio_instances(true, false)) {
3745 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
3747 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
3748 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
3750 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
3751 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
3755 $enablemanagetokens = false;
3756 if (!empty($CFG->enablerssfeeds
)) {
3757 $enablemanagetokens = true;
3758 } else if (!is_siteadmin($USER->id
)
3759 && !empty($CFG->enablewebservices
)
3760 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3761 $enablemanagetokens = true;
3764 if ($currentuser && $enablemanagetokens) {
3765 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3766 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
3770 if (!$currentuser && $usercontext->contextlevel
== CONTEXT_USER
) {
3771 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
3772 require_once($CFG->dirroot
. '/repository/lib.php');
3773 $editabletypes = repository
::get_editable_types($usercontext);
3774 $haseditabletypes = !empty($editabletypes);
3775 unset($editabletypes);
3776 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
3778 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
3780 if ($haseditabletypes) {
3781 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id
));
3782 $usersetting->add(get_string('repositories', 'repository'), $url, self
::TYPE_SETTING
);
3787 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
3788 $url = new moodle_url('/message/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
3789 $usersetting->add(get_string('editmymessage', 'message'), $url, self
::TYPE_SETTING
);
3793 if ($currentuser && !empty($CFG->bloglevel
)) {
3794 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
3795 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node
::TYPE_SETTING
);
3796 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM
))) {
3797 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node
::TYPE_SETTING
);
3798 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node
::TYPE_SETTING
);
3803 if (!$user->deleted
and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id
)) {
3804 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id
, 'user'=>$user->id
, 'sesskey'=>sesskey()));
3805 $usersetting->add(get_string('loginas'), $url, self
::TYPE_SETTING
);
3808 return $usersetting;
3812 * Loads block specific settings in the navigation
3814 * @return navigation_node
3816 protected function load_block_settings() {
3819 $blocknode = $this->add(print_context_name($this->context
));
3820 $blocknode->force_open();
3822 // Assign local roles
3823 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
3824 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
);
3827 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
3828 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
3829 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3831 // Check role permissions
3832 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
3833 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
3834 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3841 * Loads category specific settings in the navigation
3843 * @return navigation_node
3845 protected function load_category_settings() {
3848 $categorynode = $this->add(print_context_name($this->context
));
3849 $categorynode->force_open();
3851 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context
)) {
3852 $url = new moodle_url('/course/category.php', array('id'=>$this->context
->instanceid
, 'sesskey'=>sesskey()));
3853 if ($this->page
->user_is_editing()) {
3854 $url->param('categoryedit', '0');
3855 $editstring = get_string('turneditingoff');
3857 $url->param('categoryedit', '1');
3858 $editstring = get_string('turneditingon');
3860 $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3863 if ($this->page
->user_is_editing() && has_capability('moodle/category:manage', $this->context
)) {
3864 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context
->instanceid
));
3865 $categorynode->add(get_string('editcategorythis'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
3867 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context
->instanceid
));
3868 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
3871 // Assign local roles
3872 if (has_capability('moodle/role:assign', $this->context
)) {
3873 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
3874 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/roles', ''));
3878 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
3879 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
3880 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
3882 // Check role permissions
3883 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
3884 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
3885 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
3889 if (has_capability('moodle/cohort:manage', $this->context
) or has_capability('moodle/cohort:view', $this->context
)) {
3890 $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', ''));
3894 if (has_capability('moodle/filter:manage', $this->context
) && count(filter_get_available_in_context($this->context
))>0) {
3895 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context
->id
));
3896 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
3899 return $categorynode;
3903 * Determine whether the user is assuming another role
3905 * This function checks to see if the user is assuming another role by means of
3906 * role switching. In doing this we compare each RSW key (context path) against
3907 * the current context path. This ensures that we can provide the switching
3908 * options against both the course and any page shown under the course.
3910 * @return bool|int The role(int) if the user is in another role, false otherwise
3912 protected function in_alternative_role() {
3914 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
3915 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
3916 return $USER->access
['rsw'][$this->page
->context
->path
];
3918 foreach ($USER->access
['rsw'] as $key=>$role) {
3919 if (strpos($this->context
->path
,$key)===0) {
3928 * This function loads all of the front page settings into the settings navigation.
3929 * This function is called when the user is on the front page, or $COURSE==$SITE
3930 * @return navigation_node
3932 protected function load_front_page_settings($forceopen = false) {
3935 $course = clone($SITE);
3936 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3938 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
3940 $frontpage->force_open();
3942 $frontpage->id
= 'frontpagesettings';
3944 if (has_capability('moodle/course:update', $coursecontext)) {
3946 // Add the turn on/off settings
3947 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
3948 if ($this->page
->user_is_editing()) {
3949 $url->param('edit', 'off');
3950 $editstring = get_string('turneditingoff');
3952 $url->param('edit', 'on');
3953 $editstring = get_string('turneditingon');
3955 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3957 // Add the course settings link
3958 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
3959 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3963 enrol_add_course_navigation($frontpage, $course);
3966 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3967 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
3968 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
3971 // Backup this course
3972 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3973 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
3974 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
3977 // Restore to this course
3978 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3979 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
3980 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
3984 require_once($CFG->libdir
. '/questionlib.php');
3985 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
3988 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $this->context
)) {
3989 //hiden in new installs
3990 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
3991 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/files', ''));
3997 * This function marks the cache as volatile so it is cleared during shutdown
3999 public function clear_cache() {
4000 $this->cache
->volatile();
4005 * Simple class used to output a navigation branch in XML
4007 * @package moodlecore
4008 * @subpackage navigation
4009 * @copyright 2009 Sam Hemelryk
4010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4012 class navigation_json
{
4014 protected $nodetype = array('node','branch');
4016 protected $expandable = array();
4018 * Turns a branch and all of its children into XML
4020 * @param navigation_node $branch
4021 * @return string XML string
4023 public function convert($branch) {
4024 $xml = $this->convert_child($branch);
4028 * Set the expandable items in the array so that we have enough information
4029 * to attach AJAX events
4030 * @param array $expandable
4032 public function set_expandable($expandable) {
4033 foreach ($expandable as $node) {
4034 $this->expandable
[$node['key'].':'.$node['type']] = $node;
4038 * Recusively converts a child node and its children to XML for output
4040 * @param navigation_node $child The child to convert
4041 * @param int $depth Pointlessly used to track the depth of the XML structure
4042 * @return string JSON
4044 protected function convert_child($child, $depth=1) {
4045 if (!$child->display
) {
4048 $attributes = array();
4049 $attributes['id'] = $child->id
;
4050 $attributes['name'] = $child->text
;
4051 $attributes['type'] = $child->type
;
4052 $attributes['key'] = $child->key
;
4053 $attributes['class'] = $child->get_css_type();
4055 if ($child->icon
instanceof pix_icon
) {
4056 $attributes['icon'] = array(
4057 'component' => $child->icon
->component
,
4058 'pix' => $child->icon
->pix
,
4060 foreach ($child->icon
->attributes
as $key=>$value) {
4061 if ($key == 'class') {
4062 $attributes['icon']['classes'] = explode(' ', $value);
4063 } else if (!array_key_exists($key, $attributes['icon'])) {
4064 $attributes['icon'][$key] = $value;
4068 } else if (!empty($child->icon
)) {
4069 $attributes['icon'] = (string)$child->icon
;
4072 if ($child->forcetitle ||
$child->title
!== $child->text
) {
4073 $attributes['title'] = htmlentities($child->title
);
4075 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
4076 $attributes['expandable'] = $child->key
;
4077 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
4080 if (count($child->classes
)>0) {
4081 $attributes['class'] .= ' '.join(' ',$child->classes
);
4083 if (is_string($child->action
)) {
4084 $attributes['link'] = $child->action
;
4085 } else if ($child->action
instanceof moodle_url
) {
4086 $attributes['link'] = $child->action
->out();
4087 } else if ($child->action
instanceof action_link
) {
4088 $attributes['link'] = $child->action
->url
->out();
4090 $attributes['hidden'] = ($child->hidden
);
4091 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
4093 if ($child->children
->count() > 0) {
4094 $attributes['children'] = array();
4095 foreach ($child->children
as $subchild) {
4096 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
4103 return json_encode($attributes);
4109 * The cache class used by global navigation and settings navigation to cache bits
4110 * and bobs that are used during their generation.
4112 * It is basically an easy access point to session with a bit of smarts to make
4113 * sure that the information that is cached is valid still.
4117 * if (!$cache->viewdiscussion()) {
4118 * // Code to do stuff and produce cachable content
4119 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4121 * $content = $cache->viewdiscussion;
4124 * @package moodlecore
4125 * @subpackage navigation
4126 * @copyright 2009 Sam Hemelryk
4127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4129 class navigation_cache
{
4131 protected $creation;
4138 /** @var stdClass */
4139 protected $currentcontext;
4141 const CACHETIME
= 0;
4143 const CACHEUSERID
= 1;
4145 const CACHEVALUE
= 2;
4146 /** @var null|array An array of navigation cache areas to expire on shutdown */
4147 public static $volatilecaches;
4150 * Contructor for the cache. Requires two arguments
4152 * @param string $area The string to use to segregate this particular cache
4153 * it can either be unique to start a fresh cache or if you want
4154 * to share a cache then make it the string used in the original
4156 * @param int $timeout The number of seconds to time the information out after
4158 public function __construct($area, $timeout=1800) {
4159 $this->creation
= time();
4160 $this->area
= $area;
4161 $this->timeout
= time() - $timeout;
4162 if (rand(0,100) === 0) {
4163 $this->garbage_collection();
4168 * Used to set up the cache within the SESSION.
4170 * This is called for each access and ensure that we don't put anything into the session before
4173 protected function ensure_session_cache_initialised() {
4175 if (empty($this->session
)) {
4176 if (!isset($SESSION->navcache
)) {
4177 $SESSION->navcache
= new stdClass
;
4179 if (!isset($SESSION->navcache
->{$this->area
})) {
4180 $SESSION->navcache
->{$this->area
} = array();
4182 $this->session
= &$SESSION->navcache
->{$this->area
};
4187 * Magic Method to retrieve something by simply calling using = cache->key
4189 * @param mixed $key The identifier for the information you want out again
4190 * @return void|mixed Either void or what ever was put in
4192 public function __get($key) {
4193 if (!$this->cached($key)) {
4196 $information = $this->session
[$key][self
::CACHEVALUE
];
4197 return unserialize($information);
4201 * Magic method that simply uses {@link set();} to store something in the cache
4203 * @param string|int $key
4204 * @param mixed $information
4206 public function __set($key, $information) {
4207 $this->set($key, $information);
4211 * Sets some information against the cache (session) for later retrieval
4213 * @param string|int $key
4214 * @param mixed $information
4216 public function set($key, $information) {
4218 $this->ensure_session_cache_initialised();
4219 $information = serialize($information);
4220 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
4223 * Check the existence of the identifier in the cache
4225 * @param string|int $key
4228 public function cached($key) {
4230 $this->ensure_session_cache_initialised();
4231 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
) {
4237 * Compare something to it's equivilant in the cache
4239 * @param string $key
4240 * @param mixed $value
4241 * @param bool $serialise Whether to serialise the value before comparison
4242 * this should only be set to false if the value is already
4244 * @return bool If the value is the same false if it is not set or doesn't match
4246 public function compare($key, $value, $serialise = true) {
4247 if ($this->cached($key)) {
4249 $value = serialize($value);
4251 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
4258 * Wipes the entire cache, good to force regeneration
4260 public function clear() {
4262 unset($SESSION->navcache
);
4263 $this->session
= null;
4266 * Checks all cache entries and removes any that have expired, good ole cleanup
4268 protected function garbage_collection() {
4269 if (empty($this->session
)) {
4272 foreach ($this->session
as $key=>$cachedinfo) {
4273 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
4274 unset($this->session
[$key]);
4280 * Marks the cache as being volatile (likely to change)
4282 * Any caches marked as volatile will be destroyed at the on shutdown by
4283 * {@link navigation_node::destroy_volatile_caches()} which is registered
4284 * as a shutdown function if any caches are marked as volatile.
4286 * @param bool $setting True to destroy the cache false not too
4288 public function volatile($setting = true) {
4289 if (self
::$volatilecaches===null) {
4290 self
::$volatilecaches = array();
4291 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4295 self
::$volatilecaches[$this->area
] = $this->area
;
4296 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
4297 unset(self
::$volatilecaches[$this->area
]);
4302 * Destroys all caches marked as volatile
4304 * This function is static and works in conjunction with the static volatilecaches
4305 * property of navigation cache.
4306 * Because this function is static it manually resets the cached areas back to an
4309 public static function destroy_volatile_caches() {
4311 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
4312 foreach (self
::$volatilecaches as $area) {
4313 $SESSION->navcache
->{$area} = array();
4316 $SESSION->navcache
= new stdClass
;