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 * Gets the CSS class to add to this node to describe its type
694 public function get_css_type() {
695 if (array_key_exists($this->type
, $this->namedtypes
)) {
696 return 'type_'.$this->namedtypes
[$this->type
];
698 return 'type_unknown';
702 * Finds all nodes that are expandable by AJAX
704 * @param array $expandable An array by reference to populate with expandable nodes.
706 public function find_expandable(array &$expandable) {
707 foreach ($this->children
as &$child) {
708 if ($child->display
&& $child->has_children() && $child->children
->count() == 0) {
709 $child->id
= 'expandable_branch_'.$child->type
.'_'.clean_param($child->key
, PARAM_ALPHANUMEXT
);
710 $this->add_class('canexpand');
711 $child->requiresajaxloading
= true;
712 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
714 $child->find_expandable($expandable);
719 * Finds all nodes of a given type (recursive)
721 * @param int $type One of navigation_node::TYPE_*
724 public function find_all_of_type($type) {
725 $nodes = $this->children
->type($type);
726 foreach ($this->children
as &$node) {
727 $childnodes = $node->find_all_of_type($type);
728 $nodes = array_merge($nodes, $childnodes);
734 * Removes this node if it is empty
736 public function trim_if_empty() {
737 if ($this->children
->count() == 0) {
743 * Creates a tab representation of this nodes children that can be used
744 * with print_tabs to produce the tabs on a page.
746 * call_user_func_array('print_tabs', $node->get_tabs_array());
748 * @param array $inactive
749 * @param bool $return
750 * @return array Array (tabs, selected, inactive, activated, return)
752 public function get_tabs_array(array $inactive=array(), $return=false) {
756 $activated = array();
757 foreach ($this->children
as $node) {
758 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
759 if ($node->contains_active_node()) {
760 if ($node->children
->count() > 0) {
761 $activated[] = $node->key
;
762 foreach ($node->children
as $child) {
763 if ($child->contains_active_node()) {
764 $selected = $child->key
;
766 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
769 $selected = $node->key
;
773 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
777 * Sets the parent for this node and if this node is active ensures that the tree is properly
780 * @param navigation_node $parent
782 public function set_parent(navigation_node
$parent) {
783 // Set the parent (thats the easy part)
784 $this->parent
= $parent;
785 // Check if this node is active (this is checked during construction)
786 if ($this->isactive
) {
787 // Force all of the parent nodes open so you can see this node
788 $this->parent
->force_open();
789 // Make all parents inactive so that its clear where we are.
790 $this->parent
->make_inactive();
795 * Hides the node and any children it has.
798 * @param array $typestohide Optional. An array of node types that should be hidden.
799 * If null all nodes will be hidden.
800 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
801 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
803 public function hide(array $typestohide = null) {
804 if ($typestohide === null ||
in_array($this->type
, $typestohide)) {
805 $this->display
= false;
806 if ($this->has_children()) {
807 foreach ($this->children
as $child) {
808 $child->hide($typestohide);
815 * Get the action url for this navigation node.
816 * Called from templates.
820 public function action() {
821 if ($this->action
instanceof moodle_url
) {
822 return $this->action
;
823 } else if ($this->action
instanceof action_link
) {
824 return $this->action
->url
;
826 return $this->action
;
831 * Navigation node collection
833 * This class is responsible for managing a collection of navigation nodes.
834 * It is required because a node's unique identifier is a combination of both its
837 * Originally an array was used with a string key that was a combination of the two
838 * however it was decided that a better solution would be to use a class that
839 * implements the standard IteratorAggregate interface.
842 * @category navigation
843 * @copyright 2010 Sam Hemelryk
844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
846 class navigation_node_collection
implements IteratorAggregate
, Countable
{
848 * A multidimensional array to where the first key is the type and the second
849 * key is the nodes key.
852 protected $collection = array();
854 * An array that contains references to nodes in the same order they were added.
855 * This is maintained as a progressive array.
858 protected $orderedcollection = array();
860 * A reference to the last node that was added to the collection
861 * @var navigation_node
863 protected $last = null;
865 * The total number of items added to this array.
868 protected $count = 0;
871 * Adds a navigation node to the collection
873 * @param navigation_node $node Node to add
874 * @param string $beforekey If specified, adds before a node with this key,
875 * otherwise adds at end
876 * @return navigation_node Added node
878 public function add(navigation_node
$node, $beforekey=null) {
883 // First check we have a 2nd dimension for this type
884 if (!array_key_exists($type, $this->orderedcollection
)) {
885 $this->orderedcollection
[$type] = array();
887 // Check for a collision and report if debugging is turned on
888 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
889 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
892 // Find the key to add before
893 $newindex = $this->count
;
895 if ($beforekey !== null) {
896 foreach ($this->collection
as $index => $othernode) {
897 if ($othernode->key
=== $beforekey) {
903 if ($newindex === $this->count
) {
904 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
905 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
909 // Add the node to the appropriate place in the by-type structure (which
910 // is not ordered, despite the variable name)
911 $this->orderedcollection
[$type][$key] = $node;
913 // Update existing references in the ordered collection (which is the
914 // one that isn't called 'ordered') to shuffle them along if required
915 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
916 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
919 // Add a reference to the node to the progressive collection.
920 $this->collection
[$newindex] = $this->orderedcollection
[$type][$key];
921 // Update the last property to a reference to this new node.
922 $this->last
= $this->orderedcollection
[$type][$key];
924 // Reorder the array by index if needed
926 ksort($this->collection
);
929 // Return the reference to the now added node
934 * Return a list of all the keys of all the nodes.
935 * @return array the keys.
937 public function get_key_list() {
939 foreach ($this->collection
as $node) {
940 $keys[] = $node->key
;
946 * Fetches a node from this collection.
948 * @param string|int $key The key of the node we want to find.
949 * @param int $type One of navigation_node::TYPE_*.
950 * @return navigation_node|null
952 public function get($key, $type=null) {
953 if ($type !== null) {
954 // If the type is known then we can simply check and fetch
955 if (!empty($this->orderedcollection
[$type][$key])) {
956 return $this->orderedcollection
[$type][$key];
959 // Because we don't know the type we look in the progressive array
960 foreach ($this->collection
as $node) {
961 if ($node->key
=== $key) {
970 * Searches for a node with matching key and type.
972 * This function searches both the nodes in this collection and all of
973 * the nodes in each collection belonging to the nodes in this collection.
977 * @param string|int $key The key of the node we want to find.
978 * @param int $type One of navigation_node::TYPE_*.
979 * @return navigation_node|null
981 public function find($key, $type=null) {
982 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
983 return $this->orderedcollection
[$type][$key];
985 $nodes = $this->getIterator();
986 // Search immediate children first
987 foreach ($nodes as &$node) {
988 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
992 // Now search each childs children
993 foreach ($nodes as &$node) {
994 $result = $node->children
->find($key, $type);
995 if ($result !== false) {
1004 * Fetches the last node that was added to this collection
1006 * @return navigation_node
1008 public function last() {
1013 * Fetches all nodes of a given type from this collection
1015 * @param string|int $type node type being searched for.
1016 * @return array ordered collection
1018 public function type($type) {
1019 if (!array_key_exists($type, $this->orderedcollection
)) {
1020 $this->orderedcollection
[$type] = array();
1022 return $this->orderedcollection
[$type];
1025 * Removes the node with the given key and type from the collection
1027 * @param string|int $key The key of the node we want to find.
1031 public function remove($key, $type=null) {
1032 $child = $this->get($key, $type);
1033 if ($child !== false) {
1034 foreach ($this->collection
as $colkey => $node) {
1035 if ($node->key
=== $key && (is_null($type) ||
$node->type
== $type)) {
1036 unset($this->collection
[$colkey]);
1037 $this->collection
= array_values($this->collection
);
1041 unset($this->orderedcollection
[$child->type
][$child->key
]);
1049 * Gets the number of nodes in this collection
1051 * This option uses an internal count rather than counting the actual options to avoid
1052 * a performance hit through the count function.
1056 public function count() {
1057 return $this->count
;
1060 * Gets an array iterator for the collection.
1062 * This is required by the IteratorAggregator interface and is used by routines
1063 * such as the foreach loop.
1065 * @return ArrayIterator
1067 public function getIterator() {
1068 return new ArrayIterator($this->collection
);
1073 * The global navigation class used for... the global navigation
1075 * This class is used by PAGE to store the global navigation for the site
1076 * and is then used by the settings nav and navbar to save on processing and DB calls
1079 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1080 * {@link lib/ajax/getnavbranch.php} Called by ajax
1083 * @category navigation
1084 * @copyright 2009 Sam Hemelryk
1085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1087 class global_navigation
extends navigation_node
{
1088 /** @var moodle_page The Moodle page this navigation object belongs to. */
1090 /** @var bool switch to let us know if the navigation object is initialised*/
1091 protected $initialised = false;
1092 /** @var array An array of course information */
1093 protected $mycourses = array();
1094 /** @var navigation_node[] An array for containing root navigation nodes */
1095 protected $rootnodes = array();
1096 /** @var bool A switch for whether to show empty sections in the navigation */
1097 protected $showemptysections = true;
1098 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1099 protected $showcategories = null;
1100 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1101 protected $showmycategories = null;
1102 /** @var array An array of stdClasses for users that the navigation is extended for */
1103 protected $extendforuser = array();
1104 /** @var navigation_cache */
1106 /** @var array An array of course ids that are present in the navigation */
1107 protected $addedcourses = array();
1109 protected $allcategoriesloaded = false;
1110 /** @var array An array of category ids that are included in the navigation */
1111 protected $addedcategories = array();
1112 /** @var int expansion limit */
1113 protected $expansionlimit = 0;
1114 /** @var int userid to allow parent to see child's profile page navigation */
1115 protected $useridtouseforparentchecks = 0;
1116 /** @var cache_session A cache that stores information on expanded courses */
1117 protected $cacheexpandcourse = null;
1119 /** Used when loading categories to load all top level categories [parent = 0] **/
1120 const LOAD_ROOT_CATEGORIES
= 0;
1121 /** Used when loading categories to load all categories **/
1122 const LOAD_ALL_CATEGORIES
= -1;
1125 * Constructs a new global navigation
1127 * @param moodle_page $page The page this navigation object belongs to
1129 public function __construct(moodle_page
$page) {
1130 global $CFG, $SITE, $USER;
1132 if (during_initial_install()) {
1136 if (get_home_page() == HOMEPAGE_SITE
) {
1137 // We are using the site home for the root element
1138 $properties = array(
1140 'type' => navigation_node
::TYPE_SYSTEM
,
1141 'text' => get_string('home'),
1142 'action' => new moodle_url('/')
1145 // We are using the users my moodle for the root element
1146 $properties = array(
1148 'type' => navigation_node
::TYPE_SYSTEM
,
1149 'text' => get_string('myhome'),
1150 'action' => new moodle_url('/my/')
1154 // Use the parents constructor.... good good reuse
1155 parent
::__construct($properties);
1156 $this->showinflatnavigation
= true;
1158 // Initalise and set defaults
1159 $this->page
= $page;
1160 $this->forceopen
= true;
1161 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
1165 * Mutator to set userid to allow parent to see child's profile
1166 * page navigation. See MDL-25805 for initial issue. Linked to it
1167 * is an issue explaining why this is a REALLY UGLY HACK thats not
1170 * @param int $userid userid of profile page that parent wants to navigate around.
1172 public function set_userid_for_parent_checks($userid) {
1173 $this->useridtouseforparentchecks
= $userid;
1178 * Initialises the navigation object.
1180 * This causes the navigation object to look at the current state of the page
1181 * that it is associated with and then load the appropriate content.
1183 * This should only occur the first time that the navigation structure is utilised
1184 * which will normally be either when the navbar is called to be displayed or
1185 * when a block makes use of it.
1189 public function initialise() {
1190 global $CFG, $SITE, $USER;
1191 // Check if it has already been initialised
1192 if ($this->initialised ||
during_initial_install()) {
1195 $this->initialised
= true;
1197 // Set up the five base root nodes. These are nodes where we will put our
1198 // content and are as follows:
1199 // site: Navigation for the front page.
1200 // myprofile: User profile information goes here.
1201 // currentcourse: The course being currently viewed.
1202 // mycourses: The users courses get added here.
1203 // courses: Additional courses are added here.
1204 // users: Other users information loaded here.
1205 $this->rootnodes
= array();
1206 if (get_home_page() == HOMEPAGE_SITE
) {
1207 // The home element should be my moodle because the root element is the site
1208 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1209 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_SETTING
, null, 'home');
1210 $this->rootnodes
['home']->showinflatnavigation
= true;
1213 // The home element should be the site because the root node is my moodle
1214 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self
::TYPE_SETTING
, null, 'home');
1215 $this->rootnodes
['home']->showinflatnavigation
= true;
1216 if (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_MY
)) {
1217 // We need to stop automatic redirection
1218 $this->rootnodes
['home']->action
->param('redirect', '0');
1221 $this->rootnodes
['site'] = $this->add_course($SITE);
1222 $this->rootnodes
['myprofile'] = $this->add(get_string('profile'), null, self
::TYPE_USER
, null, 'myprofile');
1223 $this->rootnodes
['currentcourse'] = $this->add(get_string('currentcourse'), null, self
::TYPE_ROOTNODE
, null, 'currentcourse');
1224 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses');
1225 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1226 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1228 // We always load the frontpage course to ensure it is available without
1229 // JavaScript enabled.
1230 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1231 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1233 $course = $this->page
->course
;
1234 $this->load_courses_enrolled();
1236 // $issite gets set to true if the current pages course is the sites frontpage course
1237 $issite = ($this->page
->course
->id
== $SITE->id
);
1239 // Determine if the user is enrolled in any course.
1240 $enrolledinanycourse = enrol_user_sees_own_courses();
1242 $this->rootnodes
['currentcourse']->mainnavonly
= true;
1243 if ($enrolledinanycourse) {
1244 $this->rootnodes
['mycourses']->isexpandable
= true;
1245 $this->rootnodes
['mycourses']->showinflatnavigation
= true;
1246 if ($CFG->navshowallcourses
) {
1247 // When we show all courses we need to show both the my courses and the regular courses branch.
1248 $this->rootnodes
['courses']->isexpandable
= true;
1251 $this->rootnodes
['courses']->isexpandable
= true;
1253 $this->rootnodes
['mycourses']->forceopen
= true;
1255 $canviewcourseprofile = true;
1257 // Next load context specific content into the navigation
1258 switch ($this->page
->context
->contextlevel
) {
1259 case CONTEXT_SYSTEM
:
1260 // Nothing left to do here I feel.
1262 case CONTEXT_COURSECAT
:
1263 // This is essential, we must load categories.
1264 $this->load_all_categories($this->page
->context
->instanceid
, true);
1266 case CONTEXT_BLOCK
:
1267 case CONTEXT_COURSE
:
1269 // Nothing left to do here.
1273 // Load the course associated with the current page into the navigation.
1274 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1275 // If the course wasn't added then don't try going any further.
1277 $canviewcourseprofile = false;
1281 // If the user is not enrolled then we only want to show the
1282 // course node and not populate it.
1284 // Not enrolled, can't view, and hasn't switched roles
1285 if (!can_access_course($course, null, '', true)) {
1286 if ($coursenode->isexpandable
=== true) {
1287 // Obviously the situation has changed, update the cache and adjust the node.
1288 // This occurs if the user access to a course has been revoked (one way or another) after
1289 // initially logging in for this session.
1290 $this->get_expand_course_cache()->set($course->id
, 1);
1291 $coursenode->isexpandable
= true;
1292 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1294 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1295 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1296 if (!$this->current_user_is_parent_role()) {
1297 $coursenode->make_active();
1298 $canviewcourseprofile = false;
1301 } else if ($coursenode->isexpandable
=== false) {
1302 // Obviously the situation has changed, update the cache and adjust the node.
1303 // This occurs if the user has been granted access to a course (one way or another) after initially
1304 // logging in for this session.
1305 $this->get_expand_course_cache()->set($course->id
, 1);
1306 $coursenode->isexpandable
= true;
1307 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1310 // Add the essentials such as reports etc...
1311 $this->add_course_essentials($coursenode, $course);
1312 // Extend course navigation with it's sections/activities
1313 $this->load_course_sections($course, $coursenode);
1314 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1315 $coursenode->make_active();
1319 case CONTEXT_MODULE
:
1321 // If this is the site course then most information will have
1322 // already been loaded.
1323 // However we need to check if there is more content that can
1324 // yet be loaded for the specific module instance.
1325 $activitynode = $this->rootnodes
['site']->find($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1326 if ($activitynode) {
1327 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1332 $course = $this->page
->course
;
1333 $cm = $this->page
->cm
;
1335 // Load the course associated with the page into the navigation
1336 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1338 // If the course wasn't added then don't try going any further.
1340 $canviewcourseprofile = false;
1344 // If the user is not enrolled then we only want to show the
1345 // course node and not populate it.
1346 if (!can_access_course($course, null, '', true)) {
1347 $coursenode->make_active();
1348 $canviewcourseprofile = false;
1352 $this->add_course_essentials($coursenode, $course);
1354 // Load the course sections into the page
1355 $this->load_course_sections($course, $coursenode, null, $cm);
1356 $activity = $coursenode->find($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1357 if (!empty($activity)) {
1358 // Finally load the cm specific navigaton information
1359 $this->load_activity($cm, $course, $activity);
1360 // Check if we have an active ndoe
1361 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1362 // And make the activity node active.
1363 $activity->make_active();
1369 // The users profile information etc is already loaded
1370 // for the front page.
1373 $course = $this->page
->course
;
1374 // Load the course associated with the user into the navigation
1375 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1377 // If the course wasn't added then don't try going any further.
1379 $canviewcourseprofile = false;
1383 // If the user is not enrolled then we only want to show the
1384 // course node and not populate it.
1385 if (!can_access_course($course, null, '', true)) {
1386 $coursenode->make_active();
1387 $canviewcourseprofile = false;
1390 $this->add_course_essentials($coursenode, $course);
1391 $this->load_course_sections($course, $coursenode);
1395 // Load for the current user
1396 $this->load_for_user();
1397 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
&& $canviewcourseprofile) {
1398 $this->load_for_user(null, true);
1400 // Load each extending user into the navigation.
1401 foreach ($this->extendforuser
as $user) {
1402 if ($user->id
!= $USER->id
) {
1403 $this->load_for_user($user);
1407 // Give the local plugins a chance to include some navigation if they want.
1408 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1412 // Remove any empty root nodes
1413 foreach ($this->rootnodes
as $node) {
1414 // Dont remove the home node
1415 /** @var navigation_node $node */
1416 if ($node->key
!== 'home' && !$node->has_children() && !$node->isactive
) {
1421 if (!$this->contains_active_node()) {
1422 $this->search_for_active_node();
1425 // If the user is not logged in modify the navigation structure as detailed
1426 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1427 if (!isloggedin()) {
1428 $activities = clone($this->rootnodes
['site']->children
);
1429 $this->rootnodes
['site']->remove();
1430 $children = clone($this->children
);
1431 $this->children
= new navigation_node_collection();
1432 foreach ($activities as $child) {
1433 $this->children
->add($child);
1435 foreach ($children as $child) {
1436 $this->children
->add($child);
1443 * Returns true if the current user is a parent of the user being currently viewed.
1445 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1446 * other user being viewed this function returns false.
1447 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1452 protected function current_user_is_parent_role() {
1454 if ($this->useridtouseforparentchecks
&& $this->useridtouseforparentchecks
!= $USER->id
) {
1455 $usercontext = context_user
::instance($this->useridtouseforparentchecks
, MUST_EXIST
);
1456 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1459 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))) {
1467 * Returns true if courses should be shown within categories on the navigation.
1469 * @param bool $ismycourse Set to true if you are calculating this for a course.
1472 protected function show_categories($ismycourse = false) {
1475 return $this->show_my_categories();
1477 if ($this->showcategories
=== null) {
1479 if ($this->page
->context
->contextlevel
== CONTEXT_COURSECAT
) {
1481 } else if (!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1) {
1484 $this->showcategories
= $show;
1486 return $this->showcategories
;
1490 * Returns true if we should show categories in the My Courses branch.
1493 protected function show_my_categories() {
1495 if ($this->showmycategories
=== null) {
1496 require_once('coursecatlib.php');
1497 $this->showmycategories
= !empty($CFG->navshowmycoursecategories
) && coursecat
::count_all() > 1;
1499 return $this->showmycategories
;
1503 * Loads the courses in Moodle into the navigation.
1505 * @global moodle_database $DB
1506 * @param string|array $categoryids An array containing categories to load courses
1507 * for, OR null to load courses for all categories.
1508 * @return array An array of navigation_nodes one for each course
1510 protected function load_all_courses($categoryids = null) {
1511 global $CFG, $DB, $SITE;
1513 // Work out the limit of courses.
1515 if (!empty($CFG->navcourselimit
)) {
1516 $limit = $CFG->navcourselimit
;
1519 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1521 // If we are going to show all courses AND we are showing categories then
1522 // to save us repeated DB calls load all of the categories now
1523 if ($this->show_categories()) {
1524 $this->load_all_categories($toload);
1527 // Will be the return of our efforts
1528 $coursenodes = array();
1530 // Check if we need to show categories.
1531 if ($this->show_categories()) {
1532 // Hmmm we need to show categories... this is going to be painful.
1533 // We now need to fetch up to $limit courses for each category to
1535 if ($categoryids !== null) {
1536 if (!is_array($categoryids)) {
1537 $categoryids = array($categoryids);
1539 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1540 $categorywhere = 'WHERE cc.id '.$categorywhere;
1541 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1542 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1543 $categoryparams = array();
1545 $categorywhere = '';
1546 $categoryparams = array();
1549 // First up we are going to get the categories that we are going to
1550 // need so that we can determine how best to load the courses from them.
1551 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1552 FROM {course_categories} cc
1553 LEFT JOIN {course} c ON c.category = cc.id
1556 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1557 $fullfetch = array();
1558 $partfetch = array();
1559 foreach ($categories as $category) {
1560 if (!$this->can_add_more_courses_to_category($category->id
)) {
1563 if ($category->coursecount
> $limit * 5) {
1564 $partfetch[] = $category->id
;
1565 } else if ($category->coursecount
> 0) {
1566 $fullfetch[] = $category->id
;
1569 $categories->close();
1571 if (count($fullfetch)) {
1572 // First up fetch all of the courses in categories where we know that we are going to
1573 // need the majority of courses.
1574 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1575 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1576 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1577 $categoryparams['contextlevel'] = CONTEXT_COURSE
;
1578 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1581 WHERE c.category {$categoryids}
1582 ORDER BY c.sortorder ASC";
1583 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1584 foreach ($coursesrs as $course) {
1585 if ($course->id
== $SITE->id
) {
1586 // This should not be necessary, frontpage is not in any category.
1589 if (array_key_exists($course->id
, $this->addedcourses
)) {
1590 // It is probably better to not include the already loaded courses
1591 // directly in SQL because inequalities may confuse query optimisers
1592 // and may interfere with query caching.
1595 if (!$this->can_add_more_courses_to_category($course->category
)) {
1598 context_helper
::preload_from_record($course);
1599 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1602 $coursenodes[$course->id
] = $this->add_course($course);
1604 $coursesrs->close();
1607 if (count($partfetch)) {
1608 // Next we will work our way through the categories where we will likely only need a small
1609 // proportion of the courses.
1610 foreach ($partfetch as $categoryid) {
1611 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1612 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1613 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1616 WHERE c.category = :categoryid
1617 ORDER BY c.sortorder ASC";
1618 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE
);
1619 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1620 foreach ($coursesrs as $course) {
1621 if ($course->id
== $SITE->id
) {
1622 // This should not be necessary, frontpage is not in any category.
1625 if (array_key_exists($course->id
, $this->addedcourses
)) {
1626 // It is probably better to not include the already loaded courses
1627 // directly in SQL because inequalities may confuse query optimisers
1628 // and may interfere with query caching.
1629 // This also helps to respect expected $limit on repeated executions.
1632 if (!$this->can_add_more_courses_to_category($course->category
)) {
1635 context_helper
::preload_from_record($course);
1636 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1639 $coursenodes[$course->id
] = $this->add_course($course);
1641 $coursesrs->close();
1645 // Prepare the SQL to load the courses and their contexts
1646 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1647 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1648 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1649 $courseparams['contextlevel'] = CONTEXT_COURSE
;
1650 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1653 WHERE c.id {$courseids}
1654 ORDER BY c.sortorder ASC";
1655 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1656 foreach ($coursesrs as $course) {
1657 if ($course->id
== $SITE->id
) {
1658 // frotpage is not wanted here
1661 if ($this->page
->course
&& ($this->page
->course
->id
== $course->id
)) {
1662 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1665 context_helper
::preload_from_record($course);
1666 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1669 $coursenodes[$course->id
] = $this->add_course($course);
1670 if (count($coursenodes) >= $limit) {
1674 $coursesrs->close();
1677 return $coursenodes;
1681 * Returns true if more courses can be added to the provided category.
1683 * @param int|navigation_node|stdClass $category
1686 protected function can_add_more_courses_to_category($category) {
1689 if (!empty($CFG->navcourselimit
)) {
1690 $limit = (int)$CFG->navcourselimit
;
1692 if (is_numeric($category)) {
1693 if (!array_key_exists($category, $this->addedcategories
)) {
1696 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1697 } else if ($category instanceof navigation_node
) {
1698 if (($category->type
!= self
::TYPE_CATEGORY
) ||
($category->type
!= self
::TYPE_MY_CATEGORY
)) {
1701 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1702 } else if (is_object($category) && property_exists($category,'id')) {
1703 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1705 return ($coursecount <= $limit);
1709 * Loads all categories (top level or if an id is specified for that category)
1711 * @param int $categoryid The category id to load or null/0 to load all base level categories
1712 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1713 * as the requested category and any parent categories.
1714 * @return navigation_node|void returns a navigation node if a category has been loaded.
1716 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1719 // Check if this category has already been loaded
1720 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1724 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1725 $sqlselect = "SELECT cc.*, $catcontextsql
1726 FROM {course_categories} cc
1727 JOIN {context} ctx ON cc.id = ctx.instanceid";
1728 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1729 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1732 $categoriestoload = array();
1733 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1734 // We are going to load all categories regardless... prepare to fire
1735 // on the database server!
1736 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1737 // We are going to load all of the first level categories (categories without parents)
1738 $sqlwhere .= " AND cc.parent = 0";
1739 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1740 // The category itself has been loaded already so we just need to ensure its subcategories
1742 $addedcategories = $this->addedcategories
;
1743 unset($addedcategories[$categoryid]);
1744 if (count($addedcategories) > 0) {
1745 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED
, 'parent', false);
1746 if ($showbasecategories) {
1747 // We need to include categories with parent = 0 as well
1748 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1750 // All we need is categories that match the parent
1751 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1754 $params['categoryid'] = $categoryid;
1756 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1757 // and load this category plus all its parents and subcategories
1758 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1759 $categoriestoload = explode('/', trim($category->path
, '/'));
1760 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1761 // We are going to use select twice so double the params
1762 $params = array_merge($params, $params);
1763 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1764 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1767 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1768 $categories = array();
1769 foreach ($categoriesrs as $category) {
1770 // Preload the context.. we'll need it when adding the category in order
1771 // to format the category name.
1772 context_helper
::preload_from_record($category);
1773 if (array_key_exists($category->id
, $this->addedcategories
)) {
1774 // Do nothing, its already been added.
1775 } else if ($category->parent
== '0') {
1776 // This is a root category lets add it immediately
1777 $this->add_category($category, $this->rootnodes
['courses']);
1778 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1779 // This categories parent has already been added we can add this immediately
1780 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1782 $categories[] = $category;
1785 $categoriesrs->close();
1787 // Now we have an array of categories we need to add them to the navigation.
1788 while (!empty($categories)) {
1789 $category = reset($categories);
1790 if (array_key_exists($category->id
, $this->addedcategories
)) {
1792 } else if ($category->parent
== '0') {
1793 $this->add_category($category, $this->rootnodes
['courses']);
1794 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
1795 $this->add_category($category, $this->addedcategories
[$category->parent
]);
1797 // This category isn't in the navigation and niether is it's parent (yet).
1798 // We need to go through the category path and add all of its components in order.
1799 $path = explode('/', trim($category->path
, '/'));
1800 foreach ($path as $catid) {
1801 if (!array_key_exists($catid, $this->addedcategories
)) {
1802 // This category isn't in the navigation yet so add it.
1803 $subcategory = $categories[$catid];
1804 if ($subcategory->parent
== '0') {
1805 // Yay we have a root category - this likely means we will now be able
1806 // to add categories without problems.
1807 $this->add_category($subcategory, $this->rootnodes
['courses']);
1808 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
1809 // The parent is in the category (as we'd expect) so add it now.
1810 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
1811 // Remove the category from the categories array.
1812 unset($categories[$catid]);
1814 // We should never ever arrive here - if we have then there is a bigger
1816 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1821 // Remove the category from the categories array now that we know it has been added.
1822 unset($categories[$category->id
]);
1824 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
1825 $this->allcategoriesloaded
= true;
1827 // Check if there are any categories to load.
1828 if (count($categoriestoload) > 0) {
1829 $readytoloadcourses = array();
1830 foreach ($categoriestoload as $category) {
1831 if ($this->can_add_more_courses_to_category($category)) {
1832 $readytoloadcourses[] = $category;
1835 if (count($readytoloadcourses)) {
1836 $this->load_all_courses($readytoloadcourses);
1840 // Look for all categories which have been loaded
1841 if (!empty($this->addedcategories
)) {
1842 $categoryids = array();
1843 foreach ($this->addedcategories
as $category) {
1844 if ($this->can_add_more_courses_to_category($category)) {
1845 $categoryids[] = $category->key
;
1849 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
1850 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
1851 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1852 FROM {course_categories} cc
1853 JOIN {course} c ON c.category = cc.id
1854 WHERE cc.id {$categoriessql}
1856 HAVING COUNT(c.id) > :limit";
1857 $excessivecategories = $DB->get_records_sql($sql, $params);
1858 foreach ($categories as &$category) {
1859 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1860 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key
));
1861 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1869 * Adds a structured category to the navigation in the correct order/place
1871 * @param stdClass $category category to be added in navigation.
1872 * @param navigation_node $parent parent navigation node
1873 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1876 protected function add_category(stdClass
$category, navigation_node
$parent, $nodetype = self
::TYPE_CATEGORY
) {
1877 if (array_key_exists($category->id
, $this->addedcategories
)) {
1880 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id
));
1881 $context = context_coursecat
::instance($category->id
);
1882 $categoryname = format_string($category->name
, true, array('context' => $context));
1883 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id
);
1884 if (empty($category->visible
)) {
1885 if (has_capability('moodle/category:viewhiddencategories', context_system
::instance())) {
1886 $categorynode->hidden
= true;
1888 $categorynode->display
= false;
1891 $this->addedcategories
[$category->id
] = $categorynode;
1895 * Loads the given course into the navigation
1897 * @param stdClass $course
1898 * @return navigation_node
1900 protected function load_course(stdClass
$course) {
1902 if ($course->id
== $SITE->id
) {
1903 // This is always loaded during initialisation
1904 return $this->rootnodes
['site'];
1905 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
1906 // The course has already been loaded so return a reference
1907 return $this->addedcourses
[$course->id
];
1910 return $this->add_course($course);
1915 * Loads all of the courses section into the navigation.
1917 * This function calls method from current course format, see
1918 * {@link format_base::extend_course_navigation()}
1919 * If course module ($cm) is specified but course format failed to create the node,
1920 * the activity node is created anyway.
1922 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1924 * @param stdClass $course Database record for the course
1925 * @param navigation_node $coursenode The course node within the navigation
1926 * @param null|int $sectionnum If specified load the contents of section with this relative number
1927 * @param null|cm_info $cm If specified make sure that activity node is created (either
1928 * in containg section or by calling load_stealth_activity() )
1930 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode, $sectionnum = null, $cm = null) {
1932 require_once($CFG->dirroot
.'/course/lib.php');
1933 if (isset($cm->sectionnum
)) {
1934 $sectionnum = $cm->sectionnum
;
1936 if ($sectionnum !== null) {
1937 $this->includesectionnum
= $sectionnum;
1939 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1940 if (isset($cm->id
)) {
1941 $activity = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
1942 if (empty($activity)) {
1943 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1949 * Generates an array of sections and an array of activities for the given course.
1951 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1953 * @param stdClass $course
1954 * @return array Array($sections, $activities)
1956 protected function generate_sections_and_activities(stdClass
$course) {
1958 require_once($CFG->dirroot
.'/course/lib.php');
1960 $modinfo = get_fast_modinfo($course);
1961 $sections = $modinfo->get_section_info_all();
1963 // For course formats using 'numsections' trim the sections list
1964 $courseformatoptions = course_get_format($course)->get_format_options();
1965 if (isset($courseformatoptions['numsections'])) {
1966 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+
1, true);
1969 $activities = array();
1971 foreach ($sections as $key => $section) {
1972 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1973 $sections[$key] = clone($section);
1974 unset($sections[$key]->summary
);
1975 $sections[$key]->hasactivites
= false;
1976 if (!array_key_exists($section->section
, $modinfo->sections
)) {
1979 foreach ($modinfo->sections
[$section->section
] as $cmid) {
1980 $cm = $modinfo->cms
[$cmid];
1981 $activity = new stdClass
;
1982 $activity->id
= $cm->id
;
1983 $activity->course
= $course->id
;
1984 $activity->section
= $section->section
;
1985 $activity->name
= $cm->name
;
1986 $activity->icon
= $cm->icon
;
1987 $activity->iconcomponent
= $cm->iconcomponent
;
1988 $activity->hidden
= (!$cm->visible
);
1989 $activity->modname
= $cm->modname
;
1990 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1991 $activity->onclick
= $cm->onclick
;
1994 $activity->url
= null;
1995 $activity->display
= false;
1997 $activity->url
= $url->out();
1998 $activity->display
= $cm->is_visible_on_course_page() ?
true : false;
1999 if (self
::module_extends_navigation($cm->modname
)) {
2000 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2003 $activities[$cmid] = $activity;
2004 if ($activity->display
) {
2005 $sections[$key]->hasactivites
= true;
2010 return array($sections, $activities);
2014 * Generically loads the course sections into the course's navigation.
2016 * @param stdClass $course
2017 * @param navigation_node $coursenode
2018 * @return array An array of course section nodes
2020 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode) {
2021 global $CFG, $DB, $USER, $SITE;
2022 require_once($CFG->dirroot
.'/course/lib.php');
2024 list($sections, $activities) = $this->generate_sections_and_activities($course);
2026 $navigationsections = array();
2027 foreach ($sections as $sectionid => $section) {
2028 $section = clone($section);
2029 if ($course->id
== $SITE->id
) {
2030 $this->load_section_activities($coursenode, $section->section
, $activities);
2032 if (!$section->uservisible ||
(!$this->showemptysections
&&
2033 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
2037 $sectionname = get_section_name($course, $section);
2038 $url = course_get_url($course, $section->section
, array('navigation' => true));
2040 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
, null, $section->id
);
2041 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2042 $sectionnode->hidden
= (!$section->visible ||
!$section->available
);
2043 if ($this->includesectionnum
!== false && $this->includesectionnum
== $section->section
) {
2044 $this->load_section_activities($sectionnode, $section->section
, $activities);
2046 $section->sectionnode
= $sectionnode;
2047 $navigationsections[$sectionid] = $section;
2050 return $navigationsections;
2054 * Loads all of the activities for a section into the navigation structure.
2056 * @param navigation_node $sectionnode
2057 * @param int $sectionnumber
2058 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2059 * @param stdClass $course The course object the section and activities relate to.
2060 * @return array Array of activity nodes
2062 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2064 // A static counter for JS function naming
2065 static $legacyonclickcounter = 0;
2067 $activitynodes = array();
2068 if (empty($activities)) {
2069 return $activitynodes;
2072 if (!is_object($course)) {
2073 $activity = reset($activities);
2074 $courseid = $activity->course
;
2076 $courseid = $course->id
;
2078 $showactivities = ($courseid != $SITE->id ||
!empty($CFG->navshowfrontpagemods
));
2080 foreach ($activities as $activity) {
2081 if ($activity->section
!= $sectionnumber) {
2084 if ($activity->icon
) {
2085 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2087 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2090 // Prepare the default name and url for the node
2091 $activityname = format_string($activity->name
, true, array('context' => context_module
::instance($activity->id
)));
2092 $action = new moodle_url($activity->url
);
2094 // Check if the onclick property is set (puke!)
2095 if (!empty($activity->onclick
)) {
2096 // Increment the counter so that we have a unique number.
2097 $legacyonclickcounter++
;
2098 // Generate the function name we will use
2099 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2100 $propogrationhandler = '';
2101 // Check if we need to cancel propogation. Remember inline onclick
2102 // events would return false if they wanted to prevent propogation and the
2104 if (strpos($activity->onclick
, 'return false')) {
2105 $propogrationhandler = 'e.halt();';
2107 // Decode the onclick - it has already been encoded for display (puke)
2108 $onclick = htmlspecialchars_decode($activity->onclick
, ENT_QUOTES
);
2109 // Build the JS function the click event will call
2110 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2111 $this->page
->requires
->js_amd_inline($jscode);
2112 // Override the default url with the new action link
2113 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2116 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2117 $activitynode->title(get_string('modulename', $activity->modname
));
2118 $activitynode->hidden
= $activity->hidden
;
2119 $activitynode->display
= $showactivities && $activity->display
;
2120 $activitynode->nodetype
= $activity->nodetype
;
2121 $activitynodes[$activity->id
] = $activitynode;
2124 return $activitynodes;
2127 * Loads a stealth module from unavailable section
2128 * @param navigation_node $coursenode
2129 * @param stdClass $modinfo
2130 * @return navigation_node or null if not accessible
2132 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2133 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2136 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2138 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2140 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2143 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2144 $activitynode->title(get_string('modulename', $cm->modname
));
2145 $activitynode->hidden
= (!$cm->visible
);
2146 if (!$cm->is_visible_on_course_page()) {
2147 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2148 // Also there may be no exception at all in case when teacher is logged in as student.
2149 $activitynode->display
= false;
2151 // Don't show activities that don't have links!
2152 $activitynode->display
= false;
2153 } else if (self
::module_extends_navigation($cm->modname
)) {
2154 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2156 return $activitynode;
2159 * Loads the navigation structure for the given activity into the activities node.
2161 * This method utilises a callback within the modules lib.php file to load the
2162 * content specific to activity given.
2164 * The callback is a method: {modulename}_extend_navigation()
2166 * * {@link forum_extend_navigation()}
2167 * * {@link workshop_extend_navigation()}
2169 * @param cm_info|stdClass $cm
2170 * @param stdClass $course
2171 * @param navigation_node $activity
2174 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2177 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2178 if (!($cm instanceof cm_info
)) {
2179 $modinfo = get_fast_modinfo($course);
2180 $cm = $modinfo->get_cm($cm->id
);
2182 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2183 $activity->make_active();
2184 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2185 $function = $cm->modname
.'_extend_navigation';
2187 if (file_exists($file)) {
2188 require_once($file);
2189 if (function_exists($function)) {
2190 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2191 $function($activity, $course, $activtyrecord, $cm);
2195 // Allow the active advanced grading method plugin to append module navigation
2196 $featuresfunc = $cm->modname
.'_supports';
2197 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2198 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2199 $gradingman = get_grading_manager($cm->context
, 'mod_'.$cm->modname
);
2200 $gradingman->extend_navigation($this, $activity);
2203 return $activity->has_children();
2206 * Loads user specific information into the navigation in the appropriate place.
2208 * If no user is provided the current user is assumed.
2210 * @param stdClass $user
2211 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2214 protected function load_for_user($user=null, $forceforcontext=false) {
2215 global $DB, $CFG, $USER, $SITE;
2217 require_once($CFG->dirroot
. '/course/lib.php');
2219 if ($user === null) {
2220 // We can't require login here but if the user isn't logged in we don't
2221 // want to show anything
2222 if (!isloggedin() ||
isguestuser()) {
2226 } else if (!is_object($user)) {
2227 // If the user is not an object then get them from the database
2228 $select = context_helper
::get_preload_record_columns_sql('ctx');
2229 $sql = "SELECT u.*, $select
2231 JOIN {context} ctx ON u.id = ctx.instanceid
2232 WHERE u.id = :userid AND
2233 ctx.contextlevel = :contextlevel";
2234 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2235 context_helper
::preload_from_record($user);
2238 $iscurrentuser = ($user->id
== $USER->id
);
2240 $usercontext = context_user
::instance($user->id
);
2242 // Get the course set against the page, by default this will be the site
2243 $course = $this->page
->course
;
2244 $baseargs = array('id'=>$user->id
);
2245 if ($course->id
!= $SITE->id
&& (!$iscurrentuser ||
$forceforcontext)) {
2246 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
2247 $baseargs['course'] = $course->id
;
2248 $coursecontext = context_course
::instance($course->id
);
2249 $issitecourse = false;
2251 // Load all categories and get the context for the system
2252 $coursecontext = context_system
::instance();
2253 $issitecourse = true;
2256 // Create a node to add user information under.
2258 if (!$issitecourse) {
2259 // Not the current user so add it to the participants node for the current course.
2260 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2261 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2262 } else if ($USER->id
!= $user->id
) {
2263 // This is the site so add a users node to the root branch.
2264 $usersnode = $this->rootnodes
['users'];
2265 if (course_can_view_participants($coursecontext)) {
2266 $usersnode->action
= new moodle_url('/user/index.php', array('id' => $course->id
));
2268 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2271 // We should NEVER get here, if the course hasn't been populated
2272 // with a participants node then the navigaiton either wasn't generated
2273 // for it (you are missing a require_login or set_context call) or
2274 // you don't have access.... in the interests of no leaking informatin
2275 // we simply quit...
2278 // Add a branch for the current user.
2279 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2280 $viewprofile = true;
2281 if (!$iscurrentuser) {
2282 require_once($CFG->dirroot
. '/user/lib.php');
2283 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& !has_capability('moodle/user:viewdetails', $usercontext) ) {
2284 $viewprofile = false;
2285 } else if ($this->page
->context
->contextlevel
!= CONTEXT_USER
&& !user_can_view_profile($user, $course, $usercontext)) {
2286 $viewprofile = false;
2288 if (!$viewprofile) {
2289 $viewprofile = user_can_view_profile($user, null, $usercontext);
2293 // Now, conditionally add the user node.
2295 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2296 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, 'user' . $user->id
);
2298 $usernode = $usersnode->add(get_string('user'));
2301 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2302 $usernode->make_active();
2305 // Add user information to the participants or user node.
2306 if ($issitecourse) {
2308 // If the user is the current user or has permission to view the details of the requested
2309 // user than add a view profile link.
2310 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
2311 has_capability('moodle/user:viewdetails', $usercontext)) {
2312 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2313 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2315 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2319 if (!empty($CFG->navadduserpostslinks
)) {
2320 // Add nodes for forum posts and discussions if the user can view either or both
2321 // There are no capability checks here as the content of the page is based
2322 // purely on the forums the current user has access too.
2323 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2324 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2325 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2326 array_merge($baseargs, array('mode' => 'discussions'))));
2330 if (!empty($CFG->enableblogs
)) {
2331 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2332 require_once($CFG->dirroot
.'/blog/lib.php');
2333 // Get all options for the user.
2334 $options = blog_get_options_for_user($user);
2335 $this->cache
->set('userblogoptions'.$user->id
, $options);
2337 $options = $this->cache
->{'userblogoptions'.$user->id
};
2340 if (count($options) > 0) {
2341 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2342 foreach ($options as $type => $option) {
2343 if ($type == "rss") {
2344 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null,
2345 new pix_icon('i/rss', ''));
2347 $blogs->add($option['string'], $option['link']);
2353 // Add the messages link.
2354 // It is context based so can appear in the user's profile and in course participants information.
2355 if (!empty($CFG->messaging
)) {
2356 $messageargs = array('user1' => $USER->id
);
2357 if ($USER->id
!= $user->id
) {
2358 $messageargs['user2'] = $user->id
;
2360 $url = new moodle_url('/message/index.php', $messageargs);
2361 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2364 // Add the "My private files" link.
2365 // This link doesn't have a unique display for course context so only display it under the user's profile.
2366 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2367 $url = new moodle_url('/user/files.php');
2368 $usernode->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
2371 // Add a node to view the users notes if permitted.
2372 if (!empty($CFG->enablenotes
) &&
2373 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2374 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
2375 if ($coursecontext->instanceid
!= SITEID
) {
2376 $url->param('course', $coursecontext->instanceid
);
2378 $usernode->add(get_string('notes', 'notes'), $url);
2381 // Show the grades node.
2382 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2383 require_once($CFG->dirroot
. '/user/lib.php');
2384 // Set the grades node to link to the "Grades" page.
2385 if ($course->id
== SITEID
) {
2386 $url = user_mygrades_url($user->id
, $course->id
);
2387 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2388 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
2390 if ($USER->id
!= $user->id
) {
2391 $usernode->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'usergrades');
2393 $usernode->add(get_string('grades', 'grades'), $url);
2397 // If the user is the current user add the repositories for the current user.
2398 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2399 if (!$iscurrentuser &&
2400 $course->id
== $SITE->id
&&
2401 has_capability('moodle/user:viewdetails', $usercontext) &&
2402 (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2404 // Add view grade report is permitted.
2405 $reports = core_component
::get_plugin_list('gradereport');
2406 arsort($reports); // User is last, we want to test it first.
2408 $userscourses = enrol_get_users_courses($user->id
, false, '*');
2409 $userscoursesnode = $usernode->add(get_string('courses'));
2412 foreach ($userscourses as $usercourse) {
2413 if ($count === (int)$CFG->navcourselimit
) {
2414 $url = new moodle_url('/user/profile.php', array('id' => $user->id
, 'showallcourses' => 1));
2415 $userscoursesnode->add(get_string('showallcourses'), $url);
2419 $usercoursecontext = context_course
::instance($usercourse->id
);
2420 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2421 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2422 array('id' => $user->id
, 'course' => $usercourse->id
)), self
::TYPE_CONTAINER
);
2424 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2425 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2426 foreach ($reports as $plugin => $plugindir) {
2427 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2428 // Stop when the first visible plugin is found.
2429 $gradeavailable = true;
2435 if ($gradeavailable) {
2436 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id
));
2437 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null,
2438 new pix_icon('i/grades', ''));
2441 // Add a node to view the users notes if permitted.
2442 if (!empty($CFG->enablenotes
) &&
2443 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2444 $url = new moodle_url('/notes/index.php', array('user' => $user->id
, 'course' => $usercourse->id
));
2445 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2448 if (can_access_course($usercourse, $user->id
, '', true)) {
2449 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2450 array('id' => $usercourse->id
)), self
::TYPE_SETTING
, null, null, new pix_icon('i/course', ''));
2453 $reporttab = $usercoursenode->add(get_string('activityreports'));
2455 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2456 foreach ($reports as $reportfunction) {
2457 $reportfunction($reporttab, $user, $usercourse);
2460 $reporttab->trim_if_empty();
2464 // Let plugins hook into user navigation.
2465 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2466 foreach ($pluginsfunction as $plugintype => $plugins) {
2467 if ($plugintype != 'report') {
2468 foreach ($plugins as $pluginfunction) {
2469 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2478 * This method simply checks to see if a given module can extend the navigation.
2480 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2482 * @param string $modname
2485 public static function module_extends_navigation($modname) {
2487 static $extendingmodules = array();
2488 if (!array_key_exists($modname, $extendingmodules)) {
2489 $extendingmodules[$modname] = false;
2490 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2491 if (file_exists($file)) {
2492 $function = $modname.'_extend_navigation';
2493 require_once($file);
2494 $extendingmodules[$modname] = (function_exists($function));
2497 return $extendingmodules[$modname];
2500 * Extends the navigation for the given user.
2502 * @param stdClass $user A user from the database
2504 public function extend_for_user($user) {
2505 $this->extendforuser
[] = $user;
2509 * Returns all of the users the navigation is being extended for
2511 * @return array An array of extending users.
2513 public function get_extending_users() {
2514 return $this->extendforuser
;
2517 * Adds the given course to the navigation structure.
2519 * @param stdClass $course
2520 * @param bool $forcegeneric
2521 * @param bool $ismycourse
2522 * @return navigation_node
2524 public function add_course(stdClass
$course, $forcegeneric = false, $coursetype = self
::COURSE_OTHER
) {
2527 // We found the course... we can return it now :)
2528 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2529 return $this->addedcourses
[$course->id
];
2532 $coursecontext = context_course
::instance($course->id
);
2534 if ($course->id
!= $SITE->id
&& !$course->visible
) {
2535 if (is_role_switched($course->id
)) {
2536 // user has to be able to access course in order to switch, let's skip the visibility test here
2537 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2542 $issite = ($course->id
== $SITE->id
);
2543 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2544 $fullname = format_string($course->fullname
, true, array('context' => $coursecontext));
2545 // This is the name that will be shown for the course.
2546 $coursename = empty($CFG->navshowfullcoursenames
) ?
$shortname : $fullname;
2548 if ($coursetype == self
::COURSE_CURRENT
) {
2549 if ($coursenode = $this->rootnodes
['mycourses']->find($course->id
, self
::TYPE_COURSE
)) {
2552 $coursetype = self
::COURSE_OTHER
;
2556 // Can the user expand the course to see its content.
2557 $canexpandcourse = true;
2561 if (empty($CFG->usesitenameforsitepages
)) {
2562 $coursename = get_string('sitepages');
2564 } else if ($coursetype == self
::COURSE_CURRENT
) {
2565 $parent = $this->rootnodes
['currentcourse'];
2566 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2567 $canexpandcourse = $this->can_expand_course($course);
2568 } else if ($coursetype == self
::COURSE_MY
&& !$forcegeneric) {
2569 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_MY_CATEGORY
))) {
2570 // Nothing to do here the above statement set $parent to the category within mycourses.
2572 $parent = $this->rootnodes
['mycourses'];
2574 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2576 $parent = $this->rootnodes
['courses'];
2577 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2578 // They can only expand the course if they can access it.
2579 $canexpandcourse = $this->can_expand_course($course);
2580 if (!empty($course->category
) && $this->show_categories($coursetype == self
::COURSE_MY
)) {
2581 if (!$this->is_category_fully_loaded($course->category
)) {
2582 // We need to load the category structure for this course
2583 $this->load_all_categories($course->category
, false);
2585 if (array_key_exists($course->category
, $this->addedcategories
)) {
2586 $parent = $this->addedcategories
[$course->category
];
2587 // This could lead to the course being created so we should check whether it is the case again
2588 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2589 return $this->addedcourses
[$course->id
];
2595 $coursenode = $parent->add($coursename, $url, self
::TYPE_COURSE
, $shortname, $course->id
);
2596 $coursenode->showinflatnavigation
= $coursetype == self
::COURSE_MY
;
2598 $coursenode->hidden
= (!$course->visible
);
2599 $coursenode->title(format_string($course->fullname
, true, array('context' => $coursecontext, 'escape' => false)));
2600 if ($canexpandcourse) {
2601 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2602 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2603 $coursenode->isexpandable
= true;
2605 $coursenode->nodetype
= self
::NODETYPE_LEAF
;
2606 $coursenode->isexpandable
= false;
2608 if (!$forcegeneric) {
2609 $this->addedcourses
[$course->id
] = $coursenode;
2616 * Returns a cache instance to use for the expand course cache.
2617 * @return cache_session
2619 protected function get_expand_course_cache() {
2620 if ($this->cacheexpandcourse
=== null) {
2621 $this->cacheexpandcourse
= cache
::make('core', 'navigation_expandcourse');
2623 return $this->cacheexpandcourse
;
2627 * Checks if a user can expand a course in the navigation.
2629 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2630 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2631 * permits stale data.
2632 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2634 * It is brought up to date in only one of two ways.
2635 * 1. The user logs out and in again.
2636 * 2. The user browses to the course they've just being given access to.
2638 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2640 * @param stdClass $course
2643 protected function can_expand_course($course) {
2644 $cache = $this->get_expand_course_cache();
2645 $canexpand = $cache->get($course->id
);
2646 if ($canexpand === false) {
2647 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2648 $canexpand = (int)$canexpand;
2649 $cache->set($course->id
, $canexpand);
2651 return ($canexpand === 1);
2655 * Returns true if the category has already been loaded as have any child categories
2657 * @param int $categoryid
2660 protected function is_category_fully_loaded($categoryid) {
2661 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2665 * Adds essential course nodes to the navigation for the given course.
2667 * This method adds nodes such as reports, blogs and participants
2669 * @param navigation_node $coursenode
2670 * @param stdClass $course
2671 * @return bool returns true on successful addition of a node.
2673 public function add_course_essentials($coursenode, stdClass
$course) {
2675 require_once($CFG->dirroot
. '/course/lib.php');
2677 if ($course->id
== $SITE->id
) {
2678 return $this->add_front_page_course_essentials($coursenode, $course);
2681 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2685 $navoptions = course_get_user_navigation_options($this->page
->context
, $course);
2688 if ($navoptions->participants
) {
2689 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2691 if ($navoptions->blogs
) {
2692 $blogsurls = new moodle_url('/blog/index.php');
2693 if ($currentgroup = groups_get_course_group($course, true)) {
2694 $blogsurls->param('groupid', $currentgroup);
2696 $blogsurls->param('courseid', $course->id
);
2698 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self
::TYPE_SETTING
, null, 'courseblogs');
2701 if ($navoptions->notes
) {
2702 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id
)), self
::TYPE_SETTING
, null, 'currentcoursenotes');
2704 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2705 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2709 if ($navoptions->badges
) {
2710 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id
));
2712 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2713 navigation_node
::TYPE_SETTING
, null, 'badgesview',
2714 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2717 // Check access to the course and competencies page.
2718 if ($navoptions->competencies
) {
2719 // Just a link to course competency.
2720 $title = get_string('competencies', 'core_competency');
2721 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id
));
2722 $coursenode->add($title, $path, navigation_node
::TYPE_SETTING
, null, 'competencies',
2723 new pix_icon('i/competencies', ''));
2725 if ($navoptions->grades
) {
2726 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
2727 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, 'grades', new pix_icon('i/grades', ''));
2733 * This generates the structure of the course that won't be generated when
2734 * the modules and sections are added.
2736 * Things such as the reports branch, the participants branch, blogs... get
2737 * added to the course node by this method.
2739 * @param navigation_node $coursenode
2740 * @param stdClass $course
2741 * @return bool True for successfull generation
2743 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2745 require_once($CFG->dirroot
. '/course/lib.php');
2747 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2751 $sitecontext = context_system
::instance();
2752 $navoptions = course_get_user_navigation_options($sitecontext, $course);
2754 // Hidden node that we use to determine if the front page navigation is loaded.
2755 // This required as there are not other guaranteed nodes that may be loaded.
2756 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2759 if ($navoptions->participants
) {
2760 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
2764 if ($navoptions->blogs
) {
2765 $blogsurls = new moodle_url('/blog/index.php');
2766 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self
::TYPE_SYSTEM
, null, 'siteblog');
2772 if ($navoptions->badges
) {
2773 $url = new moodle_url($CFG->wwwroot
. '/badges/view.php', array('type' => 1));
2774 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node
::TYPE_CUSTOM
);
2778 if ($navoptions->notes
) {
2779 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2780 array('filtertype' => 'course', 'filterselect' => $filterselect)), self
::TYPE_SETTING
, null, 'notes');
2784 if ($navoptions->tags
) {
2785 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2786 self
::TYPE_SETTING
, null, 'tags');
2790 if ($navoptions->search
) {
2791 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2792 self
::TYPE_SETTING
, null, 'search');
2795 if ($navoptions->calendar
) {
2797 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2798 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self
::TYPE_CUSTOM
, null, 'calendar');
2799 $node->showinflatnavigation
= true;
2803 $usercontext = context_user
::instance($USER->id
);
2804 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2805 $url = new moodle_url('/user/files.php');
2806 $node = $coursenode->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
2807 $node->display
= false;
2808 $node->showinflatnavigation
= true;
2816 * Clears the navigation cache
2818 public function clear_cache() {
2819 $this->cache
->clear();
2823 * Sets an expansion limit for the navigation
2825 * The expansion limit is used to prevent the display of content that has a type
2826 * greater than the provided $type.
2828 * Can be used to ensure things such as activities or activity content don't get
2829 * shown on the navigation.
2830 * They are still generated in order to ensure the navbar still makes sense.
2832 * @param int $type One of navigation_node::TYPE_*
2833 * @return bool true when complete.
2835 public function set_expansion_limit($type) {
2837 $nodes = $this->find_all_of_type($type);
2839 // We only want to hide specific types of nodes.
2840 // Only nodes that represent "structure" in the navigation tree should be hidden.
2841 // If we hide all nodes then we risk hiding vital information.
2842 $typestohide = array(
2843 self
::TYPE_CATEGORY
,
2849 foreach ($nodes as $node) {
2850 // We need to generate the full site node
2851 if ($type == self
::TYPE_COURSE
&& $node->key
== $SITE->id
) {
2854 foreach ($node->children
as $child) {
2855 $child->hide($typestohide);
2861 * Attempts to get the navigation with the given key from this nodes children.
2863 * This function only looks at this nodes children, it does NOT look recursivily.
2864 * If the node can't be found then false is returned.
2866 * If you need to search recursivily then use the {@link global_navigation::find()} method.
2868 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2869 * may be of more use to you.
2871 * @param string|int $key The key of the node you wish to receive.
2872 * @param int $type One of navigation_node::TYPE_*
2873 * @return navigation_node|false
2875 public function get($key, $type = null) {
2876 if (!$this->initialised
) {
2877 $this->initialise();
2879 return parent
::get($key, $type);
2883 * Searches this nodes children and their children to find a navigation node
2884 * with the matching key and type.
2886 * This method is recursive and searches children so until either a node is
2887 * found or there are no more nodes to search.
2889 * If you know that the node being searched for is a child of this node
2890 * then use the {@link global_navigation::get()} method instead.
2892 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2893 * may be of more use to you.
2895 * @param string|int $key The key of the node you wish to receive.
2896 * @param int $type One of navigation_node::TYPE_*
2897 * @return navigation_node|false
2899 public function find($key, $type) {
2900 if (!$this->initialised
) {
2901 $this->initialise();
2903 if ($type == self
::TYPE_ROOTNODE
&& array_key_exists($key, $this->rootnodes
)) {
2904 return $this->rootnodes
[$key];
2906 return parent
::find($key, $type);
2910 * They've expanded the 'my courses' branch.
2912 protected function load_courses_enrolled() {
2915 $limit = (int) $CFG->navcourselimit
;
2917 $sortorder = 'visible DESC';
2918 // Prevent undefined $CFG->navsortmycoursessort errors.
2919 if (empty($CFG->navsortmycoursessort
)) {
2920 $CFG->navsortmycoursessort
= 'sortorder';
2922 // Append the chosen sortorder.
2923 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort
. ' ASC';
2924 $courses = enrol_get_my_courses('*', $sortorder);
2925 $flatnavcourses = [];
2927 // Go through the courses and see which ones we want to display in the flatnav.
2928 foreach ($courses as $course) {
2929 $classify = course_classify_for_timeline($course);
2931 if ($classify == COURSE_TIMELINE_INPROGRESS
) {
2932 $flatnavcourses[$course->id
] = $course;
2936 // Get the number of courses that can be displayed in the nav block and in the flatnav.
2937 $numtotalcourses = count($courses);
2938 $numtotalflatnavcourses = count($flatnavcourses);
2940 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
2941 $courses = array_slice($courses, 0, $limit, true);
2942 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
2944 // Get the number of courses we are going to show for each.
2945 $numshowncourses = count($courses);
2946 $numshownflatnavcourses = count($flatnavcourses);
2947 if ($numshowncourses && $this->show_my_categories()) {
2948 // Generate an array containing unique values of all the courses' categories.
2949 $categoryids = array();
2950 foreach ($courses as $course) {
2951 if (in_array($course->category
, $categoryids)) {
2954 $categoryids[] = $course->category
;
2957 // Array of category IDs that include the categories of the user's courses and the related course categories.
2958 $fullpathcategoryids = [];
2959 // Get the course categories for the enrolled courses' category IDs.
2960 require_once('coursecatlib.php');
2961 $mycoursecategories = coursecat
::get_many($categoryids);
2962 // Loop over each of these categories and build the category tree using each category's path.
2963 foreach ($mycoursecategories as $mycoursecat) {
2964 $pathcategoryids = explode('/', $mycoursecat->path
);
2965 // First element of the exploded path is empty since paths begin with '/'.
2966 array_shift($pathcategoryids);
2967 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
2968 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
2971 // Fetch all of the categories related to the user's courses.
2972 $pathcategories = coursecat
::get_many($fullpathcategoryids);
2973 // Loop over each of these categories and build the category tree.
2974 foreach ($pathcategories as $coursecat) {
2975 // No need to process categories that have already been added.
2976 if (isset($this->addedcategories
[$coursecat->id
])) {
2980 // Get this course category's parent node.
2982 if ($coursecat->parent
&& isset($this->addedcategories
[$coursecat->parent
])) {
2983 $parent = $this->addedcategories
[$coursecat->parent
];
2986 // If it has no parent, then it should be right under the My courses node.
2987 $parent = $this->rootnodes
['mycourses'];
2990 // Build the category object based from the coursecat object.
2991 $mycategory = new stdClass();
2992 $mycategory->id
= $coursecat->id
;
2993 $mycategory->name
= $coursecat->name
;
2994 $mycategory->visible
= $coursecat->visible
;
2996 // Add this category to the nav tree.
2997 $this->add_category($mycategory, $parent, self
::TYPE_MY_CATEGORY
);
3001 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3002 foreach ($courses as $course) {
3003 $node = $this->add_course($course, false, self
::COURSE_MY
);
3005 $node->showinflatnavigation
= false;
3006 // Check if we should also add this to the flat nav as well.
3007 if (isset($flatnavcourses[$course->id
])) {
3008 $node->showinflatnavigation
= true;
3013 // Go through each course in the flatnav now.
3014 foreach ($flatnavcourses as $course) {
3015 // Check if we haven't already added it.
3016 if (!isset($courses[$course->id
])) {
3017 // Ok, add it to the flatnav only.
3018 $node = $this->add_course($course, false, self
::COURSE_MY
);
3019 $node->display
= false;
3020 $node->showinflatnavigation
= true;
3024 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3025 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3026 // Show a link to the course page if there are more courses the user is enrolled in.
3027 if ($showmorelinkinnav ||
$showmorelinkinflatnav) {
3028 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3029 $url = new moodle_url('/course/index.php#');
3030 $parent = $this->rootnodes
['mycourses'];
3031 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self
::TYPE_CUSTOM
, null, self
::COURSE_INDEX_PAGE
);
3033 if ($showmorelinkinnav) {
3034 $coursenode->display
= true;
3037 if ($showmorelinkinflatnav) {
3038 $coursenode->showinflatnavigation
= true;
3045 * The global navigation class used especially for AJAX requests.
3047 * The primary methods that are used in the global navigation class have been overriden
3048 * to ensure that only the relevant branch is generated at the root of the tree.
3049 * This can be done because AJAX is only used when the backwards structure for the
3050 * requested branch exists.
3051 * This has been done only because it shortens the amounts of information that is generated
3052 * which of course will speed up the response time.. because no one likes laggy AJAX.
3055 * @category navigation
3056 * @copyright 2009 Sam Hemelryk
3057 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3059 class global_navigation_for_ajax
extends global_navigation
{
3061 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3062 protected $branchtype;
3064 /** @var int the instance id */
3065 protected $instanceid;
3067 /** @var array Holds an array of expandable nodes */
3068 protected $expandable = array();
3071 * Constructs the navigation for use in an AJAX request
3073 * @param moodle_page $page moodle_page object
3074 * @param int $branchtype
3077 public function __construct($page, $branchtype, $id) {
3078 $this->page
= $page;
3079 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3080 $this->children
= new navigation_node_collection();
3081 $this->branchtype
= $branchtype;
3082 $this->instanceid
= $id;
3083 $this->initialise();
3086 * Initialise the navigation given the type and id for the branch to expand.
3088 * @return array An array of the expandable nodes
3090 public function initialise() {
3093 if ($this->initialised ||
during_initial_install()) {
3094 return $this->expandable
;
3096 $this->initialised
= true;
3098 $this->rootnodes
= array();
3099 $this->rootnodes
['site'] = $this->add_course($SITE);
3100 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self
::TYPE_ROOTNODE
, null, 'mycourses');
3101 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
3102 // The courses branch is always displayed, and is always expandable (although may be empty).
3103 // This mimicks what is done during {@link global_navigation::initialise()}.
3104 $this->rootnodes
['courses']->isexpandable
= true;
3106 // Branchtype will be one of navigation_node::TYPE_*
3107 switch ($this->branchtype
) {
3109 if ($this->instanceid
=== 'mycourses') {
3110 $this->load_courses_enrolled();
3111 } else if ($this->instanceid
=== 'courses') {
3112 $this->load_courses_other();
3115 case self
::TYPE_CATEGORY
:
3116 $this->load_category($this->instanceid
);
3118 case self
::TYPE_MY_CATEGORY
:
3119 $this->load_category($this->instanceid
, self
::TYPE_MY_CATEGORY
);
3121 case self
::TYPE_COURSE
:
3122 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
3123 if (!can_access_course($course, null, '', true)) {
3124 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3125 // add the course node and break. This leads to an empty node.
3126 $this->add_course($course);
3129 require_course_login($course, true, null, false, true);
3130 $this->page
->set_context(context_course
::instance($course->id
));
3131 $coursenode = $this->add_course($course);
3132 $this->add_course_essentials($coursenode, $course);
3133 $this->load_course_sections($course, $coursenode);
3135 case self
::TYPE_SECTION
:
3136 $sql = 'SELECT c.*, cs.section AS sectionnumber
3138 LEFT JOIN {course_sections} cs ON cs.course = c.id
3140 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
3141 require_course_login($course, true, null, false, true);
3142 $this->page
->set_context(context_course
::instance($course->id
));
3143 $coursenode = $this->add_course($course);
3144 $this->add_course_essentials($coursenode, $course);
3145 $this->load_course_sections($course, $coursenode, $course->sectionnumber
);
3147 case self
::TYPE_ACTIVITY
:
3150 JOIN {course_modules} cm ON cm.course = c.id
3151 WHERE cm.id = :cmid";
3152 $params = array('cmid' => $this->instanceid
);
3153 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3154 $modinfo = get_fast_modinfo($course);
3155 $cm = $modinfo->get_cm($this->instanceid
);
3156 require_course_login($course, true, $cm, false, true);
3157 $this->page
->set_context(context_module
::instance($cm->id
));
3158 $coursenode = $this->load_course($course);
3159 $this->load_course_sections($course, $coursenode, null, $cm);
3160 $activitynode = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
3161 if ($activitynode) {
3162 $modulenode = $this->load_activity($cm, $course, $activitynode);
3166 throw new Exception('Unknown type');
3167 return $this->expandable
;
3170 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
) {
3171 $this->load_for_user(null, true);
3174 $this->find_expandable($this->expandable
);
3175 return $this->expandable
;
3179 * They've expanded the general 'courses' branch.
3181 protected function load_courses_other() {
3182 $this->load_all_courses();
3186 * Loads a single category into the AJAX navigation.
3188 * This function is special in that it doesn't concern itself with the parent of
3189 * the requested category or its siblings.
3190 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3193 * @global moodle_database $DB
3194 * @param int $categoryid id of category to load in navigation.
3195 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3198 protected function load_category($categoryid, $nodetype = self
::TYPE_CATEGORY
) {
3202 if (!empty($CFG->navcourselimit
)) {
3203 $limit = (int)$CFG->navcourselimit
;
3206 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
3207 $sql = "SELECT cc.*, $catcontextsql
3208 FROM {course_categories} cc
3209 JOIN {context} ctx ON cc.id = ctx.instanceid
3210 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
3211 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3212 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3213 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3214 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3215 $categorylist = array();
3216 $subcategories = array();
3217 $basecategory = null;
3218 foreach ($categories as $category) {
3219 $categorylist[] = $category->id
;
3220 context_helper
::preload_from_record($category);
3221 if ($category->id
== $categoryid) {
3222 $this->add_category($category, $this, $nodetype);
3223 $basecategory = $this->addedcategories
[$category->id
];
3225 $subcategories[$category->id
] = $category;
3228 $categories->close();
3231 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3232 // else show all courses.
3233 if ($nodetype === self
::TYPE_MY_CATEGORY
) {
3234 $courses = enrol_get_my_courses('*');
3235 $categoryids = array();
3237 // Only search for categories if basecategory was found.
3238 if (!is_null($basecategory)) {
3239 // Get course parent category ids.
3240 foreach ($courses as $course) {
3241 $categoryids[] = $course->category
;
3244 // Get a unique list of category ids which a part of the path
3245 // to user's courses.
3246 $coursesubcategories = array();
3247 $addedsubcategories = array();
3249 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3250 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3252 foreach ($categories as $category){
3253 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path
, "/")));
3255 $coursesubcategories = array_unique($coursesubcategories);
3257 // Only add a subcategory if it is part of the path to user's course and
3258 // wasn't already added.
3259 foreach ($subcategories as $subid => $subcategory) {
3260 if (in_array($subid, $coursesubcategories) &&
3261 !in_array($subid, $addedsubcategories)) {
3262 $this->add_category($subcategory, $basecategory, $nodetype);
3263 $addedsubcategories[] = $subid;
3268 foreach ($courses as $course) {
3269 // Add course if it's in category.
3270 if (in_array($course->category
, $categorylist)) {
3271 $this->add_course($course, true, self
::COURSE_MY
);
3275 if (!is_null($basecategory)) {
3276 foreach ($subcategories as $key=>$category) {
3277 $this->add_category($category, $basecategory, $nodetype);
3280 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3281 foreach ($courses as $course) {
3282 $this->add_course($course);
3289 * Returns an array of expandable nodes
3292 public function get_expandable() {
3293 return $this->expandable
;
3300 * This class is used to manage the navbar, which is initialised from the navigation
3301 * object held by PAGE
3304 * @category navigation
3305 * @copyright 2009 Sam Hemelryk
3306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3308 class navbar
extends navigation_node
{
3309 /** @var bool A switch for whether the navbar is initialised or not */
3310 protected $initialised = false;
3311 /** @var mixed keys used to reference the nodes on the navbar */
3312 protected $keys = array();
3313 /** @var null|string content of the navbar */
3314 protected $content = null;
3315 /** @var moodle_page object the moodle page that this navbar belongs to */
3317 /** @var bool A switch for whether to ignore the active navigation information */
3318 protected $ignoreactive = false;
3319 /** @var bool A switch to let us know if we are in the middle of an install */
3320 protected $duringinstall = false;
3321 /** @var bool A switch for whether the navbar has items */
3322 protected $hasitems = false;
3323 /** @var array An array of navigation nodes for the navbar */
3325 /** @var array An array of child node objects */
3326 public $children = array();
3327 /** @var bool A switch for whether we want to include the root node in the navbar */
3328 public $includesettingsbase = false;
3329 /** @var breadcrumb_navigation_node[] $prependchildren */
3330 protected $prependchildren = array();
3333 * The almighty constructor
3335 * @param moodle_page $page
3337 public function __construct(moodle_page
$page) {
3339 if (during_initial_install()) {
3340 $this->duringinstall
= true;
3343 $this->page
= $page;
3344 $this->text
= get_string('home');
3345 $this->shorttext
= get_string('home');
3346 $this->action
= new moodle_url($CFG->wwwroot
);
3347 $this->nodetype
= self
::NODETYPE_BRANCH
;
3348 $this->type
= self
::TYPE_SYSTEM
;
3352 * Quick check to see if the navbar will have items in.
3354 * @return bool Returns true if the navbar will have items, false otherwise
3356 public function has_items() {
3357 if ($this->duringinstall
) {
3359 } else if ($this->hasitems
!== false) {
3362 if (count($this->children
) > 0 ||
count($this->prependchildren
) > 0) {
3363 // There have been manually added items - there are definitely items.
3365 } else if (!$this->ignoreactive
) {
3366 // We will need to initialise the navigation structure to check if there are active items.
3367 $this->page
->navigation
->initialise($this->page
);
3368 $outcome = ($this->page
->navigation
->contains_active_node() ||
$this->page
->settingsnav
->contains_active_node());
3370 $this->hasitems
= $outcome;
3375 * Turn on/off ignore active
3377 * @param bool $setting
3379 public function ignore_active($setting=true) {
3380 $this->ignoreactive
= ($setting);
3384 * Gets a navigation node
3386 * @param string|int $key for referencing the navbar nodes
3387 * @param int $type breadcrumb_navigation_node::TYPE_*
3388 * @return breadcrumb_navigation_node|bool
3390 public function get($key, $type = null) {
3391 foreach ($this->children
as &$child) {
3392 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3396 foreach ($this->prependchildren
as &$child) {
3397 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3404 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3408 public function get_items() {
3411 // Make sure that navigation is initialised
3412 if (!$this->has_items()) {
3415 if ($this->items
!== null) {
3416 return $this->items
;
3419 if (count($this->children
) > 0) {
3420 // Add the custom children.
3421 $items = array_reverse($this->children
);
3424 // Check if navigation contains the active node
3425 if (!$this->ignoreactive
) {
3426 // We will need to ensure the navigation has been initialised.
3427 $this->page
->navigation
->initialise($this->page
);
3428 // Now find the active nodes on both the navigation and settings.
3429 $navigationactivenode = $this->page
->navigation
->find_active_node();
3430 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3432 if ($navigationactivenode && $settingsactivenode) {
3433 // Parse a combined navigation tree
3434 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3435 if (!$settingsactivenode->mainnavonly
) {
3436 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3438 $settingsactivenode = $settingsactivenode->parent
;
3440 if (!$this->includesettingsbase
) {
3441 // Removes the first node from the settings (root node) from the list
3444 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3445 if (!$navigationactivenode->mainnavonly
) {
3446 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3448 if (!empty($CFG->navshowcategories
) &&
3449 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3450 $navigationactivenode->parent
->key
=== 'currentcourse') {
3451 foreach ($this->get_course_categories() as $item) {
3452 $items[] = new breadcrumb_navigation_node($item);
3455 $navigationactivenode = $navigationactivenode->parent
;
3457 } else if ($navigationactivenode) {
3458 // Parse the navigation tree to get the active node
3459 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3460 if (!$navigationactivenode->mainnavonly
) {
3461 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3463 if (!empty($CFG->navshowcategories
) &&
3464 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3465 $navigationactivenode->parent
->key
=== 'currentcourse') {
3466 foreach ($this->get_course_categories() as $item) {
3467 $items[] = new breadcrumb_navigation_node($item);
3470 $navigationactivenode = $navigationactivenode->parent
;
3472 } else if ($settingsactivenode) {
3473 // Parse the settings navigation to get the active node
3474 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3475 if (!$settingsactivenode->mainnavonly
) {
3476 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3478 $settingsactivenode = $settingsactivenode->parent
;
3483 $items[] = new breadcrumb_navigation_node(array(
3484 'text' => $this->page
->navigation
->text
,
3485 'shorttext' => $this->page
->navigation
->shorttext
,
3486 'key' => $this->page
->navigation
->key
,
3487 'action' => $this->page
->navigation
->action
3490 if (count($this->prependchildren
) > 0) {
3491 // Add the custom children
3492 $items = array_merge($items, array_reverse($this->prependchildren
));
3495 $last = reset($items);
3497 $last->set_last(true);
3499 $this->items
= array_reverse($items);
3500 return $this->items
;
3504 * Get the list of categories leading to this course.
3506 * This function is used by {@link navbar::get_items()} to add back the "courses"
3507 * node and category chain leading to the current course. Note that this is only ever
3508 * called for the current course, so we don't need to bother taking in any parameters.
3512 private function get_course_categories() {
3514 require_once($CFG->dirroot
.'/course/lib.php');
3515 require_once($CFG->libdir
.'/coursecatlib.php');
3517 $categories = array();
3518 $cap = 'moodle/category:viewhiddencategories';
3519 $showcategories = coursecat
::count_all() > 1;
3521 if ($showcategories) {
3522 foreach ($this->page
->categories
as $category) {
3523 if (!$category->visible
&& !has_capability($cap, get_category_or_system_context($category->parent
))) {
3526 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id
));
3527 $name = format_string($category->name
, true, array('context' => context_coursecat
::instance($category->id
)));
3528 $categorynode = breadcrumb_navigation_node
::create($name, $url, self
::TYPE_CATEGORY
, null, $category->id
);
3529 if (!$category->visible
) {
3530 $categorynode->hidden
= true;
3532 $categories[] = $categorynode;
3536 // Don't show the 'course' node if enrolled in this course.
3537 if (!is_enrolled(context_course
::instance($this->page
->course
->id
, null, '', true))) {
3538 $courses = $this->page
->navigation
->get('courses');
3540 // Courses node may not be present.
3541 $courses = breadcrumb_navigation_node
::create(
3542 get_string('courses'),
3543 new moodle_url('/course/index.php'),
3544 self
::TYPE_CONTAINER
3547 $categories[] = $courses;
3554 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3556 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3557 * the way nodes get added to allow us to simply call add and have the node added to the
3560 * @param string $text
3561 * @param string|moodle_url|action_link $action An action to associate with this node.
3562 * @param int $type One of navigation_node::TYPE_*
3563 * @param string $shorttext
3564 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3565 * @param pix_icon $icon An optional icon to use for this node.
3566 * @return navigation_node
3568 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3569 if ($this->content
!== null) {
3570 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3573 // Properties array used when creating the new navigation node
3578 // Set the action if one was provided
3579 if ($action!==null) {
3580 $itemarray['action'] = $action;
3582 // Set the shorttext if one was provided
3583 if ($shorttext!==null) {
3584 $itemarray['shorttext'] = $shorttext;
3586 // Set the icon if one was provided
3588 $itemarray['icon'] = $icon;
3590 // Default the key to the number of children if not provided
3591 if ($key === null) {
3592 $key = count($this->children
);
3595 $itemarray['key'] = $key;
3596 // Set the parent to this node
3597 $itemarray['parent'] = $this;
3598 // Add the child using the navigation_node_collections add method
3599 $this->children
[] = new breadcrumb_navigation_node($itemarray);
3604 * Prepends a new navigation_node to the start of the navbar
3606 * @param string $text
3607 * @param string|moodle_url|action_link $action An action to associate with this node.
3608 * @param int $type One of navigation_node::TYPE_*
3609 * @param string $shorttext
3610 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3611 * @param pix_icon $icon An optional icon to use for this node.
3612 * @return navigation_node
3614 public function prepend($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3615 if ($this->content
!== null) {
3616 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3618 // Properties array used when creating the new navigation node.
3623 // Set the action if one was provided.
3624 if ($action!==null) {
3625 $itemarray['action'] = $action;
3627 // Set the shorttext if one was provided.
3628 if ($shorttext!==null) {
3629 $itemarray['shorttext'] = $shorttext;
3631 // Set the icon if one was provided.
3633 $itemarray['icon'] = $icon;
3635 // Default the key to the number of children if not provided.
3636 if ($key === null) {
3637 $key = count($this->children
);
3640 $itemarray['key'] = $key;
3641 // Set the parent to this node.
3642 $itemarray['parent'] = $this;
3643 // Add the child node to the prepend list.
3644 $this->prependchildren
[] = new breadcrumb_navigation_node($itemarray);
3650 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3651 * in particular adding extra metadata for search engine robots to leverage.
3654 * @category navigation
3655 * @copyright 2015 Brendan Heywood
3656 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3658 class breadcrumb_navigation_node
extends navigation_node
{
3660 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3661 private $last = false;
3664 * A proxy constructor
3666 * @param mixed $navnode A navigation_node or an array
3668 public function __construct($navnode) {
3669 if (is_array($navnode)) {
3670 parent
::__construct($navnode);
3671 } else if ($navnode instanceof navigation_node
) {
3673 // Just clone everything.
3674 $objvalues = get_object_vars($navnode);
3675 foreach ($objvalues as $key => $value) {
3676 $this->$key = $value;
3679 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3687 public function is_last() {
3693 * @param $val boolean
3695 public function set_last($val) {
3701 * Subclass of navigation_node allowing different rendering for the flat navigation
3702 * in particular allowing dividers and indents.
3705 * @category navigation
3706 * @copyright 2016 Damyon Wiese
3707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3709 class flat_navigation_node
extends navigation_node
{
3711 /** @var $indent integer The indent level */
3712 private $indent = 0;
3714 /** @var $showdivider bool Show a divider before this element */
3715 private $showdivider = false;
3718 * A proxy constructor
3720 * @param mixed $navnode A navigation_node or an array
3722 public function __construct($navnode, $indent) {
3723 if (is_array($navnode)) {
3724 parent
::__construct($navnode);
3725 } else if ($navnode instanceof navigation_node
) {
3727 // Just clone everything.
3728 $objvalues = get_object_vars($navnode);
3729 foreach ($objvalues as $key => $value) {
3730 $this->$key = $value;
3733 throw new coding_exception('Not a valid flat_navigation_node');
3735 $this->indent
= $indent;
3739 * Does this node represent a course section link.
3742 public function is_section() {
3743 return $this->type
== navigation_node
::TYPE_SECTION
;
3747 * In flat navigation - sections are active if we are looking at activities in the section.
3750 public function isactive() {
3753 if ($this->is_section()) {
3754 $active = $PAGE->navigation
->find_active_node();
3755 while ($active = $active->parent
) {
3756 if ($active->key
== $this->key
&& $active->type
== $this->type
) {
3761 return $this->isactive
;
3765 * Getter for "showdivider"
3768 public function showdivider() {
3769 return $this->showdivider
;
3773 * Setter for "showdivider"
3774 * @param $val boolean
3776 public function set_showdivider($val) {
3777 $this->showdivider
= $val;
3781 * Getter for "indent"
3784 public function get_indent() {
3785 return $this->indent
;
3789 * Setter for "indent"
3790 * @param $val boolean
3792 public function set_indent($val) {
3793 $this->indent
= $val;
3799 * Class used to generate a collection of navigation nodes most closely related
3800 * to the current page.
3803 * @copyright 2016 Damyon Wiese
3804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3806 class flat_navigation
extends navigation_node_collection
{
3807 /** @var moodle_page the moodle page that the navigation belongs to */
3813 * @param moodle_page $page
3815 public function __construct(moodle_page
&$page) {
3816 if (during_initial_install()) {
3819 $this->page
= $page;
3823 * Build the list of navigation nodes based on the current navigation and settings trees.
3826 public function initialise() {
3827 global $PAGE, $USER, $OUTPUT, $CFG;
3828 if (during_initial_install()) {
3834 $course = $PAGE->course
;
3836 $this->page
->navigation
->initialise();
3838 // First walk the nav tree looking for "flat_navigation" nodes.
3839 if ($course->id
> 1) {
3840 // It's a real course.
3841 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3843 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
3844 // This is the name that will be shown for the course.
3845 $coursename = empty($CFG->navshowfullcoursenames
) ?
3846 format_string($course->shortname
, true, array('context' => $coursecontext)) :
3847 format_string($course->fullname
, true, array('context' => $coursecontext));
3849 $flat = new flat_navigation_node(navigation_node
::create($coursename, $url), 0);
3850 $flat->key
= 'coursehome';
3852 $courseformat = course_get_format($course);
3853 $coursenode = $PAGE->navigation
->find_active_node();
3854 $targettype = navigation_node
::TYPE_COURSE
;
3856 // Single activity format has no course node - the course node is swapped for the activity node.
3857 if (!$courseformat->has_view_page()) {
3858 $targettype = navigation_node
::TYPE_ACTIVITY
;
3861 while (!empty($coursenode) && ($coursenode->type
!= $targettype)) {
3862 $coursenode = $coursenode->parent
;
3864 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
3865 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
3866 if ($coursenode && $coursenode->key
!= SITEID
) {
3868 foreach ($coursenode->children
as $child) {
3869 if ($child->action
) {
3870 $flat = new flat_navigation_node($child, 0);
3876 $this->page
->navigation
->build_flat_navigation_list($this, true);
3878 $this->page
->navigation
->build_flat_navigation_list($this, false);
3881 $admin = $PAGE->settingsnav
->find('siteadministration', navigation_node
::TYPE_SITE_ADMIN
);
3883 // Try again - crazy nav tree!
3884 $admin = $PAGE->settingsnav
->find('root', navigation_node
::TYPE_SITE_ADMIN
);
3887 $flat = new flat_navigation_node($admin, 0);
3888 $flat->set_showdivider(true);
3889 $flat->key
= 'sitesettings';
3893 // Add-a-block in editing mode.
3894 if (isset($this->page
->theme
->addblockposition
) &&
3895 $this->page
->theme
->addblockposition
== BLOCK_ADDBLOCK_POSITION_FLATNAV
&&
3896 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
3897 ($addable = $PAGE->blocks
->get_addable_blocks())) {
3898 $url = new moodle_url($PAGE->url
, ['bui_addblock' => '', 'sesskey' => sesskey()]);
3899 $addablock = navigation_node
::create(get_string('addblock'), $url);
3900 $flat = new flat_navigation_node($addablock, 0);
3901 $flat->set_showdivider(true);
3902 $flat->key
= 'addblock';
3905 foreach ($addable as $block) {
3906 $blocks[] = $block->name
;
3908 $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
3909 $PAGE->requires
->js_call_amd('core/addblockmodal', 'init', array($params));
3916 * Class used to manage the settings option for the current page
3918 * This class is used to manage the settings options in a tree format (recursively)
3919 * and was created initially for use with the settings blocks.
3922 * @category navigation
3923 * @copyright 2009 Sam Hemelryk
3924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3926 class settings_navigation
extends navigation_node
{
3927 /** @var stdClass the current context */
3929 /** @var moodle_page the moodle page that the navigation belongs to */
3931 /** @var string contains administration section navigation_nodes */
3932 protected $adminsection;
3933 /** @var bool A switch to see if the navigation node is initialised */
3934 protected $initialised = false;
3935 /** @var array An array of users that the nodes can extend for. */
3936 protected $userstoextendfor = array();
3937 /** @var navigation_cache **/
3941 * Sets up the object with basic settings and preparse it for use
3943 * @param moodle_page $page
3945 public function __construct(moodle_page
&$page) {
3946 if (during_initial_install()) {
3949 $this->page
= $page;
3950 // Initialise the main navigation. It is most important that this is done
3951 // before we try anything
3952 $this->page
->navigation
->initialise();
3953 // Initialise the navigation cache
3954 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3955 $this->children
= new navigation_node_collection();
3959 * Initialise the settings navigation based on the current context
3961 * This function initialises the settings navigation tree for a given context
3962 * by calling supporting functions to generate major parts of the tree.
3965 public function initialise() {
3966 global $DB, $SESSION, $SITE;
3968 if (during_initial_install()) {
3970 } else if ($this->initialised
) {
3973 $this->id
= 'settingsnav';
3974 $this->context
= $this->page
->context
;
3976 $context = $this->context
;
3977 if ($context->contextlevel
== CONTEXT_BLOCK
) {
3978 $this->load_block_settings();
3979 $context = $context->get_parent_context();
3981 switch ($context->contextlevel
) {
3982 case CONTEXT_SYSTEM
:
3983 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3984 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3987 case CONTEXT_COURSECAT
:
3988 $this->load_category_settings();
3990 case CONTEXT_COURSE
:
3991 if ($this->page
->course
->id
!= $SITE->id
) {
3992 $this->load_course_settings(($context->id
== $this->context
->id
));
3994 $this->load_front_page_settings(($context->id
== $this->context
->id
));
3997 case CONTEXT_MODULE
:
3998 $this->load_module_settings();
3999 $this->load_course_settings();
4002 if ($this->page
->course
->id
!= $SITE->id
) {
4003 $this->load_course_settings();
4008 $usersettings = $this->load_user_settings($this->page
->course
->id
);
4010 $adminsettings = false;
4011 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin
) ||
$SESSION->load_navigation_admin
)) {
4012 $isadminpage = $this->is_admin_tree_needed();
4014 if (has_capability('moodle/site:configview', context_system
::instance())) {
4015 if (has_capability('moodle/site:config', context_system
::instance())) {
4016 // Make sure this works even if config capability changes on the fly
4017 // and also make it fast for admin right after login.
4018 $SESSION->load_navigation_admin
= 1;
4020 $adminsettings = $this->load_administration_settings();
4023 } else if (!isset($SESSION->load_navigation_admin
)) {
4024 $adminsettings = $this->load_administration_settings();
4025 $SESSION->load_navigation_admin
= (int)($adminsettings->children
->count() > 0);
4027 } else if ($SESSION->load_navigation_admin
) {
4029 $adminsettings = $this->load_administration_settings();
4033 // Print empty navigation node, if needed.
4034 if ($SESSION->load_navigation_admin
&& !$isadminpage) {
4035 if ($adminsettings) {
4036 // Do not print settings tree on pages that do not need it, this helps with performance.
4037 $adminsettings->remove();
4038 $adminsettings = false;
4040 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4041 self
::TYPE_SITE_ADMIN
, null, 'siteadministration');
4042 $siteadminnode->id
= 'expandable_branch_' . $siteadminnode->type
. '_' .
4043 clean_param($siteadminnode->key
, PARAM_ALPHANUMEXT
);
4044 $siteadminnode->requiresajaxloading
= 'true';
4049 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $adminsettings) {
4050 $adminsettings->force_open();
4051 } else if ($context->contextlevel
== CONTEXT_USER
&& $usersettings) {
4052 $usersettings->force_open();
4055 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4056 $this->load_local_plugin_settings();
4058 foreach ($this->children
as $key=>$node) {
4059 if ($node->nodetype
== self
::NODETYPE_BRANCH
&& $node->children
->count() == 0) {
4060 // Site administration is shown as link.
4061 if (!empty($SESSION->load_navigation_admin
) && ($node->type
=== self
::TYPE_SITE_ADMIN
)) {
4067 $this->initialised
= true;
4070 * Override the parent function so that we can add preceeding hr's and set a
4071 * root node class against all first level element
4073 * It does this by first calling the parent's add method {@link navigation_node::add()}
4074 * and then proceeds to use the key to set class and hr
4076 * @param string $text text to be used for the link.
4077 * @param string|moodle_url $url url for the new node
4078 * @param int $type the type of node navigation_node::TYPE_*
4079 * @param string $shorttext
4080 * @param string|int $key a key to access the node by.
4081 * @param pix_icon $icon An icon that appears next to the node.
4082 * @return navigation_node with the new node added to it.
4084 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4085 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
4086 $node->add_class('root_node');
4091 * This function allows the user to add something to the start of the settings
4092 * navigation, which means it will be at the top of the settings navigation block
4094 * @param string $text text to be used for the link.
4095 * @param string|moodle_url $url url for the new node
4096 * @param int $type the type of node navigation_node::TYPE_*
4097 * @param string $shorttext
4098 * @param string|int $key a key to access the node by.
4099 * @param pix_icon $icon An icon that appears next to the node.
4100 * @return navigation_node $node with the new node added to it.
4102 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4103 $children = $this->children
;
4104 $childrenclass = get_class($children);
4105 $this->children
= new $childrenclass;
4106 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4107 foreach ($children as $child) {
4108 $this->children
->add($child);
4114 * Does this page require loading of full admin tree or is
4115 * it enough rely on AJAX?
4119 protected function is_admin_tree_needed() {
4120 if (self
::$loadadmintree) {
4121 // Usually external admin page or settings page.
4125 if ($this->page
->pagelayout
=== 'admin' or strpos($this->page
->pagetype
, 'admin-') === 0) {
4126 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4127 if ($this->page
->context
->contextlevel
!= CONTEXT_SYSTEM
) {
4137 * Load the site administration tree
4139 * This function loads the site administration tree by using the lib/adminlib library functions
4141 * @param navigation_node $referencebranch A reference to a branch in the settings
4143 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4144 * tree and start at the beginning
4145 * @return mixed A key to access the admin tree by
4147 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
4150 // Check if we are just starting to generate this navigation.
4151 if ($referencebranch === null) {
4153 // Require the admin lib then get an admin structure
4154 if (!function_exists('admin_get_root')) {
4155 require_once($CFG->dirroot
.'/lib/adminlib.php');
4157 $adminroot = admin_get_root(false, false);
4158 // This is the active section identifier
4159 $this->adminsection
= $this->page
->url
->param('section');
4161 // Disable the navigation from automatically finding the active node
4162 navigation_node
::$autofindactive = false;
4163 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self
::TYPE_SITE_ADMIN
, null, 'root');
4164 foreach ($adminroot->children
as $adminbranch) {
4165 $this->load_administration_settings($referencebranch, $adminbranch);
4167 navigation_node
::$autofindactive = true;
4169 // Use the admin structure to locate the active page
4170 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
4171 $currentnode = $this;
4172 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
4173 $currentnode = $currentnode->get($pathkey);
4176 $currentnode->make_active();
4179 $this->scan_for_active_node($referencebranch);
4181 return $referencebranch;
4182 } else if ($adminbranch->check_access()) {
4183 // We have a reference branch that we can access and is not hidden `hurrah`
4184 // Now we need to display it and any children it may have
4187 if ($adminbranch instanceof admin_settingpage
) {
4188 $url = new moodle_url('/'.$CFG->admin
.'/settings.php', array('section'=>$adminbranch->name
));
4189 } else if ($adminbranch instanceof admin_externalpage
) {
4190 $url = $adminbranch->url
;
4191 } else if (!empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
4192 $url = new moodle_url('/'.$CFG->admin
.'/category.php', array('category' => $adminbranch->name
));
4196 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
4198 if ($adminbranch->is_hidden()) {
4199 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
4200 $reference->add_class('hidden');
4202 $reference->display
= false;
4206 // Check if we are generating the admin notifications and whether notificiations exist
4207 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
4208 $reference->add_class('criticalnotification');
4210 // Check if this branch has children
4211 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
4212 foreach ($adminbranch->children
as $branch) {
4213 // Generate the child branches as well now using this branch as the reference
4214 $this->load_administration_settings($reference, $branch);
4217 $reference->icon
= new pix_icon('i/settings', '');
4223 * This function recursivily scans nodes until it finds the active node or there
4224 * are no more nodes.
4225 * @param navigation_node $node
4227 protected function scan_for_active_node(navigation_node
$node) {
4228 if (!$node->check_if_active() && $node->children
->count()>0) {
4229 foreach ($node->children
as &$child) {
4230 $this->scan_for_active_node($child);
4236 * Gets a navigation node given an array of keys that represent the path to
4239 * @param array $path
4240 * @return navigation_node|false
4242 protected function get_by_path(array $path) {
4243 $node = $this->get(array_shift($path));
4244 foreach ($path as $key) {
4251 * This function loads the course settings that are available for the user
4253 * @param bool $forceopen If set to true the course node will be forced open
4254 * @return navigation_node|false
4256 protected function load_course_settings($forceopen = false) {
4258 require_once($CFG->dirroot
. '/course/lib.php');
4260 $course = $this->page
->course
;
4261 $coursecontext = context_course
::instance($course->id
);
4262 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4264 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4266 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
4268 $coursenode->force_open();
4272 if ($adminoptions->update
) {
4273 // Add the course settings link
4274 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
4275 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, 'editsettings', new pix_icon('i/settings', ''));
4278 if ($this->page
->user_allowed_editing()) {
4279 // Add the turn on/off settings
4281 if ($this->page
->url
->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE
)) {
4282 // We are on the course page, retain the current page params e.g. section.
4283 $baseurl = clone($this->page
->url
);
4284 $baseurl->param('sesskey', sesskey());
4286 // Edit on the main course page.
4287 $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id
, 'return'=>$this->page
->url
->out_as_local_url(false), 'sesskey'=>sesskey()));
4290 $editurl = clone($baseurl);
4291 if ($this->page
->user_is_editing()) {
4292 $editurl->param('edit', 'off');
4293 $editstring = get_string('turneditingoff');
4295 $editurl->param('edit', 'on');
4296 $editstring = get_string('turneditingon');
4298 $coursenode->add($editstring, $editurl, self
::TYPE_SETTING
, null, 'turneditingonoff', new pix_icon('i/edit', ''));
4301 if ($adminoptions->editcompletion
) {
4302 // Add the course completion settings link
4303 $url = new moodle_url('/course/completion.php', array('id' => $course->id
));
4304 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self
::TYPE_SETTING
, null, null,
4305 new pix_icon('i/settings', ''));
4308 if (!$adminoptions->update
&& $adminoptions->tags
) {
4309 $url = new moodle_url('/course/tags.php', array('id' => $course->id
));
4310 $coursenode->add(get_string('coursetags', 'tag'), $url, self
::TYPE_SETTING
, null, 'coursetags', new pix_icon('i/settings', ''));
4314 enrol_add_course_navigation($coursenode, $course);
4317 if ($adminoptions->filters
) {
4318 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4319 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
4322 // View course reports.
4323 if ($adminoptions->reports
) {
4324 $reportnav = $coursenode->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, 'coursereports',
4325 new pix_icon('i/stats', ''));
4326 $coursereports = core_component
::get_plugin_list('coursereport');
4327 foreach ($coursereports as $report => $dir) {
4328 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
4329 if (file_exists($libfile)) {
4330 require_once($libfile);
4331 $reportfunction = $report.'_report_extend_navigation';
4332 if (function_exists($report.'_report_extend_navigation')) {
4333 $reportfunction($reportnav, $course, $coursecontext);
4338 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4339 foreach ($reports as $reportfunction) {
4340 $reportfunction($reportnav, $course, $coursecontext);
4344 // Check if we can view the gradebook's setup page.
4345 if ($adminoptions->gradebook
) {
4346 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id
));
4347 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self
::TYPE_SETTING
,
4348 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4351 // Add outcome if permitted
4352 if ($adminoptions->outcomes
) {
4353 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
4354 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
4357 //Add badges navigation
4358 if ($adminoptions->badges
) {
4359 require_once($CFG->libdir
.'/badgeslib.php');
4360 badges_add_course_navigation($coursenode, $course);
4363 // Backup this course
4364 if ($adminoptions->backup
) {
4365 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4366 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
4369 // Restore to this course
4370 if ($adminoptions->restore
) {
4371 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4372 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
4375 // Import data from other courses
4376 if ($adminoptions->import
) {
4377 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
4378 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/import', ''));
4381 // Publish course on a hub
4382 if ($adminoptions->publish
) {
4383 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
4384 $coursenode->add(get_string('publish'), $url, self
::TYPE_SETTING
, null, 'publish', new pix_icon('i/publish', ''));
4387 // Reset this course
4388 if ($adminoptions->reset
) {
4389 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
4390 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, 'reset', new pix_icon('i/return', ''));
4394 require_once($CFG->libdir
. '/questionlib.php');
4395 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4397 if ($adminoptions->update
) {
4398 // Repository Instances
4399 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
4400 require_once($CFG->dirroot
. '/repository/lib.php');
4401 $editabletypes = repository
::get_editable_types($coursecontext);
4402 $haseditabletypes = !empty($editabletypes);
4403 unset($editabletypes);
4404 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
4406 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
4408 if ($haseditabletypes) {
4409 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
4410 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
4415 if ($adminoptions->files
) {
4416 // hidden in new courses and courses where legacy files were turned off
4417 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
4418 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/folder', ''));
4422 // Let plugins hook into course navigation.
4423 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4424 foreach ($pluginsfunction as $plugintype => $plugins) {
4425 // Ignore the report plugin as it was already loaded above.
4426 if ($plugintype == 'report') {
4429 foreach ($plugins as $pluginfunction) {
4430 $pluginfunction($coursenode, $course, $coursecontext);
4434 // Return we are done
4439 * This function calls the module function to inject module settings into the
4440 * settings navigation tree.
4442 * This only gets called if there is a corrosponding function in the modules
4445 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4447 * @return navigation_node|false
4449 protected function load_module_settings() {
4452 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
4453 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
4454 $this->page
->set_cm($cm, $this->page
->course
);
4457 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
4458 if (file_exists($file)) {
4459 require_once($file);
4462 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
), null, self
::TYPE_SETTING
, null, 'modulesettings');
4463 $modulenode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
4464 $modulenode->force_open();
4466 // Settings for the module
4467 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
4468 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => 1));
4469 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
4471 // Assign local roles
4472 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
4473 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
4474 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
4477 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
4478 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
4479 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
4481 // Check role permissions
4482 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
4483 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
4484 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
4487 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
4488 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
4489 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
4492 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4493 foreach ($reports as $reportfunction) {
4494 $reportfunction($modulenode, $this->page
->cm
);
4496 // Add a backup link
4497 $featuresfunc = $this->page
->activityname
.'_supports';
4498 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
4499 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
4500 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
4503 // Restore this activity
4504 $featuresfunc = $this->page
->activityname
.'_supports';
4505 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
4506 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
4507 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
4510 // Allow the active advanced grading method plugin to append its settings
4511 $featuresfunc = $this->page
->activityname
.'_supports';
4512 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
4513 require_once($CFG->dirroot
.'/grade/grading/lib.php');
4514 $gradingman = get_grading_manager($this->page
->cm
->context
, 'mod_'.$this->page
->activityname
);
4515 $gradingman->extend_settings_navigation($this, $modulenode);
4518 $function = $this->page
->activityname
.'_extend_settings_navigation';
4519 if (function_exists($function)) {
4520 $function($this, $modulenode);
4523 // Remove the module node if there are no children.
4524 if ($modulenode->children
->count() <= 0) {
4525 $modulenode->remove();
4532 * Loads the user settings block of the settings nav
4534 * This function is simply works out the userid and whether we need to load
4535 * just the current users profile settings, or the current user and the user the
4536 * current user is viewing.
4538 * This function has some very ugly code to work out the user, if anyone has
4539 * any bright ideas please feel free to intervene.
4541 * @param int $courseid The course id of the current course
4542 * @return navigation_node|false
4544 protected function load_user_settings($courseid = SITEID
) {
4547 if (isguestuser() ||
!isloggedin()) {
4551 $navusers = $this->page
->navigation
->get_extending_users();
4553 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
4555 foreach ($this->userstoextendfor
as $userid) {
4556 if ($userid == $USER->id
) {
4559 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4560 if (is_null($usernode)) {
4564 foreach ($navusers as $user) {
4565 if ($user->id
== $USER->id
) {
4568 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
4569 if (is_null($usernode)) {
4573 $this->generate_user_settings($courseid, $USER->id
);
4575 $usernode = $this->generate_user_settings($courseid, $USER->id
);
4581 * Extends the settings navigation for the given user.
4583 * Note: This method gets called automatically if you call
4584 * $PAGE->navigation->extend_for_user($userid)
4586 * @param int $userid
4588 public function extend_for_user($userid) {
4591 if (!in_array($userid, $this->userstoextendfor
)) {
4592 $this->userstoextendfor
[] = $userid;
4593 if ($this->initialised
) {
4594 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
4595 $children = array();
4596 foreach ($this->children
as $child) {
4597 $children[] = $child;
4599 array_unshift($children, array_pop($children));
4600 $this->children
= new navigation_node_collection();
4601 foreach ($children as $child) {
4602 $this->children
->add($child);
4609 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4610 * what can be shown/done
4612 * @param int $courseid The current course' id
4613 * @param int $userid The user id to load for
4614 * @param string $gstitle The string to pass to get_string for the branch title
4615 * @return navigation_node|false
4617 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4618 global $DB, $CFG, $USER, $SITE;
4620 if ($courseid != $SITE->id
) {
4621 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
4622 $course = $this->page
->course
;
4624 $select = context_helper
::get_preload_record_columns_sql('ctx');
4625 $sql = "SELECT c.*, $select
4627 JOIN {context} ctx ON c.id = ctx.instanceid
4628 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4629 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
4630 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
4631 context_helper
::preload_from_record($course);
4637 $coursecontext = context_course
::instance($course->id
); // Course context
4638 $systemcontext = context_system
::instance();
4639 $currentuser = ($USER->id
== $userid);
4643 $usercontext = context_user
::instance($user->id
); // User context
4645 $select = context_helper
::get_preload_record_columns_sql('ctx');
4646 $sql = "SELECT u.*, $select
4648 JOIN {context} ctx ON u.id = ctx.instanceid
4649 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4650 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
4651 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
4655 context_helper
::preload_from_record($user);
4657 // Check that the user can view the profile
4658 $usercontext = context_user
::instance($user->id
); // User context
4659 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4661 if ($course->id
== $SITE->id
) {
4662 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4663 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4667 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4668 $userisenrolled = is_enrolled($coursecontext, $user->id
, '', true);
4669 if ((!$canviewusercourse && !$canviewuser) ||
!$userisenrolled) {
4672 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4673 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
&& !$canviewuser) {
4674 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4675 if ($courseid == $this->page
->course
->id
) {
4676 $mygroups = get_fast_modinfo($this->page
->course
)->groups
;
4678 $mygroups = groups_get_user_groups($courseid);
4680 $usergroups = groups_get_user_groups($courseid, $userid);
4681 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4688 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
4691 $prefurl = new moodle_url('/user/preferences.php');
4692 if ($gstitle != 'usercurrentsettings') {
4694 $prefurl->param('userid', $userid);
4697 // Add a user setting branch.
4698 if ($gstitle == 'usercurrentsettings') {
4699 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_CONTAINER
, null, 'dashboard');
4700 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
4702 $dashboard->display
= false;
4703 if (get_home_page() == HOMEPAGE_MY
) {
4704 $dashboard->mainnavonly
= true;
4707 $iscurrentuser = ($user->id
== $USER->id
);
4709 $baseargs = array('id' => $user->id
);
4710 if ($course->id
!= $SITE->id
&& !$iscurrentuser) {
4711 $baseargs['course'] = $course->id
;
4712 $issitecourse = false;
4714 // Load all categories and get the context for the system.
4715 $issitecourse = true;
4718 // Add the user profile to the dashboard.
4719 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
4720 array('id' => $user->id
)), self
::TYPE_SETTING
, null, 'myprofile');
4722 if (!empty($CFG->navadduserpostslinks
)) {
4723 // Add nodes for forum posts and discussions if the user can view either or both
4724 // There are no capability checks here as the content of the page is based
4725 // purely on the forums the current user has access too.
4726 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
4727 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
4728 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
4729 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
4733 if (!empty($CFG->enableblogs
)) {
4734 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
4735 require_once($CFG->dirroot
.'/blog/lib.php');
4736 // Get all options for the user.
4737 $options = blog_get_options_for_user($user);
4738 $this->cache
->set('userblogoptions'.$user->id
, $options);
4740 $options = $this->cache
->{'userblogoptions'.$user->id
};
4743 if (count($options) > 0) {
4744 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
4745 foreach ($options as $type => $option) {
4746 if ($type == "rss") {
4747 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, null,
4748 new pix_icon('i/rss', ''));
4750 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, 'blog' . $type);
4756 // Add the messages link.
4757 // It is context based so can appear in the user's profile and in course participants information.
4758 if (!empty($CFG->messaging
)) {
4759 $messageargs = array('user1' => $USER->id
);
4760 if ($USER->id
!= $user->id
) {
4761 $messageargs['user2'] = $user->id
;
4763 $url = new moodle_url('/message/index.php', $messageargs);
4764 $dashboard->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
4767 // Add the "My private files" link.
4768 // This link doesn't have a unique display for course context so only display it under the user's profile.
4769 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
4770 $url = new moodle_url('/user/files.php');
4771 $dashboard->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
4774 // Add a node to view the users notes if permitted.
4775 if (!empty($CFG->enablenotes
) &&
4776 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
4777 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
4778 if ($coursecontext->instanceid
!= SITEID
) {
4779 $url->param('course', $coursecontext->instanceid
);
4781 $profilenode->add(get_string('notes', 'notes'), $url);
4784 // Show the grades node.
4785 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
4786 require_once($CFG->dirroot
. '/user/lib.php');
4787 // Set the grades node to link to the "Grades" page.
4788 if ($course->id
== SITEID
) {
4789 $url = user_mygrades_url($user->id
, $course->id
);
4790 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
4791 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
4793 $dashboard->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'mygrades');
4796 // Let plugins hook into user navigation.
4797 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
4798 foreach ($pluginsfunction as $plugintype => $plugins) {
4799 if ($plugintype != 'report') {
4800 foreach ($plugins as $pluginfunction) {
4801 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
4806 $usersetting = navigation_node
::create(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
4807 $dashboard->add_node($usersetting);
4809 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
4810 $usersetting->display
= false;
4812 $usersetting->id
= 'usersettings';
4814 // Check if the user has been deleted.
4815 if ($user->deleted
) {
4816 if (!has_capability('moodle/user:update', $coursecontext)) {
4817 // We can't edit the user so just show the user deleted message.
4818 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
4820 // We can edit the user so show the user deleted message and link it to the profile.
4821 if ($course->id
== $SITE->id
) {
4822 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
4824 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
4826 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
4831 $userauthplugin = false;
4832 if (!empty($user->auth
)) {
4833 $userauthplugin = get_auth_plugin($user->auth
);
4836 $useraccount = $usersetting->add(get_string('useraccount'), null, self
::TYPE_CONTAINER
, null, 'useraccount');
4838 // Add the profile edit link.
4839 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4840 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) &&
4841 has_capability('moodle/user:update', $systemcontext)) {
4842 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
4843 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
4844 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
4845 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
4846 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
4847 $url = $userauthplugin->edit_profile_url();
4849 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
4851 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
4856 // Change password link.
4857 if ($userauthplugin && $currentuser && !\core\session\manager
::is_loggedinas() && !isguestuser() &&
4858 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
4859 $passwordchangeurl = $userauthplugin->change_password_url();
4860 if (empty($passwordchangeurl)) {
4861 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
4863 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
, null, 'changepassword');
4866 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4867 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4868 has_capability('moodle/user:editprofile', $usercontext)) {
4869 $url = new moodle_url('/user/language.php', array('id' => $user->id
, 'course' => $course->id
));
4870 $useraccount->add(get_string('preferredlanguage'), $url, self
::TYPE_SETTING
, null, 'preferredlanguage');
4873 $pluginmanager = core_plugin_manager
::instance();
4874 $enabled = $pluginmanager->get_enabled_plugins('mod');
4875 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4876 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4877 has_capability('moodle/user:editprofile', $usercontext)) {
4878 $url = new moodle_url('/user/forum.php', array('id' => $user->id
, 'course' => $course->id
));
4879 $useraccount->add(get_string('forumpreferences'), $url, self
::TYPE_SETTING
);
4882 $editors = editors_get_enabled();
4883 if (count($editors) > 1) {
4884 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
4885 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4886 has_capability('moodle/user:editprofile', $usercontext)) {
4887 $url = new moodle_url('/user/editor.php', array('id' => $user->id
, 'course' => $course->id
));
4888 $useraccount->add(get_string('editorpreferences'), $url, self
::TYPE_SETTING
);
4893 // Add "Course preferences" link.
4894 if (isloggedin() && !isguestuser($user)) {
4895 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4896 has_capability('moodle/user:editprofile', $usercontext)) {
4897 $url = new moodle_url('/user/course.php', array('id' => $user->id
, 'course' => $course->id
));
4898 $useraccount->add(get_string('coursepreferences'), $url, self
::TYPE_SETTING
, null, 'coursepreferences');
4902 // Add "Calendar preferences" link.
4903 if (isloggedin() && !isguestuser($user)) {
4904 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
4905 has_capability('moodle/user:editprofile', $usercontext)) {
4906 $url = new moodle_url('/user/calendar.php', array('id' => $user->id
));
4907 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self
::TYPE_SETTING
, null, 'preferredcalendar');
4911 // View the roles settings.
4912 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
4913 'moodle/role:manage'), $usercontext)) {
4914 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
4916 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
4917 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
4919 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
4921 if (!empty($assignableroles)) {
4922 $url = new moodle_url('/admin/roles/assign.php',
4923 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4924 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
4927 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
4928 $url = new moodle_url('/admin/roles/permissions.php',
4929 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4930 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
4933 $url = new moodle_url('/admin/roles/check.php',
4934 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
4935 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
4939 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
4940 require_once($CFG->dirroot
. '/repository/lib.php');
4941 $editabletypes = repository
::get_editable_types($usercontext);
4942 $haseditabletypes = !empty($editabletypes);
4943 unset($editabletypes);
4944 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
4946 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
4948 if ($haseditabletypes) {
4949 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self
::TYPE_SETTING
);
4950 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
4951 array('contextid' => $usercontext->id
)));
4955 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
4956 require_once($CFG->libdir
. '/portfoliolib.php');
4957 if (portfolio_has_visible_instances()) {
4958 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
4960 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
4961 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
4963 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
4964 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
4968 $enablemanagetokens = false;
4969 if (!empty($CFG->enablerssfeeds
)) {
4970 $enablemanagetokens = true;
4971 } else if (!is_siteadmin($USER->id
)
4972 && !empty($CFG->enablewebservices
)
4973 && has_capability('moodle/webservice:createtoken', context_system
::instance()) ) {
4974 $enablemanagetokens = true;
4977 if ($currentuser && $enablemanagetokens) {
4978 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
4979 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
4983 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) &&
4984 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
4985 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id
));
4986 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id
));
4987 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self
::TYPE_SETTING
);
4988 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self
::TYPE_SETTING
);
4992 if ($currentuser && !empty($CFG->enableblogs
)) {
4993 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
4994 if (has_capability('moodle/blog:view', $systemcontext)) {
4995 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
4996 navigation_node
::TYPE_SETTING
);
4998 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 &&
4999 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5000 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5001 navigation_node
::TYPE_SETTING
);
5002 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5003 navigation_node
::TYPE_SETTING
);
5005 // Remove the blog node if empty.
5006 $blog->trim_if_empty();
5010 if ($currentuser && !empty($CFG->enablebadges
)) {
5011 $badges = $usersetting->add(get_string('badges'), null, navigation_node
::TYPE_CONTAINER
, null, 'badges');
5012 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5013 $url = new moodle_url('/badges/mybadges.php');
5014 $badges->add(get_string('managebadges', 'badges'), $url, self
::TYPE_SETTING
);
5016 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5017 navigation_node
::TYPE_SETTING
);
5018 if (!empty($CFG->badges_allowexternalbackpack
)) {
5019 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5020 navigation_node
::TYPE_SETTING
);
5024 // Let plugins hook into user settings navigation.
5025 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5026 foreach ($pluginsfunction as $plugintype => $plugins) {
5027 foreach ($plugins as $pluginfunction) {
5028 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5032 return $usersetting;
5036 * Loads block specific settings in the navigation
5038 * @return navigation_node
5040 protected function load_block_settings() {
5043 $blocknode = $this->add($this->context
->get_context_name(), null, self
::TYPE_SETTING
, null, 'blocksettings');
5044 $blocknode->force_open();
5046 // Assign local roles
5047 if (get_assignable_roles($this->context
, ROLENAME_ORIGINAL
)) {
5048 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $this->context
->id
));
5049 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null,
5050 'roles', new pix_icon('i/assignroles', ''));
5054 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
5055 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
5056 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null,
5057 'permissions', new pix_icon('i/permissions', ''));
5059 // Check role permissions
5060 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
5061 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
5062 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null,
5063 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5070 * Loads category specific settings in the navigation
5072 * @return navigation_node
5074 protected function load_category_settings() {
5077 // We can land here while being in the context of a block, in which case we
5078 // should get the parent context which should be the category one. See self::initialise().
5079 if ($this->context
->contextlevel
== CONTEXT_BLOCK
) {
5080 $catcontext = $this->context
->get_parent_context();
5082 $catcontext = $this->context
;
5085 // Let's make sure that we always have the right context when getting here.
5086 if ($catcontext->contextlevel
!= CONTEXT_COURSECAT
) {
5087 throw new coding_exception('Unexpected context while loading category settings.');
5090 $categorynodetype = navigation_node
::TYPE_CONTAINER
;
5091 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5092 $categorynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
5093 $categorynode->force_open();
5095 if (can_edit_in_category($catcontext->instanceid
)) {
5096 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid
));
5097 $editstring = get_string('managecategorythis');
5098 $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5101 if (has_capability('moodle/category:manage', $catcontext)) {
5102 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid
));
5103 $categorynode->add(get_string('editcategorythis'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
5105 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid
));
5106 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
5109 // Assign local roles
5110 $assignableroles = get_assignable_roles($catcontext);
5111 if (!empty($assignableroles)) {
5112 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $catcontext->id
));
5113 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
5117 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5118 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid' => $catcontext->id
));
5119 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
5121 // Check role permissions
5122 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5123 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5124 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid' => $catcontext->id
));
5125 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5129 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5130 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5131 array('contextid' => $catcontext->id
)), self
::TYPE_SETTING
, null, 'cohort', new pix_icon('i/cohort', ''));
5135 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5136 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id
));
5137 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
5141 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5142 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id
));
5143 $categorynode->add(get_string('restorecourse', 'admin'), $url, self
::TYPE_SETTING
, null, 'restorecourse', new pix_icon('i/restore', ''));
5146 // Let plugins hook into category settings navigation.
5147 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5148 foreach ($pluginsfunction as $plugintype => $plugins) {
5149 foreach ($plugins as $pluginfunction) {
5150 $pluginfunction($categorynode, $catcontext);
5154 return $categorynode;
5158 * Determine whether the user is assuming another role
5160 * This function checks to see if the user is assuming another role by means of
5161 * role switching. In doing this we compare each RSW key (context path) against
5162 * the current context path. This ensures that we can provide the switching
5163 * options against both the course and any page shown under the course.
5165 * @return bool|int The role(int) if the user is in another role, false otherwise
5167 protected function in_alternative_role() {
5169 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
5170 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
5171 return $USER->access
['rsw'][$this->page
->context
->path
];
5173 foreach ($USER->access
['rsw'] as $key=>$role) {
5174 if (strpos($this->context
->path
,$key)===0) {
5183 * This function loads all of the front page settings into the settings navigation.
5184 * This function is called when the user is on the front page, or $COURSE==$SITE
5185 * @param bool $forceopen (optional)
5186 * @return navigation_node
5188 protected function load_front_page_settings($forceopen = false) {
5190 require_once($CFG->dirroot
. '/course/lib.php');
5192 $course = clone($SITE);
5193 $coursecontext = context_course
::instance($course->id
); // Course context
5194 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5196 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
5198 $frontpage->force_open();
5200 $frontpage->id
= 'frontpagesettings';
5202 if ($this->page
->user_allowed_editing()) {
5204 // Add the turn on/off settings
5205 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
5206 if ($this->page
->user_is_editing()) {
5207 $url->param('edit', 'off');
5208 $editstring = get_string('turneditingoff');
5210 $url->param('edit', 'on');
5211 $editstring = get_string('turneditingon');
5213 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5216 if ($adminoptions->update
) {
5217 // Add the course settings link
5218 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5219 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
5223 enrol_add_course_navigation($frontpage, $course);
5226 if ($adminoptions->filters
) {
5227 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
5228 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
5231 // View course reports.
5232 if ($adminoptions->reports
) {
5233 $frontpagenav = $frontpage->add(get_string('reports'), null, self
::TYPE_CONTAINER
, null, 'frontpagereports',
5234 new pix_icon('i/stats', ''));
5235 $coursereports = core_component
::get_plugin_list('coursereport');
5236 foreach ($coursereports as $report=>$dir) {
5237 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
5238 if (file_exists($libfile)) {
5239 require_once($libfile);
5240 $reportfunction = $report.'_report_extend_navigation';
5241 if (function_exists($report.'_report_extend_navigation')) {
5242 $reportfunction($frontpagenav, $course, $coursecontext);
5247 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5248 foreach ($reports as $reportfunction) {
5249 $reportfunction($frontpagenav, $course, $coursecontext);
5253 // Backup this course
5254 if ($adminoptions->backup
) {
5255 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
5256 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
5259 // Restore to this course
5260 if ($adminoptions->restore
) {
5261 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
5262 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
5266 require_once($CFG->libdir
. '/questionlib.php');
5267 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5270 if ($adminoptions->files
) {
5271 //hiden in new installs
5272 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
5273 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/folder', ''));
5276 // Let plugins hook into frontpage navigation.
5277 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5278 foreach ($pluginsfunction as $plugintype => $plugins) {
5279 foreach ($plugins as $pluginfunction) {
5280 $pluginfunction($frontpage, $course, $coursecontext);
5288 * This function gives local plugins an opportunity to modify the settings navigation.
5290 protected function load_local_plugin_settings() {
5292 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5293 $function($this, $this->context
);
5298 * This function marks the cache as volatile so it is cleared during shutdown
5300 public function clear_cache() {
5301 $this->cache
->volatile();
5305 * Checks to see if there are child nodes available in the specific user's preference node.
5306 * If so, then they have the appropriate permissions view this user's preferences.
5308 * @since Moodle 2.9.3
5309 * @param int $userid The user's ID.
5310 * @return bool True if child nodes exist to view, otherwise false.
5312 public function can_view_user_preferences($userid) {
5313 if (is_siteadmin()) {
5316 // See if any nodes are present in the preferences section for this user.
5317 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5318 if ($preferencenode && $preferencenode->has_children()) {
5319 // Run through each child node.
5320 foreach ($preferencenode->children
as $childnode) {
5321 // If the child node has children then this user has access to a link in the preferences page.
5322 if ($childnode->has_children()) {
5327 // No links found for the user to access on the preferences page.
5333 * Class used to populate site admin navigation for ajax.
5336 * @category navigation
5337 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5338 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5340 class settings_navigation_ajax
extends settings_navigation
{
5342 * Constructs the navigation for use in an AJAX request
5344 * @param moodle_page $page
5346 public function __construct(moodle_page
&$page) {
5347 $this->page
= $page;
5348 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
5349 $this->children
= new navigation_node_collection();
5350 $this->initialise();
5354 * Initialise the site admin navigation.
5356 * @return array An array of the expandable nodes
5358 public function initialise() {
5359 if ($this->initialised ||
during_initial_install()) {
5362 $this->context
= $this->page
->context
;
5363 $this->load_administration_settings();
5365 // Check if local plugins is adding node to site admin.
5366 $this->load_local_plugin_settings();
5368 $this->initialised
= true;
5373 * Simple class used to output a navigation branch in XML
5376 * @category navigation
5377 * @copyright 2009 Sam Hemelryk
5378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5380 class navigation_json
{
5381 /** @var array An array of different node types */
5382 protected $nodetype = array('node','branch');
5383 /** @var array An array of node keys and types */
5384 protected $expandable = array();
5386 * Turns a branch and all of its children into XML
5388 * @param navigation_node $branch
5389 * @return string XML string
5391 public function convert($branch) {
5392 $xml = $this->convert_child($branch);
5396 * Set the expandable items in the array so that we have enough information
5397 * to attach AJAX events
5398 * @param array $expandable
5400 public function set_expandable($expandable) {
5401 foreach ($expandable as $node) {
5402 $this->expandable
[$node['key'].':'.$node['type']] = $node;
5406 * Recusively converts a child node and its children to XML for output
5408 * @param navigation_node $child The child to convert
5409 * @param int $depth Pointlessly used to track the depth of the XML structure
5410 * @return string JSON
5412 protected function convert_child($child, $depth=1) {
5413 if (!$child->display
) {
5416 $attributes = array();
5417 $attributes['id'] = $child->id
;
5418 $attributes['name'] = (string)$child->text
; // This can be lang_string object so typecast it.
5419 $attributes['type'] = $child->type
;
5420 $attributes['key'] = $child->key
;
5421 $attributes['class'] = $child->get_css_type();
5422 $attributes['requiresajaxloading'] = $child->requiresajaxloading
;
5424 if ($child->icon
instanceof pix_icon
) {
5425 $attributes['icon'] = array(
5426 'component' => $child->icon
->component
,
5427 'pix' => $child->icon
->pix
,
5429 foreach ($child->icon
->attributes
as $key=>$value) {
5430 if ($key == 'class') {
5431 $attributes['icon']['classes'] = explode(' ', $value);
5432 } else if (!array_key_exists($key, $attributes['icon'])) {
5433 $attributes['icon'][$key] = $value;
5437 } else if (!empty($child->icon
)) {
5438 $attributes['icon'] = (string)$child->icon
;
5441 if ($child->forcetitle ||
$child->title
!== $child->text
) {
5442 $attributes['title'] = htmlentities($child->title
, ENT_QUOTES
, 'UTF-8');
5444 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
5445 $attributes['expandable'] = $child->key
;
5446 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
5449 if (count($child->classes
)>0) {
5450 $attributes['class'] .= ' '.join(' ',$child->classes
);
5452 if (is_string($child->action
)) {
5453 $attributes['link'] = $child->action
;
5454 } else if ($child->action
instanceof moodle_url
) {
5455 $attributes['link'] = $child->action
->out();
5456 } else if ($child->action
instanceof action_link
) {
5457 $attributes['link'] = $child->action
->url
->out();
5459 $attributes['hidden'] = ($child->hidden
);
5460 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
5461 $attributes['haschildren'] = $attributes['haschildren'] ||
$child->type
== navigation_node
::TYPE_MY_CATEGORY
;
5463 if ($child->children
->count() > 0) {
5464 $attributes['children'] = array();
5465 foreach ($child->children
as $subchild) {
5466 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
5473 return json_encode($attributes);
5479 * The cache class used by global navigation and settings navigation.
5481 * It is basically an easy access point to session with a bit of smarts to make
5482 * sure that the information that is cached is valid still.
5486 * if (!$cache->viewdiscussion()) {
5487 * // Code to do stuff and produce cachable content
5488 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5490 * $content = $cache->viewdiscussion;
5494 * @category navigation
5495 * @copyright 2009 Sam Hemelryk
5496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5498 class navigation_cache
{
5499 /** @var int represents the time created */
5500 protected $creation;
5501 /** @var array An array of session keys */
5504 * The string to use to segregate this particular cache. It can either be
5505 * unique to start a fresh cache or if you want to share a cache then make
5506 * it the string used in the original cache.
5510 /** @var int a time that the information will time out */
5512 /** @var stdClass The current context */
5513 protected $currentcontext;
5514 /** @var int cache time information */
5515 const CACHETIME
= 0;
5516 /** @var int cache user id */
5517 const CACHEUSERID
= 1;
5518 /** @var int cache value */
5519 const CACHEVALUE
= 2;
5520 /** @var null|array An array of navigation cache areas to expire on shutdown */
5521 public static $volatilecaches;
5524 * Contructor for the cache. Requires two arguments
5526 * @param string $area The string to use to segregate this particular cache
5527 * it can either be unique to start a fresh cache or if you want
5528 * to share a cache then make it the string used in the original
5530 * @param int $timeout The number of seconds to time the information out after
5532 public function __construct($area, $timeout=1800) {
5533 $this->creation
= time();
5534 $this->area
= $area;
5535 $this->timeout
= time() - $timeout;
5536 if (rand(0,100) === 0) {
5537 $this->garbage_collection();
5542 * Used to set up the cache within the SESSION.
5544 * This is called for each access and ensure that we don't put anything into the session before
5547 protected function ensure_session_cache_initialised() {
5549 if (empty($this->session
)) {
5550 if (!isset($SESSION->navcache
)) {
5551 $SESSION->navcache
= new stdClass
;
5553 if (!isset($SESSION->navcache
->{$this->area
})) {
5554 $SESSION->navcache
->{$this->area
} = array();
5556 $this->session
= &$SESSION->navcache
->{$this->area
}; // pointer to array, =& is correct here
5561 * Magic Method to retrieve something by simply calling using = cache->key
5563 * @param mixed $key The identifier for the information you want out again
5564 * @return void|mixed Either void or what ever was put in
5566 public function __get($key) {
5567 if (!$this->cached($key)) {
5570 $information = $this->session
[$key][self
::CACHEVALUE
];
5571 return unserialize($information);
5575 * Magic method that simply uses {@link set();} to store something in the cache
5577 * @param string|int $key
5578 * @param mixed $information
5580 public function __set($key, $information) {
5581 $this->set($key, $information);
5585 * Sets some information against the cache (session) for later retrieval
5587 * @param string|int $key
5588 * @param mixed $information
5590 public function set($key, $information) {
5592 $this->ensure_session_cache_initialised();
5593 $information = serialize($information);
5594 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
5597 * Check the existence of the identifier in the cache
5599 * @param string|int $key
5602 public function cached($key) {
5604 $this->ensure_session_cache_initialised();
5605 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
) {
5611 * Compare something to it's equivilant in the cache
5613 * @param string $key
5614 * @param mixed $value
5615 * @param bool $serialise Whether to serialise the value before comparison
5616 * this should only be set to false if the value is already
5618 * @return bool If the value is the same false if it is not set or doesn't match
5620 public function compare($key, $value, $serialise = true) {
5621 if ($this->cached($key)) {
5623 $value = serialize($value);
5625 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
5632 * Wipes the entire cache, good to force regeneration
5634 public function clear() {
5636 unset($SESSION->navcache
);
5637 $this->session
= null;
5640 * Checks all cache entries and removes any that have expired, good ole cleanup
5642 protected function garbage_collection() {
5643 if (empty($this->session
)) {
5646 foreach ($this->session
as $key=>$cachedinfo) {
5647 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
5648 unset($this->session
[$key]);
5654 * Marks the cache as being volatile (likely to change)
5656 * Any caches marked as volatile will be destroyed at the on shutdown by
5657 * {@link navigation_node::destroy_volatile_caches()} which is registered
5658 * as a shutdown function if any caches are marked as volatile.
5660 * @param bool $setting True to destroy the cache false not too
5662 public function volatile($setting = true) {
5663 if (self
::$volatilecaches===null) {
5664 self
::$volatilecaches = array();
5665 core_shutdown_manager
::register_function(array('navigation_cache','destroy_volatile_caches'));
5669 self
::$volatilecaches[$this->area
] = $this->area
;
5670 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
5671 unset(self
::$volatilecaches[$this->area
]);
5676 * Destroys all caches marked as volatile
5678 * This function is static and works in conjunction with the static volatilecaches
5679 * property of navigation cache.
5680 * Because this function is static it manually resets the cached areas back to an
5683 public static function destroy_volatile_caches() {
5685 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
5686 foreach (self
::$volatilecaches as $area) {
5687 $SESSION->navcache
->{$area} = array();
5690 $SESSION->navcache
= new stdClass
;