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 * @copyright 2009 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') ||
die();
31 * The name that will be used to separate the navigation cache within SESSION
33 define('NAVIGATION_CACHE_NAME', 'navigation');
36 * This class is used to represent a node in a navigation tree
38 * This class is used to represent a node in a navigation tree within Moodle,
39 * the tree could be one of global navigation, settings navigation, or the navbar.
40 * Each node can be one of two types either a Leaf (default) or a branch.
41 * When a node is first created it is created as a leaf, when/if children are added
42 * the node then becomes a branch.
45 * @category navigation
46 * @copyright 2009 Sam Hemelryk
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class navigation_node
implements renderable
{
50 /** @var int Used to identify this node a leaf (default) 0 */
51 const NODETYPE_LEAF
= 0;
52 /** @var int Used to identify this node a branch, happens with children 1 */
53 const NODETYPE_BRANCH
= 1;
54 /** @var null Unknown node type null */
55 const TYPE_UNKNOWN
= null;
56 /** @var int System node type 0 */
57 const TYPE_ROOTNODE
= 0;
58 /** @var int System node type 1 */
59 const TYPE_SYSTEM
= 1;
60 /** @var int Category node type 10 */
61 const TYPE_CATEGORY
= 10;
62 /** @var int Course node type 20 */
63 const TYPE_COURSE
= 20;
64 /** @var int Course Structure node type 30 */
65 const TYPE_SECTION
= 30;
66 /** @var int Activity node type, e.g. Forum, Quiz 40 */
67 const TYPE_ACTIVITY
= 40;
68 /** @var int Resource node type, e.g. Link to a file, or label 50 */
69 const TYPE_RESOURCE
= 50;
70 /** @var int A custom node type, default when adding without specifing type 60 */
71 const TYPE_CUSTOM
= 60;
72 /** @var int Setting node type, used only within settings nav 70 */
73 const TYPE_SETTING
= 70;
74 /** @var int Setting node type, used only within settings nav 80 */
76 /** @var int Setting node type, used for containers of no importance 90 */
77 const TYPE_CONTAINER
= 90;
79 /** @var int Parameter to aid the coder in tracking [optional] */
81 /** @var string|int The identifier for the node, used to retrieve the node */
83 /** @var string The text to use for the node */
85 /** @var string Short text to use if requested [optional] */
86 public $shorttext = null;
87 /** @var string The title attribute for an action if one is defined */
89 /** @var string A string that can be used to build a help button */
90 public $helpbutton = null;
91 /** @var moodle_url|action_link|null An action for the node (link) */
92 public $action = null;
93 /** @var pix_icon The path to an icon to use for this node */
95 /** @var int See TYPE_* constants defined for this class */
96 public $type = self
::TYPE_UNKNOWN
;
97 /** @var int See NODETYPE_* constants defined for this class */
98 public $nodetype = self
::NODETYPE_LEAF
;
99 /** @var bool If set to true the node will be collapsed by default */
100 public $collapse = false;
101 /** @var bool If set to true the node will be expanded by default */
102 public $forceopen = false;
103 /** @var array An array of CSS classes for the node */
104 public $classes = array();
105 /** @var navigation_node_collection An array of child nodes */
106 public $children = array();
107 /** @var bool If set to true the node will be recognised as active */
108 public $isactive = false;
109 /** @var bool If set to true the node will be dimmed */
110 public $hidden = false;
111 /** @var bool If set to false the node will not be displayed */
112 public $display = true;
113 /** @var bool If set to true then an HR will be printed before the node */
114 public $preceedwithhr = false;
115 /** @var bool If set to true the the navigation bar should ignore this node */
116 public $mainnavonly = false;
117 /** @var bool If set to true a title will be added to the action no matter what */
118 public $forcetitle = false;
119 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
120 public $parent = null;
121 /** @var bool Override to not display the icon even if one is provided **/
122 public $hideicon = false;
124 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
125 /** @var moodle_url */
126 protected static $fullmeurl = null;
127 /** @var bool toogles auto matching of active node */
128 public static $autofindactive = true;
129 /** @var mixed If set to an int, that section will be included even if it has no activities */
130 public $includesectionnum = false;
133 * Constructs a new navigation_node
135 * @param array|string $properties Either an array of properties or a string to use
136 * as the text for the node
138 public function __construct($properties) {
139 if (is_array($properties)) {
140 // Check the array for each property that we allow to set at construction.
141 // text - The main content for the node
142 // shorttext - A short text if required for the node
143 // icon - The icon to display for the node
144 // type - The type of the node
145 // key - The key to use to identify the node
146 // parent - A reference to the nodes parent
147 // action - The action to attribute to this node, usually a URL to link to
148 if (array_key_exists('text', $properties)) {
149 $this->text
= $properties['text'];
151 if (array_key_exists('shorttext', $properties)) {
152 $this->shorttext
= $properties['shorttext'];
154 if (!array_key_exists('icon', $properties)) {
155 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
157 $this->icon
= $properties['icon'];
158 if ($this->icon
instanceof pix_icon
) {
159 if (empty($this->icon
->attributes
['class'])) {
160 $this->icon
->attributes
['class'] = 'navicon';
162 $this->icon
->attributes
['class'] .= ' navicon';
165 if (array_key_exists('type', $properties)) {
166 $this->type
= $properties['type'];
168 $this->type
= self
::TYPE_CUSTOM
;
170 if (array_key_exists('key', $properties)) {
171 $this->key
= $properties['key'];
173 // This needs to happen last because of the check_if_active call that occurs
174 if (array_key_exists('action', $properties)) {
175 $this->action
= $properties['action'];
176 if (is_string($this->action
)) {
177 $this->action
= new moodle_url($this->action
);
179 if (self
::$autofindactive) {
180 $this->check_if_active();
183 if (array_key_exists('parent', $properties)) {
184 $this->set_parent($properties['parent']);
186 } else if (is_string($properties)) {
187 $this->text
= $properties;
189 if ($this->text
=== null) {
190 throw new coding_exception('You must set the text for the node when you create it.');
192 // Default the title to the text
193 $this->title
= $this->text
;
194 // Instantiate a new navigation node collection for this nodes children
195 $this->children
= new navigation_node_collection();
199 * Checks if this node is the active node.
201 * This is determined by comparing the action for the node against the
202 * defined URL for the page. A match will see this node marked as active.
204 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
207 public function check_if_active($strength=URL_MATCH_EXACT
) {
208 global $FULLME, $PAGE;
209 // Set fullmeurl if it hasn't already been set
210 if (self
::$fullmeurl == null) {
211 if ($PAGE->has_set_url()) {
212 self
::override_active_url(new moodle_url($PAGE->url
));
214 self
::override_active_url(new moodle_url($FULLME));
218 // Compare the action of this node against the fullmeurl
219 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
220 $this->make_active();
227 * This sets the URL that the URL of new nodes get compared to when locating
230 * The active node is the node that matches the URL set here. By default this
231 * is either $PAGE->url or if that hasn't been set $FULLME.
233 * @param moodle_url $url The url to use for the fullmeurl.
235 public static function override_active_url(moodle_url
$url) {
236 // Clone the URL, in case the calling script changes their URL later.
237 self
::$fullmeurl = new moodle_url($url);
241 * Creates a navigation node, ready to add it as a child using add_node
242 * function. (The created node needs to be added before you can use it.)
243 * @param string $text
244 * @param moodle_url|action_link $action
246 * @param string $shorttext
247 * @param string|int $key
248 * @param pix_icon $icon
249 * @return navigation_node
251 public static function create($text, $action=null, $type=self
::TYPE_CUSTOM
,
252 $shorttext=null, $key=null, pix_icon
$icon=null) {
253 // Properties array used when creating the new navigation node
258 // Set the action if one was provided
259 if ($action!==null) {
260 $itemarray['action'] = $action;
262 // Set the shorttext if one was provided
263 if ($shorttext!==null) {
264 $itemarray['shorttext'] = $shorttext;
266 // Set the icon if one was provided
268 $itemarray['icon'] = $icon;
271 $itemarray['key'] = $key;
272 // Construct and return
273 return new navigation_node($itemarray);
277 * Adds a navigation node as a child of this node.
279 * @param string $text
280 * @param moodle_url|action_link $action
282 * @param string $shorttext
283 * @param string|int $key
284 * @param pix_icon $icon
285 * @return navigation_node
287 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
289 $childnode = self
::create($text, $action, $type, $shorttext, $key, $icon);
291 // Add the child to end and return
292 return $this->add_node($childnode);
296 * Adds a navigation node as a child of this one, given a $node object
297 * created using the create function.
298 * @param navigation_node $childnode Node to add
299 * @param string $beforekey
300 * @return navigation_node The added node
302 public function add_node(navigation_node
$childnode, $beforekey=null) {
303 // First convert the nodetype for this node to a branch as it will now have children
304 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
305 $this->nodetype
= self
::NODETYPE_BRANCH
;
307 // Set the parent to this node
308 $childnode->set_parent($this);
310 // Default the key to the number of children if not provided
311 if ($childnode->key
=== null) {
312 $childnode->key
= $this->children
->count();
315 // Add the child using the navigation_node_collections add method
316 $node = $this->children
->add($childnode, $beforekey);
318 // If added node is a category node or the user is logged in and it's a course
319 // then mark added node as a branch (makes it expandable by AJAX)
320 $type = $childnode->type
;
321 if (($type==self
::TYPE_CATEGORY
) ||
(isloggedin() && $type==self
::TYPE_COURSE
)) {
322 $node->nodetype
= self
::NODETYPE_BRANCH
;
324 // If this node is hidden mark it's children as hidden also
326 $node->hidden
= true;
328 // Return added node (reference returned by $this->children->add()
333 * Return a list of all the keys of all the child nodes.
334 * @return array the keys.
336 public function get_children_key_list() {
337 return $this->children
->get_key_list();
341 * Searches for a node of the given type with the given key.
343 * This searches this node plus all of its children, and their children....
344 * If you know the node you are looking for is a child of this node then please
345 * use the get method instead.
347 * @param int|string $key The key of the node we are looking for
348 * @param int $type One of navigation_node::TYPE_*
349 * @return navigation_node|false
351 public function find($key, $type) {
352 return $this->children
->find($key, $type);
356 * Get the child of this node that has the given key + (optional) type.
358 * If you are looking for a node and want to search all children + thier children
359 * then please use the find method instead.
361 * @param int|string $key The key of the node we are looking for
362 * @param int $type One of navigation_node::TYPE_*
363 * @return navigation_node|false
365 public function get($key, $type=null) {
366 return $this->children
->get($key, $type);
374 public function remove() {
375 return $this->parent
->children
->remove($this->key
, $this->type
);
379 * Checks if this node has or could have any children
381 * @return bool Returns true if it has children or could have (by AJAX expansion)
383 public function has_children() {
384 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0);
388 * Marks this node as active and forces it open.
390 * Important: If you are here because you need to mark a node active to get
391 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
392 * You can use it to specify a different URL to match the active navigation node on
393 * rather than having to locate and manually mark a node active.
395 public function make_active() {
396 $this->isactive
= true;
397 $this->add_class('active_tree_node');
399 if ($this->parent
!== null) {
400 $this->parent
->make_inactive();
405 * Marks a node as inactive and recusised back to the base of the tree
406 * doing the same to all parents.
408 public function make_inactive() {
409 $this->isactive
= false;
410 $this->remove_class('active_tree_node');
411 if ($this->parent
!== null) {
412 $this->parent
->make_inactive();
417 * Forces this node to be open and at the same time forces open all
418 * parents until the root node.
422 public function force_open() {
423 $this->forceopen
= true;
424 if ($this->parent
!== null) {
425 $this->parent
->force_open();
430 * Adds a CSS class to this node.
432 * @param string $class
435 public function add_class($class) {
436 if (!in_array($class, $this->classes
)) {
437 $this->classes
[] = $class;
443 * Removes a CSS class from this node.
445 * @param string $class
446 * @return bool True if the class was successfully removed.
448 public function remove_class($class) {
449 if (in_array($class, $this->classes
)) {
450 $key = array_search($class,$this->classes
);
452 unset($this->classes
[$key]);
460 * Sets the title for this node and forces Moodle to utilise it.
461 * @param string $title
463 public function title($title) {
464 $this->title
= $title;
465 $this->forcetitle
= true;
469 * Resets the page specific information on this node if it is being unserialised.
471 public function __wakeup(){
472 $this->forceopen
= false;
473 $this->isactive
= false;
474 $this->remove_class('active_tree_node');
478 * Checks if this node or any of its children contain the active node.
484 public function contains_active_node() {
485 if ($this->isactive
) {
488 foreach ($this->children
as $child) {
489 if ($child->isactive ||
$child->contains_active_node()) {
498 * Finds the active node.
500 * Searches this nodes children plus all of the children for the active node
501 * and returns it if found.
505 * @return navigation_node|false
507 public function find_active_node() {
508 if ($this->isactive
) {
511 foreach ($this->children
as &$child) {
512 $outcome = $child->find_active_node();
513 if ($outcome !== false) {
522 * Searches all children for the best matching active node
523 * @return navigation_node|false
525 public function search_for_active_node() {
526 if ($this->check_if_active(URL_MATCH_BASE
)) {
529 foreach ($this->children
as &$child) {
530 $outcome = $child->search_for_active_node();
531 if ($outcome !== false) {
540 * Gets the content for this node.
542 * @param bool $shorttext If true shorttext is used rather than the normal text
545 public function get_content($shorttext=false) {
546 if ($shorttext && $this->shorttext
!==null) {
547 return format_string($this->shorttext
);
549 return format_string($this->text
);
554 * Gets the title to use for this node.
558 public function get_title() {
559 if ($this->forcetitle ||
$this->action
!= null){
567 * Gets the CSS class to add to this node to describe its type
571 public function get_css_type() {
572 if (array_key_exists($this->type
, $this->namedtypes
)) {
573 return 'type_'.$this->namedtypes
[$this->type
];
575 return 'type_unknown';
579 * Finds all nodes that are expandable by AJAX
581 * @param array $expandable An array by reference to populate with expandable nodes.
583 public function find_expandable(array &$expandable) {
584 foreach ($this->children
as &$child) {
585 if ($child->nodetype
== self
::NODETYPE_BRANCH
&& $child->children
->count() == 0 && $child->display
) {
586 $child->id
= 'expandable_branch_'.(count($expandable)+
1);
587 $this->add_class('canexpand');
588 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
590 $child->find_expandable($expandable);
595 * Finds all nodes of a given type (recursive)
597 * @param int $type One of navigation_node::TYPE_*
600 public function find_all_of_type($type) {
601 $nodes = $this->children
->type($type);
602 foreach ($this->children
as &$node) {
603 $childnodes = $node->find_all_of_type($type);
604 $nodes = array_merge($nodes, $childnodes);
610 * Removes this node if it is empty
612 public function trim_if_empty() {
613 if ($this->children
->count() == 0) {
619 * Creates a tab representation of this nodes children that can be used
620 * with print_tabs to produce the tabs on a page.
622 * call_user_func_array('print_tabs', $node->get_tabs_array());
624 * @param array $inactive
625 * @param bool $return
626 * @return array Array (tabs, selected, inactive, activated, return)
628 public function get_tabs_array(array $inactive=array(), $return=false) {
632 $activated = array();
633 foreach ($this->children
as $node) {
634 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
635 if ($node->contains_active_node()) {
636 if ($node->children
->count() > 0) {
637 $activated[] = $node->key
;
638 foreach ($node->children
as $child) {
639 if ($child->contains_active_node()) {
640 $selected = $child->key
;
642 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
645 $selected = $node->key
;
649 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
653 * Sets the parent for this node and if this node is active ensures that the tree is properly
656 * @param navigation_node $parent
658 public function set_parent(navigation_node
$parent) {
659 // Set the parent (thats the easy part)
660 $this->parent
= $parent;
661 // Check if this node is active (this is checked during construction)
662 if ($this->isactive
) {
663 // Force all of the parent nodes open so you can see this node
664 $this->parent
->force_open();
665 // Make all parents inactive so that its clear where we are.
666 $this->parent
->make_inactive();
672 * Navigation node collection
674 * This class is responsible for managing a collection of navigation nodes.
675 * It is required because a node's unique identifier is a combination of both its
678 * Originally an array was used with a string key that was a combination of the two
679 * however it was decided that a better solution would be to use a class that
680 * implements the standard IteratorAggregate interface.
683 * @category navigation
684 * @copyright 2010 Sam Hemelryk
685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
687 class navigation_node_collection
implements IteratorAggregate
{
689 * A multidimensional array to where the first key is the type and the second
690 * key is the nodes key.
693 protected $collection = array();
695 * An array that contains references to nodes in the same order they were added.
696 * This is maintained as a progressive array.
699 protected $orderedcollection = array();
701 * A reference to the last node that was added to the collection
702 * @var navigation_node
704 protected $last = null;
706 * The total number of items added to this array.
709 protected $count = 0;
712 * Adds a navigation node to the collection
714 * @param navigation_node $node Node to add
715 * @param string $beforekey If specified, adds before a node with this key,
716 * otherwise adds at end
717 * @return navigation_node Added node
719 public function add(navigation_node
$node, $beforekey=null) {
724 // First check we have a 2nd dimension for this type
725 if (!array_key_exists($type, $this->orderedcollection
)) {
726 $this->orderedcollection
[$type] = array();
728 // Check for a collision and report if debugging is turned on
729 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
730 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
733 // Find the key to add before
734 $newindex = $this->count
;
736 if ($beforekey !== null) {
737 foreach ($this->collection
as $index => $othernode) {
738 if ($othernode->key
=== $beforekey) {
744 if ($newindex === $this->count
) {
745 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
746 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
750 // Add the node to the appropriate place in the by-type structure (which
751 // is not ordered, despite the variable name)
752 $this->orderedcollection
[$type][$key] = $node;
754 // Update existing references in the ordered collection (which is the
755 // one that isn't called 'ordered') to shuffle them along if required
756 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
757 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
760 // Add a reference to the node to the progressive collection.
761 $this->collection
[$newindex] = &$this->orderedcollection
[$type][$key];
762 // Update the last property to a reference to this new node.
763 $this->last
= &$this->orderedcollection
[$type][$key];
765 // Reorder the array by index if needed
767 ksort($this->collection
);
770 // Return the reference to the now added node
775 * Return a list of all the keys of all the nodes.
776 * @return array the keys.
778 public function get_key_list() {
780 foreach ($this->collection
as $node) {
781 $keys[] = $node->key
;
787 * Fetches a node from this collection.
789 * @param string|int $key The key of the node we want to find.
790 * @param int $type One of navigation_node::TYPE_*.
791 * @return navigation_node|null
793 public function get($key, $type=null) {
794 if ($type !== null) {
795 // If the type is known then we can simply check and fetch
796 if (!empty($this->orderedcollection
[$type][$key])) {
797 return $this->orderedcollection
[$type][$key];
800 // Because we don't know the type we look in the progressive array
801 foreach ($this->collection
as $node) {
802 if ($node->key
=== $key) {
811 * Searches for a node with matching key and type.
813 * This function searches both the nodes in this collection and all of
814 * the nodes in each collection belonging to the nodes in this collection.
818 * @param string|int $key The key of the node we want to find.
819 * @param int $type One of navigation_node::TYPE_*.
820 * @return navigation_node|null
822 public function find($key, $type=null) {
823 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
824 return $this->orderedcollection
[$type][$key];
826 $nodes = $this->getIterator();
827 // Search immediate children first
828 foreach ($nodes as &$node) {
829 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
833 // Now search each childs children
834 foreach ($nodes as &$node) {
835 $result = $node->children
->find($key, $type);
836 if ($result !== false) {
845 * Fetches the last node that was added to this collection
847 * @return navigation_node
849 public function last() {
854 * Fetches all nodes of a given type from this collection
856 * @param string|int $type node type being searched for.
857 * @return array ordered collection
859 public function type($type) {
860 if (!array_key_exists($type, $this->orderedcollection
)) {
861 $this->orderedcollection
[$type] = array();
863 return $this->orderedcollection
[$type];
866 * Removes the node with the given key and type from the collection
868 * @param string|int $key The key of the node we want to find.
872 public function remove($key, $type=null) {
873 $child = $this->get($key, $type);
874 if ($child !== false) {
875 foreach ($this->collection
as $colkey => $node) {
876 if ($node->key
== $key && $node->type
== $type) {
877 unset($this->collection
[$colkey]);
881 unset($this->orderedcollection
[$child->type
][$child->key
]);
889 * Gets the number of nodes in this collection
891 * This option uses an internal count rather than counting the actual options to avoid
892 * a performance hit through the count function.
896 public function count() {
900 * Gets an array iterator for the collection.
902 * This is required by the IteratorAggregator interface and is used by routines
903 * such as the foreach loop.
905 * @return ArrayIterator
907 public function getIterator() {
908 return new ArrayIterator($this->collection
);
913 * The global navigation class used for... the global navigation
915 * This class is used by PAGE to store the global navigation for the site
916 * and is then used by the settings nav and navbar to save on processing and DB calls
919 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
920 * {@link lib/ajax/getnavbranch.php} Called by ajax
923 * @category navigation
924 * @copyright 2009 Sam Hemelryk
925 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
927 class global_navigation
extends navigation_node
{
928 /** @var moodle_page The Moodle page this navigation object belongs to. */
930 /** @var bool switch to let us know if the navigation object is initialised*/
931 protected $initialised = false;
932 /** @var array An array of course information */
933 protected $mycourses = array();
934 /** @var array An array for containing root navigation nodes */
935 protected $rootnodes = array();
936 /** @var bool A switch for whether to show empty sections in the navigation */
937 protected $showemptysections = true;
938 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
939 protected $showcategories = null;
940 /** @var array An array of stdClasses for users that the navigation is extended for */
941 protected $extendforuser = array();
942 /** @var navigation_cache */
944 /** @var array An array of course ids that are present in the navigation */
945 protected $addedcourses = array();
947 protected $allcategoriesloaded = false;
948 /** @var array An array of category ids that are included in the navigation */
949 protected $addedcategories = array();
950 /** @var int expansion limit */
951 protected $expansionlimit = 0;
952 /** @var int userid to allow parent to see child's profile page navigation */
953 protected $useridtouseforparentchecks = 0;
955 /** Used when loading categories to load all top level categories [parent = 0] **/
956 const LOAD_ROOT_CATEGORIES
= 0;
957 /** Used when loading categories to load all categories **/
958 const LOAD_ALL_CATEGORIES
= -1;
961 * Constructs a new global navigation
963 * @param moodle_page $page The page this navigation object belongs to
965 public function __construct(moodle_page
$page) {
966 global $CFG, $SITE, $USER;
968 if (during_initial_install()) {
972 if (get_home_page() == HOMEPAGE_SITE
) {
973 // We are using the site home for the root element
976 'type' => navigation_node
::TYPE_SYSTEM
,
977 'text' => get_string('home'),
978 'action' => new moodle_url('/')
981 // We are using the users my moodle for the root element
984 'type' => navigation_node
::TYPE_SYSTEM
,
985 'text' => get_string('myhome'),
986 'action' => new moodle_url('/my/')
990 // Use the parents constructor.... good good reuse
991 parent
::__construct($properties);
993 // Initalise and set defaults
995 $this->forceopen
= true;
996 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
1000 * Mutator to set userid to allow parent to see child's profile
1001 * page navigation. See MDL-25805 for initial issue. Linked to it
1002 * is an issue explaining why this is a REALLY UGLY HACK thats not
1005 * @param int $userid userid of profile page that parent wants to navigate around.
1007 public function set_userid_for_parent_checks($userid) {
1008 $this->useridtouseforparentchecks
= $userid;
1013 * Initialises the navigation object.
1015 * This causes the navigation object to look at the current state of the page
1016 * that it is associated with and then load the appropriate content.
1018 * This should only occur the first time that the navigation structure is utilised
1019 * which will normally be either when the navbar is called to be displayed or
1020 * when a block makes use of it.
1024 public function initialise() {
1025 global $CFG, $SITE, $USER, $DB;
1026 // Check if it has alread been initialised
1027 if ($this->initialised ||
during_initial_install()) {
1030 $this->initialised
= true;
1032 // Set up the five base root nodes. These are nodes where we will put our
1033 // content and are as follows:
1034 // site: Navigation for the front page.
1035 // myprofile: User profile information goes here.
1036 // mycourses: The users courses get added here.
1037 // courses: Additional courses are added here.
1038 // users: Other users information loaded here.
1039 $this->rootnodes
= array();
1040 if (get_home_page() == HOMEPAGE_SITE
) {
1041 // The home element should be my moodle because the root element is the site
1042 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1043 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_SETTING
, null, 'home');
1046 // The home element should be the site because the root node is my moodle
1047 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self
::TYPE_SETTING
, null, 'home');
1048 if (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_MY
)) {
1049 // We need to stop automatic redirection
1050 $this->rootnodes
['home']->action
->param('redirect', '0');
1053 $this->rootnodes
['site'] = $this->add_course($SITE);
1054 $this->rootnodes
['myprofile'] = $this->add(get_string('myprofile'), null, self
::TYPE_USER
, null, 'myprofile');
1055 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses');
1056 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1057 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1059 // We always load the frontpage course to ensure it is available without
1060 // JavaScript enabled.
1061 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1062 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1064 // Fetch all of the users courses.
1065 $mycourses = enrol_get_my_courses();
1066 // We need to show categories if we can show categories and the user isn't enrolled in any courses or we're not showing all courses
1067 $showcategories = ($this->show_categories() && (count($mycourses) == 0 ||
!empty($CFG->navshowallcourses
)));
1068 // $issite gets set to true if the current pages course is the sites frontpage course
1069 $issite = ($this->page
->course
->id
== SITEID
);
1070 // $ismycourse gets set to true if the user is enrolled in the current pages course.
1071 $ismycourse = !$issite && (array_key_exists($this->page
->course
->id
, $mycourses));
1073 // Check if any courses were returned.
1074 if (count($mycourses) > 0) {
1076 // Check if categories should be displayed within the my courses branch
1077 if (!empty($CFG->navshowmycoursecategories
)) {
1079 // Find the category of each mycourse
1080 $categories = array();
1081 foreach ($mycourses as $course) {
1082 $categories[] = $course->category
;
1085 // Do a single DB query to get the categories immediately associated with
1086 // courses the user is enrolled in.
1087 $categories = $DB->get_records_list('course_categories', 'id', array_unique($categories), 'depth ASC, sortorder ASC');
1088 // Work out the parent categories that we need to load that we havn't
1090 $categoryids = array();
1091 foreach ($categories as $category) {
1092 $categoryids = array_merge($categoryids, explode('/', trim($category->path
, '/')));
1094 $categoryids = array_unique($categoryids);
1095 $categoryids = array_diff($categoryids, array_keys($categories));
1097 if (count($categoryids)) {
1098 // Fetch any other categories we need.
1099 $allcategories = $DB->get_records_list('course_categories', 'id', $categoryids, 'depth ASC, sortorder ASC');
1100 if (is_array($allcategories) && count($allcategories) > 0) {
1101 $categories = array_merge($categories, $allcategories);
1105 // We ONLY want the categories, we need to get rid of the keys
1106 $categories = array_values($categories);
1107 $addedcategories = array();
1108 while (($category = array_shift($categories)) !== null) {
1109 if ($category->parent
== '0') {
1110 $categoryparent = $this->rootnodes
['mycourses'];
1111 } else if (array_key_exists($category->parent
, $addedcategories)) {
1112 $categoryparent = $addedcategories[$category->parent
];
1114 // Prepare to count iterations. We don't want to loop forever
1115 // accidentally if for some reason a category can't be placed.
1116 if (!isset($category->loopcount
)) {
1117 $category->loopcount
= 0;
1119 $category->loopcount++
;
1120 if ($category->loopcount
> 5) {
1121 // This is a pretty serious problem and this should never happen.
1122 // If it does then for some reason a category has been loaded but
1123 // its parents have now. It could be data corruption.
1124 debugging('Category '.$category->id
.' could not be placed within the navigation', DEBUG_DEVELOPER
);
1126 // Add it back to the end of the categories array
1127 array_push($categories, $category);
1132 $url = new moodle_url('/course/category.php', array('id' => $category->id
));
1133 $addedcategories[$category->id
] = $categoryparent->add($category->name
, $url, self
::TYPE_CATEGORY
, $category->name
, $category->id
);
1135 if (!$category->visible
) {
1136 if (!has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_COURSECAT
, $category->parent
))) {
1137 $addedcategories[$category->id
]->display
= false;
1139 $addedcategories[$category->id
]->hidden
= true;
1145 // Add all of the users courses to the navigation.
1146 // First up we need to add to the mycourses section.
1147 foreach ($mycourses as $course) {
1148 $course->coursenode
= $this->add_course($course, false, true);
1151 if (!empty($CFG->navshowallcourses
)) {
1153 $this->load_all_courses();
1156 // Next if nasvshowallcourses is enabled then we need to add courses
1157 // to the courses branch as well.
1158 if (!empty($CFG->navshowallcourses
)) {
1159 foreach ($mycourses as $course) {
1160 if (!empty($course->category
) && !$this->can_add_more_courses_to_category($course->category
)) {
1163 $genericcoursenode = $this->add_course($course, true);
1164 if ($genericcoursenode->isactive
) {
1165 // We don't want this node to be active because we want the
1166 // node in the mycourses branch to be active.
1167 $genericcoursenode->make_inactive();
1168 $genericcoursenode->collapse
= true;
1169 if ($genericcoursenode->parent
&& $genericcoursenode->parent
->type
== self
::TYPE_CATEGORY
) {
1170 $parent = $genericcoursenode->parent
;
1171 while ($parent && $parent->type
== self
::TYPE_CATEGORY
) {
1172 $parent->collapse
= true;
1173 $parent = $parent->parent
;
1179 } else if (!empty($CFG->navshowallcourses
) ||
!$this->show_categories()) {
1181 $this->load_all_courses();
1184 $canviewcourseprofile = true;
1186 // Next load context specific content into the navigation
1187 switch ($this->page
->context
->contextlevel
) {
1188 case CONTEXT_SYSTEM
:
1189 // This has already been loaded we just need to map the variable
1190 if ($showcategories) {
1191 $this->load_all_categories(self
::LOAD_ROOT_CATEGORIES
, true);
1194 case CONTEXT_COURSECAT
:
1195 // This has already been loaded we just need to map the variable
1196 if ($showcategories) {
1197 $this->load_all_categories($this->page
->context
->instanceid
, true);
1200 case CONTEXT_BLOCK
:
1201 case CONTEXT_COURSE
:
1203 // If it is the front page course, or a block on it then
1204 // all we need to do is load the root categories if required
1205 if ($showcategories) {
1206 $this->load_all_categories(self
::LOAD_ROOT_CATEGORIES
, true);
1210 // Load the course associated with the page into the navigation
1211 $course = $this->page
->course
;
1212 if ($this->show_categories() && !$ismycourse) {
1213 // The user isn't enrolled in the course and we need to show categories in which case we need
1214 // to load the category relating to the course and depending up $showcategories all of the root categories as well.
1215 $this->load_all_categories($course->category
, $showcategories);
1217 $coursenode = $this->load_course($course);
1219 // If the course wasn't added then don't try going any further.
1221 $canviewcourseprofile = false;
1225 // If the user is not enrolled then we only want to show the
1226 // course node and not populate it.
1228 // Not enrolled, can't view, and hasn't switched roles
1229 if (!can_access_course($course)) {
1230 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1231 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1233 if ($this->useridtouseforparentchecks
) {
1234 if ($this->useridtouseforparentchecks
!= $USER->id
) {
1235 $usercontext = get_context_instance(CONTEXT_USER
, $this->useridtouseforparentchecks
, MUST_EXIST
);
1236 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))
1237 and has_capability('moodle/user:viewdetails', $usercontext)) {
1244 $coursenode->make_active();
1245 $canviewcourseprofile = false;
1249 // Add the essentials such as reports etc...
1250 $this->add_course_essentials($coursenode, $course);
1251 if ($this->format_display_course_content($course->format
)) {
1252 // Load the course sections
1253 $sections = $this->load_course_sections($course, $coursenode);
1255 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1256 $coursenode->make_active();
1259 case CONTEXT_MODULE
:
1261 // If this is the site course then most information will have
1262 // already been loaded.
1263 // However we need to check if there is more content that can
1264 // yet be loaded for the specific module instance.
1265 $activitynode = $this->rootnodes
['site']->get($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1266 if ($activitynode) {
1267 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1272 $course = $this->page
->course
;
1273 $cm = $this->page
->cm
;
1275 if ($this->show_categories() && !$ismycourse) {
1276 $this->load_all_categories($course->category
, $showcategories);
1279 // Load the course associated with the page into the navigation
1280 $coursenode = $this->load_course($course);
1282 // If the course wasn't added then don't try going any further.
1284 $canviewcourseprofile = false;
1288 // If the user is not enrolled then we only want to show the
1289 // course node and not populate it.
1290 if (!can_access_course($course)) {
1291 $coursenode->make_active();
1292 $canviewcourseprofile = false;
1296 $this->add_course_essentials($coursenode, $course);
1298 // Get section number from $cm (if provided) - we need this
1299 // before loading sections in order to tell it to load this section
1300 // even if it would not normally display (=> it contains only
1301 // a label, which we are now editing)
1302 $sectionnum = isset($cm->sectionnum
) ?
$cm->sectionnum
: 0;
1304 // This value has to be stored in a member variable because
1305 // otherwise we would have to pass it through a public API
1306 // to course formats and they would need to change their
1307 // functions to pass it along again...
1308 $this->includesectionnum
= $sectionnum;
1310 $this->includesectionnum
= false;
1313 // Load the course sections into the page
1314 $sections = $this->load_course_sections($course, $coursenode);
1315 if ($course->id
!= SITEID
) {
1316 // Find the section for the $CM associated with the page and collect
1317 // its section number.
1319 $cm->sectionnumber
= $sectionnum;
1321 foreach ($sections as $section) {
1322 if ($section->id
== $cm->section
) {
1323 $cm->sectionnumber
= $section->section
;
1329 // Load all of the section activities for the section the cm belongs to.
1330 if (isset($cm->sectionnumber
) and !empty($sections[$cm->sectionnumber
])) {
1331 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1332 $activities = $this->load_section_activities($sections[$cm->sectionnumber
]->sectionnode
, $cm->sectionnumber
, $activityarray);
1334 $activities = array();
1335 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1336 // "stealth" activity from unavailable section
1337 $activities[$cm->id
] = $activity;
1341 $activities = array();
1342 $activities[$cm->id
] = $coursenode->get($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1344 if (!empty($activities[$cm->id
])) {
1345 // Finally load the cm specific navigaton information
1346 $this->load_activity($cm, $course, $activities[$cm->id
]);
1347 // Check if we have an active ndoe
1348 if (!$activities[$cm->id
]->contains_active_node() && !$activities[$cm->id
]->search_for_active_node()) {
1349 // And make the activity node active.
1350 $activities[$cm->id
]->make_active();
1353 //TODO: something is wrong, what to do? (Skodak)
1358 // The users profile information etc is already loaded
1359 // for the front page.
1362 $course = $this->page
->course
;
1363 if ($this->show_categories() && !$ismycourse) {
1364 $this->load_all_categories($course->category
, $showcategories);
1366 // Load the course associated with the user into the navigation
1367 $coursenode = $this->load_course($course);
1369 // If the course wasn't added then don't try going any further.
1371 $canviewcourseprofile = false;
1375 // If the user is not enrolled then we only want to show the
1376 // course node and not populate it.
1377 if (!can_access_course($course)) {
1378 $coursenode->make_active();
1379 $canviewcourseprofile = false;
1382 $this->add_course_essentials($coursenode, $course);
1383 $sections = $this->load_course_sections($course, $coursenode);
1387 // Look for all categories which have been loaded
1388 if ($showcategories) {
1389 $categories = $this->find_all_of_type(self
::TYPE_CATEGORY
);
1390 if (count($categories) !== 0) {
1391 $categoryids = array();
1392 foreach ($categories as $category) {
1393 $categoryids[] = $category->key
;
1395 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
1396 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
1397 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1398 FROM {course_categories} cc
1399 JOIN {course} c ON c.category = cc.id
1400 WHERE cc.id {$categoriessql}
1402 HAVING COUNT(c.id) > :limit";
1403 $excessivecategories = $DB->get_records_sql($sql, $params);
1404 foreach ($categories as &$category) {
1405 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1406 $url = new moodle_url('/course/category.php', array('id'=>$category->key
));
1407 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1411 } else if ((!empty($CFG->navshowallcourses
) ||
empty($mycourses)) && !$this->can_add_more_courses_to_category($this->rootnodes
['courses'])) {
1412 $this->rootnodes
['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self
::TYPE_SETTING
);
1415 // Load for the current user
1416 $this->load_for_user();
1417 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
&& $canviewcourseprofile) {
1418 $this->load_for_user(null, true);
1420 // Load each extending user into the navigation.
1421 foreach ($this->extendforuser
as $user) {
1422 if ($user->id
!= $USER->id
) {
1423 $this->load_for_user($user);
1427 // Give the local plugins a chance to include some navigation if they want.
1428 foreach (get_list_of_plugins('local') as $plugin) {
1429 if (!file_exists($CFG->dirroot
.'/local/'.$plugin.'/lib.php')) {
1432 require_once($CFG->dirroot
.'/local/'.$plugin.'/lib.php');
1433 $function = $plugin.'_extends_navigation';
1434 if (function_exists($function)) {
1439 // Remove any empty root nodes
1440 foreach ($this->rootnodes
as $node) {
1441 // Dont remove the home node
1442 if ($node->key
!== 'home' && !$node->has_children()) {
1447 if (!$this->contains_active_node()) {
1448 $this->search_for_active_node();
1451 // If the user is not logged in modify the navigation structure as detailed
1452 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1453 if (!isloggedin()) {
1454 $activities = clone($this->rootnodes
['site']->children
);
1455 $this->rootnodes
['site']->remove();
1456 $children = clone($this->children
);
1457 $this->children
= new navigation_node_collection();
1458 foreach ($activities as $child) {
1459 $this->children
->add($child);
1461 foreach ($children as $child) {
1462 $this->children
->add($child);
1469 * Returns true if courses should be shown within categories on the navigation.
1473 protected function show_categories() {
1475 if ($this->showcategories
=== null) {
1476 $show = $this->page
->context
->contextlevel
== CONTEXT_COURSECAT
;
1477 $show = $show ||
(!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1);
1478 $this->showcategories
= $show;
1480 return $this->showcategories
;
1484 * Checks the course format to see whether it wants the navigation to load
1485 * additional information for the course.
1487 * This function utilises a callback that can exist within the course format lib.php file
1488 * The callback should be a function called:
1489 * callback_{formatname}_display_content()
1490 * It doesn't get any arguments and should return true if additional content is
1491 * desired. If the callback doesn't exist we assume additional content is wanted.
1493 * @param string $format The course format
1496 protected function format_display_course_content($format) {
1498 $formatlib = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
1499 if (file_exists($formatlib)) {
1500 require_once($formatlib);
1501 $displayfunc = 'callback_'.$format.'_display_content';
1502 if (function_exists($displayfunc) && !$displayfunc()) {
1503 return $displayfunc();
1510 * Loads the courses in Moodle into the navigation.
1512 * @global moodle_database $DB
1513 * @param string|array $categoryids An array containing categories to load courses
1514 * for, OR null to load courses for all categories.
1515 * @return array An array of navigation_nodes one for each course
1517 protected function load_all_courses($categoryids = null) {
1520 // Work out the limit of courses.
1522 if (!empty($CFG->navcourselimit
)) {
1523 $limit = $CFG->navcourselimit
;
1526 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1528 // If we are going to show all courses AND we are showing categories then
1529 // to save us repeated DB calls load all of the categories now
1530 if ($this->show_categories()) {
1531 $this->load_all_categories($toload);
1534 // Will be the return of our efforts
1535 $coursenodes = array();
1537 // Check if we need to show categories.
1538 if ($this->show_categories()) {
1539 // Hmmm we need to show categories... this is going to be painful.
1540 // We now need to fetch up to $limit courses for each category to
1542 if ($categoryids !== null) {
1543 if (!is_array($categoryids)) {
1544 $categoryids = array($categoryids);
1546 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1547 $categorywhere = 'WHERE cc.id '.$categorywhere;
1548 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1549 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1550 $categoryparams = array();
1552 $categorywhere = '';
1553 $categoryparams = array();
1556 // First up we are going to get the categories that we are going to
1557 // need so that we can determine how best to load the courses from them.
1558 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1559 FROM {course_categories} cc
1560 LEFT JOIN {course} c ON c.category = cc.id
1563 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1564 $fullfetch = array();
1565 $partfetch = array();
1566 foreach ($categories as $category) {
1567 if (!$this->can_add_more_courses_to_category($category->id
)) {
1570 if ($category->coursecount
> $limit * 5) {
1571 $partfetch[] = $category->id
;
1572 } else if ($category->coursecount
> 0) {
1573 $fullfetch[] = $category->id
;
1576 $categories->close();
1578 if (count($fullfetch)) {
1579 // First up fetch all of the courses in categories where we know that we are going to
1580 // need the majority of courses.
1581 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1582 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
) +
array(SITEID
), SQL_PARAMS_NAMED
, 'lcourse', false);
1583 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1584 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1587 WHERE c.category {$categoryids} AND
1589 ORDER BY c.sortorder ASC";
1590 $coursesrs = $DB->get_recordset_sql($sql, $courseparams +
$categoryparams);
1591 foreach ($coursesrs as $course) {
1592 if (!$this->can_add_more_courses_to_category($course->category
)) {
1595 context_instance_preload($course);
1596 if ($course->id
!= SITEID
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1599 $coursenodes[$course->id
] = $this->add_course($course);
1601 $coursesrs->close();
1604 if (count($partfetch)) {
1605 // Next we will work our way through the categories where we will likely only need a small
1606 // proportion of the courses.
1607 foreach ($partfetch as $categoryid) {
1608 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1609 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
) +
array(SITEID
), SQL_PARAMS_NAMED
, 'lcourse', false);
1610 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1613 WHERE c.category = :categoryid AND
1615 ORDER BY c.sortorder ASC";
1616 $courseparams['categoryid'] = $categoryid;
1617 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1618 foreach ($coursesrs as $course) {
1619 if (!$this->can_add_more_courses_to_category($course->category
)) {
1622 context_instance_preload($course);
1623 if ($course->id
!= SITEID
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1626 $coursenodes[$course->id
] = $this->add_course($course);
1628 $coursesrs->close();
1632 // Prepare the SQL to load the courses and their contexts
1633 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1634 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1635 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1638 WHERE c.id {$courseids}
1639 ORDER BY c.sortorder ASC";
1640 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1641 foreach ($coursesrs as $course) {
1642 context_instance_preload($course);
1643 if ($course->id
!= SITEID
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1646 $coursenodes[$course->id
] = $this->add_course($course);
1647 if (count($coursenodes) >= $limit) {
1651 $coursesrs->close();
1654 return $coursenodes;
1658 * Returns true if more courses can be added to the provided category.
1661 * @param type $categoryid
1664 protected function can_add_more_courses_to_category($category) {
1667 if (!empty($CFG->navcourselimit
)) {
1668 $limit = (int)$CFG->navcourselimit
;
1670 if (is_numeric($category)) {
1671 if (!array_key_exists($category, $this->addedcategories
)) {
1674 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1675 } else if ($category instanceof navigation_node
) {
1676 if ($category->type
!= self
::TYPE_CATEGORY
) {
1679 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1680 } else if (is_object($category) && property_exists($category,'id')) {
1681 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1683 return ($coursecount <= $limit);
1687 * Loads all categories (top level or if an id is specified for that category)
1689 * @param int $categoryid The category id to load or null/0 to load all base level categories
1690 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1691 * as the requested category and any parent categories.
1692 * @return navigation_node|void returns a navigation node if a category has been loaded.
1694 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1697 // Check if this category has already been loaded
1698 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1702 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1703 $sqlselect = "SELECT cc.*, $catcontextsql
1704 FROM {course_categories} cc
1705 JOIN {context} ctx ON cc.id = ctx.instanceid";
1706 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1707 $sqlorder = "ORDER BY depth ASC, sortorder ASC, id ASC";
1710 $categoriestoload = array();
1711 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1712 // We are going to load all categories regardless... prepare to fire
1713 // on the database server!
1714 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1715 // We are going to load all of the first level categories (categories without parents)
1716 $sqlwhere .= " AND cc.parent = 0";
1717 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1718 // The category itself has been loaded already so we just need to ensure its subcategories
1720 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories
), SQL_PARAMS_NAMED
, 'parent', false);
1721 if ($showbasecategories) {
1722 // We need to include categories with parent = 0 as well
1723 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1725 // All we need is categories that match the parent
1726 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1728 $params['categoryid'] = $categoryid;
1730 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1731 // and load this category plus all its parents and subcategories
1732 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1733 $categoriestoload = explode('/', trim($category->path
, '/'));
1734 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1735 // We are going to use select twice so double the params
1736 $params = array_merge($params, $params);
1737 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1738 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1741 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1742 $categories = array();
1743 foreach ($categoriesrs as $category) {
1744 // Preload the context.. we'll need it when adding the category in order
1745 // to format the category name.
1746 context_helper
::preload_from_record($category);
1747 if (array_key_exists($category->id
, $this->addedcategories
)) {
1748 // Do nothing, its already been added.
1749 } else if ($category->parent
== '0') {
1750 // This is a root category lets add it immediately
1751 $this->add_category($category, $this->rootnodes
['courses']);
1752 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1753 // This categories parent has already been added we can add this immediately
1754 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1756 $categories[] = $category;
1759 $categoriesrs->close();
1761 // Now we have an array of categories we need to add them to the navigation.
1762 while (!empty($categories)) {
1763 $category = reset($categories);
1764 if (array_key_exists($category->id
, $this->addedcategories
)) {
1766 } else if ($category->parent
== '0') {
1767 $this->add_category($category, $this->rootnodes
['courses']);
1768 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1769 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1771 // This category isn't in the navigation and niether is it's parent (yet).
1772 // We need to go through the category path and add all of its components in order.
1773 $path = explode('/', trim($category->path
, '/'));
1774 foreach ($path as $catid) {
1775 if (!array_key_exists($catid, $this->addedcategories
)) {
1776 // This category isn't in the navigation yet so add it.
1777 $subcategory = $categories[$catid];
1778 if ($subcategory->parent
== '0') {
1779 // Yay we have a root category - this likely means we will now be able
1780 // to add categories without problems.
1781 $this->add_category($subcategory, $this->rootnodes
['courses']);
1782 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
1783 // The parent is in the category (as we'd expect) so add it now.
1784 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
1785 // Remove the category from the categories array.
1786 unset($categories[$catid]);
1788 // We should never ever arrive here - if we have then there is a bigger
1790 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1795 // Remove the category from the categories array now that we know it has been added.
1796 unset($categories[$category->id
]);
1798 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
1799 $this->allcategoriesloaded
= true;
1801 // Check if there are any categories to load.
1802 if (count($categoriestoload) > 0) {
1803 $readytoloadcourses = array();
1804 foreach ($categoriestoload as $category) {
1805 if ($this->can_add_more_courses_to_category($category)) {
1806 $readytoloadcourses[] = $category;
1809 if (count($readytoloadcourses)) {
1810 $this->load_all_courses($readytoloadcourses);
1816 * Adds a structured category to the navigation in the correct order/place
1818 * @param stdClass $category
1819 * @param navigation_node $parent
1821 protected function add_category(stdClass
$category, navigation_node
$parent) {
1822 if (array_key_exists($category->id
, $this->addedcategories
)) {
1825 $url = new moodle_url('/course/category.php', array('id' => $category->id
));
1826 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
1827 $categoryname = format_string($category->name
, true, array('context' => $context));
1828 $categorynode = $parent->add($categoryname, $url, self
::TYPE_CATEGORY
, $categoryname, $category->id
);
1829 if (empty($category->visible
)) {
1830 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1831 $categorynode->hidden
= true;
1833 $categorynode->display
= false;
1836 $this->addedcategories
[$category->id
] = &$categorynode;
1840 * Loads the given course into the navigation
1842 * @param stdClass $course
1843 * @return navigation_node
1845 protected function load_course(stdClass
$course) {
1846 if ($course->id
== SITEID
) {
1847 // This is always loaded during initialisation
1848 return $this->rootnodes
['site'];
1849 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
1850 // The course has already been loaded so return a reference
1851 return $this->addedcourses
[$course->id
];
1854 return $this->add_course($course);
1859 * Loads all of the courses section into the navigation.
1861 * This function utilisies a callback that can be implemented within the course
1862 * formats lib.php file to customise the navigation that is generated at this
1863 * point for the course.
1865 * By default (if not defined) the method {@link global_navigation::load_generic_course_sections()} is
1868 * @param stdClass $course Database record for the course
1869 * @param navigation_node $coursenode The course node within the navigation
1870 * @return array Array of navigation nodes for the section with key = section id
1872 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode) {
1874 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
1875 $structurefunc = 'callback_'.$course->format
.'_load_content';
1876 if (function_exists($structurefunc)) {
1877 return $structurefunc($this, $course, $coursenode);
1878 } else if (file_exists($structurefile)) {
1879 require_once $structurefile;
1880 if (function_exists($structurefunc)) {
1881 return $structurefunc($this, $course, $coursenode);
1883 return $this->load_generic_course_sections($course, $coursenode);
1886 return $this->load_generic_course_sections($course, $coursenode);
1891 * Generates an array of sections and an array of activities for the given course.
1893 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1895 * @param stdClass $course
1896 * @return array Array($sections, $activities)
1898 protected function generate_sections_and_activities(stdClass
$course) {
1900 require_once($CFG->dirroot
.'/course/lib.php');
1902 $modinfo = get_fast_modinfo($course);
1904 $sections = array_slice(get_all_sections($course->id
), 0, $course->numsections+
1, true);
1905 $activities = array();
1907 foreach ($sections as $key => $section) {
1908 $sections[$key]->hasactivites
= false;
1909 if (!array_key_exists($section->section
, $modinfo->sections
)) {
1912 foreach ($modinfo->sections
[$section->section
] as $cmid) {
1913 $cm = $modinfo->cms
[$cmid];
1914 if (!$cm->uservisible
) {
1917 $activity = new stdClass
;
1918 $activity->id
= $cm->id
;
1919 $activity->course
= $course->id
;
1920 $activity->section
= $section->section
;
1921 $activity->name
= $cm->name
;
1922 $activity->icon
= $cm->icon
;
1923 $activity->iconcomponent
= $cm->iconcomponent
;
1924 $activity->hidden
= (!$cm->visible
);
1925 $activity->modname
= $cm->modname
;
1926 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1927 $activity->onclick
= $cm->get_on_click();
1928 $url = $cm->get_url();
1930 $activity->url
= null;
1931 $activity->display
= false;
1933 $activity->url
= $cm->get_url()->out();
1934 $activity->display
= true;
1935 if (self
::module_extends_navigation($cm->modname
)) {
1936 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1939 $activities[$cmid] = $activity;
1940 if ($activity->display
) {
1941 $sections[$key]->hasactivites
= true;
1946 return array($sections, $activities);
1950 * Generically loads the course sections into the course's navigation.
1952 * @param stdClass $course
1953 * @param navigation_node $coursenode
1954 * @param string $courseformat The course format
1955 * @return array An array of course section nodes
1957 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode, $courseformat='unknown') {
1958 global $CFG, $DB, $USER;
1959 require_once($CFG->dirroot
.'/course/lib.php');
1961 list($sections, $activities) = $this->generate_sections_and_activities($course);
1963 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1964 $namingfunctionexists = (function_exists($namingfunction));
1966 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page
->context
);
1968 $urlfunction = 'callback_'.$courseformat.'_get_section_url';
1969 if (function_exists($urlfunction)) {
1970 // This code path is deprecated but we decided not to warn developers as
1971 // major changes are likely to follow in 2.4. See MDL-32504.
1973 $urlfunction = null;
1977 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT
== '0' && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1978 $key = optional_param('section', $key, PARAM_INT
);
1981 $navigationsections = array();
1982 foreach ($sections as $sectionid => $section) {
1983 $section = clone($section);
1984 if ($course->id
== SITEID
) {
1985 $this->load_section_activities($coursenode, $section->section
, $activities);
1987 if ((!$viewhiddensections && !$section->visible
) ||
(!$this->showemptysections
&&
1988 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
1991 if ($namingfunctionexists) {
1992 $sectionname = $namingfunction($course, $section, $sections);
1994 $sectionname = get_string('section').' '.$section->section
;
1999 // pre 2.3 style format url
2000 $url = $urlfunction($course->id
, $section->section
);
2002 if ($course->coursedisplay
== COURSE_DISPLAY_MULTIPAGE
) {
2003 $url = course_get_url($course, $section->section
);
2006 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
, null, $section->id
);
2007 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2008 $sectionnode->hidden
= (!$section->visible
);
2009 if ($key != '0' && $section->section
!= '0' && $section->section
== $key && $this->page
->context
->contextlevel
!= CONTEXT_MODULE
&& $section->hasactivites
) {
2010 $sectionnode->make_active();
2011 $this->load_section_activities($sectionnode, $section->section
, $activities);
2013 $section->sectionnode
= $sectionnode;
2014 $navigationsections[$sectionid] = $section;
2017 return $navigationsections;
2020 * Loads all of the activities for a section into the navigation structure.
2022 * @param navigation_node $sectionnode
2023 * @param int $sectionnumber
2024 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2025 * @param stdClass $course The course object the section and activities relate to.
2026 * @return array Array of activity nodes
2028 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2030 // A static counter for JS function naming
2031 static $legacyonclickcounter = 0;
2033 $activitynodes = array();
2034 if (empty($activities)) {
2035 return $activitynodes;
2038 if (!is_object($course)) {
2039 $activity = reset($activities);
2040 $courseid = $activity->course
;
2042 $courseid = $course->id
;
2044 $showactivities = ($courseid != SITEID ||
!empty($CFG->navshowfrontpagemods
));
2046 foreach ($activities as $activity) {
2047 if ($activity->section
!= $sectionnumber) {
2050 if ($activity->icon
) {
2051 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2053 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2056 // Prepare the default name and url for the node
2057 $activityname = format_string($activity->name
, true, array('context' => get_context_instance(CONTEXT_MODULE
, $activity->id
)));
2058 $action = new moodle_url($activity->url
);
2060 // Check if the onclick property is set (puke!)
2061 if (!empty($activity->onclick
)) {
2062 // Increment the counter so that we have a unique number.
2063 $legacyonclickcounter++
;
2064 // Generate the function name we will use
2065 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2066 $propogrationhandler = '';
2067 // Check if we need to cancel propogation. Remember inline onclick
2068 // events would return false if they wanted to prevent propogation and the
2070 if (strpos($activity->onclick
, 'return false')) {
2071 $propogrationhandler = 'e.halt();';
2073 // Decode the onclick - it has already been encoded for display (puke)
2074 $onclick = htmlspecialchars_decode($activity->onclick
);
2075 // Build the JS function the click event will call
2076 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2077 $this->page
->requires
->js_init_code($jscode);
2078 // Override the default url with the new action link
2079 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2082 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2083 $activitynode->title(get_string('modulename', $activity->modname
));
2084 $activitynode->hidden
= $activity->hidden
;
2085 $activitynode->display
= $showactivities && $activity->display
;
2086 $activitynode->nodetype
= $activity->nodetype
;
2087 $activitynodes[$activity->id
] = $activitynode;
2090 return $activitynodes;
2093 * Loads a stealth module from unavailable section
2094 * @param navigation_node $coursenode
2095 * @param stdClass $modinfo
2096 * @return navigation_node or null if not accessible
2098 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2099 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2102 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2103 if (!$cm->uservisible
) {
2107 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2109 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2111 $url = $cm->get_url();
2112 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2113 $activitynode->title(get_string('modulename', $cm->modname
));
2114 $activitynode->hidden
= (!$cm->visible
);
2116 // Don't show activities that don't have links!
2117 $activitynode->display
= false;
2118 } else if (self
::module_extends_navigation($cm->modname
)) {
2119 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2121 return $activitynode;
2124 * Loads the navigation structure for the given activity into the activities node.
2126 * This method utilises a callback within the modules lib.php file to load the
2127 * content specific to activity given.
2129 * The callback is a method: {modulename}_extend_navigation()
2131 * * {@link forum_extend_navigation()}
2132 * * {@link workshop_extend_navigation()}
2134 * @param cm_info|stdClass $cm
2135 * @param stdClass $course
2136 * @param navigation_node $activity
2139 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2142 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2143 if (!($cm instanceof cm_info
)) {
2144 $modinfo = get_fast_modinfo($course);
2145 $cm = $modinfo->get_cm($cm->id
);
2148 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2149 $activity->make_active();
2150 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2151 $function = $cm->modname
.'_extend_navigation';
2153 if (file_exists($file)) {
2154 require_once($file);
2155 if (function_exists($function)) {
2156 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2157 $function($activity, $course, $activtyrecord, $cm);
2161 // Allow the active advanced grading method plugin to append module navigation
2162 $featuresfunc = $cm->modname
.'_supports';
2163 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2164 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2165 $gradingman = get_grading_manager($cm->context
, $cm->modname
);
2166 $gradingman->extend_navigation($this, $activity);
2169 return $activity->has_children();
2172 * Loads user specific information into the navigation in the appropriate place.
2174 * If no user is provided the current user is assumed.
2176 * @param stdClass $user
2177 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2180 protected function load_for_user($user=null, $forceforcontext=false) {
2181 global $DB, $CFG, $USER;
2183 if ($user === null) {
2184 // We can't require login here but if the user isn't logged in we don't
2185 // want to show anything
2186 if (!isloggedin() ||
isguestuser()) {
2190 } else if (!is_object($user)) {
2191 // If the user is not an object then get them from the database
2192 $select = context_helper
::get_preload_record_columns_sql('ctx');
2193 $sql = "SELECT u.*, $select
2195 JOIN {context} ctx ON u.id = ctx.instanceid
2196 WHERE u.id = :userid AND
2197 ctx.contextlevel = :contextlevel";
2198 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2199 context_helper
::preload_from_record($user);
2202 $iscurrentuser = ($user->id
== $USER->id
);
2204 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
2206 // Get the course set against the page, by default this will be the site
2207 $course = $this->page
->course
;
2208 $baseargs = array('id'=>$user->id
);
2209 if ($course->id
!= SITEID
&& (!$iscurrentuser ||
$forceforcontext)) {
2210 $coursenode = $this->load_course($course);
2211 $baseargs['course'] = $course->id
;
2212 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2213 $issitecourse = false;
2215 // Load all categories and get the context for the system
2216 $coursecontext = get_context_instance(CONTEXT_SYSTEM
);
2217 $issitecourse = true;
2220 // Create a node to add user information under.
2221 if ($iscurrentuser && !$forceforcontext) {
2222 // If it's the current user the information will go under the profile root node
2223 $usernode = $this->rootnodes
['myprofile'];
2224 $course = get_site();
2225 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2226 $issitecourse = true;
2228 if (!$issitecourse) {
2229 // Not the current user so add it to the participants node for the current course
2230 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2231 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2233 // This is the site so add a users node to the root branch
2234 $usersnode = $this->rootnodes
['users'];
2235 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2236 $usersnode->action
= new moodle_url('/user/index.php', array('id'=>$course->id
));
2238 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2241 // We should NEVER get here, if the course hasn't been populated
2242 // with a participants node then the navigaiton either wasn't generated
2243 // for it (you are missing a require_login or set_context call) or
2244 // you don't have access.... in the interests of no leaking informatin
2245 // we simply quit...
2248 // Add a branch for the current user
2249 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2250 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, $user->id
);
2252 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2253 $usernode->make_active();
2257 // If the user is the current user or has permission to view the details of the requested
2258 // user than add a view profile link.
2259 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2260 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2261 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2263 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2267 if (!empty($CFG->navadduserpostslinks
)) {
2268 // Add nodes for forum posts and discussions if the user can view either or both
2269 // There are no capability checks here as the content of the page is based
2270 // purely on the forums the current user has access too.
2271 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2272 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2273 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2277 if (!empty($CFG->bloglevel
)) {
2278 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2279 require_once($CFG->dirroot
.'/blog/lib.php');
2280 // Get all options for the user
2281 $options = blog_get_options_for_user($user);
2282 $this->cache
->set('userblogoptions'.$user->id
, $options);
2284 $options = $this->cache
->{'userblogoptions'.$user->id
};
2287 if (count($options) > 0) {
2288 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2289 foreach ($options as $type => $option) {
2290 if ($type == "rss") {
2291 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
2293 $blogs->add($option['string'], $option['link']);
2299 if (!empty($CFG->messaging
)) {
2300 $messageargs = null;
2301 if ($USER->id
!=$user->id
) {
2302 $messageargs = array('id'=>$user->id
);
2304 $url = new moodle_url('/message/index.php',$messageargs);
2305 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2308 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
2309 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2310 $url = new moodle_url('/user/files.php');
2311 $usernode->add(get_string('myfiles'), $url, self
::TYPE_SETTING
);
2314 // Add a node to view the users notes if permitted
2315 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2316 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
));
2317 if ($coursecontext->instanceid
) {
2318 $url->param('course', $coursecontext->instanceid
);
2320 $usernode->add(get_string('notes', 'notes'), $url);
2324 $reporttab = $usernode->add(get_string('activityreports'));
2325 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2326 foreach ($reports as $reportfunction) {
2327 $reportfunction($reporttab, $user, $course);
2329 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2330 if ($anyreport ||
($course->showreports
&& $iscurrentuser && $forceforcontext)) {
2331 // Add grade hardcoded grade report if necessary
2332 $gradeaccess = false;
2333 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2334 //ok - can view all course grades
2335 $gradeaccess = true;
2336 } else if ($course->showgrades
) {
2337 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2338 //ok - can view own grades
2339 $gradeaccess = true;
2340 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2341 // ok - can view grades of this user - parent most probably
2342 $gradeaccess = true;
2343 } else if ($anyreport) {
2344 // ok - can view grades of this user - parent most probably
2345 $gradeaccess = true;
2349 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id
, 'user'=>$usercontext->instanceid
)));
2352 // Check the number of nodes in the report node... if there are none remove the node
2353 $reporttab->trim_if_empty();
2355 // If the user is the current user add the repositories for the current user
2356 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2357 if ($iscurrentuser) {
2358 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
2359 require_once($CFG->dirroot
. '/repository/lib.php');
2360 $editabletypes = repository
::get_editable_types($usercontext);
2361 $haseditabletypes = !empty($editabletypes);
2362 unset($editabletypes);
2363 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
2365 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
2367 if ($haseditabletypes) {
2368 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id
)));
2370 } else if ($course->id
== SITEID
&& has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2372 // Add view grade report is permitted
2373 $reports = get_plugin_list('gradereport');
2374 arsort($reports); // user is last, we want to test it first
2376 $userscourses = enrol_get_users_courses($user->id
);
2377 $userscoursesnode = $usernode->add(get_string('courses'));
2379 foreach ($userscourses as $usercourse) {
2380 $usercoursecontext = get_context_instance(CONTEXT_COURSE
, $usercourse->id
);
2381 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2382 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$usercourse->id
)), self
::TYPE_CONTAINER
);
2384 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2385 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2386 foreach ($reports as $plugin => $plugindir) {
2387 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2388 //stop when the first visible plugin is found
2389 $gradeavailable = true;
2395 if ($gradeavailable) {
2396 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id
));
2397 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/grades', ''));
2400 // Add a node to view the users notes if permitted
2401 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2402 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
, 'course'=>$usercourse->id
));
2403 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2406 if (can_access_course($usercourse, $user->id
)) {
2407 $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', ''));
2410 $reporttab = $usercoursenode->add(get_string('activityreports'));
2412 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2413 foreach ($reports as $reportfunction) {
2414 $reportfunction($reporttab, $user, $usercourse);
2417 $reporttab->trim_if_empty();
2424 * This method simply checks to see if a given module can extend the navigation.
2426 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2428 * @param string $modname
2431 protected static function module_extends_navigation($modname) {
2433 static $extendingmodules = array();
2434 if (!array_key_exists($modname, $extendingmodules)) {
2435 $extendingmodules[$modname] = false;
2436 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2437 if (file_exists($file)) {
2438 $function = $modname.'_extend_navigation';
2439 require_once($file);
2440 $extendingmodules[$modname] = (function_exists($function));
2443 return $extendingmodules[$modname];
2446 * Extends the navigation for the given user.
2448 * @param stdClass $user A user from the database
2450 public function extend_for_user($user) {
2451 $this->extendforuser
[] = $user;
2455 * Returns all of the users the navigation is being extended for
2457 * @return array An array of extending users.
2459 public function get_extending_users() {
2460 return $this->extendforuser
;
2463 * Adds the given course to the navigation structure.
2465 * @param stdClass $course
2466 * @param bool $forcegeneric
2467 * @param bool $ismycourse
2468 * @return navigation_node
2470 public function add_course(stdClass
$course, $forcegeneric = false, $ismycourse = false) {
2473 // We found the course... we can return it now :)
2474 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2475 return $this->addedcourses
[$course->id
];
2478 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2480 if ($course->id
!= SITEID
&& !$course->visible
) {
2481 if (is_role_switched($course->id
)) {
2482 // user has to be able to access course in order to switch, let's skip the visibility test here
2483 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2488 $issite = ($course->id
== SITEID
);
2489 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2494 if (empty($CFG->usesitenameforsitepages
)) {
2495 $shortname = get_string('sitepages');
2497 } else if ($ismycourse && !$forcegeneric) {
2498 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_CATEGORY
))) {
2499 // Nothing to do here the above statement set $parent to the category within mycourses.
2501 $parent = $this->rootnodes
['mycourses'];
2503 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2505 $parent = $this->rootnodes
['courses'];
2506 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2507 if (!empty($course->category
) && $this->show_categories()) {
2508 if ($this->show_categories() && !$this->is_category_fully_loaded($course->category
)) {
2509 // We need to load the category structure for this course
2510 $this->load_all_categories($course->category
, false);
2512 if (array_key_exists($course->category
, $this->addedcategories
)) {
2513 $parent = $this->addedcategories
[$course->category
];
2514 // This could lead to the course being created so we should check whether it is the case again
2515 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2516 return $this->addedcourses
[$course->id
];
2522 $coursenode = $parent->add($shortname, $url, self
::TYPE_COURSE
, $shortname, $course->id
);
2523 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2524 $coursenode->hidden
= (!$course->visible
);
2525 $coursenode->title(format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
))));
2526 if (!$forcegeneric) {
2527 $this->addedcourses
[$course->id
] = &$coursenode;
2534 * Returns true if the category has already been loaded as have any child categories
2536 * @param int $categoryid
2539 protected function is_category_fully_loaded($categoryid) {
2540 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2544 * Adds essential course nodes to the navigation for the given course.
2546 * This method adds nodes such as reports, blogs and participants
2548 * @param navigation_node $coursenode
2549 * @param stdClass $course
2550 * @return bool returns true on successful addition of a node.
2552 public function add_course_essentials($coursenode, stdClass
$course) {
2555 if ($course->id
== SITEID
) {
2556 return $this->add_front_page_course_essentials($coursenode, $course);
2559 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2564 if (has_capability('moodle/course:viewparticipants', $this->page
->context
)) {
2565 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2566 $currentgroup = groups_get_course_group($course, true);
2567 if ($course->id
== SITEID
) {
2569 } else if ($course->id
&& !$currentgroup) {
2570 $filterselect = $course->id
;
2572 $filterselect = $currentgroup;
2574 $filterselect = clean_param($filterselect, PARAM_INT
);
2575 if (($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2576 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2577 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2578 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2580 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2581 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id
)));
2583 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2584 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2587 // View course reports
2588 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2589 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2590 $coursereports = get_plugin_list('coursereport'); // deprecated
2591 foreach ($coursereports as $report=>$dir) {
2592 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2593 if (file_exists($libfile)) {
2594 require_once($libfile);
2595 $reportfunction = $report.'_report_extend_navigation';
2596 if (function_exists($report.'_report_extend_navigation')) {
2597 $reportfunction($reportnav, $course, $this->page
->context
);
2602 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2603 foreach ($reports as $reportfunction) {
2604 $reportfunction($reportnav, $course, $this->page
->context
);
2610 * This generates the structure of the course that won't be generated when
2611 * the modules and sections are added.
2613 * Things such as the reports branch, the participants branch, blogs... get
2614 * added to the course node by this method.
2616 * @param navigation_node $coursenode
2617 * @param stdClass $course
2618 * @return bool True for successfull generation
2620 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2623 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2627 // Hidden node that we use to determine if the front page navigation is loaded.
2628 // This required as there are not other guaranteed nodes that may be loaded.
2629 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2632 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2633 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
2639 if (!empty($CFG->bloglevel
)
2640 and ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2641 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2642 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2643 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2647 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2648 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2652 if (!empty($CFG->usetags
) && isloggedin()) {
2653 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2658 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2659 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self
::TYPE_CUSTOM
, null, 'calendar');
2662 // View course reports
2663 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2664 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2665 $coursereports = get_plugin_list('coursereport'); // deprecated
2666 foreach ($coursereports as $report=>$dir) {
2667 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2668 if (file_exists($libfile)) {
2669 require_once($libfile);
2670 $reportfunction = $report.'_report_extend_navigation';
2671 if (function_exists($report.'_report_extend_navigation')) {
2672 $reportfunction($reportnav, $course, $this->page
->context
);
2677 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2678 foreach ($reports as $reportfunction) {
2679 $reportfunction($reportnav, $course, $this->page
->context
);
2686 * Clears the navigation cache
2688 public function clear_cache() {
2689 $this->cache
->clear();
2693 * Sets an expansion limit for the navigation
2695 * The expansion limit is used to prevent the display of content that has a type
2696 * greater than the provided $type.
2698 * Can be used to ensure things such as activities or activity content don't get
2699 * shown on the navigation.
2700 * They are still generated in order to ensure the navbar still makes sense.
2702 * @param int $type One of navigation_node::TYPE_*
2703 * @return bool true when complete.
2705 public function set_expansion_limit($type) {
2706 $nodes = $this->find_all_of_type($type);
2707 foreach ($nodes as &$node) {
2708 // We need to generate the full site node
2709 if ($type == self
::TYPE_COURSE
&& $node->key
== SITEID
) {
2712 foreach ($node->children
as &$child) {
2713 // We still want to show course reports and participants containers
2714 // or there will be navigation missing.
2715 if ($type == self
::TYPE_COURSE
&& $child->type
=== self
::TYPE_CONTAINER
) {
2718 $child->display
= false;
2724 * Attempts to get the navigation with the given key from this nodes children.
2726 * This function only looks at this nodes children, it does NOT look recursivily.
2727 * If the node can't be found then false is returned.
2729 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2731 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2732 * may be of more use to you.
2734 * @param string|int $key The key of the node you wish to receive.
2735 * @param int $type One of navigation_node::TYPE_*
2736 * @return navigation_node|false
2738 public function get($key, $type = null) {
2739 if (!$this->initialised
) {
2740 $this->initialise();
2742 return parent
::get($key, $type);
2746 * Searches this nodes children and their children to find a navigation node
2747 * with the matching key and type.
2749 * This method is recursive and searches children so until either a node is
2750 * found or there are no more nodes to search.
2752 * If you know that the node being searched for is a child of this node
2753 * then use the {@link global_navigation::get()} method instead.
2755 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2756 * may be of more use to you.
2758 * @param string|int $key The key of the node you wish to receive.
2759 * @param int $type One of navigation_node::TYPE_*
2760 * @return navigation_node|false
2762 public function find($key, $type) {
2763 if (!$this->initialised
) {
2764 $this->initialise();
2766 return parent
::find($key, $type);
2771 * The limited global navigation class used for the AJAX extension of the global
2774 * The primary methods that are used in the global navigation class have been overriden
2775 * to ensure that only the relevant branch is generated at the root of the tree.
2776 * This can be done because AJAX is only used when the backwards structure for the
2777 * requested branch exists.
2778 * This has been done only because it shortens the amounts of information that is generated
2779 * which of course will speed up the response time.. because no one likes laggy AJAX.
2782 * @category navigation
2783 * @copyright 2009 Sam Hemelryk
2784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2786 class global_navigation_for_ajax
extends global_navigation
{
2788 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2789 protected $branchtype;
2791 /** @var int the instance id */
2792 protected $instanceid;
2794 /** @var array Holds an array of expandable nodes */
2795 protected $expandable = array();
2798 * Constructs the navigation for use in an AJAX request
2800 * @param moodle_page $page moodle_page object
2801 * @param int $branchtype
2804 public function __construct($page, $branchtype, $id) {
2805 $this->page
= $page;
2806 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2807 $this->children
= new navigation_node_collection();
2808 $this->branchtype
= $branchtype;
2809 $this->instanceid
= $id;
2810 $this->initialise();
2813 * Initialise the navigation given the type and id for the branch to expand.
2815 * @return array An array of the expandable nodes
2817 public function initialise() {
2818 global $CFG, $DB, $SITE;
2820 if ($this->initialised ||
during_initial_install()) {
2821 return $this->expandable
;
2823 $this->initialised
= true;
2825 $this->rootnodes
= array();
2826 $this->rootnodes
['site'] = $this->add_course($SITE);
2827 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
2829 // Branchtype will be one of navigation_node::TYPE_*
2830 switch ($this->branchtype
) {
2831 case self
::TYPE_CATEGORY
:
2832 $this->load_category($this->instanceid
);
2834 case self
::TYPE_COURSE
:
2835 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
2836 require_course_login($course, true, null, false, true);
2837 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2838 $coursenode = $this->add_course($course);
2839 $this->add_course_essentials($coursenode, $course);
2840 if ($this->format_display_course_content($course->format
)) {
2841 $this->load_course_sections($course, $coursenode);
2844 case self
::TYPE_SECTION
:
2845 $sql = 'SELECT c.*, cs.section AS sectionnumber
2847 LEFT JOIN {course_sections} cs ON cs.course = c.id
2849 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
2850 require_course_login($course, true, null, false, true);
2851 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2852 $coursenode = $this->add_course($course);
2853 $this->add_course_essentials($coursenode, $course);
2854 $sections = $this->load_course_sections($course, $coursenode);
2855 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2856 $this->load_section_activities($sections[$course->sectionnumber
]->sectionnode
, $course->sectionnumber
, $activities);
2858 case self
::TYPE_ACTIVITY
:
2861 JOIN {course_modules} cm ON cm.course = c.id
2862 WHERE cm.id = :cmid";
2863 $params = array('cmid' => $this->instanceid
);
2864 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
2865 $modinfo = get_fast_modinfo($course);
2866 $cm = $modinfo->get_cm($this->instanceid
);
2867 require_course_login($course, true, $cm, false, true);
2868 $this->page
->set_context(get_context_instance(CONTEXT_MODULE
, $cm->id
));
2869 $coursenode = $this->load_course($course);
2870 if ($course->id
== SITEID
) {
2871 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
));
2873 $sections = $this->load_course_sections($course, $coursenode);
2874 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2875 $activities = $this->load_section_activities($sections[$cm->sectionnum
]->sectionnode
, $cm->sectionnum
, $activities);
2876 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id
]);
2880 throw new Exception('Unknown type');
2881 return $this->expandable
;
2884 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
) {
2885 $this->load_for_user(null, true);
2888 $this->find_expandable($this->expandable
);
2889 return $this->expandable
;
2893 * Loads a single category into the AJAX navigation.
2895 * This function is special in that it doesn't concern itself with the parent of
2896 * the requested category or its siblings.
2897 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2900 * @global moodle_database $DB
2901 * @param int $categoryid
2903 protected function load_category($categoryid) {
2907 if (!empty($CFG->navcourselimit
)) {
2908 $limit = (int)$CFG->navcourselimit
;
2911 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
2912 $sql = "SELECT cc.*, $catcontextsql
2913 FROM {course_categories} cc
2914 JOIN {context} ctx ON cc.id = ctx.instanceid
2915 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
2916 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2917 ORDER BY depth ASC, sortorder ASC, id ASC";
2918 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2919 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2920 $subcategories = array();
2921 $basecategory = null;
2922 foreach ($categories as $category) {
2923 context_helper
::preload_from_record($category);
2924 if ($category->id
== $categoryid) {
2925 $this->add_category($category, $this);
2926 $basecategory = $this->addedcategories
[$category->id
];
2928 $subcategories[] = $category;
2931 $categories->close();
2933 if (!is_null($basecategory)) {
2934 //echo "<pre>".print_r($subcategories, true).'</pre>';
2935 foreach ($subcategories as $category) {
2936 $this->add_category($category, $basecategory);
2940 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder','*', 0, $limit);
2941 foreach ($courses as $course) {
2942 $this->add_course($course);
2948 * Returns an array of expandable nodes
2951 public function get_expandable() {
2952 return $this->expandable
;
2959 * This class is used to manage the navbar, which is initialised from the navigation
2960 * object held by PAGE
2963 * @category navigation
2964 * @copyright 2009 Sam Hemelryk
2965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2967 class navbar
extends navigation_node
{
2968 /** @var bool A switch for whether the navbar is initialised or not */
2969 protected $initialised = false;
2970 /** @var mixed keys used to reference the nodes on the navbar */
2971 protected $keys = array();
2972 /** @var null|string content of the navbar */
2973 protected $content = null;
2974 /** @var moodle_page object the moodle page that this navbar belongs to */
2976 /** @var bool A switch for whether to ignore the active navigation information */
2977 protected $ignoreactive = false;
2978 /** @var bool A switch to let us know if we are in the middle of an install */
2979 protected $duringinstall = false;
2980 /** @var bool A switch for whether the navbar has items */
2981 protected $hasitems = false;
2982 /** @var array An array of navigation nodes for the navbar */
2984 /** @var array An array of child node objects */
2985 public $children = array();
2986 /** @var bool A switch for whether we want to include the root node in the navbar */
2987 public $includesettingsbase = false;
2989 * The almighty constructor
2991 * @param moodle_page $page
2993 public function __construct(moodle_page
$page) {
2995 if (during_initial_install()) {
2996 $this->duringinstall
= true;
2999 $this->page
= $page;
3000 $this->text
= get_string('home');
3001 $this->shorttext
= get_string('home');
3002 $this->action
= new moodle_url($CFG->wwwroot
);
3003 $this->nodetype
= self
::NODETYPE_BRANCH
;
3004 $this->type
= self
::TYPE_SYSTEM
;
3008 * Quick check to see if the navbar will have items in.
3010 * @return bool Returns true if the navbar will have items, false otherwise
3012 public function has_items() {
3013 if ($this->duringinstall
) {
3015 } else if ($this->hasitems
!== false) {
3018 $this->page
->navigation
->initialise($this->page
);
3020 $activenodefound = ($this->page
->navigation
->contains_active_node() ||
3021 $this->page
->settingsnav
->contains_active_node());
3023 $outcome = (count($this->children
)>0 ||
(!$this->ignoreactive
&& $activenodefound));
3024 $this->hasitems
= $outcome;
3029 * Turn on/off ignore active
3031 * @param bool $setting
3033 public function ignore_active($setting=true) {
3034 $this->ignoreactive
= ($setting);
3038 * Gets a navigation node
3040 * @param string|int $key for referencing the navbar nodes
3041 * @param int $type navigation_node::TYPE_*
3042 * @return navigation_node|bool
3044 public function get($key, $type = null) {
3045 foreach ($this->children
as &$child) {
3046 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3053 * Returns an array of navigation_node's that make up the navbar.
3057 public function get_items() {
3059 // Make sure that navigation is initialised
3060 if (!$this->has_items()) {
3063 if ($this->items
!== null) {
3064 return $this->items
;
3067 if (count($this->children
) > 0) {
3068 // Add the custom children
3069 $items = array_reverse($this->children
);
3072 $navigationactivenode = $this->page
->navigation
->find_active_node();
3073 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3075 // Check if navigation contains the active node
3076 if (!$this->ignoreactive
) {
3078 if ($navigationactivenode && $settingsactivenode) {
3079 // Parse a combined navigation tree
3080 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3081 if (!$settingsactivenode->mainnavonly
) {
3082 $items[] = $settingsactivenode;
3084 $settingsactivenode = $settingsactivenode->parent
;
3086 if (!$this->includesettingsbase
) {
3087 // Removes the first node from the settings (root node) from the list
3090 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3091 if (!$navigationactivenode->mainnavonly
) {
3092 $items[] = $navigationactivenode;
3094 $navigationactivenode = $navigationactivenode->parent
;
3096 } else if ($navigationactivenode) {
3097 // Parse the navigation tree to get the active node
3098 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3099 if (!$navigationactivenode->mainnavonly
) {
3100 $items[] = $navigationactivenode;
3102 $navigationactivenode = $navigationactivenode->parent
;
3104 } else if ($settingsactivenode) {
3105 // Parse the settings navigation to get the active node
3106 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3107 if (!$settingsactivenode->mainnavonly
) {
3108 $items[] = $settingsactivenode;
3110 $settingsactivenode = $settingsactivenode->parent
;
3115 $items[] = new navigation_node(array(
3116 'text'=>$this->page
->navigation
->text
,
3117 'shorttext'=>$this->page
->navigation
->shorttext
,
3118 'key'=>$this->page
->navigation
->key
,
3119 'action'=>$this->page
->navigation
->action
3122 $this->items
= array_reverse($items);
3123 return $this->items
;
3127 * Add a new navigation_node to the navbar, overrides parent::add
3129 * This function overrides {@link navigation_node::add()} so that we can change
3130 * the way nodes get added to allow us to simply call add and have the node added to the
3133 * @param string $text
3134 * @param string|moodle_url $action
3136 * @param string|int $key
3137 * @param string $shorttext
3138 * @param string $icon
3139 * @return navigation_node
3141 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3142 if ($this->content
!== null) {
3143 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3146 // Properties array used when creating the new navigation node
3151 // Set the action if one was provided
3152 if ($action!==null) {
3153 $itemarray['action'] = $action;
3155 // Set the shorttext if one was provided
3156 if ($shorttext!==null) {
3157 $itemarray['shorttext'] = $shorttext;
3159 // Set the icon if one was provided
3161 $itemarray['icon'] = $icon;
3163 // Default the key to the number of children if not provided
3164 if ($key === null) {
3165 $key = count($this->children
);
3168 $itemarray['key'] = $key;
3169 // Set the parent to this node
3170 $itemarray['parent'] = $this;
3171 // Add the child using the navigation_node_collections add method
3172 $this->children
[] = new navigation_node($itemarray);
3178 * Class used to manage the settings option for the current page
3180 * This class is used to manage the settings options in a tree format (recursively)
3181 * and was created initially for use with the settings blocks.
3184 * @category navigation
3185 * @copyright 2009 Sam Hemelryk
3186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3188 class settings_navigation
extends navigation_node
{
3189 /** @var stdClass the current context */
3191 /** @var moodle_page the moodle page that the navigation belongs to */
3193 /** @var string contains administration section navigation_nodes */
3194 protected $adminsection;
3195 /** @var bool A switch to see if the navigation node is initialised */
3196 protected $initialised = false;
3197 /** @var array An array of users that the nodes can extend for. */
3198 protected $userstoextendfor = array();
3199 /** @var navigation_cache **/
3203 * Sets up the object with basic settings and preparse it for use
3205 * @param moodle_page $page
3207 public function __construct(moodle_page
&$page) {
3208 if (during_initial_install()) {
3211 $this->page
= $page;
3212 // Initialise the main navigation. It is most important that this is done
3213 // before we try anything
3214 $this->page
->navigation
->initialise();
3215 // Initialise the navigation cache
3216 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3217 $this->children
= new navigation_node_collection();
3220 * Initialise the settings navigation based on the current context
3222 * This function initialises the settings navigation tree for a given context
3223 * by calling supporting functions to generate major parts of the tree.
3226 public function initialise() {
3227 global $DB, $SESSION;
3229 if (during_initial_install()) {
3231 } else if ($this->initialised
) {
3234 $this->id
= 'settingsnav';
3235 $this->context
= $this->page
->context
;
3237 $context = $this->context
;
3238 if ($context->contextlevel
== CONTEXT_BLOCK
) {
3239 $this->load_block_settings();
3240 $context = $context->get_parent_context();
3243 switch ($context->contextlevel
) {
3244 case CONTEXT_SYSTEM
:
3245 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3246 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3249 case CONTEXT_COURSECAT
:
3250 $this->load_category_settings();
3252 case CONTEXT_COURSE
:
3253 if ($this->page
->course
->id
!= SITEID
) {
3254 $this->load_course_settings(($context->id
== $this->context
->id
));
3256 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3259 case CONTEXT_MODULE
:
3260 $this->load_module_settings();
3261 $this->load_course_settings();
3264 if ($this->page
->course
->id
!= SITEID
) {
3265 $this->load_course_settings();
3270 $settings = $this->load_user_settings($this->page
->course
->id
);
3272 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') ||
$SESSION->load_navigation_admin
)) {
3273 $admin = $this->load_administration_settings();
3274 $SESSION->load_navigation_admin
= ($admin->has_children());
3279 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $admin) {
3280 $admin->force_open();
3281 } else if ($context->contextlevel
== CONTEXT_USER
&& $settings) {
3282 $settings->force_open();
3285 // Check if the user is currently logged in as another user
3286 if (session_is_loggedinas()) {
3287 // Get the actual user, we need this so we can display an informative return link
3288 $realuser = session_get_realuser();
3289 // Add the informative return to original user link
3290 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page
->course
->id
, 'return'=>1,'sesskey'=>sesskey()));
3291 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self
::TYPE_SETTING
, null, null, new pix_icon('t/left', ''));
3294 foreach ($this->children
as $key=>$node) {
3295 if ($node->nodetype
!= self
::NODETYPE_BRANCH ||
$node->children
->count()===0) {
3299 $this->initialised
= true;
3302 * Override the parent function so that we can add preceeding hr's and set a
3303 * root node class against all first level element
3305 * It does this by first calling the parent's add method {@link navigation_node::add()}
3306 * and then proceeds to use the key to set class and hr
3308 * @param string $text text to be used for the link.
3309 * @param string|moodle_url $url url for the new node
3310 * @param int $type the type of node navigation_node::TYPE_*
3311 * @param string $shorttext
3312 * @param string|int $key a key to access the node by.
3313 * @param pix_icon $icon An icon that appears next to the node.
3314 * @return navigation_node with the new node added to it.
3316 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
3317 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
3318 $node->add_class('root_node');
3323 * This function allows the user to add something to the start of the settings
3324 * navigation, which means it will be at the top of the settings navigation block
3326 * @param string $text text to be used for the link.
3327 * @param string|moodle_url $url url for the new node
3328 * @param int $type the type of node navigation_node::TYPE_*
3329 * @param string $shorttext
3330 * @param string|int $key a key to access the node by.
3331 * @param pix_icon $icon An icon that appears next to the node.
3332 * @return navigation_node $node with the new node added to it.
3334 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
3335 $children = $this->children
;
3336 $childrenclass = get_class($children);
3337 $this->children
= new $childrenclass;
3338 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3339 foreach ($children as $child) {
3340 $this->children
->add($child);
3345 * Load the site administration tree
3347 * This function loads the site administration tree by using the lib/adminlib library functions
3349 * @param navigation_node $referencebranch A reference to a branch in the settings
3351 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3352 * tree and start at the beginning
3353 * @return mixed A key to access the admin tree by
3355 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
3358 // Check if we are just starting to generate this navigation.
3359 if ($referencebranch === null) {
3361 // Require the admin lib then get an admin structure
3362 if (!function_exists('admin_get_root')) {
3363 require_once($CFG->dirroot
.'/lib/adminlib.php');
3365 $adminroot = admin_get_root(false, false);
3366 // This is the active section identifier
3367 $this->adminsection
= $this->page
->url
->param('section');
3369 // Disable the navigation from automatically finding the active node
3370 navigation_node
::$autofindactive = false;
3371 $referencebranch = $this->add(get_string('administrationsite'), null, self
::TYPE_SETTING
, null, 'root');
3372 foreach ($adminroot->children
as $adminbranch) {
3373 $this->load_administration_settings($referencebranch, $adminbranch);
3375 navigation_node
::$autofindactive = true;
3377 // Use the admin structure to locate the active page
3378 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
3379 $currentnode = $this;
3380 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
3381 $currentnode = $currentnode->get($pathkey);
3384 $currentnode->make_active();
3387 $this->scan_for_active_node($referencebranch);
3389 return $referencebranch;
3390 } else if ($adminbranch->check_access()) {
3391 // We have a reference branch that we can access and is not hidden `hurrah`
3392 // Now we need to display it and any children it may have
3395 if ($adminbranch instanceof admin_settingpage
) {
3396 $url = new moodle_url('/'.$CFG->admin
.'/settings.php', array('section'=>$adminbranch->name
));
3397 } else if ($adminbranch instanceof admin_externalpage
) {
3398 $url = $adminbranch->url
;
3399 } else if (!empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
3400 $url = new moodle_url('/'.$CFG->admin
.'/category.php', array('category' => $adminbranch->name
));
3404 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
3406 if ($adminbranch->is_hidden()) {
3407 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
3408 $reference->add_class('hidden');
3410 $reference->display
= false;
3414 // Check if we are generating the admin notifications and whether notificiations exist
3415 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
3416 $reference->add_class('criticalnotification');
3418 // Check if this branch has children
3419 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
3420 foreach ($adminbranch->children
as $branch) {
3421 // Generate the child branches as well now using this branch as the reference
3422 $this->load_administration_settings($reference, $branch);
3425 $reference->icon
= new pix_icon('i/settings', '');
3431 * This function recursivily scans nodes until it finds the active node or there
3432 * are no more nodes.
3433 * @param navigation_node $node
3435 protected function scan_for_active_node(navigation_node
$node) {
3436 if (!$node->check_if_active() && $node->children
->count()>0) {
3437 foreach ($node->children
as &$child) {
3438 $this->scan_for_active_node($child);
3444 * Gets a navigation node given an array of keys that represent the path to
3447 * @param array $path
3448 * @return navigation_node|false
3450 protected function get_by_path(array $path) {
3451 $node = $this->get(array_shift($path));
3452 foreach ($path as $key) {
3459 * Generate the list of modules for the given course.
3461 * @param stdClass $course The course to get modules for
3463 protected function get_course_modules($course) {
3465 $mods = $modnames = $modnamesplural = $modnamesused = array();
3466 // This function is included when we include course/lib.php at the top
3468 get_all_mods($course->id
, $mods, $modnames, $modnamesplural, $modnamesused);
3469 $resources = array();
3470 $activities = array();
3471 foreach($modnames as $modname=>$modnamestr) {
3472 if (!course_allowed_module($course, $modname)) {
3476 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3477 if (!file_exists($libfile)) {
3480 include_once($libfile);
3481 $gettypesfunc = $modname.'_get_types';
3482 if (function_exists($gettypesfunc)) {
3483 $types = $gettypesfunc();
3484 foreach($types as $type) {
3485 if (!isset($type->modclass
) ||
!isset($type->typestr
)) {
3486 debugging('Incorrect activity type in '.$modname);
3489 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
3490 $resources[html_entity_decode($type->type
)] = $type->typestr
;
3492 $activities[html_entity_decode($type->type
)] = $type->typestr
;
3496 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
3497 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
3498 $resources[$modname] = $modnamestr;
3500 // all other archetypes are considered activity
3501 $activities[$modname] = $modnamestr;
3505 return array($resources, $activities);
3509 * This function loads the course settings that are available for the user
3511 * @param bool $forceopen If set to true the course node will be forced open
3512 * @return navigation_node|false
3514 protected function load_course_settings($forceopen = false) {
3517 $course = $this->page
->course
;
3518 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
3520 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3522 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
3524 $coursenode->force_open();
3527 if (has_capability('moodle/course:update', $coursecontext)) {
3528 // Add the turn on/off settings
3530 if ($this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
3531 // We are on the course page, retain the current page params e.g. section.
3532 $url = clone($this->page
->url
);
3533 $url->param('sesskey', sesskey());
3535 // Edit on the main course page.
3536 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
3538 if ($this->page
->user_is_editing()) {
3539 $url->param('edit', 'off');
3540 $editstring = get_string('turneditingoff');
3542 $url->param('edit', 'on');
3543 $editstring = get_string('turneditingon');
3545 $coursenode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3547 if ($this->page
->user_is_editing()) {
3548 // Removed as per MDL-22732
3549 // $this->add_course_editing_links($course);
3552 // Add the course settings link
3553 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
3554 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3556 // Add the course completion settings link
3557 if ($CFG->enablecompletion
&& $course->enablecompletion
) {
3558 $url = new moodle_url('/course/completion.php', array('id'=>$course->id
));
3559 $coursenode->add(get_string('completion', 'completion'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3564 enrol_add_course_navigation($coursenode, $course);
3567 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3568 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
3569 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
3572 // Add view grade report is permitted
3573 $reportavailable = false;
3574 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3575 $reportavailable = true;
3576 } else if (!empty($course->showgrades
)) {
3577 $reports = get_plugin_list('gradereport');
3578 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3579 arsort($reports); // user is last, we want to test it first
3580 foreach ($reports as $plugin => $plugindir) {
3581 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3582 //stop when the first visible plugin is found
3583 $reportavailable = true;
3589 if ($reportavailable) {
3590 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
3591 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, 'grades', new pix_icon('i/grades', ''));
3594 // Add outcome if permitted
3595 if (!empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $coursecontext)) {
3596 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
3597 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
3600 // Backup this course
3601 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3602 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
3603 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
3606 // Restore to this course
3607 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3608 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
3609 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
3612 // Import data from other courses
3613 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3614 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
3615 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/restore', ''));
3618 // Publish course on a hub
3619 if (has_capability('moodle/course:publish', $coursecontext)) {
3620 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
3621 $coursenode->add(get_string('publish'), $url, self
::TYPE_SETTING
, null, 'publish', new pix_icon('i/publish', ''));
3624 // Reset this course
3625 if (has_capability('moodle/course:reset', $coursecontext)) {
3626 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
3627 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/return', ''));
3631 require_once($CFG->libdir
. '/questionlib.php');
3632 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3634 if (has_capability('moodle/course:update', $coursecontext)) {
3635 // Repository Instances
3636 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
3637 require_once($CFG->dirroot
. '/repository/lib.php');
3638 $editabletypes = repository
::get_editable_types($coursecontext);
3639 $haseditabletypes = !empty($editabletypes);
3640 unset($editabletypes);
3641 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
3643 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
3645 if ($haseditabletypes) {
3646 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
3647 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
3652 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3653 // hidden in new courses and courses where legacy files were turned off
3654 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
3655 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/files', ''));
3661 $assumedrole = $this->in_alternative_role();
3662 if ($assumedrole !== false) {
3663 $roles[0] = get_string('switchrolereturn');
3665 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3666 $availableroles = get_switchable_roles($coursecontext);
3667 if (is_array($availableroles)) {
3668 foreach ($availableroles as $key=>$role) {
3669 if ($assumedrole == (int)$key) {
3672 $roles[$key] = $role;
3676 if (is_array($roles) && count($roles)>0) {
3677 $switchroles = $this->add(get_string('switchroleto'));
3678 if ((count($roles)==1 && array_key_exists(0, $roles))||
$assumedrole!==false) {
3679 $switchroles->force_open();
3681 $returnurl = $this->page
->url
;
3682 $returnurl->param('sesskey', sesskey());
3683 foreach ($roles as $key => $name) {
3684 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3685 $switchroles->add($name, $url, self
::TYPE_SETTING
, null, $key, new pix_icon('i/roles', ''));
3688 // Return we are done
3693 * Adds branches and links to the settings navigation to add course activities
3696 * @param stdClass $course
3698 protected function add_course_editing_links($course) {
3701 require_once($CFG->dirroot
.'/course/lib.php');
3703 // Add `add` resources|activities branches
3704 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3705 if (file_exists($structurefile)) {
3706 require_once($structurefile);
3707 $requestkey = call_user_func('callback_'.$course->format
.'_request_key');
3708 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3710 $requestkey = get_string('section');
3711 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3714 $sections = get_all_sections($course->id
);
3716 $addresource = $this->add(get_string('addresource'));
3717 $addactivity = $this->add(get_string('addactivity'));
3718 if ($formatidentifier!==0) {
3719 $addresource->force_open();
3720 $addactivity->force_open();
3723 $this->get_course_modules($course);
3725 foreach ($sections as $section) {
3726 if ($formatidentifier !== 0 && $section->section
!= $formatidentifier) {
3729 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id
, $requestkey=>$section->section
));
3730 if ($section->section
== 0) {
3731 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3732 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3734 $sectionname = get_section_name($course, $section);
3735 $sectionresources = $addresource->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3736 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3738 foreach ($resources as $value=>$resource) {
3739 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3740 $pos = strpos($value, '&type=');
3742 $url->param('add', textlib
::substr($value, 0,$pos));
3743 $url->param('type', textlib
::substr($value, $pos+
6));
3745 $url->param('add', $value);
3747 $sectionresources->add($resource, $url, self
::TYPE_SETTING
);
3750 foreach ($activities as $activityname=>$activity) {
3751 if ($activity==='--') {
3755 if (strpos($activity, '--')===0) {
3756 $subbranch = $sectionactivities->add(trim($activity, '-'));
3759 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3760 $pos = strpos($activityname, '&type=');
3762 $url->param('add', textlib
::substr($activityname, 0,$pos));
3763 $url->param('type', textlib
::substr($activityname, $pos+
6));
3765 $url->param('add', $activityname);
3767 if ($subbranch !== false) {
3768 $subbranch->add($activity, $url, self
::TYPE_SETTING
);
3770 $sectionactivities->add($activity, $url, self
::TYPE_SETTING
);
3777 * This function calls the module function to inject module settings into the
3778 * settings navigation tree.
3780 * This only gets called if there is a corrosponding function in the modules
3783 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3785 * @return navigation_node|false
3787 protected function load_module_settings() {
3790 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
3791 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
3792 $this->page
->set_cm($cm, $this->page
->course
);
3795 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
3796 if (file_exists($file)) {
3797 require_once($file);
3800 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
));
3801 $modulenode->force_open();
3803 // Settings for the module
3804 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
3805 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => true, 'sesskey' => sesskey()));
3806 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
3808 // Assign local roles
3809 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
3810 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
3811 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
3814 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
3815 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
3816 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
3818 // Check role permissions
3819 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
3820 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
3821 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
3824 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
3825 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
3826 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
3829 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3830 foreach ($reports as $reportfunction) {
3831 $reportfunction($modulenode, $this->page
->cm
);
3833 // Add a backup link
3834 $featuresfunc = $this->page
->activityname
.'_supports';
3835 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
3836 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
3837 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
3840 // Restore this activity
3841 $featuresfunc = $this->page
->activityname
.'_supports';
3842 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
3843 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
3844 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
3847 // Allow the active advanced grading method plugin to append its settings
3848 $featuresfunc = $this->page
->activityname
.'_supports';
3849 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
3850 require_once($CFG->dirroot
.'/grade/grading/lib.php');
3851 $gradingman = get_grading_manager($this->page
->cm
->context
, $this->page
->activityname
);
3852 $gradingman->extend_settings_navigation($this, $modulenode);
3855 $function = $this->page
->activityname
.'_extend_settings_navigation';
3856 if (!function_exists($function)) {
3860 $function($this, $modulenode);
3862 // Remove the module node if there are no children
3863 if (empty($modulenode->children
)) {
3864 $modulenode->remove();
3871 * Loads the user settings block of the settings nav
3873 * This function is simply works out the userid and whether we need to load
3874 * just the current users profile settings, or the current user and the user the
3875 * current user is viewing.
3877 * This function has some very ugly code to work out the user, if anyone has
3878 * any bright ideas please feel free to intervene.
3880 * @param int $courseid The course id of the current course
3881 * @return navigation_node|false
3883 protected function load_user_settings($courseid=SITEID
) {
3886 if (isguestuser() ||
!isloggedin()) {
3890 $navusers = $this->page
->navigation
->get_extending_users();
3892 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
3894 foreach ($this->userstoextendfor
as $userid) {
3895 if ($userid == $USER->id
) {
3898 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3899 if (is_null($usernode)) {
3903 foreach ($navusers as $user) {
3904 if ($user->id
== $USER->id
) {
3907 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
3908 if (is_null($usernode)) {
3912 $this->generate_user_settings($courseid, $USER->id
);
3914 $usernode = $this->generate_user_settings($courseid, $USER->id
);
3920 * Extends the settings navigation for the given user.
3922 * Note: This method gets called automatically if you call
3923 * $PAGE->navigation->extend_for_user($userid)
3925 * @param int $userid
3927 public function extend_for_user($userid) {
3930 if (!in_array($userid, $this->userstoextendfor
)) {
3931 $this->userstoextendfor
[] = $userid;
3932 if ($this->initialised
) {
3933 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
3934 $children = array();
3935 foreach ($this->children
as $child) {
3936 $children[] = $child;
3938 array_unshift($children, array_pop($children));
3939 $this->children
= new navigation_node_collection();
3940 foreach ($children as $child) {
3941 $this->children
->add($child);
3948 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3949 * what can be shown/done
3951 * @param int $courseid The current course' id
3952 * @param int $userid The user id to load for
3953 * @param string $gstitle The string to pass to get_string for the branch title
3954 * @return navigation_node|false
3956 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3957 global $DB, $CFG, $USER, $SITE;
3959 if ($courseid != SITEID
) {
3960 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
3961 $course = $this->page
->course
;
3963 $select = context_helper
::get_preload_record_columns_sql('ctx');
3964 $sql = "SELECT c.*, $select
3966 JOIN {context} ctx ON c.id = ctx.instanceid
3967 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3968 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
3969 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3970 context_helper
::preload_from_record($course);
3976 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3977 $systemcontext = get_system_context();
3978 $currentuser = ($USER->id
== $userid);
3982 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3984 $select = context_helper
::get_preload_record_columns_sql('ctx');
3985 $sql = "SELECT u.*, $select
3987 JOIN {context} ctx ON u.id = ctx.instanceid
3988 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3989 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
3990 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
3994 context_helper
::preload_from_record($user);
3996 // Check that the user can view the profile
3997 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3998 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4000 if ($course->id
== SITEID
) {
4001 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4002 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4006 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4007 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4008 if ((!$canviewusercourse && !$canviewuser) ||
!can_access_course($course, $user->id
)) {
4011 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
) {
4012 // If groups are in use, make sure we can see that group
4018 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
4021 if ($gstitle != 'usercurrentsettings') {
4025 // Add a user setting branch
4026 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self
::TYPE_CONTAINER
, null, $key);
4027 $usersetting->id
= 'usersettings';
4028 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $this->page
->context
->instanceid
== $user->id
) {
4029 // Automatically start by making it active
4030 $usersetting->make_active();
4033 // Check if the user has been deleted
4034 if ($user->deleted
) {
4035 if (!has_capability('moodle/user:update', $coursecontext)) {
4036 // We can't edit the user so just show the user deleted message
4037 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
4039 // We can edit the user so show the user deleted message and link it to the profile
4040 if ($course->id
== SITEID
) {
4041 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
4043 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
4045 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
4050 $userauthplugin = false;
4051 if (!empty($user->auth
)) {
4052 $userauthplugin = get_auth_plugin($user->auth
);
4055 // Add the profile edit link
4056 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4057 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4058 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
4059 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
4060 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4061 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4062 $url = $userauthplugin->edit_profile_url();
4064 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4066 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
4071 // Change password link
4072 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4073 $passwordchangeurl = $userauthplugin->change_password_url();
4074 if (empty($passwordchangeurl)) {
4075 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
4077 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
);
4080 // View the roles settings
4081 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4082 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
4084 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
4085 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
4087 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
4089 if (!empty($assignableroles)) {
4090 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4091 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
4094 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
4095 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4096 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4099 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4100 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4104 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
4105 require_once($CFG->libdir
. '/portfoliolib.php');
4106 if (portfolio_instances(true, false)) {
4107 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
4109 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
4110 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
4112 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
4113 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
4117 $enablemanagetokens = false;
4118 if (!empty($CFG->enablerssfeeds
)) {
4119 $enablemanagetokens = true;
4120 } else if (!is_siteadmin($USER->id
)
4121 && !empty($CFG->enablewebservices
)
4122 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
4123 $enablemanagetokens = true;
4126 if ($currentuser && $enablemanagetokens) {
4127 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4128 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
4132 if (!$currentuser && $usercontext->contextlevel
== CONTEXT_USER
) {
4133 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
4134 require_once($CFG->dirroot
. '/repository/lib.php');
4135 $editabletypes = repository
::get_editable_types($usercontext);
4136 $haseditabletypes = !empty($editabletypes);
4137 unset($editabletypes);
4138 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
4140 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
4142 if ($haseditabletypes) {
4143 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id
));
4144 $usersetting->add(get_string('repositories', 'repository'), $url, self
::TYPE_SETTING
);
4149 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
4150 $url = new moodle_url('/message/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4151 $usersetting->add(get_string('editmymessage', 'message'), $url, self
::TYPE_SETTING
);
4155 if ($currentuser && !empty($CFG->bloglevel
)) {
4156 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
4157 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node
::TYPE_SETTING
);
4158 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM
))) {
4159 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node
::TYPE_SETTING
);
4160 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node
::TYPE_SETTING
);
4165 if (!$user->deleted
and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id
)) {
4166 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id
, 'user'=>$user->id
, 'sesskey'=>sesskey()));
4167 $usersetting->add(get_string('loginas'), $url, self
::TYPE_SETTING
);
4170 return $usersetting;
4174 * Loads block specific settings in the navigation
4176 * @return navigation_node
4178 protected function load_block_settings() {
4181 $blocknode = $this->add(print_context_name($this->context
));
4182 $blocknode->force_open();
4184 // Assign local roles
4185 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
4186 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
);
4189 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
4190 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
4191 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4193 // Check role permissions
4194 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
4195 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
4196 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4203 * Loads category specific settings in the navigation
4205 * @return navigation_node
4207 protected function load_category_settings() {
4210 $categorynode = $this->add(print_context_name($this->context
));
4211 $categorynode->force_open();
4213 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context
)) {
4214 $url = new moodle_url('/course/category.php', array('id'=>$this->context
->instanceid
, 'sesskey'=>sesskey()));
4215 if ($this->page
->user_is_editing()) {
4216 $url->param('categoryedit', '0');
4217 $editstring = get_string('turneditingoff');
4219 $url->param('categoryedit', '1');
4220 $editstring = get_string('turneditingon');
4222 $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
4225 if ($this->page
->user_is_editing() && has_capability('moodle/category:manage', $this->context
)) {
4226 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context
->instanceid
));
4227 $categorynode->add(get_string('editcategorythis'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
4229 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context
->instanceid
));
4230 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4233 // Assign local roles
4234 if (has_capability('moodle/role:assign', $this->context
)) {
4235 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
4236 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/roles', ''));
4240 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
4241 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
4242 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
4244 // Check role permissions
4245 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
4246 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
4247 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4251 if (has_capability('moodle/cohort:manage', $this->context
) or has_capability('moodle/cohort:view', $this->context
)) {
4252 $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', ''));
4256 if (has_capability('moodle/filter:manage', $this->context
) && count(filter_get_available_in_context($this->context
))>0) {
4257 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context
->id
));
4258 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
4261 return $categorynode;
4265 * Determine whether the user is assuming another role
4267 * This function checks to see if the user is assuming another role by means of
4268 * role switching. In doing this we compare each RSW key (context path) against
4269 * the current context path. This ensures that we can provide the switching
4270 * options against both the course and any page shown under the course.
4272 * @return bool|int The role(int) if the user is in another role, false otherwise
4274 protected function in_alternative_role() {
4276 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
4277 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
4278 return $USER->access
['rsw'][$this->page
->context
->path
];
4280 foreach ($USER->access
['rsw'] as $key=>$role) {
4281 if (strpos($this->context
->path
,$key)===0) {
4290 * This function loads all of the front page settings into the settings navigation.
4291 * This function is called when the user is on the front page, or $COURSE==$SITE
4292 * @param bool $forceopen (optional)
4293 * @return navigation_node
4295 protected function load_front_page_settings($forceopen = false) {
4298 $course = clone($SITE);
4299 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
4301 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
4303 $frontpage->force_open();
4305 $frontpage->id
= 'frontpagesettings';
4307 if (has_capability('moodle/course:update', $coursecontext)) {
4309 // Add the turn on/off settings
4310 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
4311 if ($this->page
->user_is_editing()) {
4312 $url->param('edit', 'off');
4313 $editstring = get_string('turneditingoff');
4315 $url->param('edit', 'on');
4316 $editstring = get_string('turneditingon');
4318 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
4320 // Add the course settings link
4321 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4322 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
4326 enrol_add_course_navigation($frontpage, $course);
4329 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4330 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4331 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
4334 // Backup this course
4335 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4336 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4337 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
4340 // Restore to this course
4341 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4342 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4343 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
4347 require_once($CFG->libdir
. '/questionlib.php');
4348 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4351 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $this->context
)) {
4352 //hiden in new installs
4353 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4354 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/files', ''));
4360 * This function marks the cache as volatile so it is cleared during shutdown
4362 public function clear_cache() {
4363 $this->cache
->volatile();
4368 * Simple class used to output a navigation branch in XML
4371 * @category navigation
4372 * @copyright 2009 Sam Hemelryk
4373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4375 class navigation_json
{
4376 /** @var array An array of different node types */
4377 protected $nodetype = array('node','branch');
4378 /** @var array An array of node keys and types */
4379 protected $expandable = array();
4381 * Turns a branch and all of its children into XML
4383 * @param navigation_node $branch
4384 * @return string XML string
4386 public function convert($branch) {
4387 $xml = $this->convert_child($branch);
4391 * Set the expandable items in the array so that we have enough information
4392 * to attach AJAX events
4393 * @param array $expandable
4395 public function set_expandable($expandable) {
4396 foreach ($expandable as $node) {
4397 $this->expandable
[$node['key'].':'.$node['type']] = $node;
4401 * Recusively converts a child node and its children to XML for output
4403 * @param navigation_node $child The child to convert
4404 * @param int $depth Pointlessly used to track the depth of the XML structure
4405 * @return string JSON
4407 protected function convert_child($child, $depth=1) {
4408 if (!$child->display
) {
4411 $attributes = array();
4412 $attributes['id'] = $child->id
;
4413 $attributes['name'] = $child->text
;
4414 $attributes['type'] = $child->type
;
4415 $attributes['key'] = $child->key
;
4416 $attributes['class'] = $child->get_css_type();
4418 if ($child->icon
instanceof pix_icon
) {
4419 $attributes['icon'] = array(
4420 'component' => $child->icon
->component
,
4421 'pix' => $child->icon
->pix
,
4423 foreach ($child->icon
->attributes
as $key=>$value) {
4424 if ($key == 'class') {
4425 $attributes['icon']['classes'] = explode(' ', $value);
4426 } else if (!array_key_exists($key, $attributes['icon'])) {
4427 $attributes['icon'][$key] = $value;
4431 } else if (!empty($child->icon
)) {
4432 $attributes['icon'] = (string)$child->icon
;
4435 if ($child->forcetitle ||
$child->title
!== $child->text
) {
4436 $attributes['title'] = htmlentities($child->title
);
4438 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
4439 $attributes['expandable'] = $child->key
;
4440 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
4443 if (count($child->classes
)>0) {
4444 $attributes['class'] .= ' '.join(' ',$child->classes
);
4446 if (is_string($child->action
)) {
4447 $attributes['link'] = $child->action
;
4448 } else if ($child->action
instanceof moodle_url
) {
4449 $attributes['link'] = $child->action
->out();
4450 } else if ($child->action
instanceof action_link
) {
4451 $attributes['link'] = $child->action
->url
->out();
4453 $attributes['hidden'] = ($child->hidden
);
4454 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
4456 if ($child->children
->count() > 0) {
4457 $attributes['children'] = array();
4458 foreach ($child->children
as $subchild) {
4459 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
4466 return json_encode($attributes);
4472 * The cache class used by global navigation and settings navigation to cache bits
4473 * and bobs that are used during their generation.
4475 * It is basically an easy access point to session with a bit of smarts to make
4476 * sure that the information that is cached is valid still.
4480 * if (!$cache->viewdiscussion()) {
4481 * // Code to do stuff and produce cachable content
4482 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4484 * $content = $cache->viewdiscussion;
4488 * @category navigation
4489 * @copyright 2009 Sam Hemelryk
4490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4492 class navigation_cache
{
4493 /** @var int represents the time created */
4494 protected $creation;
4495 /** @var array An array of session keys */
4498 * The string to use to segregate this particular cache. It can either be
4499 * unique to start a fresh cache or if you want to share a cache then make
4500 * it the string used in the original cache.
4504 /** @var int a time that the information will time out */
4506 /** @var stdClass The current context */
4507 protected $currentcontext;
4508 /** @var int cache time information */
4509 const CACHETIME
= 0;
4510 /** @var int cache user id */
4511 const CACHEUSERID
= 1;
4512 /** @var int cache value */
4513 const CACHEVALUE
= 2;
4514 /** @var null|array An array of navigation cache areas to expire on shutdown */
4515 public static $volatilecaches;
4518 * Contructor for the cache. Requires two arguments
4520 * @param string $area The string to use to segregate this particular cache
4521 * it can either be unique to start a fresh cache or if you want
4522 * to share a cache then make it the string used in the original
4524 * @param int $timeout The number of seconds to time the information out after
4526 public function __construct($area, $timeout=1800) {
4527 $this->creation
= time();
4528 $this->area
= $area;
4529 $this->timeout
= time() - $timeout;
4530 if (rand(0,100) === 0) {
4531 $this->garbage_collection();
4536 * Used to set up the cache within the SESSION.
4538 * This is called for each access and ensure that we don't put anything into the session before
4541 protected function ensure_session_cache_initialised() {
4543 if (empty($this->session
)) {
4544 if (!isset($SESSION->navcache
)) {
4545 $SESSION->navcache
= new stdClass
;
4547 if (!isset($SESSION->navcache
->{$this->area
})) {
4548 $SESSION->navcache
->{$this->area
} = array();
4550 $this->session
= &$SESSION->navcache
->{$this->area
};
4555 * Magic Method to retrieve something by simply calling using = cache->key
4557 * @param mixed $key The identifier for the information you want out again
4558 * @return void|mixed Either void or what ever was put in
4560 public function __get($key) {
4561 if (!$this->cached($key)) {
4564 $information = $this->session
[$key][self
::CACHEVALUE
];
4565 return unserialize($information);
4569 * Magic method that simply uses {@link set();} to store something in the cache
4571 * @param string|int $key
4572 * @param mixed $information
4574 public function __set($key, $information) {
4575 $this->set($key, $information);
4579 * Sets some information against the cache (session) for later retrieval
4581 * @param string|int $key
4582 * @param mixed $information
4584 public function set($key, $information) {
4586 $this->ensure_session_cache_initialised();
4587 $information = serialize($information);
4588 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
4591 * Check the existence of the identifier in the cache
4593 * @param string|int $key
4596 public function cached($key) {
4598 $this->ensure_session_cache_initialised();
4599 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
) {
4605 * Compare something to it's equivilant in the cache
4607 * @param string $key
4608 * @param mixed $value
4609 * @param bool $serialise Whether to serialise the value before comparison
4610 * this should only be set to false if the value is already
4612 * @return bool If the value is the same false if it is not set or doesn't match
4614 public function compare($key, $value, $serialise = true) {
4615 if ($this->cached($key)) {
4617 $value = serialize($value);
4619 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
4626 * Wipes the entire cache, good to force regeneration
4628 public function clear() {
4630 unset($SESSION->navcache
);
4631 $this->session
= null;
4634 * Checks all cache entries and removes any that have expired, good ole cleanup
4636 protected function garbage_collection() {
4637 if (empty($this->session
)) {
4640 foreach ($this->session
as $key=>$cachedinfo) {
4641 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
4642 unset($this->session
[$key]);
4648 * Marks the cache as being volatile (likely to change)
4650 * Any caches marked as volatile will be destroyed at the on shutdown by
4651 * {@link navigation_node::destroy_volatile_caches()} which is registered
4652 * as a shutdown function if any caches are marked as volatile.
4654 * @param bool $setting True to destroy the cache false not too
4656 public function volatile($setting = true) {
4657 if (self
::$volatilecaches===null) {
4658 self
::$volatilecaches = array();
4659 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4663 self
::$volatilecaches[$this->area
] = $this->area
;
4664 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
4665 unset(self
::$volatilecaches[$this->area
]);
4670 * Destroys all caches marked as volatile
4672 * This function is static and works in conjunction with the static volatilecaches
4673 * property of navigation cache.
4674 * Because this function is static it manually resets the cached areas back to an
4677 public static function destroy_volatile_caches() {
4679 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
4680 foreach (self
::$volatilecaches as $area) {
4681 $SESSION->navcache
->{$area} = array();
4684 $SESSION->navcache
= new stdClass
;