2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains classes used to manage the navigation structures within Moodle.
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 * The name that will be used to separate the navigation cache within SESSION
31 define('NAVIGATION_CACHE_NAME', 'navigation');
34 * This class is used to represent a node in a navigation tree
36 * This class is used to represent a node in a navigation tree within Moodle,
37 * the tree could be one of global navigation, settings navigation, or the navbar.
38 * Each node can be one of two types either a Leaf (default) or a branch.
39 * When a node is first created it is created as a leaf, when/if children are added
40 * the node then becomes a branch.
43 * @category navigation
44 * @copyright 2009 Sam Hemelryk
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class navigation_node
implements renderable
{
48 /** @var int Used to identify this node a leaf (default) 0 */
49 const NODETYPE_LEAF
= 0;
50 /** @var int Used to identify this node a branch, happens with children 1 */
51 const NODETYPE_BRANCH
= 1;
52 /** @var null Unknown node type null */
53 const TYPE_UNKNOWN
= null;
54 /** @var int System node type 0 */
55 const TYPE_ROOTNODE
= 0;
56 /** @var int System node type 1 */
57 const TYPE_SYSTEM
= 1;
58 /** @var int Category node type 10 */
59 const TYPE_CATEGORY
= 10;
60 /** @var int Course node type 20 */
61 const TYPE_COURSE
= 20;
62 /** @var int Course Structure node type 30 */
63 const TYPE_SECTION
= 30;
64 /** @var int Activity node type, e.g. Forum, Quiz 40 */
65 const TYPE_ACTIVITY
= 40;
66 /** @var int Resource node type, e.g. Link to a file, or label 50 */
67 const TYPE_RESOURCE
= 50;
68 /** @var int A custom node type, default when adding without specifing type 60 */
69 const TYPE_CUSTOM
= 60;
70 /** @var int Setting node type, used only within settings nav 70 */
71 const TYPE_SETTING
= 70;
72 /** @var int Setting node type, used only within settings nav 80 */
74 /** @var int Setting node type, used for containers of no importance 90 */
75 const TYPE_CONTAINER
= 90;
77 /** @var int Parameter to aid the coder in tracking [optional] */
79 /** @var string|int The identifier for the node, used to retrieve the node */
81 /** @var string The text to use for the node */
83 /** @var string Short text to use if requested [optional] */
84 public $shorttext = null;
85 /** @var string The title attribute for an action if one is defined */
87 /** @var string A string that can be used to build a help button */
88 public $helpbutton = null;
89 /** @var moodle_url|action_link|null An action for the node (link) */
90 public $action = null;
91 /** @var pix_icon The path to an icon to use for this node */
93 /** @var int See TYPE_* constants defined for this class */
94 public $type = self
::TYPE_UNKNOWN
;
95 /** @var int See NODETYPE_* constants defined for this class */
96 public $nodetype = self
::NODETYPE_LEAF
;
97 /** @var bool If set to true the node will be collapsed by default */
98 public $collapse = false;
99 /** @var bool If set to true the node will be expanded by default */
100 public $forceopen = false;
101 /** @var array An array of CSS classes for the node */
102 public $classes = array();
103 /** @var navigation_node_collection An array of child nodes */
104 public $children = array();
105 /** @var bool If set to true the node will be recognised as active */
106 public $isactive = false;
107 /** @var bool If set to true the node will be dimmed */
108 public $hidden = false;
109 /** @var bool If set to false the node will not be displayed */
110 public $display = true;
111 /** @var bool If set to true then an HR will be printed before the node */
112 public $preceedwithhr = false;
113 /** @var bool If set to true the the navigation bar should ignore this node */
114 public $mainnavonly = false;
115 /** @var bool If set to true a title will be added to the action no matter what */
116 public $forcetitle = false;
117 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
118 public $parent = null;
119 /** @var bool Override to not display the icon even if one is provided **/
120 public $hideicon = false;
122 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
123 /** @var moodle_url */
124 protected static $fullmeurl = null;
125 /** @var bool toogles auto matching of active node */
126 public static $autofindactive = true;
127 /** @var mixed If set to an int, that section will be included even if it has no activities */
128 public $includesectionnum = false;
131 * Constructs a new navigation_node
133 * @param array|string $properties Either an array of properties or a string to use
134 * as the text for the node
136 public function __construct($properties) {
137 if (is_array($properties)) {
138 // Check the array for each property that we allow to set at construction.
139 // text - The main content for the node
140 // shorttext - A short text if required for the node
141 // icon - The icon to display for the node
142 // type - The type of the node
143 // key - The key to use to identify the node
144 // parent - A reference to the nodes parent
145 // action - The action to attribute to this node, usually a URL to link to
146 if (array_key_exists('text', $properties)) {
147 $this->text
= $properties['text'];
149 if (array_key_exists('shorttext', $properties)) {
150 $this->shorttext
= $properties['shorttext'];
152 if (!array_key_exists('icon', $properties)) {
153 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
155 $this->icon
= $properties['icon'];
156 if ($this->icon
instanceof pix_icon
) {
157 if (empty($this->icon
->attributes
['class'])) {
158 $this->icon
->attributes
['class'] = 'navicon';
160 $this->icon
->attributes
['class'] .= ' navicon';
163 if (array_key_exists('type', $properties)) {
164 $this->type
= $properties['type'];
166 $this->type
= self
::TYPE_CUSTOM
;
168 if (array_key_exists('key', $properties)) {
169 $this->key
= $properties['key'];
171 // This needs to happen last because of the check_if_active call that occurs
172 if (array_key_exists('action', $properties)) {
173 $this->action
= $properties['action'];
174 if (is_string($this->action
)) {
175 $this->action
= new moodle_url($this->action
);
177 if (self
::$autofindactive) {
178 $this->check_if_active();
181 if (array_key_exists('parent', $properties)) {
182 $this->set_parent($properties['parent']);
184 } else if (is_string($properties)) {
185 $this->text
= $properties;
187 if ($this->text
=== null) {
188 throw new coding_exception('You must set the text for the node when you create it.');
190 // Default the title to the text
191 $this->title
= $this->text
;
192 // Instantiate a new navigation node collection for this nodes children
193 $this->children
= new navigation_node_collection();
197 * Checks if this node is the active node.
199 * This is determined by comparing the action for the node against the
200 * defined URL for the page. A match will see this node marked as active.
202 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
205 public function check_if_active($strength=URL_MATCH_EXACT
) {
206 global $FULLME, $PAGE;
207 // Set fullmeurl if it hasn't already been set
208 if (self
::$fullmeurl == null) {
209 if ($PAGE->has_set_url()) {
210 self
::override_active_url(new moodle_url($PAGE->url
));
212 self
::override_active_url(new moodle_url($FULLME));
216 // Compare the action of this node against the fullmeurl
217 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
218 $this->make_active();
225 * This sets the URL that the URL of new nodes get compared to when locating
228 * The active node is the node that matches the URL set here. By default this
229 * is either $PAGE->url or if that hasn't been set $FULLME.
231 * @param moodle_url $url The url to use for the fullmeurl.
233 public static function override_active_url(moodle_url
$url) {
234 // Clone the URL, in case the calling script changes their URL later.
235 self
::$fullmeurl = new moodle_url($url);
239 * Creates a navigation node, ready to add it as a child using add_node
240 * function. (The created node needs to be added before you can use it.)
241 * @param string $text
242 * @param moodle_url|action_link $action
244 * @param string $shorttext
245 * @param string|int $key
246 * @param pix_icon $icon
247 * @return navigation_node
249 public static function create($text, $action=null, $type=self
::TYPE_CUSTOM
,
250 $shorttext=null, $key=null, pix_icon
$icon=null) {
251 // Properties array used when creating the new navigation node
256 // Set the action if one was provided
257 if ($action!==null) {
258 $itemarray['action'] = $action;
260 // Set the shorttext if one was provided
261 if ($shorttext!==null) {
262 $itemarray['shorttext'] = $shorttext;
264 // Set the icon if one was provided
266 $itemarray['icon'] = $icon;
269 $itemarray['key'] = $key;
270 // Construct and return
271 return new navigation_node($itemarray);
275 * Adds a navigation node as a child of this node.
277 * @param string $text
278 * @param moodle_url|action_link $action
280 * @param string $shorttext
281 * @param string|int $key
282 * @param pix_icon $icon
283 * @return navigation_node
285 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
287 $childnode = self
::create($text, $action, $type, $shorttext, $key, $icon);
289 // Add the child to end and return
290 return $this->add_node($childnode);
294 * Adds a navigation node as a child of this one, given a $node object
295 * created using the create function.
296 * @param navigation_node $childnode Node to add
297 * @param string $beforekey
298 * @return navigation_node The added node
300 public function add_node(navigation_node
$childnode, $beforekey=null) {
301 // First convert the nodetype for this node to a branch as it will now have children
302 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
303 $this->nodetype
= self
::NODETYPE_BRANCH
;
305 // Set the parent to this node
306 $childnode->set_parent($this);
308 // Default the key to the number of children if not provided
309 if ($childnode->key
=== null) {
310 $childnode->key
= $this->children
->count();
313 // Add the child using the navigation_node_collections add method
314 $node = $this->children
->add($childnode, $beforekey);
316 // If added node is a category node or the user is logged in and it's a course
317 // then mark added node as a branch (makes it expandable by AJAX)
318 $type = $childnode->type
;
319 if (($type==self
::TYPE_CATEGORY
) ||
(isloggedin() && $type==self
::TYPE_COURSE
)) {
320 $node->nodetype
= self
::NODETYPE_BRANCH
;
322 // If this node is hidden mark it's children as hidden also
324 $node->hidden
= true;
326 // Return added node (reference returned by $this->children->add()
331 * Return a list of all the keys of all the child nodes.
332 * @return array the keys.
334 public function get_children_key_list() {
335 return $this->children
->get_key_list();
339 * Searches for a node of the given type with the given key.
341 * This searches this node plus all of its children, and their children....
342 * If you know the node you are looking for is a child of this node then please
343 * use the get method instead.
345 * @param int|string $key The key of the node we are looking for
346 * @param int $type One of navigation_node::TYPE_*
347 * @return navigation_node|false
349 public function find($key, $type) {
350 return $this->children
->find($key, $type);
354 * Get the child of this node that has the given key + (optional) type.
356 * If you are looking for a node and want to search all children + thier children
357 * then please use the find method instead.
359 * @param int|string $key The key of the node we are looking for
360 * @param int $type One of navigation_node::TYPE_*
361 * @return navigation_node|false
363 public function get($key, $type=null) {
364 return $this->children
->get($key, $type);
372 public function remove() {
373 return $this->parent
->children
->remove($this->key
, $this->type
);
377 * Checks if this node has or could have any children
379 * @return bool Returns true if it has children or could have (by AJAX expansion)
381 public function has_children() {
382 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0);
386 * Marks this node as active and forces it open.
388 * Important: If you are here because you need to mark a node active to get
389 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
390 * You can use it to specify a different URL to match the active navigation node on
391 * rather than having to locate and manually mark a node active.
393 public function make_active() {
394 $this->isactive
= true;
395 $this->add_class('active_tree_node');
397 if ($this->parent
!== null) {
398 $this->parent
->make_inactive();
403 * Marks a node as inactive and recusised back to the base of the tree
404 * doing the same to all parents.
406 public function make_inactive() {
407 $this->isactive
= false;
408 $this->remove_class('active_tree_node');
409 if ($this->parent
!== null) {
410 $this->parent
->make_inactive();
415 * Forces this node to be open and at the same time forces open all
416 * parents until the root node.
420 public function force_open() {
421 $this->forceopen
= true;
422 if ($this->parent
!== null) {
423 $this->parent
->force_open();
428 * Adds a CSS class to this node.
430 * @param string $class
433 public function add_class($class) {
434 if (!in_array($class, $this->classes
)) {
435 $this->classes
[] = $class;
441 * Removes a CSS class from this node.
443 * @param string $class
444 * @return bool True if the class was successfully removed.
446 public function remove_class($class) {
447 if (in_array($class, $this->classes
)) {
448 $key = array_search($class,$this->classes
);
450 unset($this->classes
[$key]);
458 * Sets the title for this node and forces Moodle to utilise it.
459 * @param string $title
461 public function title($title) {
462 $this->title
= $title;
463 $this->forcetitle
= true;
467 * Resets the page specific information on this node if it is being unserialised.
469 public function __wakeup(){
470 $this->forceopen
= false;
471 $this->isactive
= false;
472 $this->remove_class('active_tree_node');
476 * Checks if this node or any of its children contain the active node.
482 public function contains_active_node() {
483 if ($this->isactive
) {
486 foreach ($this->children
as $child) {
487 if ($child->isactive ||
$child->contains_active_node()) {
496 * Finds the active node.
498 * Searches this nodes children plus all of the children for the active node
499 * and returns it if found.
503 * @return navigation_node|false
505 public function find_active_node() {
506 if ($this->isactive
) {
509 foreach ($this->children
as &$child) {
510 $outcome = $child->find_active_node();
511 if ($outcome !== false) {
520 * Searches all children for the best matching active node
521 * @return navigation_node|false
523 public function search_for_active_node() {
524 if ($this->check_if_active(URL_MATCH_BASE
)) {
527 foreach ($this->children
as &$child) {
528 $outcome = $child->search_for_active_node();
529 if ($outcome !== false) {
538 * Gets the content for this node.
540 * @param bool $shorttext If true shorttext is used rather than the normal text
543 public function get_content($shorttext=false) {
544 if ($shorttext && $this->shorttext
!==null) {
545 return format_string($this->shorttext
);
547 return format_string($this->text
);
552 * Gets the title to use for this node.
556 public function get_title() {
557 if ($this->forcetitle ||
$this->action
!= null){
565 * Gets the CSS class to add to this node to describe its type
569 public function get_css_type() {
570 if (array_key_exists($this->type
, $this->namedtypes
)) {
571 return 'type_'.$this->namedtypes
[$this->type
];
573 return 'type_unknown';
577 * Finds all nodes that are expandable by AJAX
579 * @param array $expandable An array by reference to populate with expandable nodes.
581 public function find_expandable(array &$expandable) {
582 foreach ($this->children
as &$child) {
583 if ($child->nodetype
== self
::NODETYPE_BRANCH
&& $child->children
->count() == 0 && $child->display
) {
584 $child->id
= 'expandable_branch_'.(count($expandable)+
1);
585 $this->add_class('canexpand');
586 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
588 $child->find_expandable($expandable);
593 * Finds all nodes of a given type (recursive)
595 * @param int $type One of navigation_node::TYPE_*
598 public function find_all_of_type($type) {
599 $nodes = $this->children
->type($type);
600 foreach ($this->children
as &$node) {
601 $childnodes = $node->find_all_of_type($type);
602 $nodes = array_merge($nodes, $childnodes);
608 * Removes this node if it is empty
610 public function trim_if_empty() {
611 if ($this->children
->count() == 0) {
617 * Creates a tab representation of this nodes children that can be used
618 * with print_tabs to produce the tabs on a page.
620 * call_user_func_array('print_tabs', $node->get_tabs_array());
622 * @param array $inactive
623 * @param bool $return
624 * @return array Array (tabs, selected, inactive, activated, return)
626 public function get_tabs_array(array $inactive=array(), $return=false) {
630 $activated = array();
631 foreach ($this->children
as $node) {
632 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
633 if ($node->contains_active_node()) {
634 if ($node->children
->count() > 0) {
635 $activated[] = $node->key
;
636 foreach ($node->children
as $child) {
637 if ($child->contains_active_node()) {
638 $selected = $child->key
;
640 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
643 $selected = $node->key
;
647 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
651 * Sets the parent for this node and if this node is active ensures that the tree is properly
654 * @param navigation_node $parent
656 public function set_parent(navigation_node
$parent) {
657 // Set the parent (thats the easy part)
658 $this->parent
= $parent;
659 // Check if this node is active (this is checked during construction)
660 if ($this->isactive
) {
661 // Force all of the parent nodes open so you can see this node
662 $this->parent
->force_open();
663 // Make all parents inactive so that its clear where we are.
664 $this->parent
->make_inactive();
670 * Navigation node collection
672 * This class is responsible for managing a collection of navigation nodes.
673 * It is required because a node's unique identifier is a combination of both its
676 * Originally an array was used with a string key that was a combination of the two
677 * however it was decided that a better solution would be to use a class that
678 * implements the standard IteratorAggregate interface.
681 * @category navigation
682 * @copyright 2010 Sam Hemelryk
683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
685 class navigation_node_collection
implements IteratorAggregate
{
687 * A multidimensional array to where the first key is the type and the second
688 * key is the nodes key.
691 protected $collection = array();
693 * An array that contains references to nodes in the same order they were added.
694 * This is maintained as a progressive array.
697 protected $orderedcollection = array();
699 * A reference to the last node that was added to the collection
700 * @var navigation_node
702 protected $last = null;
704 * The total number of items added to this array.
707 protected $count = 0;
710 * Adds a navigation node to the collection
712 * @param navigation_node $node Node to add
713 * @param string $beforekey If specified, adds before a node with this key,
714 * otherwise adds at end
715 * @return navigation_node Added node
717 public function add(navigation_node
$node, $beforekey=null) {
722 // First check we have a 2nd dimension for this type
723 if (!array_key_exists($type, $this->orderedcollection
)) {
724 $this->orderedcollection
[$type] = array();
726 // Check for a collision and report if debugging is turned on
727 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
728 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
731 // Find the key to add before
732 $newindex = $this->count
;
734 if ($beforekey !== null) {
735 foreach ($this->collection
as $index => $othernode) {
736 if ($othernode->key
=== $beforekey) {
742 if ($newindex === $this->count
) {
743 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
744 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
748 // Add the node to the appropriate place in the by-type structure (which
749 // is not ordered, despite the variable name)
750 $this->orderedcollection
[$type][$key] = $node;
752 // Update existing references in the ordered collection (which is the
753 // one that isn't called 'ordered') to shuffle them along if required
754 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
755 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
758 // Add a reference to the node to the progressive collection.
759 $this->collection
[$newindex] = $this->orderedcollection
[$type][$key];
760 // Update the last property to a reference to this new node.
761 $this->last
= $this->orderedcollection
[$type][$key];
763 // Reorder the array by index if needed
765 ksort($this->collection
);
768 // Return the reference to the now added node
773 * Return a list of all the keys of all the nodes.
774 * @return array the keys.
776 public function get_key_list() {
778 foreach ($this->collection
as $node) {
779 $keys[] = $node->key
;
785 * Fetches a node from this collection.
787 * @param string|int $key The key of the node we want to find.
788 * @param int $type One of navigation_node::TYPE_*.
789 * @return navigation_node|null
791 public function get($key, $type=null) {
792 if ($type !== null) {
793 // If the type is known then we can simply check and fetch
794 if (!empty($this->orderedcollection
[$type][$key])) {
795 return $this->orderedcollection
[$type][$key];
798 // Because we don't know the type we look in the progressive array
799 foreach ($this->collection
as $node) {
800 if ($node->key
=== $key) {
809 * Searches for a node with matching key and type.
811 * This function searches both the nodes in this collection and all of
812 * the nodes in each collection belonging to the nodes in this collection.
816 * @param string|int $key The key of the node we want to find.
817 * @param int $type One of navigation_node::TYPE_*.
818 * @return navigation_node|null
820 public function find($key, $type=null) {
821 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
822 return $this->orderedcollection
[$type][$key];
824 $nodes = $this->getIterator();
825 // Search immediate children first
826 foreach ($nodes as &$node) {
827 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
831 // Now search each childs children
832 foreach ($nodes as &$node) {
833 $result = $node->children
->find($key, $type);
834 if ($result !== false) {
843 * Fetches the last node that was added to this collection
845 * @return navigation_node
847 public function last() {
852 * Fetches all nodes of a given type from this collection
854 * @param string|int $type node type being searched for.
855 * @return array ordered collection
857 public function type($type) {
858 if (!array_key_exists($type, $this->orderedcollection
)) {
859 $this->orderedcollection
[$type] = array();
861 return $this->orderedcollection
[$type];
864 * Removes the node with the given key and type from the collection
866 * @param string|int $key The key of the node we want to find.
870 public function remove($key, $type=null) {
871 $child = $this->get($key, $type);
872 if ($child !== false) {
873 foreach ($this->collection
as $colkey => $node) {
874 if ($node->key
== $key && $node->type
== $type) {
875 unset($this->collection
[$colkey]);
879 unset($this->orderedcollection
[$child->type
][$child->key
]);
887 * Gets the number of nodes in this collection
889 * This option uses an internal count rather than counting the actual options to avoid
890 * a performance hit through the count function.
894 public function count() {
898 * Gets an array iterator for the collection.
900 * This is required by the IteratorAggregator interface and is used by routines
901 * such as the foreach loop.
903 * @return ArrayIterator
905 public function getIterator() {
906 return new ArrayIterator($this->collection
);
911 * The global navigation class used for... the global navigation
913 * This class is used by PAGE to store the global navigation for the site
914 * and is then used by the settings nav and navbar to save on processing and DB calls
917 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
918 * {@link lib/ajax/getnavbranch.php} Called by ajax
921 * @category navigation
922 * @copyright 2009 Sam Hemelryk
923 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
925 class global_navigation
extends navigation_node
{
926 /** @var moodle_page The Moodle page this navigation object belongs to. */
928 /** @var bool switch to let us know if the navigation object is initialised*/
929 protected $initialised = false;
930 /** @var array An array of course information */
931 protected $mycourses = array();
932 /** @var array An array for containing root navigation nodes */
933 protected $rootnodes = array();
934 /** @var bool A switch for whether to show empty sections in the navigation */
935 protected $showemptysections = true;
936 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
937 protected $showcategories = null;
938 /** @var array An array of stdClasses for users that the navigation is extended for */
939 protected $extendforuser = array();
940 /** @var navigation_cache */
942 /** @var array An array of course ids that are present in the navigation */
943 protected $addedcourses = array();
945 protected $allcategoriesloaded = false;
946 /** @var array An array of category ids that are included in the navigation */
947 protected $addedcategories = array();
948 /** @var int expansion limit */
949 protected $expansionlimit = 0;
950 /** @var int userid to allow parent to see child's profile page navigation */
951 protected $useridtouseforparentchecks = 0;
953 /** Used when loading categories to load all top level categories [parent = 0] **/
954 const LOAD_ROOT_CATEGORIES
= 0;
955 /** Used when loading categories to load all categories **/
956 const LOAD_ALL_CATEGORIES
= -1;
959 * Constructs a new global navigation
961 * @param moodle_page $page The page this navigation object belongs to
963 public function __construct(moodle_page
$page) {
964 global $CFG, $SITE, $USER;
966 if (during_initial_install()) {
970 if (get_home_page() == HOMEPAGE_SITE
) {
971 // We are using the site home for the root element
974 'type' => navigation_node
::TYPE_SYSTEM
,
975 'text' => get_string('home'),
976 'action' => new moodle_url('/')
979 // We are using the users my moodle for the root element
982 'type' => navigation_node
::TYPE_SYSTEM
,
983 'text' => get_string('myhome'),
984 'action' => new moodle_url('/my/')
988 // Use the parents constructor.... good good reuse
989 parent
::__construct($properties);
991 // Initalise and set defaults
993 $this->forceopen
= true;
994 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
998 * Mutator to set userid to allow parent to see child's profile
999 * page navigation. See MDL-25805 for initial issue. Linked to it
1000 * is an issue explaining why this is a REALLY UGLY HACK thats not
1003 * @param int $userid userid of profile page that parent wants to navigate around.
1005 public function set_userid_for_parent_checks($userid) {
1006 $this->useridtouseforparentchecks
= $userid;
1011 * Initialises the navigation object.
1013 * This causes the navigation object to look at the current state of the page
1014 * that it is associated with and then load the appropriate content.
1016 * This should only occur the first time that the navigation structure is utilised
1017 * which will normally be either when the navbar is called to be displayed or
1018 * when a block makes use of it.
1022 public function initialise() {
1023 global $CFG, $SITE, $USER, $DB;
1024 // Check if it has alread been initialised
1025 if ($this->initialised ||
during_initial_install()) {
1028 $this->initialised
= true;
1030 // Set up the five base root nodes. These are nodes where we will put our
1031 // content and are as follows:
1032 // site: Navigation for the front page.
1033 // myprofile: User profile information goes here.
1034 // mycourses: The users courses get added here.
1035 // courses: Additional courses are added here.
1036 // users: Other users information loaded here.
1037 $this->rootnodes
= array();
1038 if (get_home_page() == HOMEPAGE_SITE
) {
1039 // The home element should be my moodle because the root element is the site
1040 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1041 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_SETTING
, null, 'home');
1044 // The home element should be the site because the root node is my moodle
1045 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self
::TYPE_SETTING
, null, 'home');
1046 if (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_MY
)) {
1047 // We need to stop automatic redirection
1048 $this->rootnodes
['home']->action
->param('redirect', '0');
1051 $this->rootnodes
['site'] = $this->add_course($SITE);
1052 $this->rootnodes
['myprofile'] = $this->add(get_string('myprofile'), null, self
::TYPE_USER
, null, 'myprofile');
1053 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses');
1054 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1055 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1057 // We always load the frontpage course to ensure it is available without
1058 // JavaScript enabled.
1059 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1060 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1062 // Fetch all of the users courses.
1063 $mycourses = enrol_get_my_courses();
1064 // 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
1065 $showcategories = ($this->show_categories() && (count($mycourses) == 0 ||
!empty($CFG->navshowallcourses
)));
1066 // $issite gets set to true if the current pages course is the sites frontpage course
1067 $issite = ($this->page
->course
->id
== $SITE->id
);
1068 // $ismycourse gets set to true if the user is enrolled in the current pages course.
1069 $ismycourse = !$issite && (array_key_exists($this->page
->course
->id
, $mycourses));
1071 // Check if any courses were returned.
1072 if (count($mycourses) > 0) {
1074 // Check if categories should be displayed within the my courses branch
1075 if (!empty($CFG->navshowmycoursecategories
)) {
1077 // Find the category of each mycourse
1078 $categories = array();
1079 foreach ($mycourses as $course) {
1080 $categories[] = $course->category
;
1083 // Do a single DB query to get the categories immediately associated with
1084 // courses the user is enrolled in.
1085 $categories = $DB->get_records_list('course_categories', 'id', array_unique($categories), 'depth ASC, sortorder ASC');
1086 // Work out the parent categories that we need to load that we havn't
1088 $categoryids = array();
1089 foreach ($categories as $category) {
1090 $categoryids = array_merge($categoryids, explode('/', trim($category->path
, '/')));
1092 $categoryids = array_unique($categoryids);
1093 $categoryids = array_diff($categoryids, array_keys($categories));
1095 if (count($categoryids)) {
1096 // Fetch any other categories we need.
1097 $allcategories = $DB->get_records_list('course_categories', 'id', $categoryids, 'depth ASC, sortorder ASC');
1098 if (is_array($allcategories) && count($allcategories) > 0) {
1099 $categories = array_merge($categories, $allcategories);
1103 // We ONLY want the categories, we need to get rid of the keys
1104 $categories = array_values($categories);
1105 $addedcategories = array();
1106 while (($category = array_shift($categories)) !== null) {
1107 if ($category->parent
== '0') {
1108 $categoryparent = $this->rootnodes
['mycourses'];
1109 } else if (array_key_exists($category->parent
, $addedcategories)) {
1110 $categoryparent = $addedcategories[$category->parent
];
1112 // Prepare to count iterations. We don't want to loop forever
1113 // accidentally if for some reason a category can't be placed.
1114 if (!isset($category->loopcount
)) {
1115 $category->loopcount
= 0;
1117 $category->loopcount++
;
1118 if ($category->loopcount
> 5) {
1119 // This is a pretty serious problem and this should never happen.
1120 // If it does then for some reason a category has been loaded but
1121 // its parents have now. It could be data corruption.
1122 debugging('Category '.$category->id
.' could not be placed within the navigation', DEBUG_DEVELOPER
);
1124 // Add it back to the end of the categories array
1125 array_push($categories, $category);
1130 $url = new moodle_url('/course/category.php', array('id' => $category->id
));
1131 $addedcategories[$category->id
] = $categoryparent->add($category->name
, $url, self
::TYPE_CATEGORY
, $category->name
, $category->id
);
1133 if (!$category->visible
) {
1134 if (!has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_COURSECAT
, $category->parent
))) {
1135 $addedcategories[$category->id
]->display
= false;
1137 $addedcategories[$category->id
]->hidden
= true;
1143 // Add all of the users courses to the navigation.
1144 // First up we need to add to the mycourses section.
1145 foreach ($mycourses as $course) {
1146 $course->coursenode
= $this->add_course($course, false, true);
1149 if (!empty($CFG->navshowallcourses
)) {
1151 $this->load_all_courses();
1154 // Next if nasvshowallcourses is enabled then we need to add courses
1155 // to the courses branch as well.
1156 if (!empty($CFG->navshowallcourses
)) {
1157 foreach ($mycourses as $course) {
1158 if (!empty($course->category
) && !$this->can_add_more_courses_to_category($course->category
)) {
1161 $genericcoursenode = $this->add_course($course, true);
1162 if ($genericcoursenode->isactive
) {
1163 // We don't want this node to be active because we want the
1164 // node in the mycourses branch to be active.
1165 $genericcoursenode->make_inactive();
1166 $genericcoursenode->collapse
= true;
1167 if ($genericcoursenode->parent
&& $genericcoursenode->parent
->type
== self
::TYPE_CATEGORY
) {
1168 $parent = $genericcoursenode->parent
;
1169 while ($parent && $parent->type
== self
::TYPE_CATEGORY
) {
1170 $parent->collapse
= true;
1171 $parent = $parent->parent
;
1177 } else if (!empty($CFG->navshowallcourses
) ||
!$this->show_categories()) {
1179 $this->load_all_courses();
1182 $canviewcourseprofile = true;
1184 // Next load context specific content into the navigation
1185 switch ($this->page
->context
->contextlevel
) {
1186 case CONTEXT_SYSTEM
:
1187 // This has already been loaded we just need to map the variable
1188 if ($showcategories) {
1189 $this->load_all_categories(self
::LOAD_ROOT_CATEGORIES
, true);
1192 case CONTEXT_COURSECAT
:
1193 // This has already been loaded we just need to map the variable
1194 if ($showcategories) {
1195 $this->load_all_categories($this->page
->context
->instanceid
, true);
1198 case CONTEXT_BLOCK
:
1199 case CONTEXT_COURSE
:
1201 // If it is the front page course, or a block on it then
1202 // all we need to do is load the root categories if required
1203 if ($showcategories) {
1204 $this->load_all_categories(self
::LOAD_ROOT_CATEGORIES
, true);
1208 // Load the course associated with the page into the navigation
1209 $course = $this->page
->course
;
1210 if ($this->show_categories() && !$ismycourse) {
1211 // The user isn't enrolled in the course and we need to show categories in which case we need
1212 // to load the category relating to the course and depending up $showcategories all of the root categories as well.
1213 $this->load_all_categories($course->category
, $showcategories);
1215 $coursenode = $this->load_course($course);
1217 // If the course wasn't added then don't try going any further.
1219 $canviewcourseprofile = false;
1223 // If the user is not enrolled then we only want to show the
1224 // course node and not populate it.
1226 // Not enrolled, can't view, and hasn't switched roles
1227 if (!can_access_course($course)) {
1228 // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1229 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1231 if ($this->useridtouseforparentchecks
) {
1232 if ($this->useridtouseforparentchecks
!= $USER->id
) {
1233 $usercontext = get_context_instance(CONTEXT_USER
, $this->useridtouseforparentchecks
, MUST_EXIST
);
1234 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))
1235 and has_capability('moodle/user:viewdetails', $usercontext)) {
1242 $coursenode->make_active();
1243 $canviewcourseprofile = false;
1247 // Add the essentials such as reports etc...
1248 $this->add_course_essentials($coursenode, $course);
1249 if ($this->format_display_course_content($course->format
)) {
1250 // Load the course sections
1251 $sections = $this->load_course_sections($course, $coursenode);
1253 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1254 $coursenode->make_active();
1257 case CONTEXT_MODULE
:
1259 // If this is the site course then most information will have
1260 // already been loaded.
1261 // However we need to check if there is more content that can
1262 // yet be loaded for the specific module instance.
1263 $activitynode = $this->rootnodes
['site']->get($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1264 if ($activitynode) {
1265 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1270 $course = $this->page
->course
;
1271 $cm = $this->page
->cm
;
1273 if ($this->show_categories() && !$ismycourse) {
1274 $this->load_all_categories($course->category
, $showcategories);
1277 // Load the course associated with the page into the navigation
1278 $coursenode = $this->load_course($course);
1280 // If the course wasn't added then don't try going any further.
1282 $canviewcourseprofile = false;
1286 // If the user is not enrolled then we only want to show the
1287 // course node and not populate it.
1288 if (!can_access_course($course)) {
1289 $coursenode->make_active();
1290 $canviewcourseprofile = false;
1294 $this->add_course_essentials($coursenode, $course);
1296 // Get section number from $cm (if provided) - we need this
1297 // before loading sections in order to tell it to load this section
1298 // even if it would not normally display (=> it contains only
1299 // a label, which we are now editing)
1300 $sectionnum = isset($cm->sectionnum
) ?
$cm->sectionnum
: 0;
1302 // This value has to be stored in a member variable because
1303 // otherwise we would have to pass it through a public API
1304 // to course formats and they would need to change their
1305 // functions to pass it along again...
1306 $this->includesectionnum
= $sectionnum;
1308 $this->includesectionnum
= false;
1311 // Load the course sections into the page
1312 $sections = $this->load_course_sections($course, $coursenode);
1313 if ($course->id
!= $SITE->id
) {
1314 // Find the section for the $CM associated with the page and collect
1315 // its section number.
1317 $cm->sectionnumber
= $sectionnum;
1319 foreach ($sections as $section) {
1320 if ($section->id
== $cm->section
) {
1321 $cm->sectionnumber
= $section->section
;
1327 // Load all of the section activities for the section the cm belongs to.
1328 if (isset($cm->sectionnumber
) and !empty($sections[$cm->sectionnumber
])) {
1329 list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1330 $activities = $this->load_section_activities($sections[$cm->sectionnumber
]->sectionnode
, $cm->sectionnumber
, $activityarray);
1332 $activities = array();
1333 if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1334 // "stealth" activity from unavailable section
1335 $activities[$cm->id
] = $activity;
1339 $activities = array();
1340 $activities[$cm->id
] = $coursenode->get($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1342 if (!empty($activities[$cm->id
])) {
1343 // Finally load the cm specific navigaton information
1344 $this->load_activity($cm, $course, $activities[$cm->id
]);
1345 // Check if we have an active ndoe
1346 if (!$activities[$cm->id
]->contains_active_node() && !$activities[$cm->id
]->search_for_active_node()) {
1347 // And make the activity node active.
1348 $activities[$cm->id
]->make_active();
1351 //TODO: something is wrong, what to do? (Skodak)
1356 // The users profile information etc is already loaded
1357 // for the front page.
1360 $course = $this->page
->course
;
1361 if ($this->show_categories() && !$ismycourse) {
1362 $this->load_all_categories($course->category
, $showcategories);
1364 // Load the course associated with the user into the navigation
1365 $coursenode = $this->load_course($course);
1367 // If the course wasn't added then don't try going any further.
1369 $canviewcourseprofile = false;
1373 // If the user is not enrolled then we only want to show the
1374 // course node and not populate it.
1375 if (!can_access_course($course)) {
1376 $coursenode->make_active();
1377 $canviewcourseprofile = false;
1380 $this->add_course_essentials($coursenode, $course);
1381 $sections = $this->load_course_sections($course, $coursenode);
1385 // Look for all categories which have been loaded
1386 if ($showcategories) {
1387 $categories = $this->find_all_of_type(self
::TYPE_CATEGORY
);
1388 if (count($categories) !== 0) {
1389 $categoryids = array();
1390 foreach ($categories as $category) {
1391 $categoryids[] = $category->key
;
1393 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
1394 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
1395 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1396 FROM {course_categories} cc
1397 JOIN {course} c ON c.category = cc.id
1398 WHERE cc.id {$categoriessql}
1400 HAVING COUNT(c.id) > :limit";
1401 $excessivecategories = $DB->get_records_sql($sql, $params);
1402 foreach ($categories as &$category) {
1403 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1404 $url = new moodle_url('/course/category.php', array('id'=>$category->key
));
1405 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1409 } else if ((!empty($CFG->navshowallcourses
) ||
empty($mycourses)) && !$this->can_add_more_courses_to_category($this->rootnodes
['courses'])) {
1410 $this->rootnodes
['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self
::TYPE_SETTING
);
1413 // Load for the current user
1414 $this->load_for_user();
1415 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
&& $canviewcourseprofile) {
1416 $this->load_for_user(null, true);
1418 // Load each extending user into the navigation.
1419 foreach ($this->extendforuser
as $user) {
1420 if ($user->id
!= $USER->id
) {
1421 $this->load_for_user($user);
1425 // Give the local plugins a chance to include some navigation if they want.
1426 foreach (get_list_of_plugins('local') as $plugin) {
1427 if (!file_exists($CFG->dirroot
.'/local/'.$plugin.'/lib.php')) {
1430 require_once($CFG->dirroot
.'/local/'.$plugin.'/lib.php');
1431 $function = $plugin.'_extends_navigation';
1432 if (function_exists($function)) {
1437 // Remove any empty root nodes
1438 foreach ($this->rootnodes
as $node) {
1439 // Dont remove the home node
1440 if ($node->key
!== 'home' && !$node->has_children()) {
1445 if (!$this->contains_active_node()) {
1446 $this->search_for_active_node();
1449 // If the user is not logged in modify the navigation structure as detailed
1450 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1451 if (!isloggedin()) {
1452 $activities = clone($this->rootnodes
['site']->children
);
1453 $this->rootnodes
['site']->remove();
1454 $children = clone($this->children
);
1455 $this->children
= new navigation_node_collection();
1456 foreach ($activities as $child) {
1457 $this->children
->add($child);
1459 foreach ($children as $child) {
1460 $this->children
->add($child);
1467 * Returns true if courses should be shown within categories on the navigation.
1471 protected function show_categories() {
1473 if ($this->showcategories
=== null) {
1474 $show = $this->page
->context
->contextlevel
== CONTEXT_COURSECAT
;
1475 $show = $show ||
(!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1);
1476 $this->showcategories
= $show;
1478 return $this->showcategories
;
1482 * Checks the course format to see whether it wants the navigation to load
1483 * additional information for the course.
1485 * This function utilises a callback that can exist within the course format lib.php file
1486 * The callback should be a function called:
1487 * callback_{formatname}_display_content()
1488 * It doesn't get any arguments and should return true if additional content is
1489 * desired. If the callback doesn't exist we assume additional content is wanted.
1491 * @param string $format The course format
1494 protected function format_display_course_content($format) {
1496 $formatlib = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
1497 if (file_exists($formatlib)) {
1498 require_once($formatlib);
1499 $displayfunc = 'callback_'.$format.'_display_content';
1500 if (function_exists($displayfunc) && !$displayfunc()) {
1501 return $displayfunc();
1508 * Loads the courses in Moodle into the navigation.
1510 * @global moodle_database $DB
1511 * @param string|array $categoryids An array containing categories to load courses
1512 * for, OR null to load courses for all categories.
1513 * @return array An array of navigation_nodes one for each course
1515 protected function load_all_courses($categoryids = null) {
1516 global $CFG, $DB, $SITE;
1518 // Work out the limit of courses.
1520 if (!empty($CFG->navcourselimit
)) {
1521 $limit = $CFG->navcourselimit
;
1524 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1526 // If we are going to show all courses AND we are showing categories then
1527 // to save us repeated DB calls load all of the categories now
1528 if ($this->show_categories()) {
1529 $this->load_all_categories($toload);
1532 // Will be the return of our efforts
1533 $coursenodes = array();
1535 // Check if we need to show categories.
1536 if ($this->show_categories()) {
1537 // Hmmm we need to show categories... this is going to be painful.
1538 // We now need to fetch up to $limit courses for each category to
1540 if ($categoryids !== null) {
1541 if (!is_array($categoryids)) {
1542 $categoryids = array($categoryids);
1544 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1545 $categorywhere = 'WHERE cc.id '.$categorywhere;
1546 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1547 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1548 $categoryparams = array();
1550 $categorywhere = '';
1551 $categoryparams = array();
1554 // First up we are going to get the categories that we are going to
1555 // need so that we can determine how best to load the courses from them.
1556 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1557 FROM {course_categories} cc
1558 LEFT JOIN {course} c ON c.category = cc.id
1561 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1562 $fullfetch = array();
1563 $partfetch = array();
1564 foreach ($categories as $category) {
1565 if (!$this->can_add_more_courses_to_category($category->id
)) {
1568 if ($category->coursecount
> $limit * 5) {
1569 $partfetch[] = $category->id
;
1570 } else if ($category->coursecount
> 0) {
1571 $fullfetch[] = $category->id
;
1574 $categories->close();
1576 if (count($fullfetch)) {
1577 // First up fetch all of the courses in categories where we know that we are going to
1578 // need the majority of courses.
1579 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1580 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
) +
array($SITE->id
), SQL_PARAMS_NAMED
, 'lcourse', false);
1581 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1582 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1585 WHERE c.category {$categoryids} AND
1587 ORDER BY c.sortorder ASC";
1588 $coursesrs = $DB->get_recordset_sql($sql, $courseparams +
$categoryparams);
1589 foreach ($coursesrs as $course) {
1590 if (!$this->can_add_more_courses_to_category($course->category
)) {
1593 context_instance_preload($course);
1594 if ($course->id
!= $SITE->id
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1597 $coursenodes[$course->id
] = $this->add_course($course);
1599 $coursesrs->close();
1602 if (count($partfetch)) {
1603 // Next we will work our way through the categories where we will likely only need a small
1604 // proportion of the courses.
1605 foreach ($partfetch as $categoryid) {
1606 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1607 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
) +
array($SITE->id
), SQL_PARAMS_NAMED
, 'lcourse', false);
1608 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1611 WHERE c.category = :categoryid AND
1613 ORDER BY c.sortorder ASC";
1614 $courseparams['categoryid'] = $categoryid;
1615 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1616 foreach ($coursesrs as $course) {
1617 if (!$this->can_add_more_courses_to_category($course->category
)) {
1620 context_instance_preload($course);
1621 if ($course->id
!= $SITE->id
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1624 $coursenodes[$course->id
] = $this->add_course($course);
1626 $coursesrs->close();
1630 // Prepare the SQL to load the courses and their contexts
1631 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1632 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1633 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1636 WHERE c.id {$courseids}
1637 ORDER BY c.sortorder ASC";
1638 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1639 foreach ($coursesrs as $course) {
1640 context_instance_preload($course);
1641 if ($course->id
!= $SITE->id
&& !$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1644 $coursenodes[$course->id
] = $this->add_course($course);
1645 if (count($coursenodes) >= $limit) {
1649 $coursesrs->close();
1652 return $coursenodes;
1656 * Returns true if more courses can be added to the provided category.
1658 * @param int|navigation_node|stdClass $category
1661 protected function can_add_more_courses_to_category($category) {
1664 if (!empty($CFG->navcourselimit
)) {
1665 $limit = (int)$CFG->navcourselimit
;
1667 if (is_numeric($category)) {
1668 if (!array_key_exists($category, $this->addedcategories
)) {
1671 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1672 } else if ($category instanceof navigation_node
) {
1673 if ($category->type
!= self
::TYPE_CATEGORY
) {
1676 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1677 } else if (is_object($category) && property_exists($category,'id')) {
1678 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1680 return ($coursecount <= $limit);
1684 * Loads all categories (top level or if an id is specified for that category)
1686 * @param int $categoryid The category id to load or null/0 to load all base level categories
1687 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1688 * as the requested category and any parent categories.
1689 * @return navigation_node|void returns a navigation node if a category has been loaded.
1691 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1694 // Check if this category has already been loaded
1695 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1699 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1700 $sqlselect = "SELECT cc.*, $catcontextsql
1701 FROM {course_categories} cc
1702 JOIN {context} ctx ON cc.id = ctx.instanceid";
1703 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1704 $sqlorder = "ORDER BY depth ASC, sortorder ASC, id ASC";
1707 $categoriestoload = array();
1708 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1709 // We are going to load all categories regardless... prepare to fire
1710 // on the database server!
1711 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1712 // We are going to load all of the first level categories (categories without parents)
1713 $sqlwhere .= " AND cc.parent = 0";
1714 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1715 // The category itself has been loaded already so we just need to ensure its subcategories
1717 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories
), SQL_PARAMS_NAMED
, 'parent', false);
1718 if ($showbasecategories) {
1719 // We need to include categories with parent = 0 as well
1720 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1722 // All we need is categories that match the parent
1723 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1725 $params['categoryid'] = $categoryid;
1727 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1728 // and load this category plus all its parents and subcategories
1729 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1730 $categoriestoload = explode('/', trim($category->path
, '/'));
1731 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1732 // We are going to use select twice so double the params
1733 $params = array_merge($params, $params);
1734 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1735 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1738 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1739 $categories = array();
1740 foreach ($categoriesrs as $category) {
1741 // Preload the context.. we'll need it when adding the category in order
1742 // to format the category name.
1743 context_helper
::preload_from_record($category);
1744 if (array_key_exists($category->id
, $this->addedcategories
)) {
1745 // Do nothing, its already been added.
1746 } else if ($category->parent
== '0') {
1747 // This is a root category lets add it immediately
1748 $this->add_category($category, $this->rootnodes
['courses']);
1749 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1750 // This categories parent has already been added we can add this immediately
1751 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1753 $categories[] = $category;
1756 $categoriesrs->close();
1758 // Now we have an array of categories we need to add them to the navigation.
1759 while (!empty($categories)) {
1760 $category = reset($categories);
1761 if (array_key_exists($category->id
, $this->addedcategories
)) {
1763 } else if ($category->parent
== '0') {
1764 $this->add_category($category, $this->rootnodes
['courses']);
1765 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1766 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1768 // This category isn't in the navigation and niether is it's parent (yet).
1769 // We need to go through the category path and add all of its components in order.
1770 $path = explode('/', trim($category->path
, '/'));
1771 foreach ($path as $catid) {
1772 if (!array_key_exists($catid, $this->addedcategories
)) {
1773 // This category isn't in the navigation yet so add it.
1774 $subcategory = $categories[$catid];
1775 if ($subcategory->parent
== '0') {
1776 // Yay we have a root category - this likely means we will now be able
1777 // to add categories without problems.
1778 $this->add_category($subcategory, $this->rootnodes
['courses']);
1779 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
1780 // The parent is in the category (as we'd expect) so add it now.
1781 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
1782 // Remove the category from the categories array.
1783 unset($categories[$catid]);
1785 // We should never ever arrive here - if we have then there is a bigger
1787 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1792 // Remove the category from the categories array now that we know it has been added.
1793 unset($categories[$category->id
]);
1795 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
1796 $this->allcategoriesloaded
= true;
1798 // Check if there are any categories to load.
1799 if (count($categoriestoload) > 0) {
1800 $readytoloadcourses = array();
1801 foreach ($categoriestoload as $category) {
1802 if ($this->can_add_more_courses_to_category($category)) {
1803 $readytoloadcourses[] = $category;
1806 if (count($readytoloadcourses)) {
1807 $this->load_all_courses($readytoloadcourses);
1813 * Adds a structured category to the navigation in the correct order/place
1815 * @param stdClass $category
1816 * @param navigation_node $parent
1818 protected function add_category(stdClass
$category, navigation_node
$parent) {
1819 if (array_key_exists($category->id
, $this->addedcategories
)) {
1822 $url = new moodle_url('/course/category.php', array('id' => $category->id
));
1823 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
1824 $categoryname = format_string($category->name
, true, array('context' => $context));
1825 $categorynode = $parent->add($categoryname, $url, self
::TYPE_CATEGORY
, $categoryname, $category->id
);
1826 if (empty($category->visible
)) {
1827 if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1828 $categorynode->hidden
= true;
1830 $categorynode->display
= false;
1833 $this->addedcategories
[$category->id
] = $categorynode;
1837 * Loads the given course into the navigation
1839 * @param stdClass $course
1840 * @return navigation_node
1842 protected function load_course(stdClass
$course) {
1844 if ($course->id
== $SITE->id
) {
1845 // This is always loaded during initialisation
1846 return $this->rootnodes
['site'];
1847 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
1848 // The course has already been loaded so return a reference
1849 return $this->addedcourses
[$course->id
];
1852 return $this->add_course($course);
1857 * Loads all of the courses section into the navigation.
1859 * This function utilisies a callback that can be implemented within the course
1860 * formats lib.php file to customise the navigation that is generated at this
1861 * point for the course.
1863 * By default (if not defined) the method {@link global_navigation::load_generic_course_sections()} is
1866 * @param stdClass $course Database record for the course
1867 * @param navigation_node $coursenode The course node within the navigation
1868 * @return array Array of navigation nodes for the section with key = section id
1870 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode) {
1872 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
1873 $structurefunc = 'callback_'.$course->format
.'_load_content';
1874 if (function_exists($structurefunc)) {
1875 return $structurefunc($this, $course, $coursenode);
1876 } else if (file_exists($structurefile)) {
1877 require_once $structurefile;
1878 if (function_exists($structurefunc)) {
1879 return $structurefunc($this, $course, $coursenode);
1881 return $this->load_generic_course_sections($course, $coursenode);
1884 return $this->load_generic_course_sections($course, $coursenode);
1889 * Generates an array of sections and an array of activities for the given course.
1891 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1893 * @param stdClass $course
1894 * @return array Array($sections, $activities)
1896 protected function generate_sections_and_activities(stdClass
$course) {
1898 require_once($CFG->dirroot
.'/course/lib.php');
1900 $modinfo = get_fast_modinfo($course);
1902 $sections = array_slice(get_all_sections($course->id
), 0, $course->numsections+
1, true);
1903 $activities = array();
1905 foreach ($sections as $key => $section) {
1906 $sections[$key]->hasactivites
= false;
1907 if (!array_key_exists($section->section
, $modinfo->sections
)) {
1910 foreach ($modinfo->sections
[$section->section
] as $cmid) {
1911 $cm = $modinfo->cms
[$cmid];
1912 if (!$cm->uservisible
) {
1915 $activity = new stdClass
;
1916 $activity->id
= $cm->id
;
1917 $activity->course
= $course->id
;
1918 $activity->section
= $section->section
;
1919 $activity->name
= $cm->name
;
1920 $activity->icon
= $cm->icon
;
1921 $activity->iconcomponent
= $cm->iconcomponent
;
1922 $activity->hidden
= (!$cm->visible
);
1923 $activity->modname
= $cm->modname
;
1924 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1925 $activity->onclick
= $cm->get_on_click();
1926 $url = $cm->get_url();
1928 $activity->url
= null;
1929 $activity->display
= false;
1931 $activity->url
= $cm->get_url()->out();
1932 $activity->display
= true;
1933 if (self
::module_extends_navigation($cm->modname
)) {
1934 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1937 $activities[$cmid] = $activity;
1938 if ($activity->display
) {
1939 $sections[$key]->hasactivites
= true;
1944 return array($sections, $activities);
1948 * Generically loads the course sections into the course's navigation.
1950 * @param stdClass $course
1951 * @param navigation_node $coursenode
1952 * @param string $courseformat The course format
1953 * @return array An array of course section nodes
1955 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode, $courseformat='unknown') {
1956 global $CFG, $DB, $USER, $SITE;
1957 require_once($CFG->dirroot
.'/course/lib.php');
1959 list($sections, $activities) = $this->generate_sections_and_activities($course);
1961 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1962 $namingfunctionexists = (function_exists($namingfunction));
1964 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page
->context
);
1966 $urlfunction = 'callback_'.$courseformat.'_get_section_url';
1967 if (function_exists($urlfunction)) {
1968 // This code path is deprecated but we decided not to warn developers as
1969 // major changes are likely to follow in 2.4. See MDL-32504.
1971 $urlfunction = null;
1975 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT
== '0' && $this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
1976 $key = optional_param('section', $key, PARAM_INT
);
1979 $navigationsections = array();
1980 foreach ($sections as $sectionid => $section) {
1981 $section = clone($section);
1982 if ($course->id
== $SITE->id
) {
1983 $this->load_section_activities($coursenode, $section->section
, $activities);
1985 if ((!$viewhiddensections && !$section->visible
) ||
(!$this->showemptysections
&&
1986 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
1989 if ($namingfunctionexists) {
1990 $sectionname = $namingfunction($course, $section, $sections);
1992 $sectionname = get_string('section').' '.$section->section
;
1997 // pre 2.3 style format url
1998 $url = $urlfunction($course->id
, $section->section
);
2000 if ($course->coursedisplay
== COURSE_DISPLAY_MULTIPAGE
) {
2001 $url = course_get_url($course, $section->section
);
2004 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
, null, $section->id
);
2005 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2006 $sectionnode->hidden
= (!$section->visible
);
2007 if ($key != '0' && $section->section
!= '0' && $section->section
== $key && $this->page
->context
->contextlevel
!= CONTEXT_MODULE
&& $section->hasactivites
) {
2008 $sectionnode->make_active();
2009 $this->load_section_activities($sectionnode, $section->section
, $activities);
2011 $section->sectionnode
= $sectionnode;
2012 $navigationsections[$sectionid] = $section;
2015 return $navigationsections;
2018 * Loads all of the activities for a section into the navigation structure.
2020 * @param navigation_node $sectionnode
2021 * @param int $sectionnumber
2022 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2023 * @param stdClass $course The course object the section and activities relate to.
2024 * @return array Array of activity nodes
2026 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2028 // A static counter for JS function naming
2029 static $legacyonclickcounter = 0;
2031 $activitynodes = array();
2032 if (empty($activities)) {
2033 return $activitynodes;
2036 if (!is_object($course)) {
2037 $activity = reset($activities);
2038 $courseid = $activity->course
;
2040 $courseid = $course->id
;
2042 $showactivities = ($courseid != $SITE->id ||
!empty($CFG->navshowfrontpagemods
));
2044 foreach ($activities as $activity) {
2045 if ($activity->section
!= $sectionnumber) {
2048 if ($activity->icon
) {
2049 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2051 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2054 // Prepare the default name and url for the node
2055 $activityname = format_string($activity->name
, true, array('context' => get_context_instance(CONTEXT_MODULE
, $activity->id
)));
2056 $action = new moodle_url($activity->url
);
2058 // Check if the onclick property is set (puke!)
2059 if (!empty($activity->onclick
)) {
2060 // Increment the counter so that we have a unique number.
2061 $legacyonclickcounter++
;
2062 // Generate the function name we will use
2063 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2064 $propogrationhandler = '';
2065 // Check if we need to cancel propogation. Remember inline onclick
2066 // events would return false if they wanted to prevent propogation and the
2068 if (strpos($activity->onclick
, 'return false')) {
2069 $propogrationhandler = 'e.halt();';
2071 // Decode the onclick - it has already been encoded for display (puke)
2072 $onclick = htmlspecialchars_decode($activity->onclick
);
2073 // Build the JS function the click event will call
2074 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2075 $this->page
->requires
->js_init_code($jscode);
2076 // Override the default url with the new action link
2077 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2080 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2081 $activitynode->title(get_string('modulename', $activity->modname
));
2082 $activitynode->hidden
= $activity->hidden
;
2083 $activitynode->display
= $showactivities && $activity->display
;
2084 $activitynode->nodetype
= $activity->nodetype
;
2085 $activitynodes[$activity->id
] = $activitynode;
2088 return $activitynodes;
2091 * Loads a stealth module from unavailable section
2092 * @param navigation_node $coursenode
2093 * @param stdClass $modinfo
2094 * @return navigation_node or null if not accessible
2096 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2097 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2100 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2101 if (!$cm->uservisible
) {
2105 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2107 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2109 $url = $cm->get_url();
2110 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2111 $activitynode->title(get_string('modulename', $cm->modname
));
2112 $activitynode->hidden
= (!$cm->visible
);
2114 // Don't show activities that don't have links!
2115 $activitynode->display
= false;
2116 } else if (self
::module_extends_navigation($cm->modname
)) {
2117 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2119 return $activitynode;
2122 * Loads the navigation structure for the given activity into the activities node.
2124 * This method utilises a callback within the modules lib.php file to load the
2125 * content specific to activity given.
2127 * The callback is a method: {modulename}_extend_navigation()
2129 * * {@link forum_extend_navigation()}
2130 * * {@link workshop_extend_navigation()}
2132 * @param cm_info|stdClass $cm
2133 * @param stdClass $course
2134 * @param navigation_node $activity
2137 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2140 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2141 if (!($cm instanceof cm_info
)) {
2142 $modinfo = get_fast_modinfo($course);
2143 $cm = $modinfo->get_cm($cm->id
);
2146 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2147 $activity->make_active();
2148 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2149 $function = $cm->modname
.'_extend_navigation';
2151 if (file_exists($file)) {
2152 require_once($file);
2153 if (function_exists($function)) {
2154 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2155 $function($activity, $course, $activtyrecord, $cm);
2159 // Allow the active advanced grading method plugin to append module navigation
2160 $featuresfunc = $cm->modname
.'_supports';
2161 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2162 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2163 $gradingman = get_grading_manager($cm->context
, $cm->modname
);
2164 $gradingman->extend_navigation($this, $activity);
2167 return $activity->has_children();
2170 * Loads user specific information into the navigation in the appropriate place.
2172 * If no user is provided the current user is assumed.
2174 * @param stdClass $user
2175 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2178 protected function load_for_user($user=null, $forceforcontext=false) {
2179 global $DB, $CFG, $USER, $SITE;
2181 if ($user === null) {
2182 // We can't require login here but if the user isn't logged in we don't
2183 // want to show anything
2184 if (!isloggedin() ||
isguestuser()) {
2188 } else if (!is_object($user)) {
2189 // If the user is not an object then get them from the database
2190 $select = context_helper
::get_preload_record_columns_sql('ctx');
2191 $sql = "SELECT u.*, $select
2193 JOIN {context} ctx ON u.id = ctx.instanceid
2194 WHERE u.id = :userid AND
2195 ctx.contextlevel = :contextlevel";
2196 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2197 context_helper
::preload_from_record($user);
2200 $iscurrentuser = ($user->id
== $USER->id
);
2202 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
2204 // Get the course set against the page, by default this will be the site
2205 $course = $this->page
->course
;
2206 $baseargs = array('id'=>$user->id
);
2207 if ($course->id
!= $SITE->id
&& (!$iscurrentuser ||
$forceforcontext)) {
2208 $coursenode = $this->load_course($course);
2209 $baseargs['course'] = $course->id
;
2210 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2211 $issitecourse = false;
2213 // Load all categories and get the context for the system
2214 $coursecontext = get_context_instance(CONTEXT_SYSTEM
);
2215 $issitecourse = true;
2218 // Create a node to add user information under.
2219 if ($iscurrentuser && !$forceforcontext) {
2220 // If it's the current user the information will go under the profile root node
2221 $usernode = $this->rootnodes
['myprofile'];
2222 $course = get_site();
2223 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2224 $issitecourse = true;
2226 if (!$issitecourse) {
2227 // Not the current user so add it to the participants node for the current course
2228 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2229 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2231 // This is the site so add a users node to the root branch
2232 $usersnode = $this->rootnodes
['users'];
2233 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2234 $usersnode->action
= new moodle_url('/user/index.php', array('id'=>$course->id
));
2236 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2239 // We should NEVER get here, if the course hasn't been populated
2240 // with a participants node then the navigaiton either wasn't generated
2241 // for it (you are missing a require_login or set_context call) or
2242 // you don't have access.... in the interests of no leaking informatin
2243 // we simply quit...
2246 // Add a branch for the current user
2247 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2248 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, $user->id
);
2250 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2251 $usernode->make_active();
2255 // If the user is the current user or has permission to view the details of the requested
2256 // user than add a view profile link.
2257 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2258 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2259 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2261 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2265 if (!empty($CFG->navadduserpostslinks
)) {
2266 // Add nodes for forum posts and discussions if the user can view either or both
2267 // There are no capability checks here as the content of the page is based
2268 // purely on the forums the current user has access too.
2269 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2270 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2271 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2275 if (!empty($CFG->bloglevel
)) {
2276 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2277 require_once($CFG->dirroot
.'/blog/lib.php');
2278 // Get all options for the user
2279 $options = blog_get_options_for_user($user);
2280 $this->cache
->set('userblogoptions'.$user->id
, $options);
2282 $options = $this->cache
->{'userblogoptions'.$user->id
};
2285 if (count($options) > 0) {
2286 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2287 foreach ($options as $type => $option) {
2288 if ($type == "rss") {
2289 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
2291 $blogs->add($option['string'], $option['link']);
2297 if (!empty($CFG->messaging
)) {
2298 $messageargs = null;
2299 if ($USER->id
!=$user->id
) {
2300 $messageargs = array('id'=>$user->id
);
2302 $url = new moodle_url('/message/index.php',$messageargs);
2303 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2306 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
2307 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
2308 $url = new moodle_url('/user/files.php');
2309 $usernode->add(get_string('myfiles'), $url, self
::TYPE_SETTING
);
2312 // Add a node to view the users notes if permitted
2313 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2314 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
));
2315 if ($coursecontext->instanceid
) {
2316 $url->param('course', $coursecontext->instanceid
);
2318 $usernode->add(get_string('notes', 'notes'), $url);
2322 $reporttab = $usernode->add(get_string('activityreports'));
2323 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2324 foreach ($reports as $reportfunction) {
2325 $reportfunction($reporttab, $user, $course);
2327 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
2328 if ($anyreport ||
($course->showreports
&& $iscurrentuser && $forceforcontext)) {
2329 // Add grade hardcoded grade report if necessary
2330 $gradeaccess = false;
2331 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2332 //ok - can view all course grades
2333 $gradeaccess = true;
2334 } else if ($course->showgrades
) {
2335 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
2336 //ok - can view own grades
2337 $gradeaccess = true;
2338 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
2339 // ok - can view grades of this user - parent most probably
2340 $gradeaccess = true;
2341 } else if ($anyreport) {
2342 // ok - can view grades of this user - parent most probably
2343 $gradeaccess = true;
2347 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id
, 'user'=>$usercontext->instanceid
)));
2350 // Check the number of nodes in the report node... if there are none remove the node
2351 $reporttab->trim_if_empty();
2353 // If the user is the current user add the repositories for the current user
2354 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2355 if ($iscurrentuser) {
2356 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
2357 require_once($CFG->dirroot
. '/repository/lib.php');
2358 $editabletypes = repository
::get_editable_types($usercontext);
2359 $haseditabletypes = !empty($editabletypes);
2360 unset($editabletypes);
2361 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
2363 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
2365 if ($haseditabletypes) {
2366 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id
)));
2368 } else if ($course->id
== $SITE->id
&& has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2370 // Add view grade report is permitted
2371 $reports = get_plugin_list('gradereport');
2372 arsort($reports); // user is last, we want to test it first
2374 $userscourses = enrol_get_users_courses($user->id
);
2375 $userscoursesnode = $usernode->add(get_string('courses'));
2377 foreach ($userscourses as $usercourse) {
2378 $usercoursecontext = get_context_instance(CONTEXT_COURSE
, $usercourse->id
);
2379 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2380 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$usercourse->id
)), self
::TYPE_CONTAINER
);
2382 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2383 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2384 foreach ($reports as $plugin => $plugindir) {
2385 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2386 //stop when the first visible plugin is found
2387 $gradeavailable = true;
2393 if ($gradeavailable) {
2394 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id
));
2395 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/grades', ''));
2398 // Add a node to view the users notes if permitted
2399 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2400 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
, 'course'=>$usercourse->id
));
2401 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2404 if (can_access_course($usercourse, $user->id
)) {
2405 $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', ''));
2408 $reporttab = $usercoursenode->add(get_string('activityreports'));
2410 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2411 foreach ($reports as $reportfunction) {
2412 $reportfunction($reporttab, $user, $usercourse);
2415 $reporttab->trim_if_empty();
2422 * This method simply checks to see if a given module can extend the navigation.
2424 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2426 * @param string $modname
2429 protected static function module_extends_navigation($modname) {
2431 static $extendingmodules = array();
2432 if (!array_key_exists($modname, $extendingmodules)) {
2433 $extendingmodules[$modname] = false;
2434 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2435 if (file_exists($file)) {
2436 $function = $modname.'_extend_navigation';
2437 require_once($file);
2438 $extendingmodules[$modname] = (function_exists($function));
2441 return $extendingmodules[$modname];
2444 * Extends the navigation for the given user.
2446 * @param stdClass $user A user from the database
2448 public function extend_for_user($user) {
2449 $this->extendforuser
[] = $user;
2453 * Returns all of the users the navigation is being extended for
2455 * @return array An array of extending users.
2457 public function get_extending_users() {
2458 return $this->extendforuser
;
2461 * Adds the given course to the navigation structure.
2463 * @param stdClass $course
2464 * @param bool $forcegeneric
2465 * @param bool $ismycourse
2466 * @return navigation_node
2468 public function add_course(stdClass
$course, $forcegeneric = false, $ismycourse = false) {
2471 // We found the course... we can return it now :)
2472 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2473 return $this->addedcourses
[$course->id
];
2476 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2478 if ($course->id
!= $SITE->id
&& !$course->visible
) {
2479 if (is_role_switched($course->id
)) {
2480 // user has to be able to access course in order to switch, let's skip the visibility test here
2481 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2486 $issite = ($course->id
== $SITE->id
);
2487 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2492 if (empty($CFG->usesitenameforsitepages
)) {
2493 $shortname = get_string('sitepages');
2495 } else if ($ismycourse && !$forcegeneric) {
2496 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_CATEGORY
))) {
2497 // Nothing to do here the above statement set $parent to the category within mycourses.
2499 $parent = $this->rootnodes
['mycourses'];
2501 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2503 $parent = $this->rootnodes
['courses'];
2504 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2505 if (!empty($course->category
) && $this->show_categories()) {
2506 if ($this->show_categories() && !$this->is_category_fully_loaded($course->category
)) {
2507 // We need to load the category structure for this course
2508 $this->load_all_categories($course->category
, false);
2510 if (array_key_exists($course->category
, $this->addedcategories
)) {
2511 $parent = $this->addedcategories
[$course->category
];
2512 // This could lead to the course being created so we should check whether it is the case again
2513 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2514 return $this->addedcourses
[$course->id
];
2520 $coursenode = $parent->add($shortname, $url, self
::TYPE_COURSE
, $shortname, $course->id
);
2521 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2522 $coursenode->hidden
= (!$course->visible
);
2523 $coursenode->title(format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
))));
2524 if (!$forcegeneric) {
2525 $this->addedcourses
[$course->id
] = $coursenode;
2532 * Returns true if the category has already been loaded as have any child categories
2534 * @param int $categoryid
2537 protected function is_category_fully_loaded($categoryid) {
2538 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2542 * Adds essential course nodes to the navigation for the given course.
2544 * This method adds nodes such as reports, blogs and participants
2546 * @param navigation_node $coursenode
2547 * @param stdClass $course
2548 * @return bool returns true on successful addition of a node.
2550 public function add_course_essentials($coursenode, stdClass
$course) {
2553 if ($course->id
== $SITE->id
) {
2554 return $this->add_front_page_course_essentials($coursenode, $course);
2557 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2562 if (has_capability('moodle/course:viewparticipants', $this->page
->context
)) {
2563 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2564 $currentgroup = groups_get_course_group($course, true);
2565 if ($course->id
== $SITE->id
) {
2567 } else if ($course->id
&& !$currentgroup) {
2568 $filterselect = $course->id
;
2570 $filterselect = $currentgroup;
2572 $filterselect = clean_param($filterselect, PARAM_INT
);
2573 if (($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2574 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2575 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2576 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2578 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2579 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id
)));
2581 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2582 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2585 // View course reports
2586 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2587 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2588 $coursereports = get_plugin_list('coursereport'); // deprecated
2589 foreach ($coursereports as $report=>$dir) {
2590 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2591 if (file_exists($libfile)) {
2592 require_once($libfile);
2593 $reportfunction = $report.'_report_extend_navigation';
2594 if (function_exists($report.'_report_extend_navigation')) {
2595 $reportfunction($reportnav, $course, $this->page
->context
);
2600 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2601 foreach ($reports as $reportfunction) {
2602 $reportfunction($reportnav, $course, $this->page
->context
);
2608 * This generates the structure of the course that won't be generated when
2609 * the modules and sections are added.
2611 * Things such as the reports branch, the participants branch, blogs... get
2612 * added to the course node by this method.
2614 * @param navigation_node $coursenode
2615 * @param stdClass $course
2616 * @return bool True for successfull generation
2618 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2621 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2625 // Hidden node that we use to determine if the front page navigation is loaded.
2626 // This required as there are not other guaranteed nodes that may be loaded.
2627 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2630 if (has_capability('moodle/course:viewparticipants', get_system_context())) {
2631 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
2637 if (!empty($CFG->bloglevel
)
2638 and ($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
or ($CFG->bloglevel
== BLOG_SITE_LEVEL
and (isloggedin() and !isguestuser())))
2639 and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM
))) {
2640 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2641 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2645 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
2646 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2650 if (!empty($CFG->usetags
) && isloggedin()) {
2651 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2656 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2657 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self
::TYPE_CUSTOM
, null, 'calendar');
2660 // View course reports
2661 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2662 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2663 $coursereports = get_plugin_list('coursereport'); // deprecated
2664 foreach ($coursereports as $report=>$dir) {
2665 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2666 if (file_exists($libfile)) {
2667 require_once($libfile);
2668 $reportfunction = $report.'_report_extend_navigation';
2669 if (function_exists($report.'_report_extend_navigation')) {
2670 $reportfunction($reportnav, $course, $this->page
->context
);
2675 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2676 foreach ($reports as $reportfunction) {
2677 $reportfunction($reportnav, $course, $this->page
->context
);
2684 * Clears the navigation cache
2686 public function clear_cache() {
2687 $this->cache
->clear();
2691 * Sets an expansion limit for the navigation
2693 * The expansion limit is used to prevent the display of content that has a type
2694 * greater than the provided $type.
2696 * Can be used to ensure things such as activities or activity content don't get
2697 * shown on the navigation.
2698 * They are still generated in order to ensure the navbar still makes sense.
2700 * @param int $type One of navigation_node::TYPE_*
2701 * @return bool true when complete.
2703 public function set_expansion_limit($type) {
2705 $nodes = $this->find_all_of_type($type);
2706 foreach ($nodes as &$node) {
2707 // We need to generate the full site node
2708 if ($type == self
::TYPE_COURSE
&& $node->key
== $SITE->id
) {
2711 foreach ($node->children
as &$child) {
2712 // We still want to show course reports and participants containers
2713 // or there will be navigation missing.
2714 if ($type == self
::TYPE_COURSE
&& $child->type
=== self
::TYPE_CONTAINER
) {
2717 $child->display
= false;
2723 * Attempts to get the navigation with the given key from this nodes children.
2725 * This function only looks at this nodes children, it does NOT look recursivily.
2726 * If the node can't be found then false is returned.
2728 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2730 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2731 * may be of more use to you.
2733 * @param string|int $key The key of the node you wish to receive.
2734 * @param int $type One of navigation_node::TYPE_*
2735 * @return navigation_node|false
2737 public function get($key, $type = null) {
2738 if (!$this->initialised
) {
2739 $this->initialise();
2741 return parent
::get($key, $type);
2745 * Searches this nodes children and their children to find a navigation node
2746 * with the matching key and type.
2748 * This method is recursive and searches children so until either a node is
2749 * found or there are no more nodes to search.
2751 * If you know that the node being searched for is a child of this node
2752 * then use the {@link global_navigation::get()} method instead.
2754 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2755 * may be of more use to you.
2757 * @param string|int $key The key of the node you wish to receive.
2758 * @param int $type One of navigation_node::TYPE_*
2759 * @return navigation_node|false
2761 public function find($key, $type) {
2762 if (!$this->initialised
) {
2763 $this->initialise();
2765 return parent
::find($key, $type);
2770 * The global navigation class used especially for AJAX requests.
2772 * The primary methods that are used in the global navigation class have been overriden
2773 * to ensure that only the relevant branch is generated at the root of the tree.
2774 * This can be done because AJAX is only used when the backwards structure for the
2775 * requested branch exists.
2776 * This has been done only because it shortens the amounts of information that is generated
2777 * which of course will speed up the response time.. because no one likes laggy AJAX.
2780 * @category navigation
2781 * @copyright 2009 Sam Hemelryk
2782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2784 class global_navigation_for_ajax
extends global_navigation
{
2786 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2787 protected $branchtype;
2789 /** @var int the instance id */
2790 protected $instanceid;
2792 /** @var array Holds an array of expandable nodes */
2793 protected $expandable = array();
2796 * Constructs the navigation for use in an AJAX request
2798 * @param moodle_page $page moodle_page object
2799 * @param int $branchtype
2802 public function __construct($page, $branchtype, $id) {
2803 $this->page
= $page;
2804 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2805 $this->children
= new navigation_node_collection();
2806 $this->branchtype
= $branchtype;
2807 $this->instanceid
= $id;
2808 $this->initialise();
2811 * Initialise the navigation given the type and id for the branch to expand.
2813 * @return array An array of the expandable nodes
2815 public function initialise() {
2816 global $CFG, $DB, $SITE;
2818 if ($this->initialised ||
during_initial_install()) {
2819 return $this->expandable
;
2821 $this->initialised
= true;
2823 $this->rootnodes
= array();
2824 $this->rootnodes
['site'] = $this->add_course($SITE);
2825 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
2827 // Branchtype will be one of navigation_node::TYPE_*
2828 switch ($this->branchtype
) {
2829 case self
::TYPE_CATEGORY
:
2830 $this->load_category($this->instanceid
);
2832 case self
::TYPE_COURSE
:
2833 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
2834 require_course_login($course, true, null, false, true);
2835 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2836 $coursenode = $this->add_course($course);
2837 $this->add_course_essentials($coursenode, $course);
2838 if ($this->format_display_course_content($course->format
)) {
2839 $this->load_course_sections($course, $coursenode);
2842 case self
::TYPE_SECTION
:
2843 $sql = 'SELECT c.*, cs.section AS sectionnumber
2845 LEFT JOIN {course_sections} cs ON cs.course = c.id
2847 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
2848 require_course_login($course, true, null, false, true);
2849 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2850 $coursenode = $this->add_course($course);
2851 $this->add_course_essentials($coursenode, $course);
2852 $sections = $this->load_course_sections($course, $coursenode);
2853 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2854 $this->load_section_activities($sections[$course->sectionnumber
]->sectionnode
, $course->sectionnumber
, $activities);
2856 case self
::TYPE_ACTIVITY
:
2859 JOIN {course_modules} cm ON cm.course = c.id
2860 WHERE cm.id = :cmid";
2861 $params = array('cmid' => $this->instanceid
);
2862 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
2863 $modinfo = get_fast_modinfo($course);
2864 $cm = $modinfo->get_cm($this->instanceid
);
2865 require_course_login($course, true, $cm, false, true);
2866 $this->page
->set_context(get_context_instance(CONTEXT_MODULE
, $cm->id
));
2867 $coursenode = $this->load_course($course);
2868 if ($course->id
== $SITE->id
) {
2869 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
));
2871 $sections = $this->load_course_sections($course, $coursenode);
2872 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2873 $activities = $this->load_section_activities($sections[$cm->sectionnum
]->sectionnode
, $cm->sectionnum
, $activities);
2874 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id
]);
2878 throw new Exception('Unknown type');
2879 return $this->expandable
;
2882 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
) {
2883 $this->load_for_user(null, true);
2886 $this->find_expandable($this->expandable
);
2887 return $this->expandable
;
2891 * Loads a single category into the AJAX navigation.
2893 * This function is special in that it doesn't concern itself with the parent of
2894 * the requested category or its siblings.
2895 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2898 * @global moodle_database $DB
2899 * @param int $categoryid
2901 protected function load_category($categoryid) {
2905 if (!empty($CFG->navcourselimit
)) {
2906 $limit = (int)$CFG->navcourselimit
;
2909 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
2910 $sql = "SELECT cc.*, $catcontextsql
2911 FROM {course_categories} cc
2912 JOIN {context} ctx ON cc.id = ctx.instanceid
2913 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
2914 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2915 ORDER BY depth ASC, sortorder ASC, id ASC";
2916 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2917 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2918 $subcategories = array();
2919 $basecategory = null;
2920 foreach ($categories as $category) {
2921 context_helper
::preload_from_record($category);
2922 if ($category->id
== $categoryid) {
2923 $this->add_category($category, $this);
2924 $basecategory = $this->addedcategories
[$category->id
];
2926 $subcategories[] = $category;
2929 $categories->close();
2931 if (!is_null($basecategory)) {
2932 //echo "<pre>".print_r($subcategories, true).'</pre>';
2933 foreach ($subcategories as $category) {
2934 $this->add_category($category, $basecategory);
2938 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2939 foreach ($courses as $course) {
2940 $this->add_course($course);
2946 * Returns an array of expandable nodes
2949 public function get_expandable() {
2950 return $this->expandable
;
2957 * This class is used to manage the navbar, which is initialised from the navigation
2958 * object held by PAGE
2961 * @category navigation
2962 * @copyright 2009 Sam Hemelryk
2963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2965 class navbar
extends navigation_node
{
2966 /** @var bool A switch for whether the navbar is initialised or not */
2967 protected $initialised = false;
2968 /** @var mixed keys used to reference the nodes on the navbar */
2969 protected $keys = array();
2970 /** @var null|string content of the navbar */
2971 protected $content = null;
2972 /** @var moodle_page object the moodle page that this navbar belongs to */
2974 /** @var bool A switch for whether to ignore the active navigation information */
2975 protected $ignoreactive = false;
2976 /** @var bool A switch to let us know if we are in the middle of an install */
2977 protected $duringinstall = false;
2978 /** @var bool A switch for whether the navbar has items */
2979 protected $hasitems = false;
2980 /** @var array An array of navigation nodes for the navbar */
2982 /** @var array An array of child node objects */
2983 public $children = array();
2984 /** @var bool A switch for whether we want to include the root node in the navbar */
2985 public $includesettingsbase = false;
2987 * The almighty constructor
2989 * @param moodle_page $page
2991 public function __construct(moodle_page
$page) {
2993 if (during_initial_install()) {
2994 $this->duringinstall
= true;
2997 $this->page
= $page;
2998 $this->text
= get_string('home');
2999 $this->shorttext
= get_string('home');
3000 $this->action
= new moodle_url($CFG->wwwroot
);
3001 $this->nodetype
= self
::NODETYPE_BRANCH
;
3002 $this->type
= self
::TYPE_SYSTEM
;
3006 * Quick check to see if the navbar will have items in.
3008 * @return bool Returns true if the navbar will have items, false otherwise
3010 public function has_items() {
3011 if ($this->duringinstall
) {
3013 } else if ($this->hasitems
!== false) {
3016 $this->page
->navigation
->initialise($this->page
);
3018 $activenodefound = ($this->page
->navigation
->contains_active_node() ||
3019 $this->page
->settingsnav
->contains_active_node());
3021 $outcome = (count($this->children
)>0 ||
(!$this->ignoreactive
&& $activenodefound));
3022 $this->hasitems
= $outcome;
3027 * Turn on/off ignore active
3029 * @param bool $setting
3031 public function ignore_active($setting=true) {
3032 $this->ignoreactive
= ($setting);
3036 * Gets a navigation node
3038 * @param string|int $key for referencing the navbar nodes
3039 * @param int $type navigation_node::TYPE_*
3040 * @return navigation_node|bool
3042 public function get($key, $type = null) {
3043 foreach ($this->children
as &$child) {
3044 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3051 * Returns an array of navigation_node's that make up the navbar.
3055 public function get_items() {
3057 // Make sure that navigation is initialised
3058 if (!$this->has_items()) {
3061 if ($this->items
!== null) {
3062 return $this->items
;
3065 if (count($this->children
) > 0) {
3066 // Add the custom children
3067 $items = array_reverse($this->children
);
3070 $navigationactivenode = $this->page
->navigation
->find_active_node();
3071 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3073 // Check if navigation contains the active node
3074 if (!$this->ignoreactive
) {
3076 if ($navigationactivenode && $settingsactivenode) {
3077 // Parse a combined navigation tree
3078 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3079 if (!$settingsactivenode->mainnavonly
) {
3080 $items[] = $settingsactivenode;
3082 $settingsactivenode = $settingsactivenode->parent
;
3084 if (!$this->includesettingsbase
) {
3085 // Removes the first node from the settings (root node) from the list
3088 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3089 if (!$navigationactivenode->mainnavonly
) {
3090 $items[] = $navigationactivenode;
3092 $navigationactivenode = $navigationactivenode->parent
;
3094 } else if ($navigationactivenode) {
3095 // Parse the navigation tree to get the active node
3096 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3097 if (!$navigationactivenode->mainnavonly
) {
3098 $items[] = $navigationactivenode;
3100 $navigationactivenode = $navigationactivenode->parent
;
3102 } else if ($settingsactivenode) {
3103 // Parse the settings navigation to get the active node
3104 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3105 if (!$settingsactivenode->mainnavonly
) {
3106 $items[] = $settingsactivenode;
3108 $settingsactivenode = $settingsactivenode->parent
;
3113 $items[] = new navigation_node(array(
3114 'text'=>$this->page
->navigation
->text
,
3115 'shorttext'=>$this->page
->navigation
->shorttext
,
3116 'key'=>$this->page
->navigation
->key
,
3117 'action'=>$this->page
->navigation
->action
3120 $this->items
= array_reverse($items);
3121 return $this->items
;
3125 * Add a new navigation_node to the navbar, overrides parent::add
3127 * This function overrides {@link navigation_node::add()} so that we can change
3128 * the way nodes get added to allow us to simply call add and have the node added to the
3131 * @param string $text
3132 * @param string|moodle_url|action_link $action An action to associate with this node.
3133 * @param int $type One of navigation_node::TYPE_*
3134 * @param string $shorttext
3135 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3136 * @param pix_icon $icon An optional icon to use for this node.
3137 * @return navigation_node
3139 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3140 if ($this->content
!== null) {
3141 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3144 // Properties array used when creating the new navigation node
3149 // Set the action if one was provided
3150 if ($action!==null) {
3151 $itemarray['action'] = $action;
3153 // Set the shorttext if one was provided
3154 if ($shorttext!==null) {
3155 $itemarray['shorttext'] = $shorttext;
3157 // Set the icon if one was provided
3159 $itemarray['icon'] = $icon;
3161 // Default the key to the number of children if not provided
3162 if ($key === null) {
3163 $key = count($this->children
);
3166 $itemarray['key'] = $key;
3167 // Set the parent to this node
3168 $itemarray['parent'] = $this;
3169 // Add the child using the navigation_node_collections add method
3170 $this->children
[] = new navigation_node($itemarray);
3176 * Class used to manage the settings option for the current page
3178 * This class is used to manage the settings options in a tree format (recursively)
3179 * and was created initially for use with the settings blocks.
3182 * @category navigation
3183 * @copyright 2009 Sam Hemelryk
3184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3186 class settings_navigation
extends navigation_node
{
3187 /** @var stdClass the current context */
3189 /** @var moodle_page the moodle page that the navigation belongs to */
3191 /** @var string contains administration section navigation_nodes */
3192 protected $adminsection;
3193 /** @var bool A switch to see if the navigation node is initialised */
3194 protected $initialised = false;
3195 /** @var array An array of users that the nodes can extend for. */
3196 protected $userstoextendfor = array();
3197 /** @var navigation_cache **/
3201 * Sets up the object with basic settings and preparse it for use
3203 * @param moodle_page $page
3205 public function __construct(moodle_page
&$page) {
3206 if (during_initial_install()) {
3209 $this->page
= $page;
3210 // Initialise the main navigation. It is most important that this is done
3211 // before we try anything
3212 $this->page
->navigation
->initialise();
3213 // Initialise the navigation cache
3214 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3215 $this->children
= new navigation_node_collection();
3218 * Initialise the settings navigation based on the current context
3220 * This function initialises the settings navigation tree for a given context
3221 * by calling supporting functions to generate major parts of the tree.
3224 public function initialise() {
3225 global $DB, $SESSION, $SITE;
3227 if (during_initial_install()) {
3229 } else if ($this->initialised
) {
3232 $this->id
= 'settingsnav';
3233 $this->context
= $this->page
->context
;
3235 $context = $this->context
;
3236 if ($context->contextlevel
== CONTEXT_BLOCK
) {
3237 $this->load_block_settings();
3238 $context = $context->get_parent_context();
3241 switch ($context->contextlevel
) {
3242 case CONTEXT_SYSTEM
:
3243 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3244 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3247 case CONTEXT_COURSECAT
:
3248 $this->load_category_settings();
3250 case CONTEXT_COURSE
:
3251 if ($this->page
->course
->id
!= $SITE->id
) {
3252 $this->load_course_settings(($context->id
== $this->context
->id
));
3254 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3257 case CONTEXT_MODULE
:
3258 $this->load_module_settings();
3259 $this->load_course_settings();
3262 if ($this->page
->course
->id
!= $SITE->id
) {
3263 $this->load_course_settings();
3268 $settings = $this->load_user_settings($this->page
->course
->id
);
3270 if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') ||
$SESSION->load_navigation_admin
)) {
3271 $admin = $this->load_administration_settings();
3272 $SESSION->load_navigation_admin
= ($admin->has_children());
3277 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $admin) {
3278 $admin->force_open();
3279 } else if ($context->contextlevel
== CONTEXT_USER
&& $settings) {
3280 $settings->force_open();
3283 // Check if the user is currently logged in as another user
3284 if (session_is_loggedinas()) {
3285 // Get the actual user, we need this so we can display an informative return link
3286 $realuser = session_get_realuser();
3287 // Add the informative return to original user link
3288 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page
->course
->id
, 'return'=>1,'sesskey'=>sesskey()));
3289 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self
::TYPE_SETTING
, null, null, new pix_icon('t/left', ''));
3292 foreach ($this->children
as $key=>$node) {
3293 if ($node->nodetype
!= self
::NODETYPE_BRANCH ||
$node->children
->count()===0) {
3297 $this->initialised
= true;
3300 * Override the parent function so that we can add preceeding hr's and set a
3301 * root node class against all first level element
3303 * It does this by first calling the parent's add method {@link navigation_node::add()}
3304 * and then proceeds to use the key to set class and hr
3306 * @param string $text text to be used for the link.
3307 * @param string|moodle_url $url url for the new node
3308 * @param int $type the type of node navigation_node::TYPE_*
3309 * @param string $shorttext
3310 * @param string|int $key a key to access the node by.
3311 * @param pix_icon $icon An icon that appears next to the node.
3312 * @return navigation_node with the new node added to it.
3314 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
3315 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
3316 $node->add_class('root_node');
3321 * This function allows the user to add something to the start of the settings
3322 * navigation, which means it will be at the top of the settings navigation block
3324 * @param string $text text to be used for the link.
3325 * @param string|moodle_url $url url for the new node
3326 * @param int $type the type of node navigation_node::TYPE_*
3327 * @param string $shorttext
3328 * @param string|int $key a key to access the node by.
3329 * @param pix_icon $icon An icon that appears next to the node.
3330 * @return navigation_node $node with the new node added to it.
3332 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
3333 $children = $this->children
;
3334 $childrenclass = get_class($children);
3335 $this->children
= new $childrenclass;
3336 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3337 foreach ($children as $child) {
3338 $this->children
->add($child);
3343 * Load the site administration tree
3345 * This function loads the site administration tree by using the lib/adminlib library functions
3347 * @param navigation_node $referencebranch A reference to a branch in the settings
3349 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3350 * tree and start at the beginning
3351 * @return mixed A key to access the admin tree by
3353 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
3356 // Check if we are just starting to generate this navigation.
3357 if ($referencebranch === null) {
3359 // Require the admin lib then get an admin structure
3360 if (!function_exists('admin_get_root')) {
3361 require_once($CFG->dirroot
.'/lib/adminlib.php');
3363 $adminroot = admin_get_root(false, false);
3364 // This is the active section identifier
3365 $this->adminsection
= $this->page
->url
->param('section');
3367 // Disable the navigation from automatically finding the active node
3368 navigation_node
::$autofindactive = false;
3369 $referencebranch = $this->add(get_string('administrationsite'), null, self
::TYPE_SETTING
, null, 'root');
3370 foreach ($adminroot->children
as $adminbranch) {
3371 $this->load_administration_settings($referencebranch, $adminbranch);
3373 navigation_node
::$autofindactive = true;
3375 // Use the admin structure to locate the active page
3376 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
3377 $currentnode = $this;
3378 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
3379 $currentnode = $currentnode->get($pathkey);
3382 $currentnode->make_active();
3385 $this->scan_for_active_node($referencebranch);
3387 return $referencebranch;
3388 } else if ($adminbranch->check_access()) {
3389 // We have a reference branch that we can access and is not hidden `hurrah`
3390 // Now we need to display it and any children it may have
3393 if ($adminbranch instanceof admin_settingpage
) {
3394 $url = new moodle_url('/'.$CFG->admin
.'/settings.php', array('section'=>$adminbranch->name
));
3395 } else if ($adminbranch instanceof admin_externalpage
) {
3396 $url = $adminbranch->url
;
3397 } else if (!empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
3398 $url = new moodle_url('/'.$CFG->admin
.'/category.php', array('category' => $adminbranch->name
));
3402 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
3404 if ($adminbranch->is_hidden()) {
3405 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
3406 $reference->add_class('hidden');
3408 $reference->display
= false;
3412 // Check if we are generating the admin notifications and whether notificiations exist
3413 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
3414 $reference->add_class('criticalnotification');
3416 // Check if this branch has children
3417 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
3418 foreach ($adminbranch->children
as $branch) {
3419 // Generate the child branches as well now using this branch as the reference
3420 $this->load_administration_settings($reference, $branch);
3423 $reference->icon
= new pix_icon('i/settings', '');
3429 * This function recursivily scans nodes until it finds the active node or there
3430 * are no more nodes.
3431 * @param navigation_node $node
3433 protected function scan_for_active_node(navigation_node
$node) {
3434 if (!$node->check_if_active() && $node->children
->count()>0) {
3435 foreach ($node->children
as &$child) {
3436 $this->scan_for_active_node($child);
3442 * Gets a navigation node given an array of keys that represent the path to
3445 * @param array $path
3446 * @return navigation_node|false
3448 protected function get_by_path(array $path) {
3449 $node = $this->get(array_shift($path));
3450 foreach ($path as $key) {
3457 * Generate the list of modules for the given course.
3459 * @param stdClass $course The course to get modules for
3461 protected function get_course_modules($course) {
3463 $mods = $modnames = $modnamesplural = $modnamesused = array();
3464 // This function is included when we include course/lib.php at the top
3466 get_all_mods($course->id
, $mods, $modnames, $modnamesplural, $modnamesused);
3467 $resources = array();
3468 $activities = array();
3469 foreach($modnames as $modname=>$modnamestr) {
3470 if (!course_allowed_module($course, $modname)) {
3474 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3475 if (!file_exists($libfile)) {
3478 include_once($libfile);
3479 $gettypesfunc = $modname.'_get_types';
3480 if (function_exists($gettypesfunc)) {
3481 $types = $gettypesfunc();
3482 foreach($types as $type) {
3483 if (!isset($type->modclass
) ||
!isset($type->typestr
)) {
3484 debugging('Incorrect activity type in '.$modname);
3487 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
3488 $resources[html_entity_decode($type->type
)] = $type->typestr
;
3490 $activities[html_entity_decode($type->type
)] = $type->typestr
;
3494 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
3495 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
3496 $resources[$modname] = $modnamestr;
3498 // all other archetypes are considered activity
3499 $activities[$modname] = $modnamestr;
3503 return array($resources, $activities);
3507 * This function loads the course settings that are available for the user
3509 * @param bool $forceopen If set to true the course node will be forced open
3510 * @return navigation_node|false
3512 protected function load_course_settings($forceopen = false) {
3515 $course = $this->page
->course
;
3516 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
3518 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3520 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
3522 $coursenode->force_open();
3525 if (has_capability('moodle/course:update', $coursecontext)) {
3526 // Add the turn on/off settings
3528 if ($this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
3529 // We are on the course page, retain the current page params e.g. section.
3530 $url = clone($this->page
->url
);
3531 $url->param('sesskey', sesskey());
3533 // Edit on the main course page.
3534 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
3536 if ($this->page
->user_is_editing()) {
3537 $url->param('edit', 'off');
3538 $editstring = get_string('turneditingoff');
3540 $url->param('edit', 'on');
3541 $editstring = get_string('turneditingon');
3543 $coursenode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3545 if ($this->page
->user_is_editing()) {
3546 // Removed as per MDL-22732
3547 // $this->add_course_editing_links($course);
3550 // Add the course settings link
3551 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
3552 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3554 // Add the course completion settings link
3555 if ($CFG->enablecompletion
&& $course->enablecompletion
) {
3556 $url = new moodle_url('/course/completion.php', array('id'=>$course->id
));
3557 $coursenode->add(get_string('completion', 'completion'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3562 enrol_add_course_navigation($coursenode, $course);
3565 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3566 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
3567 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
3570 // Add view grade report is permitted
3571 $reportavailable = false;
3572 if (has_capability('moodle/grade:viewall', $coursecontext)) {
3573 $reportavailable = true;
3574 } else if (!empty($course->showgrades
)) {
3575 $reports = get_plugin_list('gradereport');
3576 if (is_array($reports) && count($reports)>0) { // Get all installed reports
3577 arsort($reports); // user is last, we want to test it first
3578 foreach ($reports as $plugin => $plugindir) {
3579 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3580 //stop when the first visible plugin is found
3581 $reportavailable = true;
3587 if ($reportavailable) {
3588 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
3589 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, 'grades', new pix_icon('i/grades', ''));
3592 // Add outcome if permitted
3593 if (!empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $coursecontext)) {
3594 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
3595 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
3598 // Backup this course
3599 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3600 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
3601 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
3604 // Restore to this course
3605 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3606 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
3607 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
3610 // Import data from other courses
3611 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3612 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
3613 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/restore', ''));
3616 // Publish course on a hub
3617 if (has_capability('moodle/course:publish', $coursecontext)) {
3618 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
3619 $coursenode->add(get_string('publish'), $url, self
::TYPE_SETTING
, null, 'publish', new pix_icon('i/publish', ''));
3622 // Reset this course
3623 if (has_capability('moodle/course:reset', $coursecontext)) {
3624 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
3625 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/return', ''));
3629 require_once($CFG->libdir
. '/questionlib.php');
3630 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3632 if (has_capability('moodle/course:update', $coursecontext)) {
3633 // Repository Instances
3634 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
3635 require_once($CFG->dirroot
. '/repository/lib.php');
3636 $editabletypes = repository
::get_editable_types($coursecontext);
3637 $haseditabletypes = !empty($editabletypes);
3638 unset($editabletypes);
3639 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
3641 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
3643 if ($haseditabletypes) {
3644 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
3645 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
3650 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3651 // hidden in new courses and courses where legacy files were turned off
3652 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
3653 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/files', ''));
3659 $assumedrole = $this->in_alternative_role();
3660 if ($assumedrole !== false) {
3661 $roles[0] = get_string('switchrolereturn');
3663 if (has_capability('moodle/role:switchroles', $coursecontext)) {
3664 $availableroles = get_switchable_roles($coursecontext);
3665 if (is_array($availableroles)) {
3666 foreach ($availableroles as $key=>$role) {
3667 if ($assumedrole == (int)$key) {
3670 $roles[$key] = $role;
3674 if (is_array($roles) && count($roles)>0) {
3675 $switchroles = $this->add(get_string('switchroleto'));
3676 if ((count($roles)==1 && array_key_exists(0, $roles))||
$assumedrole!==false) {
3677 $switchroles->force_open();
3679 $returnurl = $this->page
->url
;
3680 $returnurl->param('sesskey', sesskey());
3681 foreach ($roles as $key => $name) {
3682 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3683 $switchroles->add($name, $url, self
::TYPE_SETTING
, null, $key, new pix_icon('i/roles', ''));
3686 // Return we are done
3691 * Adds branches and links to the settings navigation to add course activities
3694 * @param stdClass $course
3696 protected function add_course_editing_links($course) {
3699 require_once($CFG->dirroot
.'/course/lib.php');
3701 // Add `add` resources|activities branches
3702 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3703 if (file_exists($structurefile)) {
3704 require_once($structurefile);
3705 $requestkey = call_user_func('callback_'.$course->format
.'_request_key');
3706 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3708 $requestkey = get_string('section');
3709 $formatidentifier = optional_param($requestkey, 0, PARAM_INT
);
3712 $sections = get_all_sections($course->id
);
3714 $addresource = $this->add(get_string('addresource'));
3715 $addactivity = $this->add(get_string('addactivity'));
3716 if ($formatidentifier!==0) {
3717 $addresource->force_open();
3718 $addactivity->force_open();
3721 $this->get_course_modules($course);
3723 foreach ($sections as $section) {
3724 if ($formatidentifier !== 0 && $section->section
!= $formatidentifier) {
3727 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id
, $requestkey=>$section->section
));
3728 if ($section->section
== 0) {
3729 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3730 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
3732 $sectionname = get_section_name($course, $section);
3733 $sectionresources = $addresource->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3734 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self
::TYPE_SETTING
);
3736 foreach ($resources as $value=>$resource) {
3737 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3738 $pos = strpos($value, '&type=');
3740 $url->param('add', textlib
::substr($value, 0,$pos));
3741 $url->param('type', textlib
::substr($value, $pos+
6));
3743 $url->param('add', $value);
3745 $sectionresources->add($resource, $url, self
::TYPE_SETTING
);
3748 foreach ($activities as $activityname=>$activity) {
3749 if ($activity==='--') {
3753 if (strpos($activity, '--')===0) {
3754 $subbranch = $sectionactivities->add(trim($activity, '-'));
3757 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3758 $pos = strpos($activityname, '&type=');
3760 $url->param('add', textlib
::substr($activityname, 0,$pos));
3761 $url->param('type', textlib
::substr($activityname, $pos+
6));
3763 $url->param('add', $activityname);
3765 if ($subbranch !== false) {
3766 $subbranch->add($activity, $url, self
::TYPE_SETTING
);
3768 $sectionactivities->add($activity, $url, self
::TYPE_SETTING
);
3775 * This function calls the module function to inject module settings into the
3776 * settings navigation tree.
3778 * This only gets called if there is a corrosponding function in the modules
3781 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
3783 * @return navigation_node|false
3785 protected function load_module_settings() {
3788 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
3789 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
3790 $this->page
->set_cm($cm, $this->page
->course
);
3793 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
3794 if (file_exists($file)) {
3795 require_once($file);
3798 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
));
3799 $modulenode->force_open();
3801 // Settings for the module
3802 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
3803 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => true, 'sesskey' => sesskey()));
3804 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
3806 // Assign local roles
3807 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
3808 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
3809 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
3812 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
3813 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
3814 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
3816 // Check role permissions
3817 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
3818 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
3819 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
3822 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
3823 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
3824 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
3827 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3828 foreach ($reports as $reportfunction) {
3829 $reportfunction($modulenode, $this->page
->cm
);
3831 // Add a backup link
3832 $featuresfunc = $this->page
->activityname
.'_supports';
3833 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
3834 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
3835 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
3838 // Restore this activity
3839 $featuresfunc = $this->page
->activityname
.'_supports';
3840 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
3841 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
3842 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
3845 // Allow the active advanced grading method plugin to append its settings
3846 $featuresfunc = $this->page
->activityname
.'_supports';
3847 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
3848 require_once($CFG->dirroot
.'/grade/grading/lib.php');
3849 $gradingman = get_grading_manager($this->page
->cm
->context
, $this->page
->activityname
);
3850 $gradingman->extend_settings_navigation($this, $modulenode);
3853 $function = $this->page
->activityname
.'_extend_settings_navigation';
3854 if (!function_exists($function)) {
3858 $function($this, $modulenode);
3860 // Remove the module node if there are no children
3861 if (empty($modulenode->children
)) {
3862 $modulenode->remove();
3869 * Loads the user settings block of the settings nav
3871 * This function is simply works out the userid and whether we need to load
3872 * just the current users profile settings, or the current user and the user the
3873 * current user is viewing.
3875 * This function has some very ugly code to work out the user, if anyone has
3876 * any bright ideas please feel free to intervene.
3878 * @param int $courseid The course id of the current course
3879 * @return navigation_node|false
3881 protected function load_user_settings($courseid = SITEID
) {
3884 if (isguestuser() ||
!isloggedin()) {
3888 $navusers = $this->page
->navigation
->get_extending_users();
3890 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
3892 foreach ($this->userstoextendfor
as $userid) {
3893 if ($userid == $USER->id
) {
3896 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3897 if (is_null($usernode)) {
3901 foreach ($navusers as $user) {
3902 if ($user->id
== $USER->id
) {
3905 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
3906 if (is_null($usernode)) {
3910 $this->generate_user_settings($courseid, $USER->id
);
3912 $usernode = $this->generate_user_settings($courseid, $USER->id
);
3918 * Extends the settings navigation for the given user.
3920 * Note: This method gets called automatically if you call
3921 * $PAGE->navigation->extend_for_user($userid)
3923 * @param int $userid
3925 public function extend_for_user($userid) {
3928 if (!in_array($userid, $this->userstoextendfor
)) {
3929 $this->userstoextendfor
[] = $userid;
3930 if ($this->initialised
) {
3931 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
3932 $children = array();
3933 foreach ($this->children
as $child) {
3934 $children[] = $child;
3936 array_unshift($children, array_pop($children));
3937 $this->children
= new navigation_node_collection();
3938 foreach ($children as $child) {
3939 $this->children
->add($child);
3946 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
3947 * what can be shown/done
3949 * @param int $courseid The current course' id
3950 * @param int $userid The user id to load for
3951 * @param string $gstitle The string to pass to get_string for the branch title
3952 * @return navigation_node|false
3954 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3955 global $DB, $CFG, $USER, $SITE;
3957 if ($courseid != $SITE->id
) {
3958 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
3959 $course = $this->page
->course
;
3961 $select = context_helper
::get_preload_record_columns_sql('ctx');
3962 $sql = "SELECT c.*, $select
3964 JOIN {context} ctx ON c.id = ctx.instanceid
3965 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
3966 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
3967 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3968 context_helper
::preload_from_record($course);
3974 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3975 $systemcontext = get_system_context();
3976 $currentuser = ($USER->id
== $userid);
3980 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3982 $select = context_helper
::get_preload_record_columns_sql('ctx');
3983 $sql = "SELECT u.*, $select
3985 JOIN {context} ctx ON u.id = ctx.instanceid
3986 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
3987 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
3988 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
3992 context_helper
::preload_from_record($user);
3994 // Check that the user can view the profile
3995 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3996 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3998 if ($course->id
== $SITE->id
) {
3999 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4000 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4004 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4005 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4006 if ((!$canviewusercourse && !$canviewuser) ||
!can_access_course($course, $user->id
)) {
4009 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
) {
4010 // If groups are in use, make sure we can see that group
4016 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
4019 if ($gstitle != 'usercurrentsettings') {
4023 // Add a user setting branch
4024 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self
::TYPE_CONTAINER
, null, $key);
4025 $usersetting->id
= 'usersettings';
4026 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $this->page
->context
->instanceid
== $user->id
) {
4027 // Automatically start by making it active
4028 $usersetting->make_active();
4031 // Check if the user has been deleted
4032 if ($user->deleted
) {
4033 if (!has_capability('moodle/user:update', $coursecontext)) {
4034 // We can't edit the user so just show the user deleted message
4035 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
4037 // We can edit the user so show the user deleted message and link it to the profile
4038 if ($course->id
== $SITE->id
) {
4039 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
4041 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
4043 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
4048 $userauthplugin = false;
4049 if (!empty($user->auth
)) {
4050 $userauthplugin = get_auth_plugin($user->auth
);
4053 // Add the profile edit link
4054 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4055 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
4056 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
4057 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
4058 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4059 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4060 $url = $userauthplugin->edit_profile_url();
4062 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4064 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
4069 // Change password link
4070 if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4071 $passwordchangeurl = $userauthplugin->change_password_url();
4072 if (empty($passwordchangeurl)) {
4073 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
4075 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
);
4078 // View the roles settings
4079 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
4080 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
4082 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
4083 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
4085 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
4087 if (!empty($assignableroles)) {
4088 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4089 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
4092 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
4093 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4094 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4097 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
4098 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4102 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
4103 require_once($CFG->libdir
. '/portfoliolib.php');
4104 if (portfolio_instances(true, false)) {
4105 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
4107 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
4108 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
4110 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
4111 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
4115 $enablemanagetokens = false;
4116 if (!empty($CFG->enablerssfeeds
)) {
4117 $enablemanagetokens = true;
4118 } else if (!is_siteadmin($USER->id
)
4119 && !empty($CFG->enablewebservices
)
4120 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
4121 $enablemanagetokens = true;
4124 if ($currentuser && $enablemanagetokens) {
4125 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4126 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
4130 if (!$currentuser && $usercontext->contextlevel
== CONTEXT_USER
) {
4131 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
4132 require_once($CFG->dirroot
. '/repository/lib.php');
4133 $editabletypes = repository
::get_editable_types($usercontext);
4134 $haseditabletypes = !empty($editabletypes);
4135 unset($editabletypes);
4136 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
4138 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
4140 if ($haseditabletypes) {
4141 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id
));
4142 $usersetting->add(get_string('repositories', 'repository'), $url, self
::TYPE_SETTING
);
4147 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
4148 $url = new moodle_url('/message/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4149 $usersetting->add(get_string('editmymessage', 'message'), $url, self
::TYPE_SETTING
);
4153 if ($currentuser && !empty($CFG->bloglevel
)) {
4154 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
4155 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node
::TYPE_SETTING
);
4156 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM
))) {
4157 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node
::TYPE_SETTING
);
4158 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node
::TYPE_SETTING
);
4163 if (!$user->deleted
and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id
)) {
4164 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id
, 'user'=>$user->id
, 'sesskey'=>sesskey()));
4165 $usersetting->add(get_string('loginas'), $url, self
::TYPE_SETTING
);
4168 return $usersetting;
4172 * Loads block specific settings in the navigation
4174 * @return navigation_node
4176 protected function load_block_settings() {
4179 $blocknode = $this->add(print_context_name($this->context
));
4180 $blocknode->force_open();
4182 // Assign local roles
4183 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
4184 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
);
4187 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
4188 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
4189 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4191 // Check role permissions
4192 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
4193 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
4194 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4201 * Loads category specific settings in the navigation
4203 * @return navigation_node
4205 protected function load_category_settings() {
4208 $categorynode = $this->add(print_context_name($this->context
));
4209 $categorynode->force_open();
4211 if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context
)) {
4212 $url = new moodle_url('/course/category.php', array('id'=>$this->context
->instanceid
, 'sesskey'=>sesskey()));
4213 if ($this->page
->user_is_editing()) {
4214 $url->param('categoryedit', '0');
4215 $editstring = get_string('turneditingoff');
4217 $url->param('categoryedit', '1');
4218 $editstring = get_string('turneditingon');
4220 $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
4223 if ($this->page
->user_is_editing() && has_capability('moodle/category:manage', $this->context
)) {
4224 $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context
->instanceid
));
4225 $categorynode->add(get_string('editcategorythis'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
4227 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context
->instanceid
));
4228 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
4231 // Assign local roles
4232 if (has_capability('moodle/role:assign', $this->context
)) {
4233 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
4234 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/roles', ''));
4238 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
4239 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
4240 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
4242 // Check role permissions
4243 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
4244 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
4245 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
4249 if (has_capability('moodle/cohort:manage', $this->context
) or has_capability('moodle/cohort:view', $this->context
)) {
4250 $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', ''));
4254 if (has_capability('moodle/filter:manage', $this->context
) && count(filter_get_available_in_context($this->context
))>0) {
4255 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context
->id
));
4256 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
4259 return $categorynode;
4263 * Determine whether the user is assuming another role
4265 * This function checks to see if the user is assuming another role by means of
4266 * role switching. In doing this we compare each RSW key (context path) against
4267 * the current context path. This ensures that we can provide the switching
4268 * options against both the course and any page shown under the course.
4270 * @return bool|int The role(int) if the user is in another role, false otherwise
4272 protected function in_alternative_role() {
4274 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
4275 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
4276 return $USER->access
['rsw'][$this->page
->context
->path
];
4278 foreach ($USER->access
['rsw'] as $key=>$role) {
4279 if (strpos($this->context
->path
,$key)===0) {
4288 * This function loads all of the front page settings into the settings navigation.
4289 * This function is called when the user is on the front page, or $COURSE==$SITE
4290 * @param bool $forceopen (optional)
4291 * @return navigation_node
4293 protected function load_front_page_settings($forceopen = false) {
4296 $course = clone($SITE);
4297 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
4299 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
4301 $frontpage->force_open();
4303 $frontpage->id
= 'frontpagesettings';
4305 if (has_capability('moodle/course:update', $coursecontext)) {
4307 // Add the turn on/off settings
4308 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
4309 if ($this->page
->user_is_editing()) {
4310 $url->param('edit', 'off');
4311 $editstring = get_string('turneditingoff');
4313 $url->param('edit', 'on');
4314 $editstring = get_string('turneditingon');
4316 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
4318 // Add the course settings link
4319 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
4320 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
4324 enrol_add_course_navigation($frontpage, $course);
4327 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
4328 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4329 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
4332 // Backup this course
4333 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
4334 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4335 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
4338 // Restore to this course
4339 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
4340 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4341 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
4345 require_once($CFG->libdir
. '/questionlib.php');
4346 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
4349 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $this->context
)) {
4350 //hiden in new installs
4351 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
4352 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/files', ''));
4358 * This function marks the cache as volatile so it is cleared during shutdown
4360 public function clear_cache() {
4361 $this->cache
->volatile();
4366 * Simple class used to output a navigation branch in XML
4369 * @category navigation
4370 * @copyright 2009 Sam Hemelryk
4371 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4373 class navigation_json
{
4374 /** @var array An array of different node types */
4375 protected $nodetype = array('node','branch');
4376 /** @var array An array of node keys and types */
4377 protected $expandable = array();
4379 * Turns a branch and all of its children into XML
4381 * @param navigation_node $branch
4382 * @return string XML string
4384 public function convert($branch) {
4385 $xml = $this->convert_child($branch);
4389 * Set the expandable items in the array so that we have enough information
4390 * to attach AJAX events
4391 * @param array $expandable
4393 public function set_expandable($expandable) {
4394 foreach ($expandable as $node) {
4395 $this->expandable
[$node['key'].':'.$node['type']] = $node;
4399 * Recusively converts a child node and its children to XML for output
4401 * @param navigation_node $child The child to convert
4402 * @param int $depth Pointlessly used to track the depth of the XML structure
4403 * @return string JSON
4405 protected function convert_child($child, $depth=1) {
4406 if (!$child->display
) {
4409 $attributes = array();
4410 $attributes['id'] = $child->id
;
4411 $attributes['name'] = $child->text
;
4412 $attributes['type'] = $child->type
;
4413 $attributes['key'] = $child->key
;
4414 $attributes['class'] = $child->get_css_type();
4416 if ($child->icon
instanceof pix_icon
) {
4417 $attributes['icon'] = array(
4418 'component' => $child->icon
->component
,
4419 'pix' => $child->icon
->pix
,
4421 foreach ($child->icon
->attributes
as $key=>$value) {
4422 if ($key == 'class') {
4423 $attributes['icon']['classes'] = explode(' ', $value);
4424 } else if (!array_key_exists($key, $attributes['icon'])) {
4425 $attributes['icon'][$key] = $value;
4429 } else if (!empty($child->icon
)) {
4430 $attributes['icon'] = (string)$child->icon
;
4433 if ($child->forcetitle ||
$child->title
!== $child->text
) {
4434 $attributes['title'] = htmlentities($child->title
);
4436 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
4437 $attributes['expandable'] = $child->key
;
4438 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
4441 if (count($child->classes
)>0) {
4442 $attributes['class'] .= ' '.join(' ',$child->classes
);
4444 if (is_string($child->action
)) {
4445 $attributes['link'] = $child->action
;
4446 } else if ($child->action
instanceof moodle_url
) {
4447 $attributes['link'] = $child->action
->out();
4448 } else if ($child->action
instanceof action_link
) {
4449 $attributes['link'] = $child->action
->url
->out();
4451 $attributes['hidden'] = ($child->hidden
);
4452 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
4454 if ($child->children
->count() > 0) {
4455 $attributes['children'] = array();
4456 foreach ($child->children
as $subchild) {
4457 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
4464 return json_encode($attributes);
4470 * The cache class used by global navigation and settings navigation.
4472 * It is basically an easy access point to session with a bit of smarts to make
4473 * sure that the information that is cached is valid still.
4477 * if (!$cache->viewdiscussion()) {
4478 * // Code to do stuff and produce cachable content
4479 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
4481 * $content = $cache->viewdiscussion;
4485 * @category navigation
4486 * @copyright 2009 Sam Hemelryk
4487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4489 class navigation_cache
{
4490 /** @var int represents the time created */
4491 protected $creation;
4492 /** @var array An array of session keys */
4495 * The string to use to segregate this particular cache. It can either be
4496 * unique to start a fresh cache or if you want to share a cache then make
4497 * it the string used in the original cache.
4501 /** @var int a time that the information will time out */
4503 /** @var stdClass The current context */
4504 protected $currentcontext;
4505 /** @var int cache time information */
4506 const CACHETIME
= 0;
4507 /** @var int cache user id */
4508 const CACHEUSERID
= 1;
4509 /** @var int cache value */
4510 const CACHEVALUE
= 2;
4511 /** @var null|array An array of navigation cache areas to expire on shutdown */
4512 public static $volatilecaches;
4515 * Contructor for the cache. Requires two arguments
4517 * @param string $area The string to use to segregate this particular cache
4518 * it can either be unique to start a fresh cache or if you want
4519 * to share a cache then make it the string used in the original
4521 * @param int $timeout The number of seconds to time the information out after
4523 public function __construct($area, $timeout=1800) {
4524 $this->creation
= time();
4525 $this->area
= $area;
4526 $this->timeout
= time() - $timeout;
4527 if (rand(0,100) === 0) {
4528 $this->garbage_collection();
4533 * Used to set up the cache within the SESSION.
4535 * This is called for each access and ensure that we don't put anything into the session before
4538 protected function ensure_session_cache_initialised() {
4540 if (empty($this->session
)) {
4541 if (!isset($SESSION->navcache
)) {
4542 $SESSION->navcache
= new stdClass
;
4544 if (!isset($SESSION->navcache
->{$this->area
})) {
4545 $SESSION->navcache
->{$this->area
} = array();
4547 $this->session
= &$SESSION->navcache
->{$this->area
}; // pointer to array, =& is correct here
4552 * Magic Method to retrieve something by simply calling using = cache->key
4554 * @param mixed $key The identifier for the information you want out again
4555 * @return void|mixed Either void or what ever was put in
4557 public function __get($key) {
4558 if (!$this->cached($key)) {
4561 $information = $this->session
[$key][self
::CACHEVALUE
];
4562 return unserialize($information);
4566 * Magic method that simply uses {@link set();} to store something in the cache
4568 * @param string|int $key
4569 * @param mixed $information
4571 public function __set($key, $information) {
4572 $this->set($key, $information);
4576 * Sets some information against the cache (session) for later retrieval
4578 * @param string|int $key
4579 * @param mixed $information
4581 public function set($key, $information) {
4583 $this->ensure_session_cache_initialised();
4584 $information = serialize($information);
4585 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
4588 * Check the existence of the identifier in the cache
4590 * @param string|int $key
4593 public function cached($key) {
4595 $this->ensure_session_cache_initialised();
4596 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
) {
4602 * Compare something to it's equivilant in the cache
4604 * @param string $key
4605 * @param mixed $value
4606 * @param bool $serialise Whether to serialise the value before comparison
4607 * this should only be set to false if the value is already
4609 * @return bool If the value is the same false if it is not set or doesn't match
4611 public function compare($key, $value, $serialise = true) {
4612 if ($this->cached($key)) {
4614 $value = serialize($value);
4616 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
4623 * Wipes the entire cache, good to force regeneration
4625 public function clear() {
4627 unset($SESSION->navcache
);
4628 $this->session
= null;
4631 * Checks all cache entries and removes any that have expired, good ole cleanup
4633 protected function garbage_collection() {
4634 if (empty($this->session
)) {
4637 foreach ($this->session
as $key=>$cachedinfo) {
4638 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
4639 unset($this->session
[$key]);
4645 * Marks the cache as being volatile (likely to change)
4647 * Any caches marked as volatile will be destroyed at the on shutdown by
4648 * {@link navigation_node::destroy_volatile_caches()} which is registered
4649 * as a shutdown function if any caches are marked as volatile.
4651 * @param bool $setting True to destroy the cache false not too
4653 public function volatile($setting = true) {
4654 if (self
::$volatilecaches===null) {
4655 self
::$volatilecaches = array();
4656 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
4660 self
::$volatilecaches[$this->area
] = $this->area
;
4661 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
4662 unset(self
::$volatilecaches[$this->area
]);
4667 * Destroys all caches marked as volatile
4669 * This function is static and works in conjunction with the static volatilecaches
4670 * property of navigation cache.
4671 * Because this function is static it manually resets the cached areas back to an
4674 public static function destroy_volatile_caches() {
4676 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
4677 foreach (self
::$volatilecaches as $area) {
4678 $SESSION->navcache
->{$area} = array();
4681 $SESSION->navcache
= new stdClass
;