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');
32 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
35 * This class is used to represent a node in a navigation tree
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
44 * @category navigation
45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class navigation_node
implements renderable
{
49 /** @var int Used to identify this node a leaf (default) 0 */
50 const NODETYPE_LEAF
= 0;
51 /** @var int Used to identify this node a branch, happens with children 1 */
52 const NODETYPE_BRANCH
= 1;
53 /** @var null Unknown node type null */
54 const TYPE_UNKNOWN
= null;
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE
= 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM
= 1;
59 /** @var int Category node type 10 */
60 const TYPE_CATEGORY
= 10;
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY
= 11;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE
= 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION
= 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY
= 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE
= 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM
= 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING
= 70;
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN
= 71;
77 /** @var int Setting node type, used only within settings nav 80 */
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER
= 90;
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER
= 0;
83 /** var int Course the current user is enrolled in but not viewing */
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT
= 2;
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE
= 'courseindexpage';
90 /** @var int Parameter to aid the coder in tracking [optional] */
92 /** @var string|int The identifier for the node, used to retrieve the node */
94 /** @var string The text to use for the node */
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
102 /** @var moodle_url|action_link|null An action for the node (link) */
103 public $action = null;
104 /** @var pix_icon The path to an icon to use for this node */
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self
::TYPE_UNKNOWN
;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self
::NODETYPE_LEAF
;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
114 /** @var array An array of CSS classes for the node */
115 public $classes = array();
116 /** @var navigation_node_collection An array of child nodes */
117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
120 /** @var bool If set to true the node will be dimmed */
121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
131 public $parent = null;
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
140 /** @var moodle_url */
141 protected static $fullmeurl = null;
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
154 * Constructs a new navigation_node
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
159 public function __construct($properties) {
160 if (is_array($properties)) {
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
169 if (array_key_exists('text', $properties)) {
170 $this->text
= $properties['text'];
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext
= $properties['shorttext'];
175 if (!array_key_exists('icon', $properties)) {
176 $properties['icon'] = new pix_icon('i/navigationitem', '');
178 $this->icon
= $properties['icon'];
179 if ($this->icon
instanceof pix_icon
) {
180 if (empty($this->icon
->attributes
['class'])) {
181 $this->icon
->attributes
['class'] = 'navicon';
183 $this->icon
->attributes
['class'] .= ' navicon';
186 if (array_key_exists('type', $properties)) {
187 $this->type
= $properties['type'];
189 $this->type
= self
::TYPE_CUSTOM
;
191 if (array_key_exists('key', $properties)) {
192 $this->key
= $properties['key'];
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action
= $properties['action'];
197 if (is_string($this->action
)) {
198 $this->action
= new moodle_url($this->action
);
200 if (self
::$autofindactive) {
201 $this->check_if_active();
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
207 } else if (is_string($properties)) {
208 $this->text
= $properties;
210 if ($this->text
=== null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children
= new navigation_node_collection();
218 * Checks if this node is the active node.
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
226 public function check_if_active($strength=URL_MATCH_EXACT
) {
227 global $FULLME, $PAGE;
228 // Set fullmeurl if it hasn't already been set
229 if (self
::$fullmeurl == null) {
230 if ($PAGE->has_set_url()) {
231 self
::override_active_url(new moodle_url($PAGE->url
));
233 self
::override_active_url(new moodle_url($FULLME));
237 // Compare the action of this node against the fullmeurl
238 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
239 $this->make_active();
246 * True if this nav node has siblings in the tree.
250 public function has_siblings() {
251 if (empty($this->parent
) ||
empty($this->parent
->children
)) {
254 if ($this->parent
->children
instanceof navigation_node_collection
) {
255 $count = $this->parent
->children
->count();
257 $count = count($this->parent
->children
);
263 * Get a list of sibling navigation nodes at the same level as this one.
265 * @return bool|array of navigation_node
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
272 if ($this->has_siblings()) {
274 foreach ($this->parent
->children
as $child) {
275 if ($child->display
) {
276 $siblings[] = $child;
284 * This sets the URL that the URL of new nodes get compared to when locating
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
290 * @param moodle_url $url The url to use for the fullmeurl.
291 * @param bool $loadadmintree use true if the URL point to administration tree
293 public static function override_active_url(moodle_url
$url, $loadadmintree = false) {
294 // Clone the URL, in case the calling script changes their URL later.
295 self
::$fullmeurl = new moodle_url($url);
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self
::$loadadmintree = true;
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
308 public static function require_admin_tree() {
309 self
::$loadadmintree = true;
313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
315 * @param string $text
316 * @param moodle_url|action_link $action
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
323 public static function create($text, $action=null, $type=self
::TYPE_CUSTOM
,
324 $shorttext=null, $key=null, pix_icon
$icon=null) {
325 // Properties array used when creating the new navigation node
330 // Set the action if one was provided
331 if ($action!==null) {
332 $itemarray['action'] = $action;
334 // Set the shorttext if one was provided
335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
338 // Set the icon if one was provided
340 $itemarray['icon'] = $icon;
343 $itemarray['key'] = $key;
344 // Construct and return
345 return new navigation_node($itemarray);
349 * Adds a navigation node as a child of this node.
351 * @param string $text
352 * @param moodle_url|action_link $action
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
359 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
361 $childnode = self
::create($text, $action, $type, $shorttext, $key, $icon);
363 // Add the child to end and return
364 return $this->add_node($childnode);
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
371 * @param string $beforekey
372 * @return navigation_node The added node
374 public function add_node(navigation_node
$childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
377 $this->nodetype
= self
::NODETYPE_BRANCH
;
379 // Set the parent to this node
380 $childnode->set_parent($this);
382 // Default the key to the number of children if not provided
383 if ($childnode->key
=== null) {
384 $childnode->key
= $this->children
->count();
387 // Add the child using the navigation_node_collections add method
388 $node = $this->children
->add($childnode, $beforekey);
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type
;
393 if (($type == self
::TYPE_CATEGORY
) ||
(isloggedin() && ($type == self
::TYPE_COURSE
)) ||
($type == self
::TYPE_MY_CATEGORY
) ||
394 ($type === self
::TYPE_SITE_ADMIN
)) {
395 $node->nodetype
= self
::NODETYPE_BRANCH
;
397 // If this node is hidden mark it's children as hidden also
399 $node->hidden
= true;
401 // Return added node (reference returned by $this->children->add()
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
409 public function get_children_key_list() {
410 return $this->children
->get_key_list();
414 * Searches for a node of the given type with the given key.
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
424 public function find($key, $type) {
425 return $this->children
->find($key, $type);
429 * Walk the tree building up a list of all the flat navigation nodes.
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
432 * @param boolean $showdivider Show a divider before the first node.
434 public function build_flat_navigation_list(flat_navigation
$nodes, $showdivider = false) {
435 if ($this->showinflatnavigation
) {
437 if ($this->type
== self
::TYPE_COURSE ||
$this->key
=== self
::COURSE_INDEX_PAGE
) {
440 $flat = new flat_navigation_node($this, $indent);
441 $flat->set_showdivider($showdivider);
444 foreach ($this->children
as $child) {
445 $child->build_flat_navigation_list($nodes, false);
450 * Get the child of this node that has the given key + (optional) type.
452 * If you are looking for a node and want to search all children + their children
453 * then please use the find method instead.
455 * @param int|string $key The key of the node we are looking for
456 * @param int $type One of navigation_node::TYPE_*
457 * @return navigation_node|false
459 public function get($key, $type=null) {
460 return $this->children
->get($key, $type);
468 public function remove() {
469 return $this->parent
->children
->remove($this->key
, $this->type
);
473 * Checks if this node has or could have any children
475 * @return bool Returns true if it has children or could have (by AJAX expansion)
477 public function has_children() {
478 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0 ||
$this->isexpandable
);
482 * Marks this node as active and forces it open.
484 * Important: If you are here because you need to mark a node active to get
485 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
486 * You can use it to specify a different URL to match the active navigation node on
487 * rather than having to locate and manually mark a node active.
489 public function make_active() {
490 $this->isactive
= true;
491 $this->add_class('active_tree_node');
493 if ($this->parent
!== null) {
494 $this->parent
->make_inactive();
499 * Marks a node as inactive and recusised back to the base of the tree
500 * doing the same to all parents.
502 public function make_inactive() {
503 $this->isactive
= false;
504 $this->remove_class('active_tree_node');
505 if ($this->parent
!== null) {
506 $this->parent
->make_inactive();
511 * Forces this node to be open and at the same time forces open all
512 * parents until the root node.
516 public function force_open() {
517 $this->forceopen
= true;
518 if ($this->parent
!== null) {
519 $this->parent
->force_open();
524 * Adds a CSS class to this node.
526 * @param string $class
529 public function add_class($class) {
530 if (!in_array($class, $this->classes
)) {
531 $this->classes
[] = $class;
537 * Removes a CSS class from this node.
539 * @param string $class
540 * @return bool True if the class was successfully removed.
542 public function remove_class($class) {
543 if (in_array($class, $this->classes
)) {
544 $key = array_search($class,$this->classes
);
546 unset($this->classes
[$key]);
554 * Sets the title for this node and forces Moodle to utilise it.
555 * @param string $title
557 public function title($title) {
558 $this->title
= $title;
559 $this->forcetitle
= true;
563 * Resets the page specific information on this node if it is being unserialised.
565 public function __wakeup(){
566 $this->forceopen
= false;
567 $this->isactive
= false;
568 $this->remove_class('active_tree_node');
572 * Checks if this node or any of its children contain the active node.
578 public function contains_active_node() {
579 if ($this->isactive
) {
582 foreach ($this->children
as $child) {
583 if ($child->isactive ||
$child->contains_active_node()) {
592 * To better balance the admin tree, we want to group all the short top branches together.
594 * This means < 8 nodes and no subtrees.
598 public function is_short_branch() {
600 if ($this->children
->count() >= $limit) {
603 foreach ($this->children
as $child) {
604 if ($child->has_children()) {
612 * Finds the active node.
614 * Searches this nodes children plus all of the children for the active node
615 * and returns it if found.
619 * @return navigation_node|false
621 public function find_active_node() {
622 if ($this->isactive
) {
625 foreach ($this->children
as &$child) {
626 $outcome = $child->find_active_node();
627 if ($outcome !== false) {
636 * Searches all children for the best matching active node
637 * @return navigation_node|false
639 public function search_for_active_node() {
640 if ($this->check_if_active(URL_MATCH_BASE
)) {
643 foreach ($this->children
as &$child) {
644 $outcome = $child->search_for_active_node();
645 if ($outcome !== false) {
654 * Gets the content for this node.
656 * @param bool $shorttext If true shorttext is used rather than the normal text
659 public function get_content($shorttext=false) {
660 if ($shorttext && $this->shorttext
!==null) {
661 return format_string($this->shorttext
);
663 return format_string($this->text
);
668 * Gets the title to use for this node.
672 public function get_title() {
673 if ($this->forcetitle ||
$this->action
!= null){
681 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
685 public function has_action() {
686 return !empty($this->action
);
690 * Used to easily determine if this link in the breadcrumbs is hidden.
694 public function is_hidden() {
695 return $this->hidden
;
699 * Gets the CSS class to add to this node to describe its type
703 public function get_css_type() {
704 if (array_key_exists($this->type
, $this->namedtypes
)) {
705 return 'type_'.$this->namedtypes
[$this->type
];
707 return 'type_unknown';
711 * Finds all nodes that are expandable by AJAX
713 * @param array $expandable An array by reference to populate with expandable nodes.
715 public function find_expandable(array &$expandable) {
716 foreach ($this->children
as &$child) {
717 if ($child->display
&& $child->has_children() && $child->children
->count() == 0) {
718 $child->id
= 'expandable_branch_'.$child->type
.'_'.clean_param($child->key
, PARAM_ALPHANUMEXT
);
719 $this->add_class('canexpand');
720 $child->requiresajaxloading
= true;
721 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
723 $child->find_expandable($expandable);
728 * Finds all nodes of a given type (recursive)
730 * @param int $type One of navigation_node::TYPE_*
733 public function find_all_of_type($type) {
734 $nodes = $this->children
->type($type);
735 foreach ($this->children
as &$node) {
736 $childnodes = $node->find_all_of_type($type);
737 $nodes = array_merge($nodes, $childnodes);
743 * Removes this node if it is empty
745 public function trim_if_empty() {
746 if ($this->children
->count() == 0) {
752 * Creates a tab representation of this nodes children that can be used
753 * with print_tabs to produce the tabs on a page.
755 * call_user_func_array('print_tabs', $node->get_tabs_array());
757 * @param array $inactive
758 * @param bool $return
759 * @return array Array (tabs, selected, inactive, activated, return)
761 public function get_tabs_array(array $inactive=array(), $return=false) {
765 $activated = array();
766 foreach ($this->children
as $node) {
767 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
768 if ($node->contains_active_node()) {
769 if ($node->children
->count() > 0) {
770 $activated[] = $node->key
;
771 foreach ($node->children
as $child) {
772 if ($child->contains_active_node()) {
773 $selected = $child->key
;
775 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
778 $selected = $node->key
;
782 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
786 * Sets the parent for this node and if this node is active ensures that the tree is properly
789 * @param navigation_node $parent
791 public function set_parent(navigation_node
$parent) {
792 // Set the parent (thats the easy part)
793 $this->parent
= $parent;
794 // Check if this node is active (this is checked during construction)
795 if ($this->isactive
) {
796 // Force all of the parent nodes open so you can see this node
797 $this->parent
->force_open();
798 // Make all parents inactive so that its clear where we are.
799 $this->parent
->make_inactive();
804 * Hides the node and any children it has.
807 * @param array $typestohide Optional. An array of node types that should be hidden.
808 * If null all nodes will be hidden.
809 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
810 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
812 public function hide(array $typestohide = null) {
813 if ($typestohide === null ||
in_array($this->type
, $typestohide)) {
814 $this->display
= false;
815 if ($this->has_children()) {
816 foreach ($this->children
as $child) {
817 $child->hide($typestohide);
824 * Get the action url for this navigation node.
825 * Called from templates.
829 public function action() {
830 if ($this->action
instanceof moodle_url
) {
831 return $this->action
;
832 } else if ($this->action
instanceof action_link
) {
833 return $this->action
->url
;
835 return $this->action
;
840 * Navigation node collection
842 * This class is responsible for managing a collection of navigation nodes.
843 * It is required because a node's unique identifier is a combination of both its
846 * Originally an array was used with a string key that was a combination of the two
847 * however it was decided that a better solution would be to use a class that
848 * implements the standard IteratorAggregate interface.
851 * @category navigation
852 * @copyright 2010 Sam Hemelryk
853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
855 class navigation_node_collection
implements IteratorAggregate
, Countable
{
857 * A multidimensional array to where the first key is the type and the second
858 * key is the nodes key.
861 protected $collection = array();
863 * An array that contains references to nodes in the same order they were added.
864 * This is maintained as a progressive array.
867 protected $orderedcollection = array();
869 * A reference to the last node that was added to the collection
870 * @var navigation_node
872 protected $last = null;
874 * The total number of items added to this array.
877 protected $count = 0;
880 * Adds a navigation node to the collection
882 * @param navigation_node $node Node to add
883 * @param string $beforekey If specified, adds before a node with this key,
884 * otherwise adds at end
885 * @return navigation_node Added node
887 public function add(navigation_node
$node, $beforekey=null) {
892 // First check we have a 2nd dimension for this type
893 if (!array_key_exists($type, $this->orderedcollection
)) {
894 $this->orderedcollection
[$type] = array();
896 // Check for a collision and report if debugging is turned on
897 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
898 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
901 // Find the key to add before
902 $newindex = $this->count
;
904 if ($beforekey !== null) {
905 foreach ($this->collection
as $index => $othernode) {
906 if ($othernode->key
=== $beforekey) {
912 if ($newindex === $this->count
) {
913 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
914 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
918 // Add the node to the appropriate place in the by-type structure (which
919 // is not ordered, despite the variable name)
920 $this->orderedcollection
[$type][$key] = $node;
922 // Update existing references in the ordered collection (which is the
923 // one that isn't called 'ordered') to shuffle them along if required
924 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
925 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
928 // Add a reference to the node to the progressive collection.
929 $this->collection
[$newindex] = $this->orderedcollection
[$type][$key];
930 // Update the last property to a reference to this new node.
931 $this->last
= $this->orderedcollection
[$type][$key];
933 // Reorder the array by index if needed
935 ksort($this->collection
);
938 // Return the reference to the now added node
943 * Return a list of all the keys of all the nodes.
944 * @return array the keys.
946 public function get_key_list() {
948 foreach ($this->collection
as $node) {
949 $keys[] = $node->key
;
955 * Fetches a node from this collection.
957 * @param string|int $key The key of the node we want to find.
958 * @param int $type One of navigation_node::TYPE_*.
959 * @return navigation_node|null
961 public function get($key, $type=null) {
962 if ($type !== null) {
963 // If the type is known then we can simply check and fetch
964 if (!empty($this->orderedcollection
[$type][$key])) {
965 return $this->orderedcollection
[$type][$key];
968 // Because we don't know the type we look in the progressive array
969 foreach ($this->collection
as $node) {
970 if ($node->key
=== $key) {
979 * Searches for a node with matching key and type.
981 * This function searches both the nodes in this collection and all of
982 * the nodes in each collection belonging to the nodes in this collection.
986 * @param string|int $key The key of the node we want to find.
987 * @param int $type One of navigation_node::TYPE_*.
988 * @return navigation_node|null
990 public function find($key, $type=null) {
991 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
992 return $this->orderedcollection
[$type][$key];
994 $nodes = $this->getIterator();
995 // Search immediate children first
996 foreach ($nodes as &$node) {
997 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
1001 // Now search each childs children
1002 foreach ($nodes as &$node) {
1003 $result = $node->children
->find($key, $type);
1004 if ($result !== false) {
1013 * Fetches the last node that was added to this collection
1015 * @return navigation_node
1017 public function last() {
1022 * Fetches all nodes of a given type from this collection
1024 * @param string|int $type node type being searched for.
1025 * @return array ordered collection
1027 public function type($type) {
1028 if (!array_key_exists($type, $this->orderedcollection
)) {
1029 $this->orderedcollection
[$type] = array();
1031 return $this->orderedcollection
[$type];
1034 * Removes the node with the given key and type from the collection
1036 * @param string|int $key The key of the node we want to find.
1040 public function remove($key, $type=null) {
1041 $child = $this->get($key, $type);
1042 if ($child !== false) {
1043 foreach ($this->collection
as $colkey => $node) {
1044 if ($node->key
=== $key && (is_null($type) ||
$node->type
== $type)) {
1045 unset($this->collection
[$colkey]);
1046 $this->collection
= array_values($this->collection
);
1050 unset($this->orderedcollection
[$child->type
][$child->key
]);
1058 * Gets the number of nodes in this collection
1060 * This option uses an internal count rather than counting the actual options to avoid
1061 * a performance hit through the count function.
1065 public function count() {
1066 return $this->count
;
1069 * Gets an array iterator for the collection.
1071 * This is required by the IteratorAggregator interface and is used by routines
1072 * such as the foreach loop.
1074 * @return ArrayIterator
1076 public function getIterator() {
1077 return new ArrayIterator($this->collection
);
1082 * The global navigation class used for... the global navigation
1084 * This class is used by PAGE to store the global navigation for the site
1085 * and is then used by the settings nav and navbar to save on processing and DB calls
1088 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1089 * {@link lib/ajax/getnavbranch.php} Called by ajax
1092 * @category navigation
1093 * @copyright 2009 Sam Hemelryk
1094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1096 class global_navigation
extends navigation_node
{
1097 /** @var moodle_page The Moodle page this navigation object belongs to. */
1099 /** @var bool switch to let us know if the navigation object is initialised*/
1100 protected $initialised = false;
1101 /** @var array An array of course information */
1102 protected $mycourses = array();
1103 /** @var navigation_node[] An array for containing root navigation nodes */
1104 protected $rootnodes = array();
1105 /** @var bool A switch for whether to show empty sections in the navigation */
1106 protected $showemptysections = true;
1107 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1108 protected $showcategories = null;
1109 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1110 protected $showmycategories = null;
1111 /** @var array An array of stdClasses for users that the navigation is extended for */
1112 protected $extendforuser = array();
1113 /** @var navigation_cache */
1115 /** @var array An array of course ids that are present in the navigation */
1116 protected $addedcourses = array();
1118 protected $allcategoriesloaded = false;
1119 /** @var array An array of category ids that are included in the navigation */
1120 protected $addedcategories = array();
1121 /** @var int expansion limit */
1122 protected $expansionlimit = 0;
1123 /** @var int userid to allow parent to see child's profile page navigation */
1124 protected $useridtouseforparentchecks = 0;
1125 /** @var cache_session A cache that stores information on expanded courses */
1126 protected $cacheexpandcourse = null;
1128 /** Used when loading categories to load all top level categories [parent = 0] **/
1129 const LOAD_ROOT_CATEGORIES
= 0;
1130 /** Used when loading categories to load all categories **/
1131 const LOAD_ALL_CATEGORIES
= -1;
1134 * Constructs a new global navigation
1136 * @param moodle_page $page The page this navigation object belongs to
1138 public function __construct(moodle_page
$page) {
1139 global $CFG, $SITE, $USER;
1141 if (during_initial_install()) {
1145 if (get_home_page() == HOMEPAGE_SITE
) {
1146 // We are using the site home for the root element
1147 $properties = array(
1149 'type' => navigation_node
::TYPE_SYSTEM
,
1150 'text' => get_string('home'),
1151 'action' => new moodle_url('/'),
1152 'icon' => new pix_icon('i/home', '')
1155 // We are using the users my moodle for the root element
1156 $properties = array(
1158 'type' => navigation_node
::TYPE_SYSTEM
,
1159 'text' => get_string('myhome'),
1160 'action' => new moodle_url('/my/'),
1161 'icon' => new pix_icon('i/dashboard', '')
1165 // Use the parents constructor.... good good reuse
1166 parent
::__construct($properties);
1167 $this->showinflatnavigation
= true;
1169 // Initalise and set defaults
1170 $this->page
= $page;
1171 $this->forceopen
= true;
1172 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
1176 * Mutator to set userid to allow parent to see child's profile
1177 * page navigation. See MDL-25805 for initial issue. Linked to it
1178 * is an issue explaining why this is a REALLY UGLY HACK thats not
1181 * @param int $userid userid of profile page that parent wants to navigate around.
1183 public function set_userid_for_parent_checks($userid) {
1184 $this->useridtouseforparentchecks
= $userid;
1189 * Initialises the navigation object.
1191 * This causes the navigation object to look at the current state of the page
1192 * that it is associated with and then load the appropriate content.
1194 * This should only occur the first time that the navigation structure is utilised
1195 * which will normally be either when the navbar is called to be displayed or
1196 * when a block makes use of it.
1200 public function initialise() {
1201 global $CFG, $SITE, $USER;
1202 // Check if it has already been initialised
1203 if ($this->initialised ||
during_initial_install()) {
1206 $this->initialised
= true;
1208 // Set up the five base root nodes. These are nodes where we will put our
1209 // content and are as follows:
1210 // site: Navigation for the front page.
1211 // myprofile: User profile information goes here.
1212 // currentcourse: The course being currently viewed.
1213 // mycourses: The users courses get added here.
1214 // courses: Additional courses are added here.
1215 // users: Other users information loaded here.
1216 $this->rootnodes
= array();
1217 if (get_home_page() == HOMEPAGE_SITE
) {
1218 // The home element should be my moodle because the root element is the site
1219 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1220 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1221 self
::TYPE_SETTING
, null, 'myhome', new pix_icon('i/dashboard', ''));
1222 $this->rootnodes
['home']->showinflatnavigation
= true;
1225 // The home element should be the site because the root node is my moodle
1226 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1227 self
::TYPE_SETTING
, null, 'home', new pix_icon('i/home', ''));
1228 $this->rootnodes
['home']->showinflatnavigation
= true;
1229 if (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_MY
)) {
1230 // We need to stop automatic redirection
1231 $this->rootnodes
['home']->action
->param('redirect', '0');
1234 $this->rootnodes
['site'] = $this->add_course($SITE);
1235 $this->rootnodes
['myprofile'] = $this->add(get_string('profile'), null, self
::TYPE_USER
, null, 'myprofile');
1236 $this->rootnodes
['currentcourse'] = $this->add(get_string('currentcourse'), null, self
::TYPE_ROOTNODE
, null, 'currentcourse');
1237 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses', new pix_icon('i/course', ''));
1238 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1239 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1241 // We always load the frontpage course to ensure it is available without
1242 // JavaScript enabled.
1243 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1244 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1246 $course = $this->page
->course
;
1247 $this->load_courses_enrolled();
1249 // $issite gets set to true if the current pages course is the sites frontpage course
1250 $issite = ($this->page
->course
->id
== $SITE->id
);
1252 // Determine if the user is enrolled in any course.
1253 $enrolledinanycourse = enrol_user_sees_own_courses();
1255 $this->rootnodes
['currentcourse']->mainnavonly
= true;
1256 if ($enrolledinanycourse) {
1257 $this->rootnodes
['mycourses']->isexpandable
= true;
1258 $this->rootnodes
['mycourses']->showinflatnavigation
= true;
1259 if ($CFG->navshowallcourses
) {
1260 // When we show all courses we need to show both the my courses and the regular courses branch.
1261 $this->rootnodes
['courses']->isexpandable
= true;
1264 $this->rootnodes
['courses']->isexpandable
= true;
1266 $this->rootnodes
['mycourses']->forceopen
= true;
1268 $canviewcourseprofile = true;
1270 // Next load context specific content into the navigation
1271 switch ($this->page
->context
->contextlevel
) {
1272 case CONTEXT_SYSTEM
:
1273 // Nothing left to do here I feel.
1275 case CONTEXT_COURSECAT
:
1276 // This is essential, we must load categories.
1277 $this->load_all_categories($this->page
->context
->instanceid
, true);
1279 case CONTEXT_BLOCK
:
1280 case CONTEXT_COURSE
:
1282 // Nothing left to do here.
1286 // Load the course associated with the current page into the navigation.
1287 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1288 // If the course wasn't added then don't try going any further.
1290 $canviewcourseprofile = false;
1294 // If the user is not enrolled then we only want to show the
1295 // course node and not populate it.
1297 // Not enrolled, can't view, and hasn't switched roles
1298 if (!can_access_course($course, null, '', true)) {
1299 if ($coursenode->isexpandable
=== true) {
1300 // Obviously the situation has changed, update the cache and adjust the node.
1301 // This occurs if the user access to a course has been revoked (one way or another) after
1302 // initially logging in for this session.
1303 $this->get_expand_course_cache()->set($course->id
, 1);
1304 $coursenode->isexpandable
= true;
1305 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1307 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1308 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1309 if (!$this->current_user_is_parent_role()) {
1310 $coursenode->make_active();
1311 $canviewcourseprofile = false;
1314 } else if ($coursenode->isexpandable
=== false) {
1315 // Obviously the situation has changed, update the cache and adjust the node.
1316 // This occurs if the user has been granted access to a course (one way or another) after initially
1317 // logging in for this session.
1318 $this->get_expand_course_cache()->set($course->id
, 1);
1319 $coursenode->isexpandable
= true;
1320 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1323 // Add the essentials such as reports etc...
1324 $this->add_course_essentials($coursenode, $course);
1325 // Extend course navigation with it's sections/activities
1326 $this->load_course_sections($course, $coursenode);
1327 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1328 $coursenode->make_active();
1332 case CONTEXT_MODULE
:
1334 // If this is the site course then most information will have
1335 // already been loaded.
1336 // However we need to check if there is more content that can
1337 // yet be loaded for the specific module instance.
1338 $activitynode = $this->rootnodes
['site']->find($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1339 if ($activitynode) {
1340 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1345 $course = $this->page
->course
;
1346 $cm = $this->page
->cm
;
1348 // Load the course associated with the page into the navigation
1349 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1351 // If the course wasn't added then don't try going any further.
1353 $canviewcourseprofile = false;
1357 // If the user is not enrolled then we only want to show the
1358 // course node and not populate it.
1359 if (!can_access_course($course, null, '', true)) {
1360 $coursenode->make_active();
1361 $canviewcourseprofile = false;
1365 $this->add_course_essentials($coursenode, $course);
1367 // Load the course sections into the page
1368 $this->load_course_sections($course, $coursenode, null, $cm);
1369 $activity = $coursenode->find($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1370 if (!empty($activity)) {
1371 // Finally load the cm specific navigaton information
1372 $this->load_activity($cm, $course, $activity);
1373 // Check if we have an active ndoe
1374 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1375 // And make the activity node active.
1376 $activity->make_active();
1382 // The users profile information etc is already loaded
1383 // for the front page.
1386 $course = $this->page
->course
;
1387 // Load the course associated with the user into the navigation
1388 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1390 // If the course wasn't added then don't try going any further.
1392 $canviewcourseprofile = false;
1396 // If the user is not enrolled then we only want to show the
1397 // course node and not populate it.
1398 if (!can_access_course($course, null, '', true)) {
1399 $coursenode->make_active();
1400 $canviewcourseprofile = false;
1403 $this->add_course_essentials($coursenode, $course);
1404 $this->load_course_sections($course, $coursenode);
1408 // Load for the current user
1409 $this->load_for_user();
1410 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
&& $canviewcourseprofile) {
1411 $this->load_for_user(null, true);
1413 // Load each extending user into the navigation.
1414 foreach ($this->extendforuser
as $user) {
1415 if ($user->id
!= $USER->id
) {
1416 $this->load_for_user($user);
1420 // Give the local plugins a chance to include some navigation if they want.
1421 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1425 // Remove any empty root nodes
1426 foreach ($this->rootnodes
as $node) {
1427 // Dont remove the home node
1428 /** @var navigation_node $node */
1429 if (!in_array($node->key
, ['home', 'myhome']) && !$node->has_children() && !$node->isactive
) {
1434 if (!$this->contains_active_node()) {
1435 $this->search_for_active_node();
1438 // If the user is not logged in modify the navigation structure as detailed
1439 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1440 if (!isloggedin()) {
1441 $activities = clone($this->rootnodes
['site']->children
);
1442 $this->rootnodes
['site']->remove();
1443 $children = clone($this->children
);
1444 $this->children
= new navigation_node_collection();
1445 foreach ($activities as $child) {
1446 $this->children
->add($child);
1448 foreach ($children as $child) {
1449 $this->children
->add($child);
1456 * Returns true if the current user is a parent of the user being currently viewed.
1458 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1459 * other user being viewed this function returns false.
1460 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1465 protected function current_user_is_parent_role() {
1467 if ($this->useridtouseforparentchecks
&& $this->useridtouseforparentchecks
!= $USER->id
) {
1468 $usercontext = context_user
::instance($this->useridtouseforparentchecks
, MUST_EXIST
);
1469 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1472 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))) {
1480 * Returns true if courses should be shown within categories on the navigation.
1482 * @param bool $ismycourse Set to true if you are calculating this for a course.
1485 protected function show_categories($ismycourse = false) {
1488 return $this->show_my_categories();
1490 if ($this->showcategories
=== null) {
1492 if ($this->page
->context
->contextlevel
== CONTEXT_COURSECAT
) {
1494 } else if (!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1) {
1497 $this->showcategories
= $show;
1499 return $this->showcategories
;
1503 * Returns true if we should show categories in the My Courses branch.
1506 protected function show_my_categories() {
1508 if ($this->showmycategories
=== null) {
1509 require_once('coursecatlib.php');
1510 $this->showmycategories
= !empty($CFG->navshowmycoursecategories
) && coursecat
::count_all() > 1;
1512 return $this->showmycategories
;
1516 * Loads the courses in Moodle into the navigation.
1518 * @global moodle_database $DB
1519 * @param string|array $categoryids An array containing categories to load courses
1520 * for, OR null to load courses for all categories.
1521 * @return array An array of navigation_nodes one for each course
1523 protected function load_all_courses($categoryids = null) {
1524 global $CFG, $DB, $SITE;
1526 // Work out the limit of courses.
1528 if (!empty($CFG->navcourselimit
)) {
1529 $limit = $CFG->navcourselimit
;
1532 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1534 // If we are going to show all courses AND we are showing categories then
1535 // to save us repeated DB calls load all of the categories now
1536 if ($this->show_categories()) {
1537 $this->load_all_categories($toload);
1540 // Will be the return of our efforts
1541 $coursenodes = array();
1543 // Check if we need to show categories.
1544 if ($this->show_categories()) {
1545 // Hmmm we need to show categories... this is going to be painful.
1546 // We now need to fetch up to $limit courses for each category to
1548 if ($categoryids !== null) {
1549 if (!is_array($categoryids)) {
1550 $categoryids = array($categoryids);
1552 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1553 $categorywhere = 'WHERE cc.id '.$categorywhere;
1554 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1555 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1556 $categoryparams = array();
1558 $categorywhere = '';
1559 $categoryparams = array();
1562 // First up we are going to get the categories that we are going to
1563 // need so that we can determine how best to load the courses from them.
1564 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1565 FROM {course_categories} cc
1566 LEFT JOIN {course} c ON c.category = cc.id
1569 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1570 $fullfetch = array();
1571 $partfetch = array();
1572 foreach ($categories as $category) {
1573 if (!$this->can_add_more_courses_to_category($category->id
)) {
1576 if ($category->coursecount
> $limit * 5) {
1577 $partfetch[] = $category->id
;
1578 } else if ($category->coursecount
> 0) {
1579 $fullfetch[] = $category->id
;
1582 $categories->close();
1584 if (count($fullfetch)) {
1585 // First up fetch all of the courses in categories where we know that we are going to
1586 // need the majority of courses.
1587 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1588 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1589 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1590 $categoryparams['contextlevel'] = CONTEXT_COURSE
;
1591 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1594 WHERE c.category {$categoryids}
1595 ORDER BY c.sortorder ASC";
1596 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1597 foreach ($coursesrs as $course) {
1598 if ($course->id
== $SITE->id
) {
1599 // This should not be necessary, frontpage is not in any category.
1602 if (array_key_exists($course->id
, $this->addedcourses
)) {
1603 // It is probably better to not include the already loaded courses
1604 // directly in SQL because inequalities may confuse query optimisers
1605 // and may interfere with query caching.
1608 if (!$this->can_add_more_courses_to_category($course->category
)) {
1611 context_helper
::preload_from_record($course);
1612 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1615 $coursenodes[$course->id
] = $this->add_course($course);
1617 $coursesrs->close();
1620 if (count($partfetch)) {
1621 // Next we will work our way through the categories where we will likely only need a small
1622 // proportion of the courses.
1623 foreach ($partfetch as $categoryid) {
1624 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1625 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1626 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1629 WHERE c.category = :categoryid
1630 ORDER BY c.sortorder ASC";
1631 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE
);
1632 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1633 foreach ($coursesrs as $course) {
1634 if ($course->id
== $SITE->id
) {
1635 // This should not be necessary, frontpage is not in any category.
1638 if (array_key_exists($course->id
, $this->addedcourses
)) {
1639 // It is probably better to not include the already loaded courses
1640 // directly in SQL because inequalities may confuse query optimisers
1641 // and may interfere with query caching.
1642 // This also helps to respect expected $limit on repeated executions.
1645 if (!$this->can_add_more_courses_to_category($course->category
)) {
1648 context_helper
::preload_from_record($course);
1649 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1652 $coursenodes[$course->id
] = $this->add_course($course);
1654 $coursesrs->close();
1658 // Prepare the SQL to load the courses and their contexts
1659 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1660 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1661 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1662 $courseparams['contextlevel'] = CONTEXT_COURSE
;
1663 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1666 WHERE c.id {$courseids}
1667 ORDER BY c.sortorder ASC";
1668 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1669 foreach ($coursesrs as $course) {
1670 if ($course->id
== $SITE->id
) {
1671 // frotpage is not wanted here
1674 if ($this->page
->course
&& ($this->page
->course
->id
== $course->id
)) {
1675 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1678 context_helper
::preload_from_record($course);
1679 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1682 $coursenodes[$course->id
] = $this->add_course($course);
1683 if (count($coursenodes) >= $limit) {
1687 $coursesrs->close();
1690 return $coursenodes;
1694 * Returns true if more courses can be added to the provided category.
1696 * @param int|navigation_node|stdClass $category
1699 protected function can_add_more_courses_to_category($category) {
1702 if (!empty($CFG->navcourselimit
)) {
1703 $limit = (int)$CFG->navcourselimit
;
1705 if (is_numeric($category)) {
1706 if (!array_key_exists($category, $this->addedcategories
)) {
1709 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1710 } else if ($category instanceof navigation_node
) {
1711 if (($category->type
!= self
::TYPE_CATEGORY
) ||
($category->type
!= self
::TYPE_MY_CATEGORY
)) {
1714 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1715 } else if (is_object($category) && property_exists($category,'id')) {
1716 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1718 return ($coursecount <= $limit);
1722 * Loads all categories (top level or if an id is specified for that category)
1724 * @param int $categoryid The category id to load or null/0 to load all base level categories
1725 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1726 * as the requested category and any parent categories.
1727 * @return navigation_node|void returns a navigation node if a category has been loaded.
1729 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1732 // Check if this category has already been loaded
1733 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1737 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1738 $sqlselect = "SELECT cc.*, $catcontextsql
1739 FROM {course_categories} cc
1740 JOIN {context} ctx ON cc.id = ctx.instanceid";
1741 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1742 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1745 $categoriestoload = array();
1746 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1747 // We are going to load all categories regardless... prepare to fire
1748 // on the database server!
1749 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1750 // We are going to load all of the first level categories (categories without parents)
1751 $sqlwhere .= " AND cc.parent = 0";
1752 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1753 // The category itself has been loaded already so we just need to ensure its subcategories
1755 $addedcategories = $this->addedcategories
;
1756 unset($addedcategories[$categoryid]);
1757 if (count($addedcategories) > 0) {
1758 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED
, 'parent', false);
1759 if ($showbasecategories) {
1760 // We need to include categories with parent = 0 as well
1761 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1763 // All we need is categories that match the parent
1764 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1767 $params['categoryid'] = $categoryid;
1769 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1770 // and load this category plus all its parents and subcategories
1771 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1772 $categoriestoload = explode('/', trim($category->path
, '/'));
1773 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1774 // We are going to use select twice so double the params
1775 $params = array_merge($params, $params);
1776 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1777 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1780 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1781 $categories = array();
1782 foreach ($categoriesrs as $category) {
1783 // Preload the context.. we'll need it when adding the category in order
1784 // to format the category name.
1785 context_helper
::preload_from_record($category);
1786 if (array_key_exists($category->id
, $this->addedcategories
)) {
1787 // Do nothing, its already been added.
1788 } else if ($category->parent
== '0') {
1789 // This is a root category lets add it immediately
1790 $this->add_category($category, $this->rootnodes
['courses']);
1791 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1792 // This categories parent has already been added we can add this immediately
1793 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1795 $categories[] = $category;
1798 $categoriesrs->close();
1800 // Now we have an array of categories we need to add them to the navigation.
1801 while (!empty($categories)) {
1802 $category = reset($categories);
1803 if (array_key_exists($category->id
, $this->addedcategories
)) {
1805 } else if ($category->parent
== '0') {
1806 $this->add_category($category, $this->rootnodes
['courses']);
1807 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1808 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1810 // This category isn't in the navigation and niether is it's parent (yet).
1811 // We need to go through the category path and add all of its components in order.
1812 $path = explode('/', trim($category->path
, '/'));
1813 foreach ($path as $catid) {
1814 if (!array_key_exists($catid, $this->addedcategories
)) {
1815 // This category isn't in the navigation yet so add it.
1816 $subcategory = $categories[$catid];
1817 if ($subcategory->parent
== '0') {
1818 // Yay we have a root category - this likely means we will now be able
1819 // to add categories without problems.
1820 $this->add_category($subcategory, $this->rootnodes
['courses']);
1821 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
1822 // The parent is in the category (as we'd expect) so add it now.
1823 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
1824 // Remove the category from the categories array.
1825 unset($categories[$catid]);
1827 // We should never ever arrive here - if we have then there is a bigger
1829 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1834 // Remove the category from the categories array now that we know it has been added.
1835 unset($categories[$category->id
]);
1837 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
1838 $this->allcategoriesloaded
= true;
1840 // Check if there are any categories to load.
1841 if (count($categoriestoload) > 0) {
1842 $readytoloadcourses = array();
1843 foreach ($categoriestoload as $category) {
1844 if ($this->can_add_more_courses_to_category($category)) {
1845 $readytoloadcourses[] = $category;
1848 if (count($readytoloadcourses)) {
1849 $this->load_all_courses($readytoloadcourses);
1853 // Look for all categories which have been loaded
1854 if (!empty($this->addedcategories
)) {
1855 $categoryids = array();
1856 foreach ($this->addedcategories
as $category) {
1857 if ($this->can_add_more_courses_to_category($category)) {
1858 $categoryids[] = $category->key
;
1862 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
1863 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
1864 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1865 FROM {course_categories} cc
1866 JOIN {course} c ON c.category = cc.id
1867 WHERE cc.id {$categoriessql}
1869 HAVING COUNT(c.id) > :limit";
1870 $excessivecategories = $DB->get_records_sql($sql, $params);
1871 foreach ($categories as &$category) {
1872 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1873 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key
));
1874 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1882 * Adds a structured category to the navigation in the correct order/place
1884 * @param stdClass $category category to be added in navigation.
1885 * @param navigation_node $parent parent navigation node
1886 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1889 protected function add_category(stdClass
$category, navigation_node
$parent, $nodetype = self
::TYPE_CATEGORY
) {
1890 if (array_key_exists($category->id
, $this->addedcategories
)) {
1893 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id
));
1894 $context = context_coursecat
::instance($category->id
);
1895 $categoryname = format_string($category->name
, true, array('context' => $context));
1896 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id
);
1897 if (empty($category->visible
)) {
1898 if (has_capability('moodle/category:viewhiddencategories', context_system
::instance())) {
1899 $categorynode->hidden
= true;
1901 $categorynode->display
= false;
1904 $this->addedcategories
[$category->id
] = $categorynode;
1908 * Loads the given course into the navigation
1910 * @param stdClass $course
1911 * @return navigation_node
1913 protected function load_course(stdClass
$course) {
1915 if ($course->id
== $SITE->id
) {
1916 // This is always loaded during initialisation
1917 return $this->rootnodes
['site'];
1918 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
1919 // The course has already been loaded so return a reference
1920 return $this->addedcourses
[$course->id
];
1923 return $this->add_course($course);
1928 * Loads all of the courses section into the navigation.
1930 * This function calls method from current course format, see
1931 * {@link format_base::extend_course_navigation()}
1932 * If course module ($cm) is specified but course format failed to create the node,
1933 * the activity node is created anyway.
1935 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1937 * @param stdClass $course Database record for the course
1938 * @param navigation_node $coursenode The course node within the navigation
1939 * @param null|int $sectionnum If specified load the contents of section with this relative number
1940 * @param null|cm_info $cm If specified make sure that activity node is created (either
1941 * in containg section or by calling load_stealth_activity() )
1943 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode, $sectionnum = null, $cm = null) {
1945 require_once($CFG->dirroot
.'/course/lib.php');
1946 if (isset($cm->sectionnum
)) {
1947 $sectionnum = $cm->sectionnum
;
1949 if ($sectionnum !== null) {
1950 $this->includesectionnum
= $sectionnum;
1952 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1953 if (isset($cm->id
)) {
1954 $activity = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
1955 if (empty($activity)) {
1956 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1962 * Generates an array of sections and an array of activities for the given course.
1964 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1966 * @param stdClass $course
1967 * @return array Array($sections, $activities)
1969 protected function generate_sections_and_activities(stdClass
$course) {
1971 require_once($CFG->dirroot
.'/course/lib.php');
1973 $modinfo = get_fast_modinfo($course);
1974 $sections = $modinfo->get_section_info_all();
1976 // For course formats using 'numsections' trim the sections list
1977 $courseformatoptions = course_get_format($course)->get_format_options();
1978 if (isset($courseformatoptions['numsections'])) {
1979 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+
1, true);
1982 $activities = array();
1984 foreach ($sections as $key => $section) {
1985 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1986 $sections[$key] = clone($section);
1987 unset($sections[$key]->summary
);
1988 $sections[$key]->hasactivites
= false;
1989 if (!array_key_exists($section->section
, $modinfo->sections
)) {
1992 foreach ($modinfo->sections
[$section->section
] as $cmid) {
1993 $cm = $modinfo->cms
[$cmid];
1994 $activity = new stdClass
;
1995 $activity->id
= $cm->id
;
1996 $activity->course
= $course->id
;
1997 $activity->section
= $section->section
;
1998 $activity->name
= $cm->name
;
1999 $activity->icon
= $cm->icon
;
2000 $activity->iconcomponent
= $cm->iconcomponent
;
2001 $activity->hidden
= (!$cm->visible
);
2002 $activity->modname
= $cm->modname
;
2003 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2004 $activity->onclick
= $cm->onclick
;
2007 $activity->url
= null;
2008 $activity->display
= false;
2010 $activity->url
= $url->out();
2011 $activity->display
= $cm->is_visible_on_course_page() ?
true : false;
2012 if (self
::module_extends_navigation($cm->modname
)) {
2013 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2016 $activities[$cmid] = $activity;
2017 if ($activity->display
) {
2018 $sections[$key]->hasactivites
= true;
2023 return array($sections, $activities);
2027 * Generically loads the course sections into the course's navigation.
2029 * @param stdClass $course
2030 * @param navigation_node $coursenode
2031 * @return array An array of course section nodes
2033 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode) {
2034 global $CFG, $DB, $USER, $SITE;
2035 require_once($CFG->dirroot
.'/course/lib.php');
2037 list($sections, $activities) = $this->generate_sections_and_activities($course);
2039 $navigationsections = array();
2040 foreach ($sections as $sectionid => $section) {
2041 $section = clone($section);
2042 if ($course->id
== $SITE->id
) {
2043 $this->load_section_activities($coursenode, $section->section
, $activities);
2045 if (!$section->uservisible ||
(!$this->showemptysections
&&
2046 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
2050 $sectionname = get_section_name($course, $section);
2051 $url = course_get_url($course, $section->section
, array('navigation' => true));
2053 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
,
2054 null, $section->id
, new pix_icon('i/section', ''));
2055 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2056 $sectionnode->hidden
= (!$section->visible ||
!$section->available
);
2057 if ($this->includesectionnum
!== false && $this->includesectionnum
== $section->section
) {
2058 $this->load_section_activities($sectionnode, $section->section
, $activities);
2060 $section->sectionnode
= $sectionnode;
2061 $navigationsections[$sectionid] = $section;
2064 return $navigationsections;
2068 * Loads all of the activities for a section into the navigation structure.
2070 * @param navigation_node $sectionnode
2071 * @param int $sectionnumber
2072 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2073 * @param stdClass $course The course object the section and activities relate to.
2074 * @return array Array of activity nodes
2076 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2078 // A static counter for JS function naming
2079 static $legacyonclickcounter = 0;
2081 $activitynodes = array();
2082 if (empty($activities)) {
2083 return $activitynodes;
2086 if (!is_object($course)) {
2087 $activity = reset($activities);
2088 $courseid = $activity->course
;
2090 $courseid = $course->id
;
2092 $showactivities = ($courseid != $SITE->id ||
!empty($CFG->navshowfrontpagemods
));
2094 foreach ($activities as $activity) {
2095 if ($activity->section
!= $sectionnumber) {
2098 if ($activity->icon
) {
2099 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2101 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2104 // Prepare the default name and url for the node
2105 $activityname = format_string($activity->name
, true, array('context' => context_module
::instance($activity->id
)));
2106 $action = new moodle_url($activity->url
);
2108 // Check if the onclick property is set (puke!)
2109 if (!empty($activity->onclick
)) {
2110 // Increment the counter so that we have a unique number.
2111 $legacyonclickcounter++
;
2112 // Generate the function name we will use
2113 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2114 $propogrationhandler = '';
2115 // Check if we need to cancel propogation. Remember inline onclick
2116 // events would return false if they wanted to prevent propogation and the
2118 if (strpos($activity->onclick
, 'return false')) {
2119 $propogrationhandler = 'e.halt();';
2121 // Decode the onclick - it has already been encoded for display (puke)
2122 $onclick = htmlspecialchars_decode($activity->onclick
, ENT_QUOTES
);
2123 // Build the JS function the click event will call
2124 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2125 $this->page
->requires
->js_amd_inline($jscode);
2126 // Override the default url with the new action link
2127 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2130 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2131 $activitynode->title(get_string('modulename', $activity->modname
));
2132 $activitynode->hidden
= $activity->hidden
;
2133 $activitynode->display
= $showactivities && $activity->display
;
2134 $activitynode->nodetype
= $activity->nodetype
;
2135 $activitynodes[$activity->id
] = $activitynode;
2138 return $activitynodes;
2141 * Loads a stealth module from unavailable section
2142 * @param navigation_node $coursenode
2143 * @param stdClass $modinfo
2144 * @return navigation_node or null if not accessible
2146 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2147 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2150 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2152 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2154 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2157 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2158 $activitynode->title(get_string('modulename', $cm->modname
));
2159 $activitynode->hidden
= (!$cm->visible
);
2160 if (!$cm->is_visible_on_course_page()) {
2161 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2162 // Also there may be no exception at all in case when teacher is logged in as student.
2163 $activitynode->display
= false;
2165 // Don't show activities that don't have links!
2166 $activitynode->display
= false;
2167 } else if (self
::module_extends_navigation($cm->modname
)) {
2168 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2170 return $activitynode;
2173 * Loads the navigation structure for the given activity into the activities node.
2175 * This method utilises a callback within the modules lib.php file to load the
2176 * content specific to activity given.
2178 * The callback is a method: {modulename}_extend_navigation()
2180 * * {@link forum_extend_navigation()}
2181 * * {@link workshop_extend_navigation()}
2183 * @param cm_info|stdClass $cm
2184 * @param stdClass $course
2185 * @param navigation_node $activity
2188 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2191 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2192 if (!($cm instanceof cm_info
)) {
2193 $modinfo = get_fast_modinfo($course);
2194 $cm = $modinfo->get_cm($cm->id
);
2196 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2197 $activity->make_active();
2198 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2199 $function = $cm->modname
.'_extend_navigation';
2201 if (file_exists($file)) {
2202 require_once($file);
2203 if (function_exists($function)) {
2204 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2205 $function($activity, $course, $activtyrecord, $cm);
2209 // Allow the active advanced grading method plugin to append module navigation
2210 $featuresfunc = $cm->modname
.'_supports';
2211 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2212 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2213 $gradingman = get_grading_manager($cm->context
, 'mod_'.$cm->modname
);
2214 $gradingman->extend_navigation($this, $activity);
2217 return $activity->has_children();
2220 * Loads user specific information into the navigation in the appropriate place.
2222 * If no user is provided the current user is assumed.
2224 * @param stdClass $user
2225 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2228 protected function load_for_user($user=null, $forceforcontext=false) {
2229 global $DB, $CFG, $USER, $SITE;
2231 require_once($CFG->dirroot
. '/course/lib.php');
2233 if ($user === null) {
2234 // We can't require login here but if the user isn't logged in we don't
2235 // want to show anything
2236 if (!isloggedin() ||
isguestuser()) {
2240 } else if (!is_object($user)) {
2241 // If the user is not an object then get them from the database
2242 $select = context_helper
::get_preload_record_columns_sql('ctx');
2243 $sql = "SELECT u.*, $select
2245 JOIN {context} ctx ON u.id = ctx.instanceid
2246 WHERE u.id = :userid AND
2247 ctx.contextlevel = :contextlevel";
2248 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2249 context_helper
::preload_from_record($user);
2252 $iscurrentuser = ($user->id
== $USER->id
);
2254 $usercontext = context_user
::instance($user->id
);
2256 // Get the course set against the page, by default this will be the site
2257 $course = $this->page
->course
;
2258 $baseargs = array('id'=>$user->id
);
2259 if ($course->id
!= $SITE->id
&& (!$iscurrentuser ||
$forceforcontext)) {
2260 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
2261 $baseargs['course'] = $course->id
;
2262 $coursecontext = context_course
::instance($course->id
);
2263 $issitecourse = false;
2265 // Load all categories and get the context for the system
2266 $coursecontext = context_system
::instance();
2267 $issitecourse = true;
2270 // Create a node to add user information under.
2272 if (!$issitecourse) {
2273 // Not the current user so add it to the participants node for the current course.
2274 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2275 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2276 } else if ($USER->id
!= $user->id
) {
2277 // This is the site so add a users node to the root branch.
2278 $usersnode = $this->rootnodes
['users'];
2279 if (course_can_view_participants($coursecontext)) {
2280 $usersnode->action
= new moodle_url('/user/index.php', array('id' => $course->id
));
2282 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2285 // We should NEVER get here, if the course hasn't been populated
2286 // with a participants node then the navigaiton either wasn't generated
2287 // for it (you are missing a require_login or set_context call) or
2288 // you don't have access.... in the interests of no leaking informatin
2289 // we simply quit...
2292 // Add a branch for the current user.
2293 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2294 $viewprofile = true;
2295 if (!$iscurrentuser) {
2296 require_once($CFG->dirroot
. '/user/lib.php');
2297 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& !has_capability('moodle/user:viewdetails', $usercontext) ) {
2298 $viewprofile = false;
2299 } else if ($this->page
->context
->contextlevel
!= CONTEXT_USER
&& !user_can_view_profile($user, $course, $usercontext)) {
2300 $viewprofile = false;
2302 if (!$viewprofile) {
2303 $viewprofile = user_can_view_profile($user, null, $usercontext);
2307 // Now, conditionally add the user node.
2309 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2310 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, 'user' . $user->id
);
2312 $usernode = $usersnode->add(get_string('user'));
2315 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2316 $usernode->make_active();
2319 // Add user information to the participants or user node.
2320 if ($issitecourse) {
2322 // If the user is the current user or has permission to view the details of the requested
2323 // user than add a view profile link.
2324 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
2325 has_capability('moodle/user:viewdetails', $usercontext)) {
2326 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2327 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2329 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2333 if (!empty($CFG->navadduserpostslinks
)) {
2334 // Add nodes for forum posts and discussions if the user can view either or both
2335 // There are no capability checks here as the content of the page is based
2336 // purely on the forums the current user has access too.
2337 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2338 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2339 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2340 array_merge($baseargs, array('mode' => 'discussions'))));
2344 if (!empty($CFG->enableblogs
)) {
2345 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2346 require_once($CFG->dirroot
.'/blog/lib.php');
2347 // Get all options for the user.
2348 $options = blog_get_options_for_user($user);
2349 $this->cache
->set('userblogoptions'.$user->id
, $options);
2351 $options = $this->cache
->{'userblogoptions'.$user->id
};
2354 if (count($options) > 0) {
2355 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2356 foreach ($options as $type => $option) {
2357 if ($type == "rss") {
2358 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null,
2359 new pix_icon('i/rss', ''));
2361 $blogs->add($option['string'], $option['link']);
2367 // Add the messages link.
2368 // It is context based so can appear in the user's profile and in course participants information.
2369 if (!empty($CFG->messaging
)) {
2370 $messageargs = array('user1' => $USER->id
);
2371 if ($USER->id
!= $user->id
) {
2372 $messageargs['user2'] = $user->id
;
2374 $url = new moodle_url('/message/index.php', $messageargs);
2375 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2378 // Add the "My private files" link.
2379 // This link doesn't have a unique display for course context so only display it under the user's profile.
2380 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2381 $url = new moodle_url('/user/files.php');
2382 $usernode->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
2385 // Add a node to view the users notes if permitted.
2386 if (!empty($CFG->enablenotes
) &&
2387 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2388 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
2389 if ($coursecontext->instanceid
!= SITEID
) {
2390 $url->param('course', $coursecontext->instanceid
);
2392 $usernode->add(get_string('notes', 'notes'), $url);
2395 // Show the grades node.
2396 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2397 require_once($CFG->dirroot
. '/user/lib.php');
2398 // Set the grades node to link to the "Grades" page.
2399 if ($course->id
== SITEID
) {
2400 $url = user_mygrades_url($user->id
, $course->id
);
2401 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2402 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
2404 if ($USER->id
!= $user->id
) {
2405 $usernode->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'usergrades');
2407 $usernode->add(get_string('grades', 'grades'), $url);
2411 // If the user is the current user add the repositories for the current user.
2412 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2413 if (!$iscurrentuser &&
2414 $course->id
== $SITE->id
&&
2415 has_capability('moodle/user:viewdetails', $usercontext) &&
2416 (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2418 // Add view grade report is permitted.
2419 $reports = core_component
::get_plugin_list('gradereport');
2420 arsort($reports); // User is last, we want to test it first.
2422 $userscourses = enrol_get_users_courses($user->id
, false, '*');
2423 $userscoursesnode = $usernode->add(get_string('courses'));
2426 foreach ($userscourses as $usercourse) {
2427 if ($count === (int)$CFG->navcourselimit
) {
2428 $url = new moodle_url('/user/profile.php', array('id' => $user->id
, 'showallcourses' => 1));
2429 $userscoursesnode->add(get_string('showallcourses'), $url);
2433 $usercoursecontext = context_course
::instance($usercourse->id
);
2434 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2435 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2436 array('id' => $user->id
, 'course' => $usercourse->id
)), self
::TYPE_CONTAINER
);
2438 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2439 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2440 foreach ($reports as $plugin => $plugindir) {
2441 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2442 // Stop when the first visible plugin is found.
2443 $gradeavailable = true;
2449 if ($gradeavailable) {
2450 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id
));
2451 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null,
2452 new pix_icon('i/grades', ''));
2455 // Add a node to view the users notes if permitted.
2456 if (!empty($CFG->enablenotes
) &&
2457 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2458 $url = new moodle_url('/notes/index.php', array('user' => $user->id
, 'course' => $usercourse->id
));
2459 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2462 if (can_access_course($usercourse, $user->id
, '', true)) {
2463 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2464 array('id' => $usercourse->id
)), self
::TYPE_SETTING
, null, null, new pix_icon('i/course', ''));
2467 $reporttab = $usercoursenode->add(get_string('activityreports'));
2469 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2470 foreach ($reportfunctions as $reportfunction) {
2471 $reportfunction($reporttab, $user, $usercourse);
2474 $reporttab->trim_if_empty();
2478 // Let plugins hook into user navigation.
2479 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2480 foreach ($pluginsfunction as $plugintype => $plugins) {
2481 if ($plugintype != 'report') {
2482 foreach ($plugins as $pluginfunction) {
2483 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2492 * This method simply checks to see if a given module can extend the navigation.
2494 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2496 * @param string $modname
2499 public static function module_extends_navigation($modname) {
2501 static $extendingmodules = array();
2502 if (!array_key_exists($modname, $extendingmodules)) {
2503 $extendingmodules[$modname] = false;
2504 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2505 if (file_exists($file)) {
2506 $function = $modname.'_extend_navigation';
2507 require_once($file);
2508 $extendingmodules[$modname] = (function_exists($function));
2511 return $extendingmodules[$modname];
2514 * Extends the navigation for the given user.
2516 * @param stdClass $user A user from the database
2518 public function extend_for_user($user) {
2519 $this->extendforuser
[] = $user;
2523 * Returns all of the users the navigation is being extended for
2525 * @return array An array of extending users.
2527 public function get_extending_users() {
2528 return $this->extendforuser
;
2531 * Adds the given course to the navigation structure.
2533 * @param stdClass $course
2534 * @param bool $forcegeneric
2535 * @param bool $ismycourse
2536 * @return navigation_node
2538 public function add_course(stdClass
$course, $forcegeneric = false, $coursetype = self
::COURSE_OTHER
) {
2541 // We found the course... we can return it now :)
2542 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2543 return $this->addedcourses
[$course->id
];
2546 $coursecontext = context_course
::instance($course->id
);
2548 if ($course->id
!= $SITE->id
&& !$course->visible
) {
2549 if (is_role_switched($course->id
)) {
2550 // user has to be able to access course in order to switch, let's skip the visibility test here
2551 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2556 $issite = ($course->id
== $SITE->id
);
2557 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2558 $fullname = format_string($course->fullname
, true, array('context' => $coursecontext));
2559 // This is the name that will be shown for the course.
2560 $coursename = empty($CFG->navshowfullcoursenames
) ?
$shortname : $fullname;
2562 if ($coursetype == self
::COURSE_CURRENT
) {
2563 if ($coursenode = $this->rootnodes
['mycourses']->find($course->id
, self
::TYPE_COURSE
)) {
2566 $coursetype = self
::COURSE_OTHER
;
2570 // Can the user expand the course to see its content.
2571 $canexpandcourse = true;
2575 if (empty($CFG->usesitenameforsitepages
)) {
2576 $coursename = get_string('sitepages');
2578 } else if ($coursetype == self
::COURSE_CURRENT
) {
2579 $parent = $this->rootnodes
['currentcourse'];
2580 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2581 $canexpandcourse = $this->can_expand_course($course);
2582 } else if ($coursetype == self
::COURSE_MY
&& !$forcegeneric) {
2583 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_MY_CATEGORY
))) {
2584 // Nothing to do here the above statement set $parent to the category within mycourses.
2586 $parent = $this->rootnodes
['mycourses'];
2588 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2590 $parent = $this->rootnodes
['courses'];
2591 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2592 // They can only expand the course if they can access it.
2593 $canexpandcourse = $this->can_expand_course($course);
2594 if (!empty($course->category
) && $this->show_categories($coursetype == self
::COURSE_MY
)) {
2595 if (!$this->is_category_fully_loaded($course->category
)) {
2596 // We need to load the category structure for this course
2597 $this->load_all_categories($course->category
, false);
2599 if (array_key_exists($course->category
, $this->addedcategories
)) {
2600 $parent = $this->addedcategories
[$course->category
];
2601 // This could lead to the course being created so we should check whether it is the case again
2602 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2603 return $this->addedcourses
[$course->id
];
2609 $coursenode = $parent->add($coursename, $url, self
::TYPE_COURSE
, $shortname, $course->id
, new pix_icon('i/course', ''));
2610 $coursenode->showinflatnavigation
= $coursetype == self
::COURSE_MY
;
2612 $coursenode->hidden
= (!$course->visible
);
2613 $coursenode->title(format_string($course->fullname
, true, array('context' => $coursecontext, 'escape' => false)));
2614 if ($canexpandcourse) {
2615 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2616 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2617 $coursenode->isexpandable
= true;
2619 $coursenode->nodetype
= self
::NODETYPE_LEAF
;
2620 $coursenode->isexpandable
= false;
2622 if (!$forcegeneric) {
2623 $this->addedcourses
[$course->id
] = $coursenode;
2630 * Returns a cache instance to use for the expand course cache.
2631 * @return cache_session
2633 protected function get_expand_course_cache() {
2634 if ($this->cacheexpandcourse
=== null) {
2635 $this->cacheexpandcourse
= cache
::make('core', 'navigation_expandcourse');
2637 return $this->cacheexpandcourse
;
2641 * Checks if a user can expand a course in the navigation.
2643 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2644 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2645 * permits stale data.
2646 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2648 * It is brought up to date in only one of two ways.
2649 * 1. The user logs out and in again.
2650 * 2. The user browses to the course they've just being given access to.
2652 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2654 * @param stdClass $course
2657 protected function can_expand_course($course) {
2658 $cache = $this->get_expand_course_cache();
2659 $canexpand = $cache->get($course->id
);
2660 if ($canexpand === false) {
2661 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2662 $canexpand = (int)$canexpand;
2663 $cache->set($course->id
, $canexpand);
2665 return ($canexpand === 1);
2669 * Returns true if the category has already been loaded as have any child categories
2671 * @param int $categoryid
2674 protected function is_category_fully_loaded($categoryid) {
2675 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2679 * Adds essential course nodes to the navigation for the given course.
2681 * This method adds nodes such as reports, blogs and participants
2683 * @param navigation_node $coursenode
2684 * @param stdClass $course
2685 * @return bool returns true on successful addition of a node.
2687 public function add_course_essentials($coursenode, stdClass
$course) {
2689 require_once($CFG->dirroot
. '/course/lib.php');
2691 if ($course->id
== $SITE->id
) {
2692 return $this->add_front_page_course_essentials($coursenode, $course);
2695 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2699 $navoptions = course_get_user_navigation_options($this->page
->context
, $course);
2702 if ($navoptions->participants
) {
2703 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
),
2704 self
::TYPE_CONTAINER
, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2706 if ($navoptions->blogs
) {
2707 $blogsurls = new moodle_url('/blog/index.php');
2708 if ($currentgroup = groups_get_course_group($course, true)) {
2709 $blogsurls->param('groupid', $currentgroup);
2711 $blogsurls->param('courseid', $course->id
);
2713 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self
::TYPE_SETTING
, null, 'courseblogs');
2716 if ($navoptions->notes
) {
2717 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id
)), self
::TYPE_SETTING
, null, 'currentcoursenotes');
2719 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2720 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2724 if ($navoptions->badges
) {
2725 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id
));
2727 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2728 navigation_node
::TYPE_SETTING
, null, 'badgesview',
2729 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2732 // Check access to the course and competencies page.
2733 if ($navoptions->competencies
) {
2734 // Just a link to course competency.
2735 $title = get_string('competencies', 'core_competency');
2736 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id
));
2737 $coursenode->add($title, $path, navigation_node
::TYPE_SETTING
, null, 'competencies',
2738 new pix_icon('i/competencies', ''));
2740 if ($navoptions->grades
) {
2741 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
2742 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null,
2743 'grades', new pix_icon('i/grades', ''));
2744 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2745 if ($this->page
->context
->contextlevel
< CONTEXT_MODULE
&& strpos($this->page
->pagetype
, 'grade-') === 0) {
2746 $gradenode->make_active();
2753 * This generates the structure of the course that won't be generated when
2754 * the modules and sections are added.
2756 * Things such as the reports branch, the participants branch, blogs... get
2757 * added to the course node by this method.
2759 * @param navigation_node $coursenode
2760 * @param stdClass $course
2761 * @return bool True for successfull generation
2763 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2764 global $CFG, $USER, $COURSE, $SITE;
2765 require_once($CFG->dirroot
. '/course/lib.php');
2767 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2771 $sitecontext = context_system
::instance();
2772 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2774 // Hidden node that we use to determine if the front page navigation is loaded.
2775 // This required as there are not other guaranteed nodes that may be loaded.
2776 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2779 if ($navoptions->participants
) {
2780 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
2784 if ($navoptions->blogs
) {
2785 $blogsurls = new moodle_url('/blog/index.php');
2786 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self
::TYPE_SYSTEM
, null, 'siteblog');
2792 if ($navoptions->badges
) {
2793 $url = new moodle_url($CFG->wwwroot
. '/badges/view.php', array('type' => 1));
2794 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node
::TYPE_CUSTOM
);
2798 if ($navoptions->notes
) {
2799 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2800 array('filtertype' => 'course', 'filterselect' => $filterselect)), self
::TYPE_SETTING
, null, 'notes');
2804 if ($navoptions->tags
) {
2805 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2806 self
::TYPE_SETTING
, null, 'tags');
2810 if ($navoptions->search
) {
2811 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2812 self
::TYPE_SETTING
, null, 'search');
2815 if ($navoptions->calendar
) {
2816 $courseid = $COURSE->id
;
2817 $params = array('view' => 'month');
2818 if ($courseid != $SITE->id
) {
2819 $params['course'] = $courseid;
2823 $calendarurl = new moodle_url('/calendar/view.php', $params);
2824 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2825 self
::TYPE_CUSTOM
, null, 'calendar', new pix_icon('i/calendar', ''));
2826 $node->showinflatnavigation
= true;
2830 $usercontext = context_user
::instance($USER->id
);
2831 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2832 $url = new moodle_url('/user/files.php');
2833 $node = $coursenode->add(get_string('privatefiles'), $url,
2834 self
::TYPE_SETTING
, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
2835 $node->display
= false;
2836 $node->showinflatnavigation
= true;
2844 * Clears the navigation cache
2846 public function clear_cache() {
2847 $this->cache
->clear();
2851 * Sets an expansion limit for the navigation
2853 * The expansion limit is used to prevent the display of content that has a type
2854 * greater than the provided $type.
2856 * Can be used to ensure things such as activities or activity content don't get
2857 * shown on the navigation.
2858 * They are still generated in order to ensure the navbar still makes sense.
2860 * @param int $type One of navigation_node::TYPE_*
2861 * @return bool true when complete.
2863 public function set_expansion_limit($type) {
2865 $nodes = $this->find_all_of_type($type);
2867 // We only want to hide specific types of nodes.
2868 // Only nodes that represent "structure" in the navigation tree should be hidden.
2869 // If we hide all nodes then we risk hiding vital information.
2870 $typestohide = array(
2871 self
::TYPE_CATEGORY
,
2877 foreach ($nodes as $node) {
2878 // We need to generate the full site node
2879 if ($type == self
::TYPE_COURSE
&& $node->key
== $SITE->id
) {
2882 foreach ($node->children
as $child) {
2883 $child->hide($typestohide);
2889 * Attempts to get the navigation with the given key from this nodes children.
2891 * This function only looks at this nodes children, it does NOT look recursivily.
2892 * If the node can't be found then false is returned.
2894 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2896 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2897 * may be of more use to you.
2899 * @param string|int $key The key of the node you wish to receive.
2900 * @param int $type One of navigation_node::TYPE_*
2901 * @return navigation_node|false
2903 public function get($key, $type = null) {
2904 if (!$this->initialised
) {
2905 $this->initialise();
2907 return parent
::get($key, $type);
2911 * Searches this nodes children and their children to find a navigation node
2912 * with the matching key and type.
2914 * This method is recursive and searches children so until either a node is
2915 * found or there are no more nodes to search.
2917 * If you know that the node being searched for is a child of this node
2918 * then use the {@link global_navigation::get()} method instead.
2920 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2921 * may be of more use to you.
2923 * @param string|int $key The key of the node you wish to receive.
2924 * @param int $type One of navigation_node::TYPE_*
2925 * @return navigation_node|false
2927 public function find($key, $type) {
2928 if (!$this->initialised
) {
2929 $this->initialise();
2931 if ($type == self
::TYPE_ROOTNODE
&& array_key_exists($key, $this->rootnodes
)) {
2932 return $this->rootnodes
[$key];
2934 return parent
::find($key, $type);
2938 * They've expanded the 'my courses' branch.
2940 protected function load_courses_enrolled() {
2943 $limit = (int) $CFG->navcourselimit
;
2945 $courses = enrol_get_my_courses('*');
2946 $flatnavcourses = [];
2948 // Go through the courses and see which ones we want to display in the flatnav.
2949 foreach ($courses as $course) {
2950 $classify = course_classify_for_timeline($course);
2952 if ($classify == COURSE_TIMELINE_INPROGRESS
) {
2953 $flatnavcourses[$course->id
] = $course;
2957 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2958 $numtotalcourses = count($courses);
2959 $numtotalflatnavcourses = count($flatnavcourses);
2961 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2962 $courses = array_slice($courses, 0, $limit, true);
2963 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
2965 // Get the number of courses we are going to show for each.
2966 $numshowncourses = count($courses);
2967 $numshownflatnavcourses = count($flatnavcourses);
2968 if ($numshowncourses && $this->show_my_categories()) {
2969 // Generate an array containing unique values of all the courses' categories.
2970 $categoryids = array();
2971 foreach ($courses as $course) {
2972 if (in_array($course->category
, $categoryids)) {
2975 $categoryids[] = $course->category
;
2978 // Array of category IDs that include the categories of the user's courses and the related course categories.
2979 $fullpathcategoryids = [];
2980 // Get the course categories for the enrolled courses' category IDs.
2981 require_once('coursecatlib.php');
2982 $mycoursecategories = coursecat
::get_many($categoryids);
2983 // Loop over each of these categories and build the category tree using each category's path.
2984 foreach ($mycoursecategories as $mycoursecat) {
2985 $pathcategoryids = explode('/', $mycoursecat->path
);
2986 // First element of the exploded path is empty since paths begin with '/'.
2987 array_shift($pathcategoryids);
2988 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
2989 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
2992 // Fetch all of the categories related to the user's courses.
2993 $pathcategories = coursecat
::get_many($fullpathcategoryids);
2994 // Loop over each of these categories and build the category tree.
2995 foreach ($pathcategories as $coursecat) {
2996 // No need to process categories that have already been added.
2997 if (isset($this->addedcategories
[$coursecat->id
])) {
3001 // Get this course category's parent node.
3003 if ($coursecat->parent
&& isset($this->addedcategories
[$coursecat->parent
])) {
3004 $parent = $this->addedcategories
[$coursecat->parent
];
3007 // If it has no parent, then it should be right under the My courses node.
3008 $parent = $this->rootnodes
['mycourses'];
3011 // Build the category object based from the coursecat object.
3012 $mycategory = new stdClass();
3013 $mycategory->id
= $coursecat->id
;
3014 $mycategory->name
= $coursecat->name
;
3015 $mycategory->visible
= $coursecat->visible
;
3017 // Add this category to the nav tree.
3018 $this->add_category($mycategory, $parent, self
::TYPE_MY_CATEGORY
);
3022 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3023 foreach ($courses as $course) {
3024 $node = $this->add_course($course, false, self
::COURSE_MY
);
3026 $node->showinflatnavigation
= false;
3027 // Check if we should also add this to the flat nav as well.
3028 if (isset($flatnavcourses[$course->id
])) {
3029 $node->showinflatnavigation
= true;
3034 // Go through each course in the flatnav now.
3035 foreach ($flatnavcourses as $course) {
3036 // Check if we haven't already added it.
3037 if (!isset($courses[$course->id
])) {
3038 // Ok, add it to the flatnav only.
3039 $node = $this->add_course($course, false, self
::COURSE_MY
);
3040 $node->display
= false;
3041 $node->showinflatnavigation
= true;
3045 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3046 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3047 // Show a link to the course page if there are more courses the user is enrolled in.
3048 if ($showmorelinkinnav ||
$showmorelinkinflatnav) {
3049 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3050 $url = new moodle_url('/my/?myoverviewtab=courses');
3051 $parent = $this->rootnodes
['mycourses'];
3052 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self
::TYPE_CUSTOM
, null, self
::COURSE_INDEX_PAGE
);
3054 if ($showmorelinkinnav) {
3055 $coursenode->display
= true;
3058 if ($showmorelinkinflatnav) {
3059 $coursenode->showinflatnavigation
= true;
3066 * The global navigation class used especially for AJAX requests.
3068 * The primary methods that are used in the global navigation class have been overriden
3069 * to ensure that only the relevant branch is generated at the root of the tree.
3070 * This can be done because AJAX is only used when the backwards structure for the
3071 * requested branch exists.
3072 * This has been done only because it shortens the amounts of information that is generated
3073 * which of course will speed up the response time.. because no one likes laggy AJAX.
3076 * @category navigation
3077 * @copyright 2009 Sam Hemelryk
3078 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3080 class global_navigation_for_ajax
extends global_navigation
{
3082 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3083 protected $branchtype;
3085 /** @var int the instance id */
3086 protected $instanceid;
3088 /** @var array Holds an array of expandable nodes */
3089 protected $expandable = array();
3092 * Constructs the navigation for use in an AJAX request
3094 * @param moodle_page $page moodle_page object
3095 * @param int $branchtype
3098 public function __construct($page, $branchtype, $id) {
3099 $this->page
= $page;
3100 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3101 $this->children
= new navigation_node_collection();
3102 $this->branchtype
= $branchtype;
3103 $this->instanceid
= $id;
3104 $this->initialise();
3107 * Initialise the navigation given the type and id for the branch to expand.
3109 * @return array An array of the expandable nodes
3111 public function initialise() {
3114 if ($this->initialised ||
during_initial_install()) {
3115 return $this->expandable
;
3117 $this->initialised
= true;
3119 $this->rootnodes
= array();
3120 $this->rootnodes
['site'] = $this->add_course($SITE);
3121 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self
::TYPE_ROOTNODE
, null, 'mycourses');
3122 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
3123 // The courses branch is always displayed, and is always expandable (although may be empty).
3124 // This mimicks what is done during {@link global_navigation::initialise()}.
3125 $this->rootnodes
['courses']->isexpandable
= true;
3127 // Branchtype will be one of navigation_node::TYPE_*
3128 switch ($this->branchtype
) {
3130 if ($this->instanceid
=== 'mycourses') {
3131 $this->load_courses_enrolled();
3132 } else if ($this->instanceid
=== 'courses') {
3133 $this->load_courses_other();
3136 case self
::TYPE_CATEGORY
:
3137 $this->load_category($this->instanceid
);
3139 case self
::TYPE_MY_CATEGORY
:
3140 $this->load_category($this->instanceid
, self
::TYPE_MY_CATEGORY
);
3142 case self
::TYPE_COURSE
:
3143 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
3144 if (!can_access_course($course, null, '', true)) {
3145 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3146 // add the course node and break. This leads to an empty node.
3147 $this->add_course($course);
3150 require_course_login($course, true, null, false, true);
3151 $this->page
->set_context(context_course
::instance($course->id
));
3152 $coursenode = $this->add_course($course);
3153 $this->add_course_essentials($coursenode, $course);
3154 $this->load_course_sections($course, $coursenode);
3156 case self
::TYPE_SECTION
:
3157 $sql = 'SELECT c.*, cs.section AS sectionnumber
3159 LEFT JOIN {course_sections} cs ON cs.course = c.id
3161 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
3162 require_course_login($course, true, null, false, true);
3163 $this->page
->set_context(context_course
::instance($course->id
));
3164 $coursenode = $this->add_course($course);
3165 $this->add_course_essentials($coursenode, $course);
3166 $this->load_course_sections($course, $coursenode, $course->sectionnumber
);
3168 case self
::TYPE_ACTIVITY
:
3171 JOIN {course_modules} cm ON cm.course = c.id
3172 WHERE cm.id = :cmid";
3173 $params = array('cmid' => $this->instanceid
);
3174 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3175 $modinfo = get_fast_modinfo($course);
3176 $cm = $modinfo->get_cm($this->instanceid
);
3177 require_course_login($course, true, $cm, false, true);
3178 $this->page
->set_context(context_module
::instance($cm->id
));
3179 $coursenode = $this->load_course($course);
3180 $this->load_course_sections($course, $coursenode, null, $cm);
3181 $activitynode = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
3182 if ($activitynode) {
3183 $modulenode = $this->load_activity($cm, $course, $activitynode);
3187 throw new Exception('Unknown type');
3188 return $this->expandable
;
3191 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
) {
3192 $this->load_for_user(null, true);
3195 $this->find_expandable($this->expandable
);
3196 return $this->expandable
;
3200 * They've expanded the general 'courses' branch.
3202 protected function load_courses_other() {
3203 $this->load_all_courses();
3207 * Loads a single category into the AJAX navigation.
3209 * This function is special in that it doesn't concern itself with the parent of
3210 * the requested category or its siblings.
3211 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3214 * @global moodle_database $DB
3215 * @param int $categoryid id of category to load in navigation.
3216 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3219 protected function load_category($categoryid, $nodetype = self
::TYPE_CATEGORY
) {
3223 if (!empty($CFG->navcourselimit
)) {
3224 $limit = (int)$CFG->navcourselimit
;
3227 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
3228 $sql = "SELECT cc.*, $catcontextsql
3229 FROM {course_categories} cc
3230 JOIN {context} ctx ON cc.id = ctx.instanceid
3231 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
3232 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3233 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3234 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3235 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3236 $categorylist = array();
3237 $subcategories = array();
3238 $basecategory = null;
3239 foreach ($categories as $category) {
3240 $categorylist[] = $category->id
;
3241 context_helper
::preload_from_record($category);
3242 if ($category->id
== $categoryid) {
3243 $this->add_category($category, $this, $nodetype);
3244 $basecategory = $this->addedcategories
[$category->id
];
3246 $subcategories[$category->id
] = $category;
3249 $categories->close();
3252 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3253 // else show all courses.
3254 if ($nodetype === self
::TYPE_MY_CATEGORY
) {
3255 $courses = enrol_get_my_courses('*');
3256 $categoryids = array();
3258 // Only search for categories if basecategory was found.
3259 if (!is_null($basecategory)) {
3260 // Get course parent category ids.
3261 foreach ($courses as $course) {
3262 $categoryids[] = $course->category
;
3265 // Get a unique list of category ids which a part of the path
3266 // to user's courses.
3267 $coursesubcategories = array();
3268 $addedsubcategories = array();
3270 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3271 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3273 foreach ($categories as $category){
3274 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path
, "/")));
3276 $categories->close();
3277 $coursesubcategories = array_unique($coursesubcategories);
3279 // Only add a subcategory if it is part of the path to user's course and
3280 // wasn't already added.
3281 foreach ($subcategories as $subid => $subcategory) {
3282 if (in_array($subid, $coursesubcategories) &&
3283 !in_array($subid, $addedsubcategories)) {
3284 $this->add_category($subcategory, $basecategory, $nodetype);
3285 $addedsubcategories[] = $subid;
3290 foreach ($courses as $course) {
3291 // Add course if it's in category.
3292 if (in_array($course->category
, $categorylist)) {
3293 $this->add_course($course, true, self
::COURSE_MY
);
3297 if (!is_null($basecategory)) {
3298 foreach ($subcategories as $key=>$category) {
3299 $this->add_category($category, $basecategory, $nodetype);
3302 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3303 foreach ($courses as $course) {
3304 $this->add_course($course);
3311 * Returns an array of expandable nodes
3314 public function get_expandable() {
3315 return $this->expandable
;
3322 * This class is used to manage the navbar, which is initialised from the navigation
3323 * object held by PAGE
3326 * @category navigation
3327 * @copyright 2009 Sam Hemelryk
3328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3330 class navbar
extends navigation_node
{
3331 /** @var bool A switch for whether the navbar is initialised or not */
3332 protected $initialised = false;
3333 /** @var mixed keys used to reference the nodes on the navbar */
3334 protected $keys = array();
3335 /** @var null|string content of the navbar */
3336 protected $content = null;
3337 /** @var moodle_page object the moodle page that this navbar belongs to */
3339 /** @var bool A switch for whether to ignore the active navigation information */
3340 protected $ignoreactive = false;
3341 /** @var bool A switch to let us know if we are in the middle of an install */
3342 protected $duringinstall = false;
3343 /** @var bool A switch for whether the navbar has items */
3344 protected $hasitems = false;
3345 /** @var array An array of navigation nodes for the navbar */
3347 /** @var array An array of child node objects */
3348 public $children = array();
3349 /** @var bool A switch for whether we want to include the root node in the navbar */
3350 public $includesettingsbase = false;
3351 /** @var breadcrumb_navigation_node[] $prependchildren */
3352 protected $prependchildren = array();
3355 * The almighty constructor
3357 * @param moodle_page $page
3359 public function __construct(moodle_page
$page) {
3361 if (during_initial_install()) {
3362 $this->duringinstall
= true;
3365 $this->page
= $page;
3366 $this->text
= get_string('home');
3367 $this->shorttext
= get_string('home');
3368 $this->action
= new moodle_url($CFG->wwwroot
);
3369 $this->nodetype
= self
::NODETYPE_BRANCH
;
3370 $this->type
= self
::TYPE_SYSTEM
;
3374 * Quick check to see if the navbar will have items in.
3376 * @return bool Returns true if the navbar will have items, false otherwise
3378 public function has_items() {
3379 if ($this->duringinstall
) {
3381 } else if ($this->hasitems
!== false) {
3384 if (count($this->children
) > 0 ||
count($this->prependchildren
) > 0) {
3385 // There have been manually added items - there are definitely items.
3387 } else if (!$this->ignoreactive
) {
3388 // We will need to initialise the navigation structure to check if there are active items.
3389 $this->page
->navigation
->initialise($this->page
);
3390 $outcome = ($this->page
->navigation
->contains_active_node() ||
$this->page
->settingsnav
->contains_active_node());
3392 $this->hasitems
= $outcome;
3397 * Turn on/off ignore active
3399 * @param bool $setting
3401 public function ignore_active($setting=true) {
3402 $this->ignoreactive
= ($setting);
3406 * Gets a navigation node
3408 * @param string|int $key for referencing the navbar nodes
3409 * @param int $type breadcrumb_navigation_node::TYPE_*
3410 * @return breadcrumb_navigation_node|bool
3412 public function get($key, $type = null) {
3413 foreach ($this->children
as &$child) {
3414 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3418 foreach ($this->prependchildren
as &$child) {
3419 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3426 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3430 public function get_items() {
3433 // Make sure that navigation is initialised
3434 if (!$this->has_items()) {
3437 if ($this->items
!== null) {
3438 return $this->items
;
3441 if (count($this->children
) > 0) {
3442 // Add the custom children.
3443 $items = array_reverse($this->children
);
3446 // Check if navigation contains the active node
3447 if (!$this->ignoreactive
) {
3448 // We will need to ensure the navigation has been initialised.
3449 $this->page
->navigation
->initialise($this->page
);
3450 // Now find the active nodes on both the navigation and settings.
3451 $navigationactivenode = $this->page
->navigation
->find_active_node();
3452 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3454 if ($navigationactivenode && $settingsactivenode) {
3455 // Parse a combined navigation tree
3456 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3457 if (!$settingsactivenode->mainnavonly
) {
3458 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3460 $settingsactivenode = $settingsactivenode->parent
;
3462 if (!$this->includesettingsbase
) {
3463 // Removes the first node from the settings (root node) from the list
3466 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3467 if (!$navigationactivenode->mainnavonly
) {
3468 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3470 if (!empty($CFG->navshowcategories
) &&
3471 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3472 $navigationactivenode->parent
->key
=== 'currentcourse') {
3473 foreach ($this->get_course_categories() as $item) {
3474 $items[] = new breadcrumb_navigation_node($item);
3477 $navigationactivenode = $navigationactivenode->parent
;
3479 } else if ($navigationactivenode) {
3480 // Parse the navigation tree to get the active node
3481 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3482 if (!$navigationactivenode->mainnavonly
) {
3483 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3485 if (!empty($CFG->navshowcategories
) &&
3486 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3487 $navigationactivenode->parent
->key
=== 'currentcourse') {
3488 foreach ($this->get_course_categories() as $item) {
3489 $items[] = new breadcrumb_navigation_node($item);
3492 $navigationactivenode = $navigationactivenode->parent
;
3494 } else if ($settingsactivenode) {
3495 // Parse the settings navigation to get the active node
3496 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3497 if (!$settingsactivenode->mainnavonly
) {
3498 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3500 $settingsactivenode = $settingsactivenode->parent
;
3505 $items[] = new breadcrumb_navigation_node(array(
3506 'text' => $this->page
->navigation
->text
,
3507 'shorttext' => $this->page
->navigation
->shorttext
,
3508 'key' => $this->page
->navigation
->key
,
3509 'action' => $this->page
->navigation
->action
3512 if (count($this->prependchildren
) > 0) {
3513 // Add the custom children
3514 $items = array_merge($items, array_reverse($this->prependchildren
));
3517 $last = reset($items);
3519 $last->set_last(true);
3521 $this->items
= array_reverse($items);
3522 return $this->items
;
3526 * Get the list of categories leading to this course.
3528 * This function is used by {@link navbar::get_items()} to add back the "courses"
3529 * node and category chain leading to the current course. Note that this is only ever
3530 * called for the current course, so we don't need to bother taking in any parameters.
3534 private function get_course_categories() {
3536 require_once($CFG->dirroot
.'/course/lib.php');
3537 require_once($CFG->libdir
.'/coursecatlib.php');
3539 $categories = array();
3540 $cap = 'moodle/category:viewhiddencategories';
3541 $showcategories = coursecat
::count_all() > 1;
3543 if ($showcategories) {
3544 foreach ($this->page
->categories
as $category) {
3545 if (!$category->visible
&& !has_capability($cap, get_category_or_system_context($category->parent
))) {
3548 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id
));
3549 $name = format_string($category->name
, true, array('context' => context_coursecat
::instance($category->id
)));
3550 $categorynode = breadcrumb_navigation_node
::create($name, $url, self
::TYPE_CATEGORY
, null, $category->id
);
3551 if (!$category->visible
) {
3552 $categorynode->hidden
= true;
3554 $categories[] = $categorynode;
3558 // Don't show the 'course' node if enrolled in this course.
3559 if (!is_enrolled(context_course
::instance($this->page
->course
->id
, null, '', true))) {
3560 $courses = $this->page
->navigation
->get('courses');
3562 // Courses node may not be present.
3563 $courses = breadcrumb_navigation_node
::create(
3564 get_string('courses'),
3565 new moodle_url('/course/index.php'),
3566 self
::TYPE_CONTAINER
3569 $categories[] = $courses;
3576 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3578 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3579 * the way nodes get added to allow us to simply call add and have the node added to the
3582 * @param string $text
3583 * @param string|moodle_url|action_link $action An action to associate with this node.
3584 * @param int $type One of navigation_node::TYPE_*
3585 * @param string $shorttext
3586 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3587 * @param pix_icon $icon An optional icon to use for this node.
3588 * @return navigation_node
3590 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3591 if ($this->content
!== null) {
3592 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3595 // Properties array used when creating the new navigation node
3600 // Set the action if one was provided
3601 if ($action!==null) {
3602 $itemarray['action'] = $action;
3604 // Set the shorttext if one was provided
3605 if ($shorttext!==null) {
3606 $itemarray['shorttext'] = $shorttext;
3608 // Set the icon if one was provided
3610 $itemarray['icon'] = $icon;
3612 // Default the key to the number of children if not provided
3613 if ($key === null) {
3614 $key = count($this->children
);
3617 $itemarray['key'] = $key;
3618 // Set the parent to this node
3619 $itemarray['parent'] = $this;
3620 // Add the child using the navigation_node_collections add method
3621 $this->children
[] = new breadcrumb_navigation_node($itemarray);
3626 * Prepends a new navigation_node to the start of the navbar
3628 * @param string $text
3629 * @param string|moodle_url|action_link $action An action to associate with this node.
3630 * @param int $type One of navigation_node::TYPE_*
3631 * @param string $shorttext
3632 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3633 * @param pix_icon $icon An optional icon to use for this node.
3634 * @return navigation_node
3636 public function prepend($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3637 if ($this->content
!== null) {
3638 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3640 // Properties array used when creating the new navigation node.
3645 // Set the action if one was provided.
3646 if ($action!==null) {
3647 $itemarray['action'] = $action;
3649 // Set the shorttext if one was provided.
3650 if ($shorttext!==null) {
3651 $itemarray['shorttext'] = $shorttext;
3653 // Set the icon if one was provided.
3655 $itemarray['icon'] = $icon;
3657 // Default the key to the number of children if not provided.
3658 if ($key === null) {
3659 $key = count($this->children
);
3662 $itemarray['key'] = $key;
3663 // Set the parent to this node.
3664 $itemarray['parent'] = $this;
3665 // Add the child node to the prepend list.
3666 $this->prependchildren
[] = new breadcrumb_navigation_node($itemarray);
3672 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3673 * in particular adding extra metadata for search engine robots to leverage.
3676 * @category navigation
3677 * @copyright 2015 Brendan Heywood
3678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3680 class breadcrumb_navigation_node
extends navigation_node
{
3682 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3683 private $last = false;
3686 * A proxy constructor
3688 * @param mixed $navnode A navigation_node or an array
3690 public function __construct($navnode) {
3691 if (is_array($navnode)) {
3692 parent
::__construct($navnode);
3693 } else if ($navnode instanceof navigation_node
) {
3695 // Just clone everything.
3696 $objvalues = get_object_vars($navnode);
3697 foreach ($objvalues as $key => $value) {
3698 $this->$key = $value;
3701 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3709 public function is_last() {
3715 * @param $val boolean
3717 public function set_last($val) {
3723 * Subclass of navigation_node allowing different rendering for the flat navigation
3724 * in particular allowing dividers and indents.
3727 * @category navigation
3728 * @copyright 2016 Damyon Wiese
3729 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3731 class flat_navigation_node
extends navigation_node
{
3733 /** @var $indent integer The indent level */
3734 private $indent = 0;
3736 /** @var $showdivider bool Show a divider before this element */
3737 private $showdivider = false;
3740 * A proxy constructor
3742 * @param mixed $navnode A navigation_node or an array
3744 public function __construct($navnode, $indent) {
3745 if (is_array($navnode)) {
3746 parent
::__construct($navnode);
3747 } else if ($navnode instanceof navigation_node
) {
3749 // Just clone everything.
3750 $objvalues = get_object_vars($navnode);
3751 foreach ($objvalues as $key => $value) {
3752 $this->$key = $value;
3755 throw new coding_exception('Not a valid flat_navigation_node');
3757 $this->indent
= $indent;
3761 * Does this node represent a course section link.
3764 public function is_section() {
3765 return $this->type
== navigation_node
::TYPE_SECTION
;
3769 * In flat navigation - sections are active if we are looking at activities in the section.
3772 public function isactive() {
3775 if ($this->is_section()) {
3776 $active = $PAGE->navigation
->find_active_node();
3777 while ($active = $active->parent
) {
3778 if ($active->key
== $this->key
&& $active->type
== $this->type
) {
3783 return $this->isactive
;
3787 * Getter for "showdivider"
3790 public function showdivider() {
3791 return $this->showdivider
;
3795 * Setter for "showdivider"
3796 * @param $val boolean
3798 public function set_showdivider($val) {
3799 $this->showdivider
= $val;
3803 * Getter for "indent"
3806 public function get_indent() {
3807 return $this->indent
;
3811 * Setter for "indent"
3812 * @param $val boolean
3814 public function set_indent($val) {
3815 $this->indent
= $val;
3821 * Class used to generate a collection of navigation nodes most closely related
3822 * to the current page.
3825 * @copyright 2016 Damyon Wiese
3826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3828 class flat_navigation
extends navigation_node_collection
{
3829 /** @var moodle_page the moodle page that the navigation belongs to */
3835 * @param moodle_page $page
3837 public function __construct(moodle_page
&$page) {
3838 if (during_initial_install()) {
3841 $this->page
= $page;
3845 * Build the list of navigation nodes based on the current navigation and settings trees.
3848 public function initialise() {
3849 global $PAGE, $USER, $OUTPUT, $CFG;
3850 if (during_initial_install()) {
3856 $course = $PAGE->course
;
3858 $this->page
->navigation
->initialise();
3860 // First walk the nav tree looking for "flat_navigation" nodes.
3861 if ($course->id
> 1) {
3862 // It's a real course.
3863 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3865 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
3866 // This is the name that will be shown for the course.
3867 $coursename = empty($CFG->navshowfullcoursenames
) ?
3868 format_string($course->shortname
, true, array('context' => $coursecontext)) :
3869 format_string($course->fullname
, true, array('context' => $coursecontext));
3871 $flat = new flat_navigation_node(navigation_node
::create($coursename, $url), 0);
3872 $flat->key
= 'coursehome';
3873 $flat->icon
= new pix_icon('i/course', '');
3875 $courseformat = course_get_format($course);
3876 $coursenode = $PAGE->navigation
->find_active_node();
3877 $targettype = navigation_node
::TYPE_COURSE
;
3879 // Single activity format has no course node - the course node is swapped for the activity node.
3880 if (!$courseformat->has_view_page()) {
3881 $targettype = navigation_node
::TYPE_ACTIVITY
;
3884 while (!empty($coursenode) && ($coursenode->type
!= $targettype)) {
3885 $coursenode = $coursenode->parent
;
3887 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3888 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3889 if ($coursenode && $coursenode->key
!= SITEID
) {
3891 foreach ($coursenode->children
as $child) {
3892 if ($child->action
) {
3893 $flat = new flat_navigation_node($child, 0);
3899 $this->page
->navigation
->build_flat_navigation_list($this, true);
3901 $this->page
->navigation
->build_flat_navigation_list($this, false);
3904 $admin = $PAGE->settingsnav
->find('siteadministration', navigation_node
::TYPE_SITE_ADMIN
);
3906 // Try again - crazy nav tree!
3907 $admin = $PAGE->settingsnav
->find('root', navigation_node
::TYPE_SITE_ADMIN
);
3910 $flat = new flat_navigation_node($admin, 0);
3911 $flat->set_showdivider(true);
3912 $flat->key
= 'sitesettings';
3913 $flat->icon
= new pix_icon('t/preferences', '');
3917 // Add-a-block in editing mode.
3918 if (isset($this->page
->theme
->addblockposition
) &&
3919 $this->page
->theme
->addblockposition
== BLOCK_ADDBLOCK_POSITION_FLATNAV
&&
3920 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3921 ($addable = $PAGE->blocks
->get_addable_blocks())) {
3922 $url = new moodle_url($PAGE->url
, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3923 $addablock = navigation_node
::create(get_string('addblock'), $url);
3924 $flat = new flat_navigation_node($addablock, 0);
3925 $flat->set_showdivider(true);
3926 $flat->key
= 'addblock';
3927 $flat->icon
= new pix_icon('i/addblock', '');
3930 foreach ($addable as $block) {
3931 $blocks[] = $block->name
;
3933 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3934 $PAGE->requires
->js_call_amd('core/addblockmodal', 'init', array($params));
3941 * Class used to manage the settings option for the current page
3943 * This class is used to manage the settings options in a tree format (recursively)
3944 * and was created initially for use with the settings blocks.
3947 * @category navigation
3948 * @copyright 2009 Sam Hemelryk
3949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3951 class settings_navigation
extends navigation_node
{
3952 /** @var stdClass the current context */
3954 /** @var moodle_page the moodle page that the navigation belongs to */
3956 /** @var string contains administration section navigation_nodes */
3957 protected $adminsection;
3958 /** @var bool A switch to see if the navigation node is initialised */
3959 protected $initialised = false;
3960 /** @var array An array of users that the nodes can extend for. */
3961 protected $userstoextendfor = array();
3962 /** @var navigation_cache **/
3966 * Sets up the object with basic settings and preparse it for use
3968 * @param moodle_page $page
3970 public function __construct(moodle_page
&$page) {
3971 if (during_initial_install()) {
3974 $this->page
= $page;
3975 // Initialise the main navigation. It is most important that this is done
3976 // before we try anything
3977 $this->page
->navigation
->initialise();
3978 // Initialise the navigation cache
3979 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3980 $this->children
= new navigation_node_collection();
3984 * Initialise the settings navigation based on the current context
3986 * This function initialises the settings navigation tree for a given context
3987 * by calling supporting functions to generate major parts of the tree.
3990 public function initialise() {
3991 global $DB, $SESSION, $SITE;
3993 if (during_initial_install()) {
3995 } else if ($this->initialised
) {
3998 $this->id
= 'settingsnav';
3999 $this->context
= $this->page
->context
;
4001 $context = $this->context
;
4002 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4003 $this->load_block_settings();
4004 $context = $context->get_parent_context();
4005 $this->context
= $context;
4007 switch ($context->contextlevel
) {
4008 case CONTEXT_SYSTEM
:
4009 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4010 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4013 case CONTEXT_COURSECAT
:
4014 $this->load_category_settings();
4016 case CONTEXT_COURSE
:
4017 if ($this->page
->course
->id
!= $SITE->id
) {
4018 $this->load_course_settings(($context->id
== $this->context
->id
));
4020 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4023 case CONTEXT_MODULE
:
4024 $this->load_module_settings();
4025 $this->load_course_settings();
4028 if ($this->page
->course
->id
!= $SITE->id
) {
4029 $this->load_course_settings();
4034 $usersettings = $this->load_user_settings($this->page
->course
->id
);
4036 $adminsettings = false;
4037 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin
) ||
$SESSION->load_navigation_admin
)) {
4038 $isadminpage = $this->is_admin_tree_needed();
4040 if (has_capability('moodle/site:configview', context_system
::instance())) {
4041 if (has_capability('moodle/site:config', context_system
::instance())) {
4042 // Make sure this works even if config capability changes on the fly
4043 // and also make it fast for admin right after login.
4044 $SESSION->load_navigation_admin
= 1;
4046 $adminsettings = $this->load_administration_settings();
4049 } else if (!isset($SESSION->load_navigation_admin
)) {
4050 $adminsettings = $this->load_administration_settings();
4051 $SESSION->load_navigation_admin
= (int)($adminsettings->children
->count() > 0);
4053 } else if ($SESSION->load_navigation_admin
) {
4055 $adminsettings = $this->load_administration_settings();
4059 // Print empty navigation node, if needed.
4060 if ($SESSION->load_navigation_admin
&& !$isadminpage) {
4061 if ($adminsettings) {
4062 // Do not print settings tree on pages that do not need it, this helps with performance.
4063 $adminsettings->remove();
4064 $adminsettings = false;
4066 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4067 self
::TYPE_SITE_ADMIN
, null, 'siteadministration');
4068 $siteadminnode->id
= 'expandable_branch_' . $siteadminnode->type
. '_' .
4069 clean_param($siteadminnode->key
, PARAM_ALPHANUMEXT
);
4070 $siteadminnode->requiresajaxloading
= 'true';
4075 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $adminsettings) {
4076 $adminsettings->force_open();
4077 } else if ($context->contextlevel
== CONTEXT_USER
&& $usersettings) {
4078 $usersettings->force_open();
4081 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4082 $this->load_local_plugin_settings();
4084 foreach ($this->children
as $key=>$node) {
4085 if ($node->nodetype
== self
::NODETYPE_BRANCH
&& $node->children
->count() == 0) {
4086 // Site administration is shown as link.
4087 if (!empty($SESSION->load_navigation_admin
) && ($node->type
=== self
::TYPE_SITE_ADMIN
)) {
4093 $this->initialised
= true;
4096 * Override the parent function so that we can add preceeding hr's and set a
4097 * root node class against all first level element
4099 * It does this by first calling the parent's add method {@link navigation_node::add()}
4100 * and then proceeds to use the key to set class and hr
4102 * @param string $text text to be used for the link.
4103 * @param string|moodle_url $url url for the new node
4104 * @param int $type the type of node navigation_node::TYPE_*
4105 * @param string $shorttext
4106 * @param string|int $key a key to access the node by.
4107 * @param pix_icon $icon An icon that appears next to the node.
4108 * @return navigation_node with the new node added to it.
4110 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4111 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
4112 $node->add_class('root_node');
4117 * This function allows the user to add something to the start of the settings
4118 * navigation, which means it will be at the top of the settings navigation block
4120 * @param string $text text to be used for the link.
4121 * @param string|moodle_url $url url for the new node
4122 * @param int $type the type of node navigation_node::TYPE_*
4123 * @param string $shorttext
4124 * @param string|int $key a key to access the node by.
4125 * @param pix_icon $icon An icon that appears next to the node.
4126 * @return navigation_node $node with the new node added to it.
4128 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4129 $children = $this->children
;
4130 $childrenclass = get_class($children);
4131 $this->children
= new $childrenclass;
4132 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4133 foreach ($children as $child) {
4134 $this->children
->add($child);
4140 * Does this page require loading of full admin tree or is
4141 * it enough rely on AJAX?
4145 protected function is_admin_tree_needed() {
4146 if (self
::$loadadmintree) {
4147 // Usually external admin page or settings page.
4151 if ($this->page
->pagelayout
=== 'admin' or strpos($this->page
->pagetype
, 'admin-') === 0) {
4152 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4153 if ($this->page
->context
->contextlevel
!= CONTEXT_SYSTEM
) {
4163 * Load the site administration tree
4165 * This function loads the site administration tree by using the lib/adminlib library functions
4167 * @param navigation_node $referencebranch A reference to a branch in the settings
4169 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4170 * tree and start at the beginning
4171 * @return mixed A key to access the admin tree by
4173 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
4176 // Check if we are just starting to generate this navigation.
4177 if ($referencebranch === null) {
4179 // Require the admin lib then get an admin structure
4180 if (!function_exists('admin_get_root')) {
4181 require_once($CFG->dirroot
.'/lib/adminlib.php');
4183 $adminroot = admin_get_root(false, false);
4184 // This is the active section identifier
4185 $this->adminsection
= $this->page
->url
->param('section');
4187 // Disable the navigation from automatically finding the active node
4188 navigation_node
::$autofindactive = false;
4189 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self
::TYPE_SITE_ADMIN
, null, 'root');
4190 foreach ($adminroot->children
as $adminbranch) {
4191 $this->load_administration_settings($referencebranch, $adminbranch);
4193 navigation_node
::$autofindactive = true;
4195 // Use the admin structure to locate the active page
4196 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
4197 $currentnode = $this;
4198 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
4199 $currentnode = $currentnode->get($pathkey);
4202 $currentnode->make_active();
4205 $this->scan_for_active_node($referencebranch);
4207 return $referencebranch;
4208 } else if ($adminbranch->check_access()) {
4209 // We have a reference branch that we can access and is not hidden `hurrah`
4210 // Now we need to display it and any children it may have
4213 if ($adminbranch instanceof admin_settingpage
) {
4214 $url = new moodle_url('/'.$CFG->admin
.'/settings.php', array('section'=>$adminbranch->name
));
4215 } else if ($adminbranch instanceof admin_externalpage
) {
4216 $url = $adminbranch->url
;
4217 } else if (!empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
4218 $url = new moodle_url('/'.$CFG->admin
.'/category.php', array('category' => $adminbranch->name
));
4222 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
4224 if ($adminbranch->is_hidden()) {
4225 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
4226 $reference->add_class('hidden');
4228 $reference->display
= false;
4232 // Check if we are generating the admin notifications and whether notificiations exist
4233 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
4234 $reference->add_class('criticalnotification');
4236 // Check if this branch has children
4237 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
4238 foreach ($adminbranch->children
as $branch) {
4239 // Generate the child branches as well now using this branch as the reference
4240 $this->load_administration_settings($reference, $branch);
4243 $reference->icon
= new pix_icon('i/settings', '');
4249 * This function recursivily scans nodes until it finds the active node or there
4250 * are no more nodes.
4251 * @param navigation_node $node
4253 protected function scan_for_active_node(navigation_node
$node) {
4254 if (!$node->check_if_active() && $node->children
->count()>0) {
4255 foreach ($node->children
as &$child) {
4256 $this->scan_for_active_node($child);
4262 * Gets a navigation node given an array of keys that represent the path to
4265 * @param array $path
4266 * @return navigation_node|false
4268 protected function get_by_path(array $path) {
4269 $node = $this->get(array_shift($path));
4270 foreach ($path as $key) {
4277 * This function loads the course settings that are available for the user
4279 * @param bool $forceopen If set to true the course node will be forced open
4280 * @return navigation_node|false
4282 protected function load_course_settings($forceopen = false) {
4284 require_once($CFG->dirroot
. '/course/lib.php');
4286 $course = $this->page
->course
;
4287 $coursecontext = context_course
::instance($course->id
);
4288 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4290 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4292 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
4294 $coursenode->force_open();
4298 if ($adminoptions->update
) {
4299 // Add the course settings link
4300 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
4301 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, 'editsettings', new pix_icon('i/settings', ''));
4304 if ($this->page
->user_allowed_editing()) {
4305 // Add the turn on/off settings
4307 if ($this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
4308 // We are on the course page, retain the current page params e.g. section.
4309 $baseurl = clone($this->page
->url
);
4310 $baseurl->param('sesskey', sesskey());
4312 // Edit on the main course page.
4313 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id
, 'return'=>$this->page
->url
->out_as_local_url(false), 'sesskey'=>sesskey()));
4316 $editurl = clone($baseurl);
4317 if ($this->page
->user_is_editing()) {
4318 $editurl->param('edit', 'off');
4319 $editstring = get_string('turneditingoff');
4321 $editurl->param('edit', 'on');
4322 $editstring = get_string('turneditingon');
4324 $coursenode->add($editstring, $editurl, self
::TYPE_SETTING
, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4327 if ($adminoptions->editcompletion
) {
4328 // Add the course completion settings link
4329 $url = new moodle_url('/course/completion.php', array('id' => $course->id
));
4330 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self
::TYPE_SETTING
, null, null,
4331 new pix_icon('i/settings', ''));
4334 if (!$adminoptions->update
&& $adminoptions->tags
) {
4335 $url = new moodle_url('/course/tags.php', array('id' => $course->id
));
4336 $coursenode->add(get_string('coursetags', 'tag'), $url, self
::TYPE_SETTING
, null, 'coursetags', new pix_icon('i/settings', ''));
4340 enrol_add_course_navigation($coursenode, $course);
4343 if ($adminoptions->filters
) {
4344 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4345 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
4348 // View course reports.
4349 if ($adminoptions->reports
) {
4350 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, 'coursereports',
4351 new pix_icon('i/stats', ''));
4352 $coursereports = core_component
::get_plugin_list('coursereport');
4353 foreach ($coursereports as $report => $dir) {
4354 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
4355 if (file_exists($libfile)) {
4356 require_once($libfile);
4357 $reportfunction = $report.'_report_extend_navigation';
4358 if (function_exists($report.'_report_extend_navigation')) {
4359 $reportfunction($reportnav, $course, $coursecontext);
4364 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4365 foreach ($reports as $reportfunction) {
4366 $reportfunction($reportnav, $course, $coursecontext);
4370 // Check if we can view the gradebook's setup page.
4371 if ($adminoptions->gradebook
) {
4372 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id
));
4373 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self
::TYPE_SETTING
,
4374 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4377 // Add outcome if permitted
4378 if ($adminoptions->outcomes
) {
4379 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
4380 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
4383 //Add badges navigation
4384 if ($adminoptions->badges
) {
4385 require_once($CFG->libdir
.'/badgeslib.php');
4386 badges_add_course_navigation($coursenode, $course);
4389 // Backup this course
4390 if ($adminoptions->backup
) {
4391 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4392 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
4395 // Restore to this course
4396 if ($adminoptions->restore
) {
4397 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4398 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
4401 // Import data from other courses
4402 if ($adminoptions->import
) {
4403 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
4404 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/import', ''));
4407 // Publish course on a hub
4408 if ($adminoptions->publish
) {
4409 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
4410 $coursenode->add(get_string('publish', 'core_hub'), $url, self
::TYPE_SETTING
, null, 'publish',
4411 new pix_icon('i/publish', ''));
4414 // Reset this course
4415 if ($adminoptions->reset
) {
4416 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
4417 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, 'reset', new pix_icon('i/return', ''));
4421 require_once($CFG->libdir
. '/questionlib.php');
4422 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4424 if ($adminoptions->update
) {
4425 // Repository Instances
4426 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
4427 require_once($CFG->dirroot
. '/repository/lib.php');
4428 $editabletypes = repository
::get_editable_types($coursecontext);
4429 $haseditabletypes = !empty($editabletypes);
4430 unset($editabletypes);
4431 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
4433 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
4435 if ($haseditabletypes) {
4436 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
4437 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
4442 if ($adminoptions->files
) {
4443 // hidden in new courses and courses where legacy files were turned off
4444 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
4445 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/folder', ''));
4449 // Let plugins hook into course navigation.
4450 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4451 foreach ($pluginsfunction as $plugintype => $plugins) {
4452 // Ignore the report plugin as it was already loaded above.
4453 if ($plugintype == 'report') {
4456 foreach ($plugins as $pluginfunction) {
4457 $pluginfunction($coursenode, $course, $coursecontext);
4461 // Return we are done
4466 * This function calls the module function to inject module settings into the
4467 * settings navigation tree.
4469 * This only gets called if there is a corrosponding function in the modules
4472 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4474 * @return navigation_node|false
4476 protected function load_module_settings() {
4479 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
4480 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
4481 $this->page
->set_cm($cm, $this->page
->course
);
4484 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
4485 if (file_exists($file)) {
4486 require_once($file);
4489 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
), null, self
::TYPE_SETTING
, null, 'modulesettings');
4490 $modulenode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
4491 $modulenode->force_open();
4493 // Settings for the module
4494 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
4495 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => 1));
4496 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
4498 // Assign local roles
4499 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
4500 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
4501 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
4504 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
4505 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
4506 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
4508 // Check role permissions
4509 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
4510 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
4511 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
4514 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
4515 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
4516 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
4519 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4520 foreach ($reports as $reportfunction) {
4521 $reportfunction($modulenode, $this->page
->cm
);
4523 // Add a backup link
4524 $featuresfunc = $this->page
->activityname
.'_supports';
4525 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
4526 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
4527 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
4530 // Restore this activity
4531 $featuresfunc = $this->page
->activityname
.'_supports';
4532 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
4533 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
4534 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
4537 // Allow the active advanced grading method plugin to append its settings
4538 $featuresfunc = $this->page
->activityname
.'_supports';
4539 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
4540 require_once($CFG->dirroot
.'/grade/grading/lib.php');
4541 $gradingman = get_grading_manager($this->page
->cm
->context
, 'mod_'.$this->page
->activityname
);
4542 $gradingman->extend_settings_navigation($this, $modulenode);
4545 $function = $this->page
->activityname
.'_extend_settings_navigation';
4546 if (function_exists($function)) {
4547 $function($this, $modulenode);
4550 // Remove the module node if there are no children.
4551 if ($modulenode->children
->count() <= 0) {
4552 $modulenode->remove();
4559 * Loads the user settings block of the settings nav
4561 * This function is simply works out the userid and whether we need to load
4562 * just the current users profile settings, or the current user and the user the
4563 * current user is viewing.
4565 * This function has some very ugly code to work out the user, if anyone has
4566 * any bright ideas please feel free to intervene.
4568 * @param int $courseid The course id of the current course
4569 * @return navigation_node|false
4571 protected function load_user_settings($courseid = SITEID
) {
4574 if (isguestuser() ||
!isloggedin()) {
4578 $navusers = $this->page
->navigation
->get_extending_users();
4580 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
4582 foreach ($this->userstoextendfor
as $userid) {
4583 if ($userid == $USER->id
) {
4586 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4587 if (is_null($usernode)) {
4591 foreach ($navusers as $user) {
4592 if ($user->id
== $USER->id
) {
4595 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
4596 if (is_null($usernode)) {
4600 $this->generate_user_settings($courseid, $USER->id
);
4602 $usernode = $this->generate_user_settings($courseid, $USER->id
);
4608 * Extends the settings navigation for the given user.
4610 * Note: This method gets called automatically if you call
4611 * $PAGE->navigation->extend_for_user($userid)
4613 * @param int $userid
4615 public function extend_for_user($userid) {
4618 if (!in_array($userid, $this->userstoextendfor
)) {
4619 $this->userstoextendfor
[] = $userid;
4620 if ($this->initialised
) {
4621 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
4622 $children = array();
4623 foreach ($this->children
as $child) {
4624 $children[] = $child;
4626 array_unshift($children, array_pop($children));
4627 $this->children
= new navigation_node_collection();
4628 foreach ($children as $child) {
4629 $this->children
->add($child);
4636 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4637 * what can be shown/done
4639 * @param int $courseid The current course' id
4640 * @param int $userid The user id to load for
4641 * @param string $gstitle The string to pass to get_string for the branch title
4642 * @return navigation_node|false
4644 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4645 global $DB, $CFG, $USER, $SITE;
4647 if ($courseid != $SITE->id
) {
4648 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
4649 $course = $this->page
->course
;
4651 $select = context_helper
::get_preload_record_columns_sql('ctx');
4652 $sql = "SELECT c.*, $select
4654 JOIN {context} ctx ON c.id = ctx.instanceid
4655 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4656 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
4657 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
4658 context_helper
::preload_from_record($course);
4664 $coursecontext = context_course
::instance($course->id
); // Course context
4665 $systemcontext = context_system
::instance();
4666 $currentuser = ($USER->id
== $userid);
4670 $usercontext = context_user
::instance($user->id
); // User context
4672 $select = context_helper
::get_preload_record_columns_sql('ctx');
4673 $sql = "SELECT u.*, $select
4675 JOIN {context} ctx ON u.id = ctx.instanceid
4676 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4677 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
4678 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
4682 context_helper
::preload_from_record($user);
4684 // Check that the user can view the profile
4685 $usercontext = context_user
::instance($user->id
); // User context
4686 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4688 if ($course->id
== $SITE->id
) {
4689 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4690 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4694 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4695 $userisenrolled = is_enrolled($coursecontext, $user->id
, '', true);
4696 if ((!$canviewusercourse && !$canviewuser) ||
!$userisenrolled) {
4699 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4700 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
&& !$canviewuser) {
4701 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4702 if ($courseid == $this->page
->course
->id
) {
4703 $mygroups = get_fast_modinfo($this->page
->course
)->groups
;
4705 $mygroups = groups_get_user_groups($courseid);
4707 $usergroups = groups_get_user_groups($courseid, $userid);
4708 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4715 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
4718 $prefurl = new moodle_url('/user/preferences.php');
4719 if ($gstitle != 'usercurrentsettings') {
4721 $prefurl->param('userid', $userid);
4724 // Add a user setting branch.
4725 if ($gstitle == 'usercurrentsettings') {
4726 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_CONTAINER
, null, 'dashboard');
4727 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4729 $dashboard->display
= false;
4730 if (get_home_page() == HOMEPAGE_MY
) {
4731 $dashboard->mainnavonly
= true;
4734 $iscurrentuser = ($user->id
== $USER->id
);
4736 $baseargs = array('id' => $user->id
);
4737 if ($course->id
!= $SITE->id
&& !$iscurrentuser) {
4738 $baseargs['course'] = $course->id
;
4739 $issitecourse = false;
4741 // Load all categories and get the context for the system.
4742 $issitecourse = true;
4745 // Add the user profile to the dashboard.
4746 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4747 array('id' => $user->id
)), self
::TYPE_SETTING
, null, 'myprofile');
4749 if (!empty($CFG->navadduserpostslinks
)) {
4750 // Add nodes for forum posts and discussions if the user can view either or both
4751 // There are no capability checks here as the content of the page is based
4752 // purely on the forums the current user has access too.
4753 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4754 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4755 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4756 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4760 if (!empty($CFG->enableblogs
)) {
4761 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
4762 require_once($CFG->dirroot
.'/blog/lib.php');
4763 // Get all options for the user.
4764 $options = blog_get_options_for_user($user);
4765 $this->cache
->set('userblogoptions'.$user->id
, $options);
4767 $options = $this->cache
->{'userblogoptions'.$user->id
};
4770 if (count($options) > 0) {
4771 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
4772 foreach ($options as $type => $option) {
4773 if ($type == "rss") {
4774 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, null,
4775 new pix_icon('i/rss', ''));
4777 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, 'blog' . $type);
4783 // Add the messages link.
4784 // It is context based so can appear in the user's profile and in course participants information.
4785 if (!empty($CFG->messaging
)) {
4786 $messageargs = array('user1' => $USER->id
);
4787 if ($USER->id
!= $user->id
) {
4788 $messageargs['user2'] = $user->id
;
4790 $url = new moodle_url('/message/index.php', $messageargs);
4791 $dashboard->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
4794 // Add the "My private files" link.
4795 // This link doesn't have a unique display for course context so only display it under the user's profile.
4796 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4797 $url = new moodle_url('/user/files.php');
4798 $dashboard->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
4801 // Add a node to view the users notes if permitted.
4802 if (!empty($CFG->enablenotes
) &&
4803 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4804 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
4805 if ($coursecontext->instanceid
!= SITEID
) {
4806 $url->param('course', $coursecontext->instanceid
);
4808 $profilenode->add(get_string('notes', 'notes'), $url);
4811 // Show the grades node.
4812 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
4813 require_once($CFG->dirroot
. '/user/lib.php');
4814 // Set the grades node to link to the "Grades" page.
4815 if ($course->id
== SITEID
) {
4816 $url = user_mygrades_url($user->id
, $course->id
);
4817 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4818 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
4820 $dashboard->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'mygrades');
4823 // Let plugins hook into user navigation.
4824 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4825 foreach ($pluginsfunction as $plugintype => $plugins) {
4826 if ($plugintype != 'report') {
4827 foreach ($plugins as $pluginfunction) {
4828 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4833 $usersetting = navigation_node
::create(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
4834 $dashboard->add_node($usersetting);
4836 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
4837 $usersetting->display
= false;
4839 $usersetting->id
= 'usersettings';
4841 // Check if the user has been deleted.
4842 if ($user->deleted
) {
4843 if (!has_capability('moodle/user:update', $coursecontext)) {
4844 // We can't edit the user so just show the user deleted message.
4845 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
4847 // We can edit the user so show the user deleted message and link it to the profile.
4848 if ($course->id
== $SITE->id
) {
4849 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
4851 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
4853 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
4858 $userauthplugin = false;
4859 if (!empty($user->auth
)) {
4860 $userauthplugin = get_auth_plugin($user->auth
);
4863 $useraccount = $usersetting->add(get_string('useraccount'), null, self
::TYPE_CONTAINER
, null, 'useraccount');
4865 // Add the profile edit link.
4866 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4867 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) &&
4868 has_capability('moodle/user:update', $systemcontext)) {
4869 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
4870 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
4871 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4872 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4873 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4874 $url = $userauthplugin->edit_profile_url();
4876 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4878 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
4883 // Change password link.
4884 if ($userauthplugin && $currentuser && !\core\session\manager
::is_loggedinas() && !isguestuser() &&
4885 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4886 $passwordchangeurl = $userauthplugin->change_password_url();
4887 if (empty($passwordchangeurl)) {
4888 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
4890 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
, null, 'changepassword');
4893 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4894 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4895 has_capability('moodle/user:editprofile', $usercontext)) {
4896 $url = new moodle_url('/user/language.php', array('id' => $user->id
, 'course' => $course->id
));
4897 $useraccount->add(get_string('preferredlanguage'), $url, self
::TYPE_SETTING
, null, 'preferredlanguage');
4900 $pluginmanager = core_plugin_manager
::instance();
4901 $enabled = $pluginmanager->get_enabled_plugins('mod');
4902 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4903 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4904 has_capability('moodle/user:editprofile', $usercontext)) {
4905 $url = new moodle_url('/user/forum.php', array('id' => $user->id
, 'course' => $course->id
));
4906 $useraccount->add(get_string('forumpreferences'), $url, self
::TYPE_SETTING
);
4909 $editors = editors_get_enabled();
4910 if (count($editors) > 1) {
4911 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4912 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4913 has_capability('moodle/user:editprofile', $usercontext)) {
4914 $url = new moodle_url('/user/editor.php', array('id' => $user->id
, 'course' => $course->id
));
4915 $useraccount->add(get_string('editorpreferences'), $url, self
::TYPE_SETTING
);
4920 // Add "Course preferences" link.
4921 if (isloggedin() && !isguestuser($user)) {
4922 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4923 has_capability('moodle/user:editprofile', $usercontext)) {
4924 $url = new moodle_url('/user/course.php', array('id' => $user->id
, 'course' => $course->id
));
4925 $useraccount->add(get_string('coursepreferences'), $url, self
::TYPE_SETTING
, null, 'coursepreferences');
4929 // Add "Calendar preferences" link.
4930 if (isloggedin() && !isguestuser($user)) {
4931 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4932 has_capability('moodle/user:editprofile', $usercontext)) {
4933 $url = new moodle_url('/user/calendar.php', array('id' => $user->id
));
4934 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self
::TYPE_SETTING
, null, 'preferredcalendar');
4938 // View the roles settings.
4939 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4940 'moodle/role:manage'), $usercontext)) {
4941 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
4943 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
4944 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
4946 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
4948 if (!empty($assignableroles)) {
4949 $url = new moodle_url('/admin/roles/assign.php',
4950 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4951 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
4954 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
4955 $url = new moodle_url('/admin/roles/permissions.php',
4956 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4957 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4960 $url = new moodle_url('/admin/roles/check.php',
4961 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4962 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4966 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
4967 require_once($CFG->dirroot
. '/repository/lib.php');
4968 $editabletypes = repository
::get_editable_types($usercontext);
4969 $haseditabletypes = !empty($editabletypes);
4970 unset($editabletypes);
4971 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
4973 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
4975 if ($haseditabletypes) {
4976 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self
::TYPE_SETTING
);
4977 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4978 array('contextid' => $usercontext->id
)));
4982 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
4983 require_once($CFG->libdir
. '/portfoliolib.php');
4984 if (portfolio_has_visible_instances()) {
4985 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
4987 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
4988 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
4990 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
4991 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
4995 $enablemanagetokens = false;
4996 if (!empty($CFG->enablerssfeeds
)) {
4997 $enablemanagetokens = true;
4998 } else if (!is_siteadmin($USER->id
)
4999 && !empty($CFG->enablewebservices
)
5000 && has_capability('moodle/webservice:createtoken', context_system
::instance()) ) {
5001 $enablemanagetokens = true;
5004 if ($currentuser && $enablemanagetokens) {
5005 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
5006 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
5010 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) &&
5011 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
5012 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id
));
5013 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id
));
5014 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self
::TYPE_SETTING
);
5015 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self
::TYPE_SETTING
);
5019 if ($currentuser && !empty($CFG->enableblogs
)) {
5020 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
5021 if (has_capability('moodle/blog:view', $systemcontext)) {
5022 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5023 navigation_node
::TYPE_SETTING
);
5025 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 &&
5026 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5027 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5028 navigation_node
::TYPE_SETTING
);
5029 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5030 navigation_node
::TYPE_SETTING
);
5032 // Remove the blog node if empty.
5033 $blog->trim_if_empty();
5037 if ($currentuser && !empty($CFG->enablebadges
)) {
5038 $badges = $usersetting->add(get_string('badges'), null, navigation_node
::TYPE_CONTAINER
, null, 'badges');
5039 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5040 $url = new moodle_url('/badges/mybadges.php');
5041 $badges->add(get_string('managebadges', 'badges'), $url, self
::TYPE_SETTING
);
5043 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5044 navigation_node
::TYPE_SETTING
);
5045 if (!empty($CFG->badges_allowexternalbackpack
)) {
5046 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5047 navigation_node
::TYPE_SETTING
);
5051 // Let plugins hook into user settings navigation.
5052 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5053 foreach ($pluginsfunction as $plugintype => $plugins) {
5054 foreach ($plugins as $pluginfunction) {
5055 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5059 return $usersetting;
5063 * Loads block specific settings in the navigation
5065 * @return navigation_node
5067 protected function load_block_settings() {
5070 $blocknode = $this->add($this->context
->get_context_name(), null, self
::TYPE_SETTING
, null, 'blocksettings');
5071 $blocknode->force_open();
5073 // Assign local roles
5074 if (get_assignable_roles($this->context
, ROLENAME_ORIGINAL
)) {
5075 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $this->context
->id
));
5076 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null,
5077 'roles', new pix_icon('i/assignroles', ''));
5081 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
5082 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
5083 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null,
5084 'permissions', new pix_icon('i/permissions', ''));
5086 // Check role permissions
5087 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
5088 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
5089 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null,
5090 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5097 * Loads category specific settings in the navigation
5099 * @return navigation_node
5101 protected function load_category_settings() {
5104 // We can land here while being in the context of a block, in which case we
5105 // should get the parent context which should be the category one. See self::initialise().
5106 if ($this->context
->contextlevel
== CONTEXT_BLOCK
) {
5107 $catcontext = $this->context
->get_parent_context();
5109 $catcontext = $this->context
;
5112 // Let's make sure that we always have the right context when getting here.
5113 if ($catcontext->contextlevel
!= CONTEXT_COURSECAT
) {
5114 throw new coding_exception('Unexpected context while loading category settings.');
5117 $categorynodetype = navigation_node
::TYPE_CONTAINER
;
5118 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5119 $categorynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
5120 $categorynode->force_open();
5122 if (can_edit_in_category($catcontext->instanceid
)) {
5123 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid
));
5124 $editstring = get_string('managecategorythis');
5125 $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5128 if (has_capability('moodle/category:manage', $catcontext)) {
5129 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid
));
5130 $categorynode->add(get_string('editcategorythis'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
5132 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid
));
5133 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5136 // Assign local roles
5137 $assignableroles = get_assignable_roles($catcontext);
5138 if (!empty($assignableroles)) {
5139 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $catcontext->id
));
5140 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
5144 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5145 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid' => $catcontext->id
));
5146 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
5148 // Check role permissions
5149 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5150 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5151 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid' => $catcontext->id
));
5152 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5156 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5157 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5158 array('contextid' => $catcontext->id
)), self
::TYPE_SETTING
, null, 'cohort', new pix_icon('i/cohort', ''));
5162 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5163 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id
));
5164 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
5168 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5169 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id
));
5170 $categorynode->add(get_string('restorecourse', 'admin'), $url, self
::TYPE_SETTING
, null, 'restorecourse', new pix_icon('i/restore', ''));
5173 // Let plugins hook into category settings navigation.
5174 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5175 foreach ($pluginsfunction as $plugintype => $plugins) {
5176 foreach ($plugins as $pluginfunction) {
5177 $pluginfunction($categorynode, $catcontext);
5181 return $categorynode;
5185 * Determine whether the user is assuming another role
5187 * This function checks to see if the user is assuming another role by means of
5188 * role switching. In doing this we compare each RSW key (context path) against
5189 * the current context path. This ensures that we can provide the switching
5190 * options against both the course and any page shown under the course.
5192 * @return bool|int The role(int) if the user is in another role, false otherwise
5194 protected function in_alternative_role() {
5196 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
5197 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
5198 return $USER->access
['rsw'][$this->page
->context
->path
];
5200 foreach ($USER->access
['rsw'] as $key=>$role) {
5201 if (strpos($this->context
->path
,$key)===0) {
5210 * This function loads all of the front page settings into the settings navigation.
5211 * This function is called when the user is on the front page, or $COURSE==$SITE
5212 * @param bool $forceopen (optional)
5213 * @return navigation_node
5215 protected function load_front_page_settings($forceopen = false) {
5217 require_once($CFG->dirroot
. '/course/lib.php');
5219 $course = clone($SITE);
5220 $coursecontext = context_course
::instance($course->id
); // Course context
5221 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5223 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
5225 $frontpage->force_open();
5227 $frontpage->id
= 'frontpagesettings';
5229 if ($this->page
->user_allowed_editing()) {
5231 // Add the turn on/off settings
5232 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
5233 if ($this->page
->user_is_editing()) {
5234 $url->param('edit', 'off');
5235 $editstring = get_string('turneditingoff');
5237 $url->param('edit', 'on');
5238 $editstring = get_string('turneditingon');
5240 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5243 if ($adminoptions->update
) {
5244 // Add the course settings link
5245 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5246 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
5250 enrol_add_course_navigation($frontpage, $course);
5253 if ($adminoptions->filters
) {
5254 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
5255 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
5258 // View course reports.
5259 if ($adminoptions->reports
) {
5260 $frontpagenav = $frontpage->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, 'frontpagereports',
5261 new pix_icon('i/stats', ''));
5262 $coursereports = core_component
::get_plugin_list('coursereport');
5263 foreach ($coursereports as $report=>$dir) {
5264 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
5265 if (file_exists($libfile)) {
5266 require_once($libfile);
5267 $reportfunction = $report.'_report_extend_navigation';
5268 if (function_exists($report.'_report_extend_navigation')) {
5269 $reportfunction($frontpagenav, $course, $coursecontext);
5274 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5275 foreach ($reports as $reportfunction) {
5276 $reportfunction($frontpagenav, $course, $coursecontext);
5280 // Backup this course
5281 if ($adminoptions->backup
) {
5282 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
5283 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
5286 // Restore to this course
5287 if ($adminoptions->restore
) {
5288 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
5289 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
5293 require_once($CFG->libdir
. '/questionlib.php');
5294 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5297 if ($adminoptions->files
) {
5298 //hiden in new installs
5299 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
5300 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/folder', ''));
5303 // Let plugins hook into frontpage navigation.
5304 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5305 foreach ($pluginsfunction as $plugintype => $plugins) {
5306 foreach ($plugins as $pluginfunction) {
5307 $pluginfunction($frontpage, $course, $coursecontext);
5315 * This function gives local plugins an opportunity to modify the settings navigation.
5317 protected function load_local_plugin_settings() {
5319 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5320 $function($this, $this->context
);
5325 * This function marks the cache as volatile so it is cleared during shutdown
5327 public function clear_cache() {
5328 $this->cache
->volatile();
5332 * Checks to see if there are child nodes available in the specific user's preference node.
5333 * If so, then they have the appropriate permissions view this user's preferences.
5335 * @since Moodle 2.9.3
5336 * @param int $userid The user's ID.
5337 * @return bool True if child nodes exist to view, otherwise false.
5339 public function can_view_user_preferences($userid) {
5340 if (is_siteadmin()) {
5343 // See if any nodes are present in the preferences section for this user.
5344 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5345 if ($preferencenode && $preferencenode->has_children()) {
5346 // Run through each child node.
5347 foreach ($preferencenode->children
as $childnode) {
5348 // If the child node has children then this user has access to a link in the preferences page.
5349 if ($childnode->has_children()) {
5354 // No links found for the user to access on the preferences page.
5360 * Class used to populate site admin navigation for ajax.
5363 * @category navigation
5364 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5367 class settings_navigation_ajax
extends settings_navigation
{
5369 * Constructs the navigation for use in an AJAX request
5371 * @param moodle_page $page
5373 public function __construct(moodle_page
&$page) {
5374 $this->page
= $page;
5375 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
5376 $this->children
= new navigation_node_collection();
5377 $this->initialise();
5381 * Initialise the site admin navigation.
5383 * @return array An array of the expandable nodes
5385 public function initialise() {
5386 if ($this->initialised ||
during_initial_install()) {
5389 $this->context
= $this->page
->context
;
5390 $this->load_administration_settings();
5392 // Check if local plugins is adding node to site admin.
5393 $this->load_local_plugin_settings();
5395 $this->initialised
= true;
5400 * Simple class used to output a navigation branch in XML
5403 * @category navigation
5404 * @copyright 2009 Sam Hemelryk
5405 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5407 class navigation_json
{
5408 /** @var array An array of different node types */
5409 protected $nodetype = array('node','branch');
5410 /** @var array An array of node keys and types */
5411 protected $expandable = array();
5413 * Turns a branch and all of its children into XML
5415 * @param navigation_node $branch
5416 * @return string XML string
5418 public function convert($branch) {
5419 $xml = $this->convert_child($branch);
5423 * Set the expandable items in the array so that we have enough information
5424 * to attach AJAX events
5425 * @param array $expandable
5427 public function set_expandable($expandable) {
5428 foreach ($expandable as $node) {
5429 $this->expandable
[$node['key'].':'.$node['type']] = $node;
5433 * Recusively converts a child node and its children to XML for output
5435 * @param navigation_node $child The child to convert
5436 * @param int $depth Pointlessly used to track the depth of the XML structure
5437 * @return string JSON
5439 protected function convert_child($child, $depth=1) {
5440 if (!$child->display
) {
5443 $attributes = array();
5444 $attributes['id'] = $child->id
;
5445 $attributes['name'] = (string)$child->text
; // This can be lang_string object so typecast it.
5446 $attributes['type'] = $child->type
;
5447 $attributes['key'] = $child->key
;
5448 $attributes['class'] = $child->get_css_type();
5449 $attributes['requiresajaxloading'] = $child->requiresajaxloading
;
5451 if ($child->icon
instanceof pix_icon
) {
5452 $attributes['icon'] = array(
5453 'component' => $child->icon
->component
,
5454 'pix' => $child->icon
->pix
,
5456 foreach ($child->icon
->attributes
as $key=>$value) {
5457 if ($key == 'class') {
5458 $attributes['icon']['classes'] = explode(' ', $value);
5459 } else if (!array_key_exists($key, $attributes['icon'])) {
5460 $attributes['icon'][$key] = $value;
5464 } else if (!empty($child->icon
)) {
5465 $attributes['icon'] = (string)$child->icon
;
5468 if ($child->forcetitle ||
$child->title
!== $child->text
) {
5469 $attributes['title'] = htmlentities($child->title
, ENT_QUOTES
, 'UTF-8');
5471 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
5472 $attributes['expandable'] = $child->key
;
5473 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
5476 if (count($child->classes
)>0) {
5477 $attributes['class'] .= ' '.join(' ',$child->classes
);
5479 if (is_string($child->action
)) {
5480 $attributes['link'] = $child->action
;
5481 } else if ($child->action
instanceof moodle_url
) {
5482 $attributes['link'] = $child->action
->out();
5483 } else if ($child->action
instanceof action_link
) {
5484 $attributes['link'] = $child->action
->url
->out();
5486 $attributes['hidden'] = ($child->hidden
);
5487 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
5488 $attributes['haschildren'] = $attributes['haschildren'] ||
$child->type
== navigation_node
::TYPE_MY_CATEGORY
;
5490 if ($child->children
->count() > 0) {
5491 $attributes['children'] = array();
5492 foreach ($child->children
as $subchild) {
5493 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
5500 return json_encode($attributes);
5506 * The cache class used by global navigation and settings navigation.
5508 * It is basically an easy access point to session with a bit of smarts to make
5509 * sure that the information that is cached is valid still.
5513 * if (!$cache->viewdiscussion()) {
5514 * // Code to do stuff and produce cachable content
5515 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5517 * $content = $cache->viewdiscussion;
5521 * @category navigation
5522 * @copyright 2009 Sam Hemelryk
5523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5525 class navigation_cache
{
5526 /** @var int represents the time created */
5527 protected $creation;
5528 /** @var array An array of session keys */
5531 * The string to use to segregate this particular cache. It can either be
5532 * unique to start a fresh cache or if you want to share a cache then make
5533 * it the string used in the original cache.
5537 /** @var int a time that the information will time out */
5539 /** @var stdClass The current context */
5540 protected $currentcontext;
5541 /** @var int cache time information */
5542 const CACHETIME
= 0;
5543 /** @var int cache user id */
5544 const CACHEUSERID
= 1;
5545 /** @var int cache value */
5546 const CACHEVALUE
= 2;
5547 /** @var null|array An array of navigation cache areas to expire on shutdown */
5548 public static $volatilecaches;
5551 * Contructor for the cache. Requires two arguments
5553 * @param string $area The string to use to segregate this particular cache
5554 * it can either be unique to start a fresh cache or if you want
5555 * to share a cache then make it the string used in the original
5557 * @param int $timeout The number of seconds to time the information out after
5559 public function __construct($area, $timeout=1800) {
5560 $this->creation
= time();
5561 $this->area
= $area;
5562 $this->timeout
= time() - $timeout;
5563 if (rand(0,100) === 0) {
5564 $this->garbage_collection();
5569 * Used to set up the cache within the SESSION.
5571 * This is called for each access and ensure that we don't put anything into the session before
5574 protected function ensure_session_cache_initialised() {
5576 if (empty($this->session
)) {
5577 if (!isset($SESSION->navcache
)) {
5578 $SESSION->navcache
= new stdClass
;
5580 if (!isset($SESSION->navcache
->{$this->area
})) {
5581 $SESSION->navcache
->{$this->area
} = array();
5583 $this->session
= &$SESSION->navcache
->{$this->area
}; // pointer to array, =& is correct here
5588 * Magic Method to retrieve something by simply calling using = cache->key
5590 * @param mixed $key The identifier for the information you want out again
5591 * @return void|mixed Either void or what ever was put in
5593 public function __get($key) {
5594 if (!$this->cached($key)) {
5597 $information = $this->session
[$key][self
::CACHEVALUE
];
5598 return unserialize($information);
5602 * Magic method that simply uses {@link set();} to store something in the cache
5604 * @param string|int $key
5605 * @param mixed $information
5607 public function __set($key, $information) {
5608 $this->set($key, $information);
5612 * Sets some information against the cache (session) for later retrieval
5614 * @param string|int $key
5615 * @param mixed $information
5617 public function set($key, $information) {
5619 $this->ensure_session_cache_initialised();
5620 $information = serialize($information);
5621 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
5624 * Check the existence of the identifier in the cache
5626 * @param string|int $key
5629 public function cached($key) {
5631 $this->ensure_session_cache_initialised();
5632 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
) {
5638 * Compare something to it's equivilant in the cache
5640 * @param string $key
5641 * @param mixed $value
5642 * @param bool $serialise Whether to serialise the value before comparison
5643 * this should only be set to false if the value is already
5645 * @return bool If the value is the same false if it is not set or doesn't match
5647 public function compare($key, $value, $serialise = true) {
5648 if ($this->cached($key)) {
5650 $value = serialize($value);
5652 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
5659 * Wipes the entire cache, good to force regeneration
5661 public function clear() {
5663 unset($SESSION->navcache
);
5664 $this->session
= null;
5667 * Checks all cache entries and removes any that have expired, good ole cleanup
5669 protected function garbage_collection() {
5670 if (empty($this->session
)) {
5673 foreach ($this->session
as $key=>$cachedinfo) {
5674 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
5675 unset($this->session
[$key]);
5681 * Marks the cache as being volatile (likely to change)
5683 * Any caches marked as volatile will be destroyed at the on shutdown by
5684 * {@link navigation_node::destroy_volatile_caches()} which is registered
5685 * as a shutdown function if any caches are marked as volatile.
5687 * @param bool $setting True to destroy the cache false not too
5689 public function volatile($setting = true) {
5690 if (self
::$volatilecaches===null) {
5691 self
::$volatilecaches = array();
5692 core_shutdown_manager
::register_function(array('navigation_cache','destroy_volatile_caches'));
5696 self
::$volatilecaches[$this->area
] = $this->area
;
5697 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
5698 unset(self
::$volatilecaches[$this->area
]);
5703 * Destroys all caches marked as volatile
5705 * This function is static and works in conjunction with the static volatilecaches
5706 * property of navigation cache.
5707 * Because this function is static it manually resets the cached areas back to an
5710 public static function destroy_volatile_caches() {
5712 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
5713 foreach (self
::$volatilecaches as $area) {
5714 $SESSION->navcache
->{$area} = array();
5717 $SESSION->navcache
= new stdClass
;