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 use core_contentbank\contentbank
;
28 defined('MOODLE_INTERNAL') ||
die();
31 * The name that will be used to separate the navigation cache within SESSION
33 define('NAVIGATION_CACHE_NAME', 'navigation');
34 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @category navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node
implements renderable
{
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF
= 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH
= 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN
= null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE
= 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM
= 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY
= 10;
63 /** var int Category displayed in MyHome navigation node */
64 const TYPE_MY_CATEGORY
= 11;
65 /** @var int Course node type 20 */
66 const TYPE_COURSE
= 20;
67 /** @var int Course Structure node type 30 */
68 const TYPE_SECTION
= 30;
69 /** @var int Activity node type, e.g. Forum, Quiz 40 */
70 const TYPE_ACTIVITY
= 40;
71 /** @var int Resource node type, e.g. Link to a file, or label 50 */
72 const TYPE_RESOURCE
= 50;
73 /** @var int A custom node type, default when adding without specifing type 60 */
74 const TYPE_CUSTOM
= 60;
75 /** @var int Setting node type, used only within settings nav 70 */
76 const TYPE_SETTING
= 70;
77 /** @var int site admin branch node type, used only within settings nav 71 */
78 const TYPE_SITE_ADMIN
= 71;
79 /** @var int Setting node type, used only within settings nav 80 */
81 /** @var int Setting node type, used for containers of no importance 90 */
82 const TYPE_CONTAINER
= 90;
83 /** var int Course the current user is not enrolled in */
84 const COURSE_OTHER
= 0;
85 /** var int Course the current user is enrolled in but not viewing */
87 /** var int Course the current user is currently viewing */
88 const COURSE_CURRENT
= 2;
89 /** var string The course index page navigation node */
90 const COURSE_INDEX_PAGE
= 'courseindexpage';
92 /** @var int Parameter to aid the coder in tracking [optional] */
94 /** @var string|int The identifier for the node, used to retrieve the node */
96 /** @var string The text to use for the node */
98 /** @var string Short text to use if requested [optional] */
99 public $shorttext = null;
100 /** @var string The title attribute for an action if one is defined */
101 public $title = null;
102 /** @var string A string that can be used to build a help button */
103 public $helpbutton = null;
104 /** @var moodle_url|action_link|null An action for the node (link) */
105 public $action = null;
106 /** @var pix_icon The path to an icon to use for this node */
108 /** @var int See TYPE_* constants defined for this class */
109 public $type = self
::TYPE_UNKNOWN
;
110 /** @var int See NODETYPE_* constants defined for this class */
111 public $nodetype = self
::NODETYPE_LEAF
;
112 /** @var bool If set to true the node will be collapsed by default */
113 public $collapse = false;
114 /** @var bool If set to true the node will be expanded by default */
115 public $forceopen = false;
116 /** @var array An array of CSS classes for the node */
117 public $classes = array();
118 /** @var navigation_node_collection An array of child nodes */
119 public $children = array();
120 /** @var bool If set to true the node will be recognised as active */
121 public $isactive = false;
122 /** @var bool If set to true the node will be dimmed */
123 public $hidden = false;
124 /** @var bool If set to false the node will not be displayed */
125 public $display = true;
126 /** @var bool If set to true then an HR will be printed before the node */
127 public $preceedwithhr = false;
128 /** @var bool If set to true the the navigation bar should ignore this node */
129 public $mainnavonly = false;
130 /** @var bool If set to true a title will be added to the action no matter what */
131 public $forcetitle = false;
132 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
133 public $parent = null;
134 /** @var bool Override to not display the icon even if one is provided **/
135 public $hideicon = false;
136 /** @var bool Set to true if we KNOW that this node can be expanded. */
137 public $isexpandable = false;
139 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
140 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
142 /** @var moodle_url */
143 protected static $fullmeurl = null;
144 /** @var bool toogles auto matching of active node */
145 public static $autofindactive = true;
146 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
147 protected static $loadadmintree = false;
148 /** @var mixed If set to an int, that section will be included even if it has no activities */
149 public $includesectionnum = false;
150 /** @var bool does the node need to be loaded via ajax */
151 public $requiresajaxloading = false;
152 /** @var bool If set to true this node will be added to the "flat" navigation */
153 public $showinflatnavigation = false;
154 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */
155 public $forceintomoremenu = false;
156 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */
157 public $showinsecondarynavigation = true;
158 /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */
159 public $showchildreninsubmenu = false;
162 * Constructs a new navigation_node
164 * @param array|string $properties Either an array of properties or a string to use
165 * as the text for the node
167 public function __construct($properties) {
168 if (is_array($properties)) {
169 // Check the array for each property that we allow to set at construction.
170 // text - The main content for the node
171 // shorttext - A short text if required for the node
172 // icon - The icon to display for the node
173 // type - The type of the node
174 // key - The key to use to identify the node
175 // parent - A reference to the nodes parent
176 // action - The action to attribute to this node, usually a URL to link to
177 if (array_key_exists('text', $properties)) {
178 $this->text
= $properties['text'];
180 if (array_key_exists('shorttext', $properties)) {
181 $this->shorttext
= $properties['shorttext'];
183 if (!array_key_exists('icon', $properties)) {
184 $properties['icon'] = new pix_icon('i/navigationitem', '');
186 $this->icon
= $properties['icon'];
187 if ($this->icon
instanceof pix_icon
) {
188 if (empty($this->icon
->attributes
['class'])) {
189 $this->icon
->attributes
['class'] = 'navicon';
191 $this->icon
->attributes
['class'] .= ' navicon';
194 if (array_key_exists('type', $properties)) {
195 $this->type
= $properties['type'];
197 $this->type
= self
::TYPE_CUSTOM
;
199 if (array_key_exists('key', $properties)) {
200 $this->key
= $properties['key'];
202 // This needs to happen last because of the check_if_active call that occurs
203 if (array_key_exists('action', $properties)) {
204 $this->action
= $properties['action'];
205 if (is_string($this->action
)) {
206 $this->action
= new moodle_url($this->action
);
208 if (self
::$autofindactive) {
209 $this->check_if_active();
212 if (array_key_exists('parent', $properties)) {
213 $this->set_parent($properties['parent']);
215 } else if (is_string($properties)) {
216 $this->text
= $properties;
218 if ($this->text
=== null) {
219 throw new coding_exception('You must set the text for the node when you create it.');
221 // Instantiate a new navigation node collection for this nodes children
222 $this->children
= new navigation_node_collection();
226 * Checks if this node is the active node.
228 * This is determined by comparing the action for the node against the
229 * defined URL for the page. A match will see this node marked as active.
231 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
234 public function check_if_active($strength=URL_MATCH_EXACT
) {
235 global $FULLME, $PAGE;
236 // Set fullmeurl if it hasn't already been set
237 if (self
::$fullmeurl == null) {
238 if ($PAGE->has_set_url()) {
239 self
::override_active_url(new moodle_url($PAGE->url
));
241 self
::override_active_url(new moodle_url($FULLME));
245 // Compare the action of this node against the fullmeurl
246 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
247 $this->make_active();
254 * True if this nav node has siblings in the tree.
258 public function has_siblings() {
259 if (empty($this->parent
) ||
empty($this->parent
->children
)) {
262 if ($this->parent
->children
instanceof navigation_node_collection
) {
263 $count = $this->parent
->children
->count();
265 $count = count($this->parent
->children
);
271 * Get a list of sibling navigation nodes at the same level as this one.
273 * @return bool|array of navigation_node
275 public function get_siblings() {
276 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
277 // the in-page links or the breadcrumb links.
280 if ($this->has_siblings()) {
282 foreach ($this->parent
->children
as $child) {
283 if ($child->display
) {
284 $siblings[] = $child;
292 * This sets the URL that the URL of new nodes get compared to when locating
295 * The active node is the node that matches the URL set here. By default this
296 * is either $PAGE->url or if that hasn't been set $FULLME.
298 * @param moodle_url $url The url to use for the fullmeurl.
299 * @param bool $loadadmintree use true if the URL point to administration tree
301 public static function override_active_url(moodle_url
$url, $loadadmintree = false) {
302 // Clone the URL, in case the calling script changes their URL later.
303 self
::$fullmeurl = new moodle_url($url);
304 // True means we do not want AJAX loaded admin tree, required for all admin pages.
305 if ($loadadmintree) {
306 // Do not change back to false if already set.
307 self
::$loadadmintree = true;
312 * Use when page is linked from the admin tree,
313 * if not used navigation could not find the page using current URL
314 * because the tree is not fully loaded.
316 public static function require_admin_tree() {
317 self
::$loadadmintree = true;
321 * Creates a navigation node, ready to add it as a child using add_node
322 * function. (The created node needs to be added before you can use it.)
323 * @param string $text
324 * @param moodle_url|action_link $action
326 * @param string $shorttext
327 * @param string|int $key
328 * @param pix_icon $icon
329 * @return navigation_node
331 public static function create($text, $action=null, $type=self
::TYPE_CUSTOM
,
332 $shorttext=null, $key=null, pix_icon
$icon=null) {
333 if ($action && !($action instanceof moodle_url ||
$action instanceof action_link
)) {
335 "It is required that the action provided be either an action_url|moodle_url." .
336 " Please update your definition.", E_NOTICE
);
338 // Properties array used when creating the new navigation node
343 // Set the action if one was provided
344 if ($action!==null) {
345 $itemarray['action'] = $action;
347 // Set the shorttext if one was provided
348 if ($shorttext!==null) {
349 $itemarray['shorttext'] = $shorttext;
351 // Set the icon if one was provided
353 $itemarray['icon'] = $icon;
356 $itemarray['key'] = $key;
357 // Construct and return
358 return new navigation_node($itemarray);
362 * Adds a navigation node as a child of this node.
364 * @param string $text
365 * @param moodle_url|action_link $action
367 * @param string $shorttext
368 * @param string|int $key
369 * @param pix_icon $icon
370 * @return navigation_node
372 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
373 if ($action && is_string($action)) {
374 $action = new moodle_url($action);
377 $childnode = self
::create($text, $action, $type, $shorttext, $key, $icon);
379 // Add the child to end and return
380 return $this->add_node($childnode);
384 * Adds a navigation node as a child of this one, given a $node object
385 * created using the create function.
386 * @param navigation_node $childnode Node to add
387 * @param string $beforekey
388 * @return navigation_node The added node
390 public function add_node(navigation_node
$childnode, $beforekey=null) {
391 // First convert the nodetype for this node to a branch as it will now have children
392 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
393 $this->nodetype
= self
::NODETYPE_BRANCH
;
395 // Set the parent to this node
396 $childnode->set_parent($this);
398 // Default the key to the number of children if not provided
399 if ($childnode->key
=== null) {
400 $childnode->key
= $this->children
->count();
403 // Add the child using the navigation_node_collections add method
404 $node = $this->children
->add($childnode, $beforekey);
406 // If added node is a category node or the user is logged in and it's a course
407 // then mark added node as a branch (makes it expandable by AJAX)
408 $type = $childnode->type
;
409 if (($type == self
::TYPE_CATEGORY
) ||
(isloggedin() && ($type == self
::TYPE_COURSE
)) ||
($type == self
::TYPE_MY_CATEGORY
) ||
410 ($type === self
::TYPE_SITE_ADMIN
)) {
411 $node->nodetype
= self
::NODETYPE_BRANCH
;
413 // If this node is hidden mark it's children as hidden also
415 $node->hidden
= true;
417 // Return added node (reference returned by $this->children->add()
422 * Return a list of all the keys of all the child nodes.
423 * @return array the keys.
425 public function get_children_key_list() {
426 return $this->children
->get_key_list();
430 * Searches for a node of the given type with the given key.
432 * This searches this node plus all of its children, and their children....
433 * If you know the node you are looking for is a child of this node then please
434 * use the get method instead.
436 * @param int|string $key The key of the node we are looking for
437 * @param int $type One of navigation_node::TYPE_*
438 * @return navigation_node|false
440 public function find($key, $type) {
441 return $this->children
->find($key, $type);
445 * Walk the tree building up a list of all the flat navigation nodes.
447 * @param flat_navigation $nodes List of the found flat navigation nodes.
448 * @param boolean $showdivider Show a divider before the first node.
449 * @param string $label A label for the collection of navigation links.
451 public function build_flat_navigation_list(flat_navigation
$nodes, $showdivider = false, $label = '') {
452 if ($this->showinflatnavigation
) {
454 if ($this->type
== self
::TYPE_COURSE ||
$this->key
=== self
::COURSE_INDEX_PAGE
) {
457 $flat = new flat_navigation_node($this, $indent);
458 $flat->set_showdivider($showdivider, $label);
461 foreach ($this->children
as $child) {
462 $child->build_flat_navigation_list($nodes, false);
467 * Get the child of this node that has the given key + (optional) type.
469 * If you are looking for a node and want to search all children + their children
470 * then please use the find method instead.
472 * @param int|string $key The key of the node we are looking for
473 * @param int $type One of navigation_node::TYPE_*
474 * @return navigation_node|false
476 public function get($key, $type=null) {
477 return $this->children
->get($key, $type);
485 public function remove() {
486 return $this->parent
->children
->remove($this->key
, $this->type
);
490 * Checks if this node has or could have any children
492 * @return bool Returns true if it has children or could have (by AJAX expansion)
494 public function has_children() {
495 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0 ||
$this->isexpandable
);
499 * Marks this node as active and forces it open.
501 * Important: If you are here because you need to mark a node active to get
502 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
503 * You can use it to specify a different URL to match the active navigation node on
504 * rather than having to locate and manually mark a node active.
506 public function make_active() {
507 $this->isactive
= true;
508 $this->add_class('active_tree_node');
510 if ($this->parent
!== null) {
511 $this->parent
->make_inactive();
516 * Marks a node as inactive and recusised back to the base of the tree
517 * doing the same to all parents.
519 public function make_inactive() {
520 $this->isactive
= false;
521 $this->remove_class('active_tree_node');
522 if ($this->parent
!== null) {
523 $this->parent
->make_inactive();
528 * Forces this node to be open and at the same time forces open all
529 * parents until the root node.
533 public function force_open() {
534 $this->forceopen
= true;
535 if ($this->parent
!== null) {
536 $this->parent
->force_open();
541 * Adds a CSS class to this node.
543 * @param string $class
546 public function add_class($class) {
547 if (!in_array($class, $this->classes
)) {
548 $this->classes
[] = $class;
554 * Removes a CSS class from this node.
556 * @param string $class
557 * @return bool True if the class was successfully removed.
559 public function remove_class($class) {
560 if (in_array($class, $this->classes
)) {
561 $key = array_search($class,$this->classes
);
563 // Remove the class' array element.
564 unset($this->classes
[$key]);
565 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
566 $this->classes
= array_values($this->classes
);
575 * Sets the title for this node and forces Moodle to utilise it.
576 * @param string $title
578 public function title($title) {
579 $this->title
= $title;
580 $this->forcetitle
= true;
584 * Resets the page specific information on this node if it is being unserialised.
586 public function __wakeup(){
587 $this->forceopen
= false;
588 $this->isactive
= false;
589 $this->remove_class('active_tree_node');
593 * Checks if this node or any of its children contain the active node.
599 public function contains_active_node() {
600 if ($this->isactive
) {
603 foreach ($this->children
as $child) {
604 if ($child->isactive ||
$child->contains_active_node()) {
613 * To better balance the admin tree, we want to group all the short top branches together.
615 * This means < 8 nodes and no subtrees.
619 public function is_short_branch() {
621 if ($this->children
->count() >= $limit) {
624 foreach ($this->children
as $child) {
625 if ($child->has_children()) {
633 * Finds the active node.
635 * Searches this nodes children plus all of the children for the active node
636 * and returns it if found.
640 * @return navigation_node|false
642 public function find_active_node() {
643 if ($this->isactive
) {
646 foreach ($this->children
as &$child) {
647 $outcome = $child->find_active_node();
648 if ($outcome !== false) {
657 * Searches all children for the best matching active node
658 * @param int $strength The url match to be made.
659 * @return navigation_node|false
661 public function search_for_active_node($strength = URL_MATCH_BASE
) {
662 if ($this->check_if_active($strength)) {
665 foreach ($this->children
as &$child) {
666 $outcome = $child->search_for_active_node($strength);
667 if ($outcome !== false) {
676 * Gets the content for this node.
678 * @param bool $shorttext If true shorttext is used rather than the normal text
681 public function get_content($shorttext=false) {
682 if ($shorttext && $this->shorttext
!==null) {
683 return format_string($this->shorttext
);
685 return format_string($this->text
);
690 * Gets the title to use for this node.
694 public function get_title() {
695 if ($this->forcetitle ||
$this->action
!= null){
703 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
707 public function has_action() {
708 return !empty($this->action
);
712 * Used to easily determine if the action is an internal link.
716 public function has_internal_action(): bool {
718 if ($this->has_action()) {
719 $url = $this->action();
720 if ($this->action() instanceof \action_link
) {
721 $url = $this->action()->url
;
724 if (($url->out() === $CFG->wwwroot
) ||
(strpos($url->out(), $CFG->wwwroot
.'/') === 0)) {
732 * Used to easily determine if this link in the breadcrumbs is hidden.
736 public function is_hidden() {
737 return $this->hidden
;
741 * Gets the CSS class to add to this node to describe its type
745 public function get_css_type() {
746 if (array_key_exists($this->type
, $this->namedtypes
)) {
747 return 'type_'.$this->namedtypes
[$this->type
];
749 return 'type_unknown';
753 * Finds all nodes that are expandable by AJAX
755 * @param array $expandable An array by reference to populate with expandable nodes.
757 public function find_expandable(array &$expandable) {
758 foreach ($this->children
as &$child) {
759 if ($child->display
&& $child->has_children() && $child->children
->count() == 0) {
760 $child->id
= 'expandable_branch_'.$child->type
.'_'.clean_param($child->key
, PARAM_ALPHANUMEXT
);
761 $this->add_class('canexpand');
762 $child->requiresajaxloading
= true;
763 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
765 $child->find_expandable($expandable);
770 * Finds all nodes of a given type (recursive)
772 * @param int $type One of navigation_node::TYPE_*
775 public function find_all_of_type($type) {
776 $nodes = $this->children
->type($type);
777 foreach ($this->children
as &$node) {
778 $childnodes = $node->find_all_of_type($type);
779 $nodes = array_merge($nodes, $childnodes);
785 * Removes this node if it is empty
787 public function trim_if_empty() {
788 if ($this->children
->count() == 0) {
794 * Creates a tab representation of this nodes children that can be used
795 * with print_tabs to produce the tabs on a page.
797 * call_user_func_array('print_tabs', $node->get_tabs_array());
799 * @param array $inactive
800 * @param bool $return
801 * @return array Array (tabs, selected, inactive, activated, return)
803 public function get_tabs_array(array $inactive=array(), $return=false) {
807 $activated = array();
808 foreach ($this->children
as $node) {
809 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
810 if ($node->contains_active_node()) {
811 if ($node->children
->count() > 0) {
812 $activated[] = $node->key
;
813 foreach ($node->children
as $child) {
814 if ($child->contains_active_node()) {
815 $selected = $child->key
;
817 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
820 $selected = $node->key
;
824 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
828 * Sets the parent for this node and if this node is active ensures that the tree is properly
831 * @param navigation_node $parent
833 public function set_parent(navigation_node
$parent) {
834 // Set the parent (thats the easy part)
835 $this->parent
= $parent;
836 // Check if this node is active (this is checked during construction)
837 if ($this->isactive
) {
838 // Force all of the parent nodes open so you can see this node
839 $this->parent
->force_open();
840 // Make all parents inactive so that its clear where we are.
841 $this->parent
->make_inactive();
846 * Hides the node and any children it has.
849 * @param array $typestohide Optional. An array of node types that should be hidden.
850 * If null all nodes will be hidden.
851 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
852 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
854 public function hide(array $typestohide = null) {
855 if ($typestohide === null ||
in_array($this->type
, $typestohide)) {
856 $this->display
= false;
857 if ($this->has_children()) {
858 foreach ($this->children
as $child) {
859 $child->hide($typestohide);
866 * Get the action url for this navigation node.
867 * Called from templates.
871 public function action() {
872 if ($this->action
instanceof moodle_url
) {
873 return $this->action
;
874 } else if ($this->action
instanceof action_link
) {
875 return $this->action
->url
;
877 return $this->action
;
881 * Return an array consisting of the additional attributes for the action url.
883 * @return array Formatted array to parse in a template
885 public function actionattributes() {
886 if ($this->action
instanceof action_link
) {
887 return array_map(function($key, $value) {
892 }, array_keys($this->action
->attributes
), $this->action
->attributes
);
899 * Check whether the node's action is of type action_link.
903 public function is_action_link() {
904 return $this->action
instanceof action_link
;
908 * Return an array consisting of the actions for the action link.
910 * @return array Formatted array to parse in a template
912 public function action_link_actions() {
915 if (!$this->is_action_link()) {
919 $actionid = $this->action
->attributes
['id'];
920 $actionsdata = array_map(function($action) use ($PAGE, $actionid) {
921 $data = $action->export_for_template($PAGE->get_renderer('core'));
922 $data->id
= $actionid;
924 }, !empty($this->action
->actions
) ?
$this->action
->actions
: []);
926 return ['actions' => $actionsdata];
930 * Sets whether the node and its children should be added into a "more" menu whenever possible.
932 * @param bool $forceintomoremenu
934 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
935 $this->forceintomoremenu
= $forceintomoremenu;
936 foreach ($this->children
as $child) {
937 $child->set_force_into_more_menu($forceintomoremenu);
942 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
946 public function set_show_in_secondary_navigation(bool $show = true) {
947 $this->showinsecondarynavigation
= $show;
948 foreach ($this->children
as $child) {
949 $child->set_show_in_secondary_navigation($show);
954 * Add the menu item to handle locking and unlocking of a conext.
956 * @param \navigation_node $node Node to add
957 * @param \context $context The context to be locked
959 protected function add_context_locking_node(\navigation_node
$node, \context
$context) {
961 // Manage context locking.
962 if (!empty($CFG->contextlocking
) && has_capability('moodle/site:managecontextlocks', $context)) {
963 $parentcontext = $context->get_parent_context();
964 if (empty($parentcontext) ||
!$parentcontext->locked
) {
965 if ($context->locked
) {
966 $lockicon = 'i/unlock';
967 $lockstring = get_string('managecontextunlock', 'admin');
969 $lockicon = 'i/lock';
970 $lockstring = get_string('managecontextlock', 'admin');
977 'id' => $context->id
,
983 new pix_icon($lockicon, '')
992 * Navigation node collection
994 * This class is responsible for managing a collection of navigation nodes.
995 * It is required because a node's unique identifier is a combination of both its
998 * Originally an array was used with a string key that was a combination of the two
999 * however it was decided that a better solution would be to use a class that
1000 * implements the standard IteratorAggregate interface.
1003 * @category navigation
1004 * @copyright 2010 Sam Hemelryk
1005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1007 class navigation_node_collection
implements IteratorAggregate
, Countable
{
1009 * A multidimensional array to where the first key is the type and the second
1010 * key is the nodes key.
1013 protected $collection = array();
1015 * An array that contains references to nodes in the same order they were added.
1016 * This is maintained as a progressive array.
1019 protected $orderedcollection = array();
1021 * A reference to the last node that was added to the collection
1022 * @var navigation_node
1024 protected $last = null;
1026 * The total number of items added to this array.
1029 protected $count = 0;
1032 * Label for collection of nodes.
1035 protected $collectionlabel = '';
1038 * Adds a navigation node to the collection
1040 * @param navigation_node $node Node to add
1041 * @param string $beforekey If specified, adds before a node with this key,
1042 * otherwise adds at end
1043 * @return navigation_node Added node
1045 public function add(navigation_node
$node, $beforekey=null) {
1048 $type = $node->type
;
1050 // First check we have a 2nd dimension for this type
1051 if (!array_key_exists($type, $this->orderedcollection
)) {
1052 $this->orderedcollection
[$type] = array();
1054 // Check for a collision and report if debugging is turned on
1055 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
1056 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
1059 // Find the key to add before
1060 $newindex = $this->count
;
1062 if ($beforekey !== null) {
1063 foreach ($this->collection
as $index => $othernode) {
1064 if ($othernode->key
=== $beforekey) {
1070 if ($newindex === $this->count
) {
1071 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1072 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
1076 // Add the node to the appropriate place in the by-type structure (which
1077 // is not ordered, despite the variable name)
1078 $this->orderedcollection
[$type][$key] = $node;
1080 // Update existing references in the ordered collection (which is the
1081 // one that isn't called 'ordered') to shuffle them along if required
1082 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
1083 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
1086 // Add a reference to the node to the progressive collection.
1087 $this->collection
[$newindex] = $this->orderedcollection
[$type][$key];
1088 // Update the last property to a reference to this new node.
1089 $this->last
= $this->orderedcollection
[$type][$key];
1091 // Reorder the array by index if needed
1093 ksort($this->collection
);
1096 // Return the reference to the now added node
1101 * Return a list of all the keys of all the nodes.
1102 * @return array the keys.
1104 public function get_key_list() {
1106 foreach ($this->collection
as $node) {
1107 $keys[] = $node->key
;
1113 * Set a label for this collection.
1115 * @param string $label
1117 public function set_collectionlabel($label) {
1118 $this->collectionlabel
= $label;
1122 * Return a label for this collection.
1126 public function get_collectionlabel() {
1127 return $this->collectionlabel
;
1131 * Fetches a node from this collection.
1133 * @param string|int $key The key of the node we want to find.
1134 * @param int $type One of navigation_node::TYPE_*.
1135 * @return navigation_node|null
1137 public function get($key, $type=null) {
1138 if ($type !== null) {
1139 // If the type is known then we can simply check and fetch
1140 if (!empty($this->orderedcollection
[$type][$key])) {
1141 return $this->orderedcollection
[$type][$key];
1144 // Because we don't know the type we look in the progressive array
1145 foreach ($this->collection
as $node) {
1146 if ($node->key
=== $key) {
1155 * Searches for a node with matching key and type.
1157 * This function searches both the nodes in this collection and all of
1158 * the nodes in each collection belonging to the nodes in this collection.
1162 * @param string|int $key The key of the node we want to find.
1163 * @param int $type One of navigation_node::TYPE_*.
1164 * @return navigation_node|null
1166 public function find($key, $type=null) {
1167 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
1168 return $this->orderedcollection
[$type][$key];
1170 $nodes = $this->getIterator();
1171 // Search immediate children first
1172 foreach ($nodes as &$node) {
1173 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
1177 // Now search each childs children
1178 foreach ($nodes as &$node) {
1179 $result = $node->children
->find($key, $type);
1180 if ($result !== false) {
1189 * Fetches the last node that was added to this collection
1191 * @return navigation_node
1193 public function last() {
1198 * Fetches all nodes of a given type from this collection
1200 * @param string|int $type node type being searched for.
1201 * @return array ordered collection
1203 public function type($type) {
1204 if (!array_key_exists($type, $this->orderedcollection
)) {
1205 $this->orderedcollection
[$type] = array();
1207 return $this->orderedcollection
[$type];
1210 * Removes the node with the given key and type from the collection
1212 * @param string|int $key The key of the node we want to find.
1216 public function remove($key, $type=null) {
1217 $child = $this->get($key, $type);
1218 if ($child !== false) {
1219 foreach ($this->collection
as $colkey => $node) {
1220 if ($node->key
=== $key && (is_null($type) ||
$node->type
== $type)) {
1221 unset($this->collection
[$colkey]);
1222 $this->collection
= array_values($this->collection
);
1226 unset($this->orderedcollection
[$child->type
][$child->key
]);
1234 * Gets the number of nodes in this collection
1236 * This option uses an internal count rather than counting the actual options to avoid
1237 * a performance hit through the count function.
1241 public function count() {
1242 return $this->count
;
1245 * Gets an array iterator for the collection.
1247 * This is required by the IteratorAggregator interface and is used by routines
1248 * such as the foreach loop.
1250 * @return ArrayIterator
1252 public function getIterator() {
1253 return new ArrayIterator($this->collection
);
1258 * The global navigation class used for... the global navigation
1260 * This class is used by PAGE to store the global navigation for the site
1261 * and is then used by the settings nav and navbar to save on processing and DB calls
1264 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1265 * {@link lib/ajax/getnavbranch.php} Called by ajax
1268 * @category navigation
1269 * @copyright 2009 Sam Hemelryk
1270 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1272 class global_navigation
extends navigation_node
{
1273 /** @var moodle_page The Moodle page this navigation object belongs to. */
1275 /** @var bool switch to let us know if the navigation object is initialised*/
1276 protected $initialised = false;
1277 /** @var array An array of course information */
1278 protected $mycourses = array();
1279 /** @var navigation_node[] An array for containing root navigation nodes */
1280 protected $rootnodes = array();
1281 /** @var bool A switch for whether to show empty sections in the navigation */
1282 protected $showemptysections = true;
1283 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1284 protected $showcategories = null;
1285 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1286 protected $showmycategories = null;
1287 /** @var array An array of stdClasses for users that the navigation is extended for */
1288 protected $extendforuser = array();
1289 /** @var navigation_cache */
1291 /** @var array An array of course ids that are present in the navigation */
1292 protected $addedcourses = array();
1294 protected $allcategoriesloaded = false;
1295 /** @var array An array of category ids that are included in the navigation */
1296 protected $addedcategories = array();
1297 /** @var int expansion limit */
1298 protected $expansionlimit = 0;
1299 /** @var int userid to allow parent to see child's profile page navigation */
1300 protected $useridtouseforparentchecks = 0;
1301 /** @var cache_session A cache that stores information on expanded courses */
1302 protected $cacheexpandcourse = null;
1304 /** Used when loading categories to load all top level categories [parent = 0] **/
1305 const LOAD_ROOT_CATEGORIES
= 0;
1306 /** Used when loading categories to load all categories **/
1307 const LOAD_ALL_CATEGORIES
= -1;
1310 * Constructs a new global navigation
1312 * @param moodle_page $page The page this navigation object belongs to
1314 public function __construct(moodle_page
$page) {
1315 global $CFG, $SITE, $USER;
1317 if (during_initial_install()) {
1321 $homepage = get_home_page();
1322 if ($homepage == HOMEPAGE_SITE
) {
1323 // We are using the site home for the root element.
1324 $properties = array(
1326 'type' => navigation_node
::TYPE_SYSTEM
,
1327 'text' => get_string('home'),
1328 'action' => new moodle_url('/'),
1329 'icon' => new pix_icon('i/home', '')
1331 } else if ($homepage == HOMEPAGE_MYCOURSES
) {
1332 // We are using the user's course summary page for the root element.
1333 $properties = array(
1334 'key' => 'mycourses',
1335 'type' => navigation_node
::TYPE_SYSTEM
,
1336 'text' => get_string('mycourses'),
1337 'action' => new moodle_url('/my/courses.php'),
1338 'icon' => new pix_icon('i/course', '')
1341 // We are using the users my moodle for the root element.
1342 $properties = array(
1344 'type' => navigation_node
::TYPE_SYSTEM
,
1345 'text' => get_string('myhome'),
1346 'action' => new moodle_url('/my/'),
1347 'icon' => new pix_icon('i/dashboard', '')
1351 // Use the parents constructor.... good good reuse
1352 parent
::__construct($properties);
1353 $this->showinflatnavigation
= true;
1355 // Initalise and set defaults
1356 $this->page
= $page;
1357 $this->forceopen
= true;
1358 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
1362 * Mutator to set userid to allow parent to see child's profile
1363 * page navigation. See MDL-25805 for initial issue. Linked to it
1364 * is an issue explaining why this is a REALLY UGLY HACK thats not
1367 * @param int $userid userid of profile page that parent wants to navigate around.
1369 public function set_userid_for_parent_checks($userid) {
1370 $this->useridtouseforparentchecks
= $userid;
1375 * Initialises the navigation object.
1377 * This causes the navigation object to look at the current state of the page
1378 * that it is associated with and then load the appropriate content.
1380 * This should only occur the first time that the navigation structure is utilised
1381 * which will normally be either when the navbar is called to be displayed or
1382 * when a block makes use of it.
1386 public function initialise() {
1387 global $CFG, $SITE, $USER;
1388 // Check if it has already been initialised
1389 if ($this->initialised ||
during_initial_install()) {
1392 $this->initialised
= true;
1394 // Set up the five base root nodes. These are nodes where we will put our
1395 // content and are as follows:
1396 // site: Navigation for the front page.
1397 // myprofile: User profile information goes here.
1398 // currentcourse: The course being currently viewed.
1399 // mycourses: The users courses get added here.
1400 // courses: Additional courses are added here.
1401 // users: Other users information loaded here.
1402 $this->rootnodes
= array();
1403 $defaulthomepage = get_home_page();
1404 if ($defaulthomepage == HOMEPAGE_SITE
) {
1405 // The home element should be my moodle because the root element is the site
1406 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1407 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1408 self
::TYPE_SETTING
, null, 'myhome', new pix_icon('i/dashboard', ''));
1409 $this->rootnodes
['home']->showinflatnavigation
= true;
1412 // The home element should be the site because the root node is my moodle
1413 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1414 self
::TYPE_SETTING
, null, 'home', new pix_icon('i/home', ''));
1415 $this->rootnodes
['home']->showinflatnavigation
= true;
1416 if (!empty($CFG->defaulthomepage
) &&
1417 ($CFG->defaulthomepage
== HOMEPAGE_MY ||
$CFG->defaulthomepage
== HOMEPAGE_MYCOURSES
)) {
1418 // We need to stop automatic redirection
1419 $this->rootnodes
['home']->action
->param('redirect', '0');
1422 $this->rootnodes
['site'] = $this->add_course($SITE);
1423 $this->rootnodes
['myprofile'] = $this->add(get_string('profile'), null, self
::TYPE_USER
, null, 'myprofile');
1424 $this->rootnodes
['currentcourse'] = $this->add(get_string('currentcourse'), null, self
::TYPE_ROOTNODE
, null, 'currentcourse');
1425 $this->rootnodes
['mycourses'] = $this->add(
1426 get_string('mycourses'),
1427 new moodle_url('/my/courses.php'),
1428 self
::TYPE_ROOTNODE
,
1431 new pix_icon('i/course', '')
1433 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses.
1434 // It will be automatically handled by the breadcrumb generator.
1435 if ($defaulthomepage == HOMEPAGE_MYCOURSES
) {
1436 $this->rootnodes
['mycourses']->mainnavonly
= true;
1439 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1440 if (!core_course_category
::user_top()) {
1441 $this->rootnodes
['courses']->hide();
1443 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1445 // We always load the frontpage course to ensure it is available without
1446 // JavaScript enabled.
1447 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1448 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1450 $course = $this->page
->course
;
1451 $this->load_courses_enrolled();
1453 // $issite gets set to true if the current pages course is the sites frontpage course
1454 $issite = ($this->page
->course
->id
== $SITE->id
);
1456 // Determine if the user is enrolled in any course.
1457 $enrolledinanycourse = enrol_user_sees_own_courses();
1459 $this->rootnodes
['currentcourse']->mainnavonly
= true;
1460 if ($enrolledinanycourse) {
1461 $this->rootnodes
['mycourses']->isexpandable
= true;
1462 $this->rootnodes
['mycourses']->showinflatnavigation
= true;
1463 if ($CFG->navshowallcourses
) {
1464 // When we show all courses we need to show both the my courses and the regular courses branch.
1465 $this->rootnodes
['courses']->isexpandable
= true;
1468 $this->rootnodes
['courses']->isexpandable
= true;
1470 $this->rootnodes
['mycourses']->forceopen
= true;
1472 $canviewcourseprofile = true;
1474 // Next load context specific content into the navigation
1475 switch ($this->page
->context
->contextlevel
) {
1476 case CONTEXT_SYSTEM
:
1477 // Nothing left to do here I feel.
1479 case CONTEXT_COURSECAT
:
1480 // This is essential, we must load categories.
1481 $this->load_all_categories($this->page
->context
->instanceid
, true);
1483 case CONTEXT_BLOCK
:
1484 case CONTEXT_COURSE
:
1486 // Nothing left to do here.
1490 // Load the course associated with the current page into the navigation.
1491 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1492 // If the course wasn't added then don't try going any further.
1494 $canviewcourseprofile = false;
1498 // If the user is not enrolled then we only want to show the
1499 // course node and not populate it.
1501 // Not enrolled, can't view, and hasn't switched roles
1502 if (!can_access_course($course, null, '', true)) {
1503 if ($coursenode->isexpandable
=== true) {
1504 // Obviously the situation has changed, update the cache and adjust the node.
1505 // This occurs if the user access to a course has been revoked (one way or another) after
1506 // initially logging in for this session.
1507 $this->get_expand_course_cache()->set($course->id
, 1);
1508 $coursenode->isexpandable
= true;
1509 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1511 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1512 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1513 if (!$this->current_user_is_parent_role()) {
1514 $coursenode->make_active();
1515 $canviewcourseprofile = false;
1518 } else if ($coursenode->isexpandable
=== false) {
1519 // Obviously the situation has changed, update the cache and adjust the node.
1520 // This occurs if the user has been granted access to a course (one way or another) after initially
1521 // logging in for this session.
1522 $this->get_expand_course_cache()->set($course->id
, 1);
1523 $coursenode->isexpandable
= true;
1524 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1527 // Add the essentials such as reports etc...
1528 $this->add_course_essentials($coursenode, $course);
1529 // Extend course navigation with it's sections/activities
1530 $this->load_course_sections($course, $coursenode);
1531 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1532 $coursenode->make_active();
1536 case CONTEXT_MODULE
:
1538 // If this is the site course then most information will have
1539 // already been loaded.
1540 // However we need to check if there is more content that can
1541 // yet be loaded for the specific module instance.
1542 $activitynode = $this->rootnodes
['site']->find($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1543 if ($activitynode) {
1544 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1549 $course = $this->page
->course
;
1550 $cm = $this->page
->cm
;
1552 // Load the course associated with the page into the navigation
1553 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1555 // If the course wasn't added then don't try going any further.
1557 $canviewcourseprofile = false;
1561 // If the user is not enrolled then we only want to show the
1562 // course node and not populate it.
1563 if (!can_access_course($course, null, '', true)) {
1564 $coursenode->make_active();
1565 $canviewcourseprofile = false;
1569 $this->add_course_essentials($coursenode, $course);
1571 // Load the course sections into the page
1572 $this->load_course_sections($course, $coursenode, null, $cm);
1573 $activity = $coursenode->find($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1574 if (!empty($activity)) {
1575 // Finally load the cm specific navigaton information
1576 $this->load_activity($cm, $course, $activity);
1577 // Check if we have an active ndoe
1578 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1579 // And make the activity node active.
1580 $activity->make_active();
1586 // The users profile information etc is already loaded
1587 // for the front page.
1590 $course = $this->page
->course
;
1591 // Load the course associated with the user into the navigation
1592 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1594 // If the course wasn't added then don't try going any further.
1596 $canviewcourseprofile = false;
1600 // If the user is not enrolled then we only want to show the
1601 // course node and not populate it.
1602 if (!can_access_course($course, null, '', true)) {
1603 $coursenode->make_active();
1604 $canviewcourseprofile = false;
1607 $this->add_course_essentials($coursenode, $course);
1608 $this->load_course_sections($course, $coursenode);
1612 // Load for the current user
1613 $this->load_for_user();
1614 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
&& $canviewcourseprofile) {
1615 $this->load_for_user(null, true);
1617 // Load each extending user into the navigation.
1618 foreach ($this->extendforuser
as $user) {
1619 if ($user->id
!= $USER->id
) {
1620 $this->load_for_user($user);
1624 // Give the local plugins a chance to include some navigation if they want.
1625 $this->load_local_plugin_navigation();
1627 // Remove any empty root nodes
1628 foreach ($this->rootnodes
as $node) {
1629 // Dont remove the home node
1630 /** @var navigation_node $node */
1631 if (!in_array($node->key
, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive
) {
1636 if (!$this->contains_active_node()) {
1637 $this->search_for_active_node();
1640 // If the user is not logged in modify the navigation structure as detailed
1641 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1642 if (!isloggedin()) {
1643 $activities = clone($this->rootnodes
['site']->children
);
1644 $this->rootnodes
['site']->remove();
1645 $children = clone($this->children
);
1646 $this->children
= new navigation_node_collection();
1647 foreach ($activities as $child) {
1648 $this->children
->add($child);
1650 foreach ($children as $child) {
1651 $this->children
->add($child);
1658 * This function gives local plugins an opportunity to modify navigation.
1660 protected function load_local_plugin_navigation() {
1661 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1667 * Returns true if the current user is a parent of the user being currently viewed.
1669 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1670 * other user being viewed this function returns false.
1671 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1676 protected function current_user_is_parent_role() {
1678 if ($this->useridtouseforparentchecks
&& $this->useridtouseforparentchecks
!= $USER->id
) {
1679 $usercontext = context_user
::instance($this->useridtouseforparentchecks
, MUST_EXIST
);
1680 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1683 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))) {
1691 * Returns true if courses should be shown within categories on the navigation.
1693 * @param bool $ismycourse Set to true if you are calculating this for a course.
1696 protected function show_categories($ismycourse = false) {
1699 return $this->show_my_categories();
1701 if ($this->showcategories
=== null) {
1703 if ($this->page
->context
->contextlevel
== CONTEXT_COURSECAT
) {
1705 } else if (!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1) {
1708 $this->showcategories
= $show;
1710 return $this->showcategories
;
1714 * Returns true if we should show categories in the My Courses branch.
1717 protected function show_my_categories() {
1719 if ($this->showmycategories
=== null) {
1720 $this->showmycategories
= !empty($CFG->navshowmycoursecategories
) && !core_course_category
::is_simple_site();
1722 return $this->showmycategories
;
1726 * Loads the courses in Moodle into the navigation.
1728 * @global moodle_database $DB
1729 * @param string|array $categoryids An array containing categories to load courses
1730 * for, OR null to load courses for all categories.
1731 * @return array An array of navigation_nodes one for each course
1733 protected function load_all_courses($categoryids = null) {
1734 global $CFG, $DB, $SITE;
1736 // Work out the limit of courses.
1738 if (!empty($CFG->navcourselimit
)) {
1739 $limit = $CFG->navcourselimit
;
1742 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1744 // If we are going to show all courses AND we are showing categories then
1745 // to save us repeated DB calls load all of the categories now
1746 if ($this->show_categories()) {
1747 $this->load_all_categories($toload);
1750 // Will be the return of our efforts
1751 $coursenodes = array();
1753 // Check if we need to show categories.
1754 if ($this->show_categories()) {
1755 // Hmmm we need to show categories... this is going to be painful.
1756 // We now need to fetch up to $limit courses for each category to
1758 if ($categoryids !== null) {
1759 if (!is_array($categoryids)) {
1760 $categoryids = array($categoryids);
1762 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1763 $categorywhere = 'WHERE cc.id '.$categorywhere;
1764 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1765 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1766 $categoryparams = array();
1768 $categorywhere = '';
1769 $categoryparams = array();
1772 // First up we are going to get the categories that we are going to
1773 // need so that we can determine how best to load the courses from them.
1774 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1775 FROM {course_categories} cc
1776 LEFT JOIN {course} c ON c.category = cc.id
1779 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1780 $fullfetch = array();
1781 $partfetch = array();
1782 foreach ($categories as $category) {
1783 if (!$this->can_add_more_courses_to_category($category->id
)) {
1786 if ($category->coursecount
> $limit * 5) {
1787 $partfetch[] = $category->id
;
1788 } else if ($category->coursecount
> 0) {
1789 $fullfetch[] = $category->id
;
1792 $categories->close();
1794 if (count($fullfetch)) {
1795 // First up fetch all of the courses in categories where we know that we are going to
1796 // need the majority of courses.
1797 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1798 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1799 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1800 $categoryparams['contextlevel'] = CONTEXT_COURSE
;
1801 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1804 WHERE c.category {$categoryids}
1805 ORDER BY c.sortorder ASC";
1806 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1807 foreach ($coursesrs as $course) {
1808 if ($course->id
== $SITE->id
) {
1809 // This should not be necessary, frontpage is not in any category.
1812 if (array_key_exists($course->id
, $this->addedcourses
)) {
1813 // It is probably better to not include the already loaded courses
1814 // directly in SQL because inequalities may confuse query optimisers
1815 // and may interfere with query caching.
1818 if (!$this->can_add_more_courses_to_category($course->category
)) {
1821 context_helper
::preload_from_record($course);
1822 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1825 $coursenodes[$course->id
] = $this->add_course($course);
1827 $coursesrs->close();
1830 if (count($partfetch)) {
1831 // Next we will work our way through the categories where we will likely only need a small
1832 // proportion of the courses.
1833 foreach ($partfetch as $categoryid) {
1834 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1835 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1836 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1839 WHERE c.category = :categoryid
1840 ORDER BY c.sortorder ASC";
1841 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE
);
1842 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1843 foreach ($coursesrs as $course) {
1844 if ($course->id
== $SITE->id
) {
1845 // This should not be necessary, frontpage is not in any category.
1848 if (array_key_exists($course->id
, $this->addedcourses
)) {
1849 // It is probably better to not include the already loaded courses
1850 // directly in SQL because inequalities may confuse query optimisers
1851 // and may interfere with query caching.
1852 // This also helps to respect expected $limit on repeated executions.
1855 if (!$this->can_add_more_courses_to_category($course->category
)) {
1858 context_helper
::preload_from_record($course);
1859 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1862 $coursenodes[$course->id
] = $this->add_course($course);
1864 $coursesrs->close();
1868 // Prepare the SQL to load the courses and their contexts
1869 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1870 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1871 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1872 $courseparams['contextlevel'] = CONTEXT_COURSE
;
1873 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1876 WHERE c.id {$courseids}
1877 ORDER BY c.sortorder ASC";
1878 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1879 foreach ($coursesrs as $course) {
1880 if ($course->id
== $SITE->id
) {
1881 // frotpage is not wanted here
1884 if ($this->page
->course
&& ($this->page
->course
->id
== $course->id
)) {
1885 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1888 context_helper
::preload_from_record($course);
1889 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1892 $coursenodes[$course->id
] = $this->add_course($course);
1893 if (count($coursenodes) >= $limit) {
1897 $coursesrs->close();
1900 return $coursenodes;
1904 * Returns true if more courses can be added to the provided category.
1906 * @param int|navigation_node|stdClass $category
1909 protected function can_add_more_courses_to_category($category) {
1912 if (!empty($CFG->navcourselimit
)) {
1913 $limit = (int)$CFG->navcourselimit
;
1915 if (is_numeric($category)) {
1916 if (!array_key_exists($category, $this->addedcategories
)) {
1919 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1920 } else if ($category instanceof navigation_node
) {
1921 if (($category->type
!= self
::TYPE_CATEGORY
) ||
($category->type
!= self
::TYPE_MY_CATEGORY
)) {
1924 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1925 } else if (is_object($category) && property_exists($category,'id')) {
1926 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1928 return ($coursecount <= $limit);
1932 * Loads all categories (top level or if an id is specified for that category)
1934 * @param int $categoryid The category id to load or null/0 to load all base level categories
1935 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1936 * as the requested category and any parent categories.
1937 * @return navigation_node|void returns a navigation node if a category has been loaded.
1939 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1942 // Check if this category has already been loaded
1943 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1947 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1948 $sqlselect = "SELECT cc.*, $catcontextsql
1949 FROM {course_categories} cc
1950 JOIN {context} ctx ON cc.id = ctx.instanceid";
1951 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1952 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1955 $categoriestoload = array();
1956 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1957 // We are going to load all categories regardless... prepare to fire
1958 // on the database server!
1959 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1960 // We are going to load all of the first level categories (categories without parents)
1961 $sqlwhere .= " AND cc.parent = 0";
1962 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1963 // The category itself has been loaded already so we just need to ensure its subcategories
1965 $addedcategories = $this->addedcategories
;
1966 unset($addedcategories[$categoryid]);
1967 if (count($addedcategories) > 0) {
1968 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED
, 'parent', false);
1969 if ($showbasecategories) {
1970 // We need to include categories with parent = 0 as well
1971 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1973 // All we need is categories that match the parent
1974 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1977 $params['categoryid'] = $categoryid;
1979 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1980 // and load this category plus all its parents and subcategories
1981 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1982 $categoriestoload = explode('/', trim($category->path
, '/'));
1983 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1984 // We are going to use select twice so double the params
1985 $params = array_merge($params, $params);
1986 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1987 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1990 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1991 $categories = array();
1992 foreach ($categoriesrs as $category) {
1993 // Preload the context.. we'll need it when adding the category in order
1994 // to format the category name.
1995 context_helper
::preload_from_record($category);
1996 if (array_key_exists($category->id
, $this->addedcategories
)) {
1997 // Do nothing, its already been added.
1998 } else if ($category->parent
== '0') {
1999 // This is a root category lets add it immediately
2000 $this->add_category($category, $this->rootnodes
['courses']);
2001 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
2002 // This categories parent has already been added we can add this immediately
2003 $this->add_category($category, $this->addedcategories
[$category->parent
]);
2005 $categories[] = $category;
2008 $categoriesrs->close();
2010 // Now we have an array of categories we need to add them to the navigation.
2011 while (!empty($categories)) {
2012 $category = reset($categories);
2013 if (array_key_exists($category->id
, $this->addedcategories
)) {
2015 } else if ($category->parent
== '0') {
2016 $this->add_category($category, $this->rootnodes
['courses']);
2017 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
2018 $this->add_category($category, $this->addedcategories
[$category->parent
]);
2020 // This category isn't in the navigation and niether is it's parent (yet).
2021 // We need to go through the category path and add all of its components in order.
2022 $path = explode('/', trim($category->path
, '/'));
2023 foreach ($path as $catid) {
2024 if (!array_key_exists($catid, $this->addedcategories
)) {
2025 // This category isn't in the navigation yet so add it.
2026 $subcategory = $categories[$catid];
2027 if ($subcategory->parent
== '0') {
2028 // Yay we have a root category - this likely means we will now be able
2029 // to add categories without problems.
2030 $this->add_category($subcategory, $this->rootnodes
['courses']);
2031 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
2032 // The parent is in the category (as we'd expect) so add it now.
2033 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
2034 // Remove the category from the categories array.
2035 unset($categories[$catid]);
2037 // We should never ever arrive here - if we have then there is a bigger
2039 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
2044 // Remove the category from the categories array now that we know it has been added.
2045 unset($categories[$category->id
]);
2047 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
2048 $this->allcategoriesloaded
= true;
2050 // Check if there are any categories to load.
2051 if (count($categoriestoload) > 0) {
2052 $readytoloadcourses = array();
2053 foreach ($categoriestoload as $category) {
2054 if ($this->can_add_more_courses_to_category($category)) {
2055 $readytoloadcourses[] = $category;
2058 if (count($readytoloadcourses)) {
2059 $this->load_all_courses($readytoloadcourses);
2063 // Look for all categories which have been loaded
2064 if (!empty($this->addedcategories
)) {
2065 $categoryids = array();
2066 foreach ($this->addedcategories
as $category) {
2067 if ($this->can_add_more_courses_to_category($category)) {
2068 $categoryids[] = $category->key
;
2072 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
2073 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
2074 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
2075 FROM {course_categories} cc
2076 JOIN {course} c ON c.category = cc.id
2077 WHERE cc.id {$categoriessql}
2079 HAVING COUNT(c.id) > :limit";
2080 $excessivecategories = $DB->get_records_sql($sql, $params);
2081 foreach ($categories as &$category) {
2082 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2083 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key
));
2084 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
2092 * Adds a structured category to the navigation in the correct order/place
2094 * @param stdClass $category category to be added in navigation.
2095 * @param navigation_node $parent parent navigation node
2096 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2099 protected function add_category(stdClass
$category, navigation_node
$parent, $nodetype = self
::TYPE_CATEGORY
) {
2100 if (array_key_exists($category->id
, $this->addedcategories
)) {
2103 $canview = core_course_category
::can_view_category($category);
2104 $url = $canview ?
new moodle_url('/course/index.php', array('categoryid' => $category->id
)) : null;
2105 $context = context_coursecat
::instance($category->id
);
2106 $categoryname = $canview ?
format_string($category->name
, true, array('context' => $context)) :
2107 get_string('categoryhidden');
2108 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id
);
2110 // User does not have required capabilities to view category.
2111 $categorynode->display
= false;
2112 } else if (!$category->visible
) {
2113 // Category is hidden but user has capability to view hidden categories.
2114 $categorynode->hidden
= true;
2116 $this->addedcategories
[$category->id
] = $categorynode;
2120 * Loads the given course into the navigation
2122 * @param stdClass $course
2123 * @return navigation_node
2125 protected function load_course(stdClass
$course) {
2127 if ($course->id
== $SITE->id
) {
2128 // This is always loaded during initialisation
2129 return $this->rootnodes
['site'];
2130 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
2131 // The course has already been loaded so return a reference
2132 return $this->addedcourses
[$course->id
];
2135 return $this->add_course($course);
2140 * Loads all of the courses section into the navigation.
2142 * This function calls method from current course format, see
2143 * core_courseformat\base::extend_course_navigation()
2144 * If course module ($cm) is specified but course format failed to create the node,
2145 * the activity node is created anyway.
2147 * By default course formats call the method global_navigation::load_generic_course_sections()
2149 * @param stdClass $course Database record for the course
2150 * @param navigation_node $coursenode The course node within the navigation
2151 * @param null|int $sectionnum If specified load the contents of section with this relative number
2152 * @param null|cm_info $cm If specified make sure that activity node is created (either
2153 * in containg section or by calling load_stealth_activity() )
2155 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode, $sectionnum = null, $cm = null) {
2157 require_once($CFG->dirroot
.'/course/lib.php');
2158 if (isset($cm->sectionnum
)) {
2159 $sectionnum = $cm->sectionnum
;
2161 if ($sectionnum !== null) {
2162 $this->includesectionnum
= $sectionnum;
2164 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2165 if (isset($cm->id
)) {
2166 $activity = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
2167 if (empty($activity)) {
2168 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2174 * Generates an array of sections and an array of activities for the given course.
2176 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2178 * @param stdClass $course
2179 * @return array Array($sections, $activities)
2181 protected function generate_sections_and_activities(stdClass
$course) {
2183 require_once($CFG->dirroot
.'/course/lib.php');
2185 $modinfo = get_fast_modinfo($course);
2186 $sections = $modinfo->get_section_info_all();
2188 // For course formats using 'numsections' trim the sections list
2189 $courseformatoptions = course_get_format($course)->get_format_options();
2190 if (isset($courseformatoptions['numsections'])) {
2191 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+
1, true);
2194 $activities = array();
2196 foreach ($sections as $key => $section) {
2197 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2198 $sections[$key] = clone($section);
2199 unset($sections[$key]->summary
);
2200 $sections[$key]->hasactivites
= false;
2201 if (!array_key_exists($section->section
, $modinfo->sections
)) {
2204 foreach ($modinfo->sections
[$section->section
] as $cmid) {
2205 $cm = $modinfo->cms
[$cmid];
2206 $activity = new stdClass
;
2207 $activity->id
= $cm->id
;
2208 $activity->course
= $course->id
;
2209 $activity->section
= $section->section
;
2210 $activity->name
= $cm->name
;
2211 $activity->icon
= $cm->icon
;
2212 $activity->iconcomponent
= $cm->iconcomponent
;
2213 $activity->hidden
= (!$cm->visible
);
2214 $activity->modname
= $cm->modname
;
2215 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2216 $activity->onclick
= $cm->onclick
;
2219 $activity->url
= null;
2220 $activity->display
= false;
2222 $activity->url
= $url->out();
2223 $activity->display
= $cm->is_visible_on_course_page() ?
true : false;
2224 if (self
::module_extends_navigation($cm->modname
)) {
2225 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2228 $activities[$cmid] = $activity;
2229 if ($activity->display
) {
2230 $sections[$key]->hasactivites
= true;
2235 return array($sections, $activities);
2239 * Generically loads the course sections into the course's navigation.
2241 * @param stdClass $course
2242 * @param navigation_node $coursenode
2243 * @return array An array of course section nodes
2245 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode) {
2246 global $CFG, $DB, $USER, $SITE;
2247 require_once($CFG->dirroot
.'/course/lib.php');
2249 list($sections, $activities) = $this->generate_sections_and_activities($course);
2251 $navigationsections = array();
2252 foreach ($sections as $sectionid => $section) {
2253 $section = clone($section);
2254 if ($course->id
== $SITE->id
) {
2255 $this->load_section_activities($coursenode, $section->section
, $activities);
2257 if (!$section->uservisible ||
(!$this->showemptysections
&&
2258 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
2262 $sectionname = get_section_name($course, $section);
2263 $url = course_get_url($course, $section->section
, array('navigation' => true));
2265 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
,
2266 null, $section->id
, new pix_icon('i/section', ''));
2267 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2268 $sectionnode->hidden
= (!$section->visible ||
!$section->available
);
2269 if ($this->includesectionnum
!== false && $this->includesectionnum
== $section->section
) {
2270 $this->load_section_activities($sectionnode, $section->section
, $activities);
2272 $section->sectionnode
= $sectionnode;
2273 $navigationsections[$sectionid] = $section;
2276 return $navigationsections;
2280 * Loads all of the activities for a section into the navigation structure.
2282 * @param navigation_node $sectionnode
2283 * @param int $sectionnumber
2284 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2285 * @param stdClass $course The course object the section and activities relate to.
2286 * @return array Array of activity nodes
2288 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2290 // A static counter for JS function naming
2291 static $legacyonclickcounter = 0;
2293 $activitynodes = array();
2294 if (empty($activities)) {
2295 return $activitynodes;
2298 if (!is_object($course)) {
2299 $activity = reset($activities);
2300 $courseid = $activity->course
;
2302 $courseid = $course->id
;
2304 $showactivities = ($courseid != $SITE->id ||
!empty($CFG->navshowfrontpagemods
));
2306 foreach ($activities as $activity) {
2307 if ($activity->section
!= $sectionnumber) {
2310 if ($activity->icon
) {
2311 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2313 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2316 // Prepare the default name and url for the node
2317 $activityname = format_string($activity->name
, true, array('context' => context_module
::instance($activity->id
)));
2318 $action = new moodle_url($activity->url
);
2320 // Check if the onclick property is set (puke!)
2321 if (!empty($activity->onclick
)) {
2322 // Increment the counter so that we have a unique number.
2323 $legacyonclickcounter++
;
2324 // Generate the function name we will use
2325 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2326 $propogrationhandler = '';
2327 // Check if we need to cancel propogation. Remember inline onclick
2328 // events would return false if they wanted to prevent propogation and the
2330 if (strpos($activity->onclick
, 'return false')) {
2331 $propogrationhandler = 'e.halt();';
2333 // Decode the onclick - it has already been encoded for display (puke)
2334 $onclick = htmlspecialchars_decode($activity->onclick
, ENT_QUOTES
);
2335 // Build the JS function the click event will call
2336 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2337 $this->page
->requires
->js_amd_inline($jscode);
2338 // Override the default url with the new action link
2339 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2342 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2343 $activitynode->title(get_string('modulename', $activity->modname
));
2344 $activitynode->hidden
= $activity->hidden
;
2345 $activitynode->display
= $showactivities && $activity->display
;
2346 $activitynode->nodetype
= $activity->nodetype
;
2347 $activitynodes[$activity->id
] = $activitynode;
2350 return $activitynodes;
2353 * Loads a stealth module from unavailable section
2354 * @param navigation_node $coursenode
2355 * @param stdClass $modinfo
2356 * @return navigation_node or null if not accessible
2358 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2359 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2362 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2364 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2366 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2369 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2370 $activitynode->title(get_string('modulename', $cm->modname
));
2371 $activitynode->hidden
= (!$cm->visible
);
2372 if (!$cm->is_visible_on_course_page()) {
2373 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2374 // Also there may be no exception at all in case when teacher is logged in as student.
2375 $activitynode->display
= false;
2377 // Don't show activities that don't have links!
2378 $activitynode->display
= false;
2379 } else if (self
::module_extends_navigation($cm->modname
)) {
2380 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2382 return $activitynode;
2385 * Loads the navigation structure for the given activity into the activities node.
2387 * This method utilises a callback within the modules lib.php file to load the
2388 * content specific to activity given.
2390 * The callback is a method: {modulename}_extend_navigation()
2392 * * {@link forum_extend_navigation()}
2393 * * {@link workshop_extend_navigation()}
2395 * @param cm_info|stdClass $cm
2396 * @param stdClass $course
2397 * @param navigation_node $activity
2400 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2403 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2404 if (!($cm instanceof cm_info
)) {
2405 $modinfo = get_fast_modinfo($course);
2406 $cm = $modinfo->get_cm($cm->id
);
2408 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2409 $activity->make_active();
2410 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2411 $function = $cm->modname
.'_extend_navigation';
2413 if (file_exists($file)) {
2414 require_once($file);
2415 if (function_exists($function)) {
2416 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2417 $function($activity, $course, $activtyrecord, $cm);
2421 // Allow the active advanced grading method plugin to append module navigation
2422 $featuresfunc = $cm->modname
.'_supports';
2423 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2424 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2425 $gradingman = get_grading_manager($cm->context
, 'mod_'.$cm->modname
);
2426 $gradingman->extend_navigation($this, $activity);
2429 return $activity->has_children();
2432 * Loads user specific information into the navigation in the appropriate place.
2434 * If no user is provided the current user is assumed.
2436 * @param stdClass $user
2437 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2440 protected function load_for_user($user=null, $forceforcontext=false) {
2441 global $DB, $CFG, $USER, $SITE;
2443 require_once($CFG->dirroot
. '/course/lib.php');
2445 if ($user === null) {
2446 // We can't require login here but if the user isn't logged in we don't
2447 // want to show anything
2448 if (!isloggedin() ||
isguestuser()) {
2452 } else if (!is_object($user)) {
2453 // If the user is not an object then get them from the database
2454 $select = context_helper
::get_preload_record_columns_sql('ctx');
2455 $sql = "SELECT u.*, $select
2457 JOIN {context} ctx ON u.id = ctx.instanceid
2458 WHERE u.id = :userid AND
2459 ctx.contextlevel = :contextlevel";
2460 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2461 context_helper
::preload_from_record($user);
2464 $iscurrentuser = ($user->id
== $USER->id
);
2466 $usercontext = context_user
::instance($user->id
);
2468 // Get the course set against the page, by default this will be the site
2469 $course = $this->page
->course
;
2470 $baseargs = array('id'=>$user->id
);
2471 if ($course->id
!= $SITE->id
&& (!$iscurrentuser ||
$forceforcontext)) {
2472 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
2473 $baseargs['course'] = $course->id
;
2474 $coursecontext = context_course
::instance($course->id
);
2475 $issitecourse = false;
2477 // Load all categories and get the context for the system
2478 $coursecontext = context_system
::instance();
2479 $issitecourse = true;
2482 // Create a node to add user information under.
2484 if (!$issitecourse) {
2485 // Not the current user so add it to the participants node for the current course.
2486 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2487 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2488 } else if ($USER->id
!= $user->id
) {
2489 // This is the site so add a users node to the root branch.
2490 $usersnode = $this->rootnodes
['users'];
2491 if (course_can_view_participants($coursecontext)) {
2492 $usersnode->action
= new moodle_url('/user/index.php', array('id' => $course->id
));
2494 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2497 // We should NEVER get here, if the course hasn't been populated
2498 // with a participants node then the navigaiton either wasn't generated
2499 // for it (you are missing a require_login or set_context call) or
2500 // you don't have access.... in the interests of no leaking informatin
2501 // we simply quit...
2504 // Add a branch for the current user.
2505 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2506 $viewprofile = true;
2507 if (!$iscurrentuser) {
2508 require_once($CFG->dirroot
. '/user/lib.php');
2509 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& !has_capability('moodle/user:viewdetails', $usercontext) ) {
2510 $viewprofile = false;
2511 } else if ($this->page
->context
->contextlevel
!= CONTEXT_USER
&& !user_can_view_profile($user, $course, $usercontext)) {
2512 $viewprofile = false;
2514 if (!$viewprofile) {
2515 $viewprofile = user_can_view_profile($user, null, $usercontext);
2519 // Now, conditionally add the user node.
2521 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2522 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, 'user' . $user->id
);
2524 $usernode = $usersnode->add(get_string('user'));
2527 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2528 $usernode->make_active();
2531 // Add user information to the participants or user node.
2532 if ($issitecourse) {
2534 // If the user is the current user or has permission to view the details of the requested
2535 // user than add a view profile link.
2536 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
2537 has_capability('moodle/user:viewdetails', $usercontext)) {
2538 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2539 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2541 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2545 if (!empty($CFG->navadduserpostslinks
)) {
2546 // Add nodes for forum posts and discussions if the user can view either or both
2547 // There are no capability checks here as the content of the page is based
2548 // purely on the forums the current user has access too.
2549 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2550 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2551 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2552 array_merge($baseargs, array('mode' => 'discussions'))));
2556 if (!empty($CFG->enableblogs
)) {
2557 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2558 require_once($CFG->dirroot
.'/blog/lib.php');
2559 // Get all options for the user.
2560 $options = blog_get_options_for_user($user);
2561 $this->cache
->set('userblogoptions'.$user->id
, $options);
2563 $options = $this->cache
->{'userblogoptions'.$user->id
};
2566 if (count($options) > 0) {
2567 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2568 foreach ($options as $type => $option) {
2569 if ($type == "rss") {
2570 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null,
2571 new pix_icon('i/rss', ''));
2573 $blogs->add($option['string'], $option['link']);
2579 // Add the messages link.
2580 // It is context based so can appear in the user's profile and in course participants information.
2581 if (!empty($CFG->messaging
)) {
2582 $messageargs = array('user1' => $USER->id
);
2583 if ($USER->id
!= $user->id
) {
2584 $messageargs['user2'] = $user->id
;
2586 $url = new moodle_url('/message/index.php', $messageargs);
2587 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2590 // Add the "My private files" link.
2591 // This link doesn't have a unique display for course context so only display it under the user's profile.
2592 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2593 $url = new moodle_url('/user/files.php');
2594 $usernode->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
2597 // Add a node to view the users notes if permitted.
2598 if (!empty($CFG->enablenotes
) &&
2599 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2600 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
2601 if ($coursecontext->instanceid
!= SITEID
) {
2602 $url->param('course', $coursecontext->instanceid
);
2604 $usernode->add(get_string('notes', 'notes'), $url);
2607 // Show the grades node.
2608 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2609 require_once($CFG->dirroot
. '/user/lib.php');
2610 // Set the grades node to link to the "Grades" page.
2611 if ($course->id
== SITEID
) {
2612 $url = user_mygrades_url($user->id
, $course->id
);
2613 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2614 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
2616 if ($USER->id
!= $user->id
) {
2617 $usernode->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'usergrades');
2619 $usernode->add(get_string('grades', 'grades'), $url);
2623 // If the user is the current user add the repositories for the current user.
2624 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2625 if (!$iscurrentuser &&
2626 $course->id
== $SITE->id
&&
2627 has_capability('moodle/user:viewdetails', $usercontext) &&
2628 (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2630 // Add view grade report is permitted.
2631 $reports = core_component
::get_plugin_list('gradereport');
2632 arsort($reports); // User is last, we want to test it first.
2634 $userscourses = enrol_get_users_courses($user->id
, false, '*');
2635 $userscoursesnode = $usernode->add(get_string('courses'));
2638 foreach ($userscourses as $usercourse) {
2639 if ($count === (int)$CFG->navcourselimit
) {
2640 $url = new moodle_url('/user/profile.php', array('id' => $user->id
, 'showallcourses' => 1));
2641 $userscoursesnode->add(get_string('showallcourses'), $url);
2645 $usercoursecontext = context_course
::instance($usercourse->id
);
2646 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2647 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2648 array('id' => $user->id
, 'course' => $usercourse->id
)), self
::TYPE_CONTAINER
);
2650 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2651 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2652 foreach ($reports as $plugin => $plugindir) {
2653 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2654 // Stop when the first visible plugin is found.
2655 $gradeavailable = true;
2661 if ($gradeavailable) {
2662 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id
));
2663 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null,
2664 new pix_icon('i/grades', ''));
2667 // Add a node to view the users notes if permitted.
2668 if (!empty($CFG->enablenotes
) &&
2669 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2670 $url = new moodle_url('/notes/index.php', array('user' => $user->id
, 'course' => $usercourse->id
));
2671 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2674 if (can_access_course($usercourse, $user->id
, '', true)) {
2675 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2676 array('id' => $usercourse->id
)), self
::TYPE_SETTING
, null, null, new pix_icon('i/course', ''));
2679 $reporttab = $usercoursenode->add(get_string('activityreports'));
2681 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2682 foreach ($reportfunctions as $reportfunction) {
2683 $reportfunction($reporttab, $user, $usercourse);
2686 $reporttab->trim_if_empty();
2690 // Let plugins hook into user navigation.
2691 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2692 foreach ($pluginsfunction as $plugintype => $plugins) {
2693 if ($plugintype != 'report') {
2694 foreach ($plugins as $pluginfunction) {
2695 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2704 * This method simply checks to see if a given module can extend the navigation.
2706 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2708 * @param string $modname
2711 public static function module_extends_navigation($modname) {
2713 static $extendingmodules = array();
2714 if (!array_key_exists($modname, $extendingmodules)) {
2715 $extendingmodules[$modname] = false;
2716 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2717 if (file_exists($file)) {
2718 $function = $modname.'_extend_navigation';
2719 require_once($file);
2720 $extendingmodules[$modname] = (function_exists($function));
2723 return $extendingmodules[$modname];
2726 * Extends the navigation for the given user.
2728 * @param stdClass $user A user from the database
2730 public function extend_for_user($user) {
2731 $this->extendforuser
[] = $user;
2735 * Returns all of the users the navigation is being extended for
2737 * @return array An array of extending users.
2739 public function get_extending_users() {
2740 return $this->extendforuser
;
2743 * Adds the given course to the navigation structure.
2745 * @param stdClass $course
2746 * @param bool $forcegeneric
2747 * @param bool $ismycourse
2748 * @return navigation_node
2750 public function add_course(stdClass
$course, $forcegeneric = false, $coursetype = self
::COURSE_OTHER
) {
2753 // We found the course... we can return it now :)
2754 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2755 return $this->addedcourses
[$course->id
];
2758 $coursecontext = context_course
::instance($course->id
);
2760 if ($coursetype != self
::COURSE_MY
&& $coursetype != self
::COURSE_CURRENT
&& $course->id
!= $SITE->id
) {
2761 if (is_role_switched($course->id
)) {
2762 // user has to be able to access course in order to switch, let's skip the visibility test here
2763 } else if (!core_course_category
::can_view_course_info($course)) {
2768 $issite = ($course->id
== $SITE->id
);
2769 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
2770 $fullname = format_string($course->fullname
, true, array('context' => $coursecontext));
2771 // This is the name that will be shown for the course.
2772 $coursename = empty($CFG->navshowfullcoursenames
) ?
$shortname : $fullname;
2774 if ($coursetype == self
::COURSE_CURRENT
) {
2775 if ($coursenode = $this->rootnodes
['mycourses']->find($course->id
, self
::TYPE_COURSE
)) {
2778 $coursetype = self
::COURSE_OTHER
;
2782 // Can the user expand the course to see its content.
2783 $canexpandcourse = true;
2787 if (empty($CFG->usesitenameforsitepages
)) {
2788 $coursename = get_string('sitepages');
2790 } else if ($coursetype == self
::COURSE_CURRENT
) {
2791 $parent = $this->rootnodes
['currentcourse'];
2792 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2793 $canexpandcourse = $this->can_expand_course($course);
2794 } else if ($coursetype == self
::COURSE_MY
&& !$forcegeneric) {
2795 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_MY_CATEGORY
))) {
2796 // Nothing to do here the above statement set $parent to the category within mycourses.
2798 $parent = $this->rootnodes
['mycourses'];
2800 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2802 $parent = $this->rootnodes
['courses'];
2803 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2804 // They can only expand the course if they can access it.
2805 $canexpandcourse = $this->can_expand_course($course);
2806 if (!empty($course->category
) && $this->show_categories($coursetype == self
::COURSE_MY
)) {
2807 if (!$this->is_category_fully_loaded($course->category
)) {
2808 // We need to load the category structure for this course
2809 $this->load_all_categories($course->category
, false);
2811 if (array_key_exists($course->category
, $this->addedcategories
)) {
2812 $parent = $this->addedcategories
[$course->category
];
2813 // This could lead to the course being created so we should check whether it is the case again
2814 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2815 return $this->addedcourses
[$course->id
];
2821 $coursenode = $parent->add($coursename, $url, self
::TYPE_COURSE
, $shortname, $course->id
, new pix_icon('i/course', ''));
2822 $coursenode->showinflatnavigation
= $coursetype == self
::COURSE_MY
;
2824 $coursenode->hidden
= (!$course->visible
);
2825 $coursenode->title(format_string($course->fullname
, true, array('context' => $coursecontext, 'escape' => false)));
2826 if ($canexpandcourse) {
2827 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2828 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2829 $coursenode->isexpandable
= true;
2831 $coursenode->nodetype
= self
::NODETYPE_LEAF
;
2832 $coursenode->isexpandable
= false;
2834 if (!$forcegeneric) {
2835 $this->addedcourses
[$course->id
] = $coursenode;
2842 * Returns a cache instance to use for the expand course cache.
2843 * @return cache_session
2845 protected function get_expand_course_cache() {
2846 if ($this->cacheexpandcourse
=== null) {
2847 $this->cacheexpandcourse
= cache
::make('core', 'navigation_expandcourse');
2849 return $this->cacheexpandcourse
;
2853 * Checks if a user can expand a course in the navigation.
2855 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2856 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2857 * permits stale data.
2858 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2860 * It is brought up to date in only one of two ways.
2861 * 1. The user logs out and in again.
2862 * 2. The user browses to the course they've just being given access to.
2864 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2866 * @param stdClass $course
2869 protected function can_expand_course($course) {
2870 $cache = $this->get_expand_course_cache();
2871 $canexpand = $cache->get($course->id
);
2872 if ($canexpand === false) {
2873 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2874 $canexpand = (int)$canexpand;
2875 $cache->set($course->id
, $canexpand);
2877 return ($canexpand === 1);
2881 * Returns true if the category has already been loaded as have any child categories
2883 * @param int $categoryid
2886 protected function is_category_fully_loaded($categoryid) {
2887 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2891 * Adds essential course nodes to the navigation for the given course.
2893 * This method adds nodes such as reports, blogs and participants
2895 * @param navigation_node $coursenode
2896 * @param stdClass $course
2897 * @return bool returns true on successful addition of a node.
2899 public function add_course_essentials($coursenode, stdClass
$course) {
2901 require_once($CFG->dirroot
. '/course/lib.php');
2903 if ($course->id
== $SITE->id
) {
2904 return $this->add_front_page_course_essentials($coursenode, $course);
2907 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2911 $navoptions = course_get_user_navigation_options($this->page
->context
, $course);
2914 if ($navoptions->participants
) {
2915 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
),
2916 self
::TYPE_CONTAINER
, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2918 if ($navoptions->blogs
) {
2919 $blogsurls = new moodle_url('/blog/index.php');
2920 if ($currentgroup = groups_get_course_group($course, true)) {
2921 $blogsurls->param('groupid', $currentgroup);
2923 $blogsurls->param('courseid', $course->id
);
2925 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self
::TYPE_SETTING
, null, 'courseblogs');
2928 if ($navoptions->notes
) {
2929 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id
)), self
::TYPE_SETTING
, null, 'currentcoursenotes');
2931 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2932 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2936 if ($navoptions->badges
) {
2937 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id
));
2939 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2940 navigation_node
::TYPE_SETTING
, null, 'badgesview',
2941 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2944 // Check access to the course and competencies page.
2945 if ($navoptions->competencies
) {
2946 // Just a link to course competency.
2947 $title = get_string('competencies', 'core_competency');
2948 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id
));
2949 $coursenode->add($title, $path, navigation_node
::TYPE_SETTING
, null, 'competencies',
2950 new pix_icon('i/competencies', ''));
2952 if ($navoptions->grades
) {
2953 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
2954 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null,
2955 'grades', new pix_icon('i/grades', ''));
2956 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2957 if ($this->page
->context
->contextlevel
< CONTEXT_MODULE
&& strpos($this->page
->pagetype
, 'grade-') === 0) {
2958 $gradenode->make_active();
2965 * This generates the structure of the course that won't be generated when
2966 * the modules and sections are added.
2968 * Things such as the reports branch, the participants branch, blogs... get
2969 * added to the course node by this method.
2971 * @param navigation_node $coursenode
2972 * @param stdClass $course
2973 * @return bool True for successfull generation
2975 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2976 global $CFG, $USER, $COURSE, $SITE;
2977 require_once($CFG->dirroot
. '/course/lib.php');
2979 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2983 $systemcontext = context_system
::instance();
2984 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2986 // Hidden node that we use to determine if the front page navigation is loaded.
2987 // This required as there are not other guaranteed nodes that may be loaded.
2988 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2990 // Add My courses to the site pages within the navigation structure so the block can read it.
2991 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self
::TYPE_CUSTOM
, null, 'mycourses');
2994 if ($navoptions->participants
) {
2995 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
),
2996 self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
3000 if ($navoptions->blogs
) {
3001 $blogsurls = new moodle_url('/blog/index.php');
3002 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self
::TYPE_SYSTEM
, null, 'siteblog');
3008 if ($navoptions->badges
) {
3009 $url = new moodle_url($CFG->wwwroot
. '/badges/view.php', array('type' => 1));
3010 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node
::TYPE_CUSTOM
);
3014 if ($navoptions->notes
) {
3015 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
3016 array('filtertype' => 'course', 'filterselect' => $filterselect)), self
::TYPE_SETTING
, null, 'notes');
3020 if ($navoptions->tags
) {
3021 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
3022 self
::TYPE_SETTING
, null, 'tags');
3026 if ($navoptions->search
) {
3027 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
3028 self
::TYPE_SETTING
, null, 'search');
3032 $usercontext = context_user
::instance($USER->id
);
3033 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
3034 $url = new moodle_url('/user/files.php');
3035 $node = $coursenode->add(get_string('privatefiles'), $url,
3036 self
::TYPE_SETTING
, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
3037 $node->display
= false;
3038 $node->showinflatnavigation
= true;
3043 $context = $this->page
->context
;
3044 switch ($context->contextlevel
) {
3045 case CONTEXT_COURSECAT
:
3046 // OK, expected context level.
3048 case CONTEXT_COURSE
:
3049 // OK, expected context level if not on frontpage.
3050 if ($COURSE->id
!= $SITE->id
) {
3054 // If this context is part of a course (excluding frontpage), use the course context.
3055 // Otherwise, use the system context.
3056 $coursecontext = $context->get_course_context(false);
3057 if ($coursecontext && $coursecontext->instanceid
!== $SITE->id
) {
3058 $context = $coursecontext;
3060 $context = $systemcontext;
3064 $params = ['contextid' => $context->id
];
3065 if (has_capability('moodle/contentbank:access', $context)) {
3066 $url = new moodle_url('/contentbank/index.php', $params);
3067 $node = $coursenode->add(get_string('contentbank'), $url,
3068 self
::TYPE_CUSTOM
, null, 'contentbank', new pix_icon('i/contentbank', ''));
3069 $node->showinflatnavigation
= true;
3077 * Clears the navigation cache
3079 public function clear_cache() {
3080 $this->cache
->clear();
3084 * Sets an expansion limit for the navigation
3086 * The expansion limit is used to prevent the display of content that has a type
3087 * greater than the provided $type.
3089 * Can be used to ensure things such as activities or activity content don't get
3090 * shown on the navigation.
3091 * They are still generated in order to ensure the navbar still makes sense.
3093 * @param int $type One of navigation_node::TYPE_*
3094 * @return bool true when complete.
3096 public function set_expansion_limit($type) {
3098 $nodes = $this->find_all_of_type($type);
3100 // We only want to hide specific types of nodes.
3101 // Only nodes that represent "structure" in the navigation tree should be hidden.
3102 // If we hide all nodes then we risk hiding vital information.
3103 $typestohide = array(
3104 self
::TYPE_CATEGORY
,
3110 foreach ($nodes as $node) {
3111 // We need to generate the full site node
3112 if ($type == self
::TYPE_COURSE
&& $node->key
== $SITE->id
) {
3115 foreach ($node->children
as $child) {
3116 $child->hide($typestohide);
3122 * Attempts to get the navigation with the given key from this nodes children.
3124 * This function only looks at this nodes children, it does NOT look recursivily.
3125 * If the node can't be found then false is returned.
3127 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3129 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3130 * may be of more use to you.
3132 * @param string|int $key The key of the node you wish to receive.
3133 * @param int $type One of navigation_node::TYPE_*
3134 * @return navigation_node|false
3136 public function get($key, $type = null) {
3137 if (!$this->initialised
) {
3138 $this->initialise();
3140 return parent
::get($key, $type);
3144 * Searches this nodes children and their children to find a navigation node
3145 * with the matching key and type.
3147 * This method is recursive and searches children so until either a node is
3148 * found or there are no more nodes to search.
3150 * If you know that the node being searched for is a child of this node
3151 * then use the {@link global_navigation::get()} method instead.
3153 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3154 * may be of more use to you.
3156 * @param string|int $key The key of the node you wish to receive.
3157 * @param int $type One of navigation_node::TYPE_*
3158 * @return navigation_node|false
3160 public function find($key, $type) {
3161 if (!$this->initialised
) {
3162 $this->initialise();
3164 if ($type == self
::TYPE_ROOTNODE
&& array_key_exists($key, $this->rootnodes
)) {
3165 return $this->rootnodes
[$key];
3167 return parent
::find($key, $type);
3171 * They've expanded the 'my courses' branch.
3173 protected function load_courses_enrolled() {
3176 $limit = (int) $CFG->navcourselimit
;
3178 $courses = enrol_get_my_courses('*');
3179 $flatnavcourses = [];
3181 // Go through the courses and see which ones we want to display in the flatnav.
3182 foreach ($courses as $course) {
3183 $classify = course_classify_for_timeline($course);
3185 if ($classify == COURSE_TIMELINE_INPROGRESS
) {
3186 $flatnavcourses[$course->id
] = $course;
3190 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3191 $numtotalcourses = count($courses);
3192 $numtotalflatnavcourses = count($flatnavcourses);
3194 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3195 $courses = array_slice($courses, 0, $limit, true);
3196 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3198 // Get the number of courses we are going to show for each.
3199 $numshowncourses = count($courses);
3200 $numshownflatnavcourses = count($flatnavcourses);
3201 if ($numshowncourses && $this->show_my_categories()) {
3202 // Generate an array containing unique values of all the courses' categories.
3203 $categoryids = array();
3204 foreach ($courses as $course) {
3205 if (in_array($course->category
, $categoryids)) {
3208 $categoryids[] = $course->category
;
3211 // Array of category IDs that include the categories of the user's courses and the related course categories.
3212 $fullpathcategoryids = [];
3213 // Get the course categories for the enrolled courses' category IDs.
3214 $mycoursecategories = core_course_category
::get_many($categoryids);
3215 // Loop over each of these categories and build the category tree using each category's path.
3216 foreach ($mycoursecategories as $mycoursecat) {
3217 $pathcategoryids = explode('/', $mycoursecat->path
);
3218 // First element of the exploded path is empty since paths begin with '/'.
3219 array_shift($pathcategoryids);
3220 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3221 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3224 // Fetch all of the categories related to the user's courses.
3225 $pathcategories = core_course_category
::get_many($fullpathcategoryids);
3226 // Loop over each of these categories and build the category tree.
3227 foreach ($pathcategories as $coursecat) {
3228 // No need to process categories that have already been added.
3229 if (isset($this->addedcategories
[$coursecat->id
])) {
3232 // Skip categories that are not visible.
3233 if (!$coursecat->is_uservisible()) {
3237 // Get this course category's parent node.
3239 if ($coursecat->parent
&& isset($this->addedcategories
[$coursecat->parent
])) {
3240 $parent = $this->addedcategories
[$coursecat->parent
];
3243 // If it has no parent, then it should be right under the My courses node.
3244 $parent = $this->rootnodes
['mycourses'];
3247 // Build the category object based from the coursecat object.
3248 $mycategory = new stdClass();
3249 $mycategory->id
= $coursecat->id
;
3250 $mycategory->name
= $coursecat->name
;
3251 $mycategory->visible
= $coursecat->visible
;
3253 // Add this category to the nav tree.
3254 $this->add_category($mycategory, $parent, self
::TYPE_MY_CATEGORY
);
3258 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3259 foreach ($courses as $course) {
3260 $node = $this->add_course($course, false, self
::COURSE_MY
);
3262 $node->showinflatnavigation
= false;
3263 // Check if we should also add this to the flat nav as well.
3264 if (isset($flatnavcourses[$course->id
])) {
3265 $node->showinflatnavigation
= true;
3270 // Go through each course in the flatnav now.
3271 foreach ($flatnavcourses as $course) {
3272 // Check if we haven't already added it.
3273 if (!isset($courses[$course->id
])) {
3274 // Ok, add it to the flatnav only.
3275 $node = $this->add_course($course, false, self
::COURSE_MY
);
3276 $node->display
= false;
3277 $node->showinflatnavigation
= true;
3281 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3282 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3283 // Show a link to the course page if there are more courses the user is enrolled in.
3284 if ($showmorelinkinnav ||
$showmorelinkinflatnav) {
3285 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3286 $url = new moodle_url('/my/');
3287 $parent = $this->rootnodes
['mycourses'];
3288 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self
::TYPE_CUSTOM
, null, self
::COURSE_INDEX_PAGE
);
3290 if ($showmorelinkinnav) {
3291 $coursenode->display
= true;
3294 if ($showmorelinkinflatnav) {
3295 $coursenode->showinflatnavigation
= true;
3302 * The global navigation class used especially for AJAX requests.
3304 * The primary methods that are used in the global navigation class have been overriden
3305 * to ensure that only the relevant branch is generated at the root of the tree.
3306 * This can be done because AJAX is only used when the backwards structure for the
3307 * requested branch exists.
3308 * This has been done only because it shortens the amounts of information that is generated
3309 * which of course will speed up the response time.. because no one likes laggy AJAX.
3312 * @category navigation
3313 * @copyright 2009 Sam Hemelryk
3314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3316 class global_navigation_for_ajax
extends global_navigation
{
3318 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3319 protected $branchtype;
3321 /** @var int the instance id */
3322 protected $instanceid;
3324 /** @var array Holds an array of expandable nodes */
3325 protected $expandable = array();
3328 * Constructs the navigation for use in an AJAX request
3330 * @param moodle_page $page moodle_page object
3331 * @param int $branchtype
3334 public function __construct($page, $branchtype, $id) {
3335 $this->page
= $page;
3336 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3337 $this->children
= new navigation_node_collection();
3338 $this->branchtype
= $branchtype;
3339 $this->instanceid
= $id;
3340 $this->initialise();
3343 * Initialise the navigation given the type and id for the branch to expand.
3345 * @return array An array of the expandable nodes
3347 public function initialise() {
3350 if ($this->initialised ||
during_initial_install()) {
3351 return $this->expandable
;
3353 $this->initialised
= true;
3355 $this->rootnodes
= array();
3356 $this->rootnodes
['site'] = $this->add_course($SITE);
3357 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self
::TYPE_ROOTNODE
, null, 'mycourses');
3358 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
3359 // The courses branch is always displayed, and is always expandable (although may be empty).
3360 // This mimicks what is done during {@link global_navigation::initialise()}.
3361 $this->rootnodes
['courses']->isexpandable
= true;
3363 // Branchtype will be one of navigation_node::TYPE_*
3364 switch ($this->branchtype
) {
3366 if ($this->instanceid
=== 'mycourses') {
3367 $this->load_courses_enrolled();
3368 } else if ($this->instanceid
=== 'courses') {
3369 $this->load_courses_other();
3372 case self
::TYPE_CATEGORY
:
3373 $this->load_category($this->instanceid
);
3375 case self
::TYPE_MY_CATEGORY
:
3376 $this->load_category($this->instanceid
, self
::TYPE_MY_CATEGORY
);
3378 case self
::TYPE_COURSE
:
3379 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
3380 if (!can_access_course($course, null, '', true)) {
3381 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3382 // add the course node and break. This leads to an empty node.
3383 $this->add_course($course);
3386 require_course_login($course, true, null, false, true);
3387 $this->page
->set_context(context_course
::instance($course->id
));
3388 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3389 $this->add_course_essentials($coursenode, $course);
3390 $this->load_course_sections($course, $coursenode);
3392 case self
::TYPE_SECTION
:
3393 $sql = 'SELECT c.*, cs.section AS sectionnumber
3395 LEFT JOIN {course_sections} cs ON cs.course = c.id
3397 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
3398 require_course_login($course, true, null, false, true);
3399 $this->page
->set_context(context_course
::instance($course->id
));
3400 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3401 $this->add_course_essentials($coursenode, $course);
3402 $this->load_course_sections($course, $coursenode, $course->sectionnumber
);
3404 case self
::TYPE_ACTIVITY
:
3407 JOIN {course_modules} cm ON cm.course = c.id
3408 WHERE cm.id = :cmid";
3409 $params = array('cmid' => $this->instanceid
);
3410 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3411 $modinfo = get_fast_modinfo($course);
3412 $cm = $modinfo->get_cm($this->instanceid
);
3413 require_course_login($course, true, $cm, false, true);
3414 $this->page
->set_context(context_module
::instance($cm->id
));
3415 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3416 $this->load_course_sections($course, $coursenode, null, $cm);
3417 $activitynode = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
3418 if ($activitynode) {
3419 $modulenode = $this->load_activity($cm, $course, $activitynode);
3423 throw new Exception('Unknown type');
3424 return $this->expandable
;
3427 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
) {
3428 $this->load_for_user(null, true);
3431 // Give the local plugins a chance to include some navigation if they want.
3432 $this->load_local_plugin_navigation();
3434 $this->find_expandable($this->expandable
);
3435 return $this->expandable
;
3439 * They've expanded the general 'courses' branch.
3441 protected function load_courses_other() {
3442 $this->load_all_courses();
3446 * Loads a single category into the AJAX navigation.
3448 * This function is special in that it doesn't concern itself with the parent of
3449 * the requested category or its siblings.
3450 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3453 * @global moodle_database $DB
3454 * @param int $categoryid id of category to load in navigation.
3455 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3458 protected function load_category($categoryid, $nodetype = self
::TYPE_CATEGORY
) {
3462 if (!empty($CFG->navcourselimit
)) {
3463 $limit = (int)$CFG->navcourselimit
;
3466 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
3467 $sql = "SELECT cc.*, $catcontextsql
3468 FROM {course_categories} cc
3469 JOIN {context} ctx ON cc.id = ctx.instanceid
3470 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
3471 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3472 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3473 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3474 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3475 $categorylist = array();
3476 $subcategories = array();
3477 $basecategory = null;
3478 foreach ($categories as $category) {
3479 $categorylist[] = $category->id
;
3480 context_helper
::preload_from_record($category);
3481 if ($category->id
== $categoryid) {
3482 $this->add_category($category, $this, $nodetype);
3483 $basecategory = $this->addedcategories
[$category->id
];
3485 $subcategories[$category->id
] = $category;
3488 $categories->close();
3491 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3492 // else show all courses.
3493 if ($nodetype === self
::TYPE_MY_CATEGORY
) {
3494 $courses = enrol_get_my_courses('*');
3495 $categoryids = array();
3497 // Only search for categories if basecategory was found.
3498 if (!is_null($basecategory)) {
3499 // Get course parent category ids.
3500 foreach ($courses as $course) {
3501 $categoryids[] = $course->category
;
3504 // Get a unique list of category ids which a part of the path
3505 // to user's courses.
3506 $coursesubcategories = array();
3507 $addedsubcategories = array();
3509 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3510 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3512 foreach ($categories as $category){
3513 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path
, "/")));
3515 $categories->close();
3516 $coursesubcategories = array_unique($coursesubcategories);
3518 // Only add a subcategory if it is part of the path to user's course and
3519 // wasn't already added.
3520 foreach ($subcategories as $subid => $subcategory) {
3521 if (in_array($subid, $coursesubcategories) &&
3522 !in_array($subid, $addedsubcategories)) {
3523 $this->add_category($subcategory, $basecategory, $nodetype);
3524 $addedsubcategories[] = $subid;
3529 foreach ($courses as $course) {
3530 // Add course if it's in category.
3531 if (in_array($course->category
, $categorylist)) {
3532 $this->add_course($course, true, self
::COURSE_MY
);
3536 if (!is_null($basecategory)) {
3537 foreach ($subcategories as $key=>$category) {
3538 $this->add_category($category, $basecategory, $nodetype);
3541 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3542 foreach ($courses as $course) {
3543 $this->add_course($course);
3550 * Returns an array of expandable nodes
3553 public function get_expandable() {
3554 return $this->expandable
;
3561 * This class is used to manage the navbar, which is initialised from the navigation
3562 * object held by PAGE
3565 * @category navigation
3566 * @copyright 2009 Sam Hemelryk
3567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3569 class navbar
extends navigation_node
{
3570 /** @var bool A switch for whether the navbar is initialised or not */
3571 protected $initialised = false;
3572 /** @var mixed keys used to reference the nodes on the navbar */
3573 protected $keys = array();
3574 /** @var null|string content of the navbar */
3575 protected $content = null;
3576 /** @var moodle_page object the moodle page that this navbar belongs to */
3578 /** @var bool A switch for whether to ignore the active navigation information */
3579 protected $ignoreactive = false;
3580 /** @var bool A switch to let us know if we are in the middle of an install */
3581 protected $duringinstall = false;
3582 /** @var bool A switch for whether the navbar has items */
3583 protected $hasitems = false;
3584 /** @var array An array of navigation nodes for the navbar */
3586 /** @var array An array of child node objects */
3587 public $children = array();
3588 /** @var bool A switch for whether we want to include the root node in the navbar */
3589 public $includesettingsbase = false;
3590 /** @var breadcrumb_navigation_node[] $prependchildren */
3591 protected $prependchildren = array();
3594 * The almighty constructor
3596 * @param moodle_page $page
3598 public function __construct(moodle_page
$page) {
3600 if (during_initial_install()) {
3601 $this->duringinstall
= true;
3604 $this->page
= $page;
3605 $this->text
= get_string('home');
3606 $this->shorttext
= get_string('home');
3607 $this->action
= new moodle_url($CFG->wwwroot
);
3608 $this->nodetype
= self
::NODETYPE_BRANCH
;
3609 $this->type
= self
::TYPE_SYSTEM
;
3613 * Quick check to see if the navbar will have items in.
3615 * @return bool Returns true if the navbar will have items, false otherwise
3617 public function has_items() {
3618 if ($this->duringinstall
) {
3620 } else if ($this->hasitems
!== false) {
3623 if (count($this->children
) > 0 ||
count($this->prependchildren
) > 0) {
3624 // There have been manually added items - there are definitely items.
3626 } else if (!$this->ignoreactive
) {
3627 // We will need to initialise the navigation structure to check if there are active items.
3628 $this->page
->navigation
->initialise($this->page
);
3629 $outcome = ($this->page
->navigation
->contains_active_node() ||
$this->page
->settingsnav
->contains_active_node());
3631 $this->hasitems
= $outcome;
3636 * Turn on/off ignore active
3638 * @param bool $setting
3640 public function ignore_active($setting=true) {
3641 $this->ignoreactive
= ($setting);
3645 * Gets a navigation node
3647 * @param string|int $key for referencing the navbar nodes
3648 * @param int $type breadcrumb_navigation_node::TYPE_*
3649 * @return breadcrumb_navigation_node|bool
3651 public function get($key, $type = null) {
3652 foreach ($this->children
as &$child) {
3653 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3657 foreach ($this->prependchildren
as &$child) {
3658 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3665 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3669 public function get_items() {
3672 // Make sure that navigation is initialised
3673 if (!$this->has_items()) {
3676 if ($this->items
!== null) {
3677 return $this->items
;
3680 if (count($this->children
) > 0) {
3681 // Add the custom children.
3682 $items = array_reverse($this->children
);
3685 // Check if navigation contains the active node
3686 if (!$this->ignoreactive
) {
3687 // We will need to ensure the navigation has been initialised.
3688 $this->page
->navigation
->initialise($this->page
);
3689 // Now find the active nodes on both the navigation and settings.
3690 $navigationactivenode = $this->page
->navigation
->find_active_node();
3691 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3693 if ($navigationactivenode && $settingsactivenode) {
3694 // Parse a combined navigation tree
3695 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3696 if (!$settingsactivenode->mainnavonly
) {
3697 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3699 $settingsactivenode = $settingsactivenode->parent
;
3701 if (!$this->includesettingsbase
) {
3702 // Removes the first node from the settings (root node) from the list
3705 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3706 if (!$navigationactivenode->mainnavonly
) {
3707 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3709 if (!empty($CFG->navshowcategories
) &&
3710 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3711 $navigationactivenode->parent
->key
=== 'currentcourse') {
3712 foreach ($this->get_course_categories() as $item) {
3713 $items[] = new breadcrumb_navigation_node($item);
3716 $navigationactivenode = $navigationactivenode->parent
;
3718 } else if ($navigationactivenode) {
3719 // Parse the navigation tree to get the active node
3720 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3721 if (!$navigationactivenode->mainnavonly
) {
3722 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3724 if (!empty($CFG->navshowcategories
) &&
3725 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3726 $navigationactivenode->parent
->key
=== 'currentcourse') {
3727 foreach ($this->get_course_categories() as $item) {
3728 $items[] = new breadcrumb_navigation_node($item);
3731 $navigationactivenode = $navigationactivenode->parent
;
3733 } else if ($settingsactivenode) {
3734 // Parse the settings navigation to get the active node
3735 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3736 if (!$settingsactivenode->mainnavonly
) {
3737 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3739 $settingsactivenode = $settingsactivenode->parent
;
3744 $items[] = new breadcrumb_navigation_node(array(
3745 'text' => $this->page
->navigation
->text
,
3746 'shorttext' => $this->page
->navigation
->shorttext
,
3747 'key' => $this->page
->navigation
->key
,
3748 'action' => $this->page
->navigation
->action
3751 if (count($this->prependchildren
) > 0) {
3752 // Add the custom children
3753 $items = array_merge($items, array_reverse($this->prependchildren
));
3756 $last = reset($items);
3758 $last->set_last(true);
3760 $this->items
= array_reverse($items);
3761 return $this->items
;
3765 * Get the list of categories leading to this course.
3767 * This function is used by {@link navbar::get_items()} to add back the "courses"
3768 * node and category chain leading to the current course. Note that this is only ever
3769 * called for the current course, so we don't need to bother taking in any parameters.
3773 private function get_course_categories() {
3775 require_once($CFG->dirroot
.'/course/lib.php');
3777 $categories = array();
3778 $cap = 'moodle/category:viewhiddencategories';
3779 $showcategories = !core_course_category
::is_simple_site();
3781 if ($showcategories) {
3782 foreach ($this->page
->categories
as $category) {
3783 $context = context_coursecat
::instance($category->id
);
3784 if (!core_course_category
::can_view_category($category)) {
3787 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id
));
3788 $name = format_string($category->name
, true, array('context' => $context));
3789 $categorynode = breadcrumb_navigation_node
::create($name, $url, self
::TYPE_CATEGORY
, null, $category->id
);
3790 if (!$category->visible
) {
3791 $categorynode->hidden
= true;
3793 $categories[] = $categorynode;
3797 // Don't show the 'course' node if enrolled in this course.
3798 $coursecontext = context_course
::instance($this->page
->course
->id
);
3799 if (!is_enrolled($coursecontext, null, '', true)) {
3800 $courses = $this->page
->navigation
->get('courses');
3802 // Courses node may not be present.
3803 $courses = breadcrumb_navigation_node
::create(
3804 get_string('courses'),
3805 new moodle_url('/course/index.php'),
3806 self
::TYPE_CONTAINER
3809 $categories[] = $courses;
3816 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3818 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3819 * the way nodes get added to allow us to simply call add and have the node added to the
3822 * @param string $text
3823 * @param string|moodle_url|action_link $action An action to associate with this node.
3824 * @param int $type One of navigation_node::TYPE_*
3825 * @param string $shorttext
3826 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3827 * @param pix_icon $icon An optional icon to use for this node.
3828 * @return navigation_node
3830 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3831 if ($this->content
!== null) {
3832 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3835 // Properties array used when creating the new navigation node
3840 // Set the action if one was provided
3841 if ($action!==null) {
3842 $itemarray['action'] = $action;
3844 // Set the shorttext if one was provided
3845 if ($shorttext!==null) {
3846 $itemarray['shorttext'] = $shorttext;
3848 // Set the icon if one was provided
3850 $itemarray['icon'] = $icon;
3852 // Default the key to the number of children if not provided
3853 if ($key === null) {
3854 $key = count($this->children
);
3857 $itemarray['key'] = $key;
3858 // Set the parent to this node
3859 $itemarray['parent'] = $this;
3860 // Add the child using the navigation_node_collections add method
3861 $this->children
[] = new breadcrumb_navigation_node($itemarray);
3866 * Prepends a new navigation_node to the start of the navbar
3868 * @param string $text
3869 * @param string|moodle_url|action_link $action An action to associate with this node.
3870 * @param int $type One of navigation_node::TYPE_*
3871 * @param string $shorttext
3872 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3873 * @param pix_icon $icon An optional icon to use for this node.
3874 * @return navigation_node
3876 public function prepend($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3877 if ($this->content
!== null) {
3878 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3880 // Properties array used when creating the new navigation node.
3885 // Set the action if one was provided.
3886 if ($action!==null) {
3887 $itemarray['action'] = $action;
3889 // Set the shorttext if one was provided.
3890 if ($shorttext!==null) {
3891 $itemarray['shorttext'] = $shorttext;
3893 // Set the icon if one was provided.
3895 $itemarray['icon'] = $icon;
3897 // Default the key to the number of children if not provided.
3898 if ($key === null) {
3899 $key = count($this->children
);
3902 $itemarray['key'] = $key;
3903 // Set the parent to this node.
3904 $itemarray['parent'] = $this;
3905 // Add the child node to the prepend list.
3906 $this->prependchildren
[] = new breadcrumb_navigation_node($itemarray);
3912 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3913 * in particular adding extra metadata for search engine robots to leverage.
3916 * @category navigation
3917 * @copyright 2015 Brendan Heywood
3918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3920 class breadcrumb_navigation_node
extends navigation_node
{
3922 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3923 private $last = false;
3926 * A proxy constructor
3928 * @param mixed $navnode A navigation_node or an array
3930 public function __construct($navnode) {
3931 if (is_array($navnode)) {
3932 parent
::__construct($navnode);
3933 } else if ($navnode instanceof navigation_node
) {
3935 // Just clone everything.
3936 $objvalues = get_object_vars($navnode);
3937 foreach ($objvalues as $key => $value) {
3938 $this->$key = $value;
3941 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3949 public function is_last() {
3955 * @param $val boolean
3957 public function set_last($val) {
3963 * Subclass of navigation_node allowing different rendering for the flat navigation
3964 * in particular allowing dividers and indents.
3967 * @category navigation
3968 * @copyright 2016 Damyon Wiese
3969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3971 class flat_navigation_node
extends navigation_node
{
3973 /** @var $indent integer The indent level */
3974 private $indent = 0;
3976 /** @var $showdivider bool Show a divider before this element */
3977 private $showdivider = false;
3979 /** @var $collectionlabel string Label for a group of nodes */
3980 private $collectionlabel = '';
3983 * A proxy constructor
3985 * @param mixed $navnode A navigation_node or an array
3987 public function __construct($navnode, $indent) {
3988 if (is_array($navnode)) {
3989 parent
::__construct($navnode);
3990 } else if ($navnode instanceof navigation_node
) {
3992 // Just clone everything.
3993 $objvalues = get_object_vars($navnode);
3994 foreach ($objvalues as $key => $value) {
3995 $this->$key = $value;
3998 throw new coding_exception('Not a valid flat_navigation_node');
4000 $this->indent
= $indent;
4004 * Setter, a label is required for a flat navigation node that shows a divider.
4006 * @param string $label
4008 public function set_collectionlabel($label) {
4009 $this->collectionlabel
= $label;
4013 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
4017 public function get_collectionlabel() {
4018 if (!empty($this->collectionlabel
)) {
4019 return $this->collectionlabel
;
4021 if ($this->parent
&& ($this->parent
instanceof flat_navigation_node ||
$this->parent
instanceof flat_navigation
)) {
4022 return $this->parent
->get_collectionlabel();
4024 debugging('Navigation region requires a label', DEBUG_DEVELOPER
);
4029 * Does this node represent a course section link.
4032 public function is_section() {
4033 return $this->type
== navigation_node
::TYPE_SECTION
;
4037 * In flat navigation - sections are active if we are looking at activities in the section.
4040 public function isactive() {
4043 if ($this->is_section()) {
4044 $active = $PAGE->navigation
->find_active_node();
4046 while ($active = $active->parent
) {
4047 if ($active->key
== $this->key
&& $active->type
== $this->type
) {
4053 return $this->isactive
;
4057 * Getter for "showdivider"
4060 public function showdivider() {
4061 return $this->showdivider
;
4065 * Setter for "showdivider"
4066 * @param $val boolean
4067 * @param $label string Label for the group of nodes
4069 public function set_showdivider($val, $label = '') {
4070 $this->showdivider
= $val;
4071 if ($this->showdivider
&& empty($label)) {
4072 debugging('Navigation region requires a label', DEBUG_DEVELOPER
);
4074 $this->set_collectionlabel($label);
4079 * Getter for "indent"
4082 public function get_indent() {
4083 return $this->indent
;
4087 * Setter for "indent"
4088 * @param $val boolean
4090 public function set_indent($val) {
4091 $this->indent
= $val;
4096 * Class used to generate a collection of navigation nodes most closely related
4097 * to the current page.
4100 * @copyright 2016 Damyon Wiese
4101 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4103 class flat_navigation
extends navigation_node_collection
{
4104 /** @var moodle_page the moodle page that the navigation belongs to */
4110 * @param moodle_page $page
4112 public function __construct(moodle_page
&$page) {
4113 if (during_initial_install()) {
4116 $this->page
= $page;
4120 * Build the list of navigation nodes based on the current navigation and settings trees.
4123 public function initialise() {
4124 global $PAGE, $USER, $OUTPUT, $CFG;
4125 if (during_initial_install()) {
4131 $course = $PAGE->course
;
4133 $this->page
->navigation
->initialise();
4135 // First walk the nav tree looking for "flat_navigation" nodes.
4136 if ($course->id
> 1) {
4137 // It's a real course.
4138 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
4140 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
4141 // This is the name that will be shown for the course.
4142 $coursename = empty($CFG->navshowfullcoursenames
) ?
4143 format_string($course->shortname
, true, array('context' => $coursecontext)) :
4144 format_string($course->fullname
, true, array('context' => $coursecontext));
4146 $flat = new flat_navigation_node(navigation_node
::create($coursename, $url), 0);
4147 $flat->set_collectionlabel($coursename);
4148 $flat->key
= 'coursehome';
4149 $flat->icon
= new pix_icon('i/course', '');
4151 $courseformat = course_get_format($course);
4152 $coursenode = $PAGE->navigation
->find_active_node();
4153 $targettype = navigation_node
::TYPE_COURSE
;
4155 // Single activity format has no course node - the course node is swapped for the activity node.
4156 if (!$courseformat->has_view_page()) {
4157 $targettype = navigation_node
::TYPE_ACTIVITY
;
4160 while (!empty($coursenode) && ($coursenode->type
!= $targettype)) {
4161 $coursenode = $coursenode->parent
;
4163 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4164 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4165 if ($coursenode && $coursenode->key
!= SITEID
) {
4167 foreach ($coursenode->children
as $child) {
4168 if ($child->action
) {
4169 $flat = new flat_navigation_node($child, 0);
4175 $this->page
->navigation
->build_flat_navigation_list($this, true, get_string('site'));
4177 $this->page
->navigation
->build_flat_navigation_list($this, false, get_string('site'));
4180 $admin = $PAGE->settingsnav
->find('siteadministration', navigation_node
::TYPE_SITE_ADMIN
);
4182 // Try again - crazy nav tree!
4183 $admin = $PAGE->settingsnav
->find('root', navigation_node
::TYPE_SITE_ADMIN
);
4186 $flat = new flat_navigation_node($admin, 0);
4187 $flat->set_showdivider(true, get_string('sitesettings'));
4188 $flat->key
= 'sitesettings';
4189 $flat->icon
= new pix_icon('t/preferences', '');
4195 * Override the parent so we can set a label for this collection if it has not been set yet.
4197 * @param navigation_node $node Node to add
4198 * @param string $beforekey If specified, adds before a node with this key,
4199 * otherwise adds at end
4200 * @return navigation_node Added node
4202 public function add(navigation_node
$node, $beforekey=null) {
4203 $result = parent
::add($node, $beforekey);
4204 // Extend the parent to get a name for the collection of nodes if required.
4205 if (empty($this->collectionlabel
)) {
4206 if ($node instanceof flat_navigation_node
) {
4207 $this->set_collectionlabel($node->get_collectionlabel());
4216 * Class used to manage the settings option for the current page
4218 * This class is used to manage the settings options in a tree format (recursively)
4219 * and was created initially for use with the settings blocks.
4222 * @category navigation
4223 * @copyright 2009 Sam Hemelryk
4224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4226 class settings_navigation
extends navigation_node
{
4227 /** @var stdClass the current context */
4229 /** @var moodle_page the moodle page that the navigation belongs to */
4231 /** @var string contains administration section navigation_nodes */
4232 protected $adminsection;
4233 /** @var bool A switch to see if the navigation node is initialised */
4234 protected $initialised = false;
4235 /** @var array An array of users that the nodes can extend for. */
4236 protected $userstoextendfor = array();
4237 /** @var navigation_cache **/
4241 * Sets up the object with basic settings and preparse it for use
4243 * @param moodle_page $page
4245 public function __construct(moodle_page
&$page) {
4246 if (during_initial_install()) {
4249 $this->page
= $page;
4250 // Initialise the main navigation. It is most important that this is done
4251 // before we try anything
4252 $this->page
->navigation
->initialise();
4253 // Initialise the navigation cache
4254 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
4255 $this->children
= new navigation_node_collection();
4259 * Initialise the settings navigation based on the current context
4261 * This function initialises the settings navigation tree for a given context
4262 * by calling supporting functions to generate major parts of the tree.
4265 public function initialise() {
4266 global $DB, $SESSION, $SITE;
4268 if (during_initial_install()) {
4270 } else if ($this->initialised
) {
4273 $this->id
= 'settingsnav';
4274 $this->context
= $this->page
->context
;
4276 $context = $this->context
;
4277 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4278 $this->load_block_settings();
4279 $context = $context->get_parent_context();
4280 $this->context
= $context;
4282 switch ($context->contextlevel
) {
4283 case CONTEXT_SYSTEM
:
4284 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4285 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4288 case CONTEXT_COURSECAT
:
4289 $this->load_category_settings();
4291 case CONTEXT_COURSE
:
4292 if ($this->page
->course
->id
!= $SITE->id
) {
4293 $this->load_course_settings(($context->id
== $this->context
->id
));
4295 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4298 case CONTEXT_MODULE
:
4299 $this->load_module_settings();
4300 $this->load_course_settings();
4303 if ($this->page
->course
->id
!= $SITE->id
) {
4304 $this->load_course_settings();
4309 $usersettings = $this->load_user_settings($this->page
->course
->id
);
4311 $adminsettings = false;
4312 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin
) ||
$SESSION->load_navigation_admin
)) {
4313 $isadminpage = $this->is_admin_tree_needed();
4315 if (has_capability('moodle/site:configview', context_system
::instance())) {
4316 if (has_capability('moodle/site:config', context_system
::instance())) {
4317 // Make sure this works even if config capability changes on the fly
4318 // and also make it fast for admin right after login.
4319 $SESSION->load_navigation_admin
= 1;
4321 $adminsettings = $this->load_administration_settings();
4324 } else if (!isset($SESSION->load_navigation_admin
)) {
4325 $adminsettings = $this->load_administration_settings();
4326 $SESSION->load_navigation_admin
= (int)($adminsettings->children
->count() > 0);
4328 } else if ($SESSION->load_navigation_admin
) {
4330 $adminsettings = $this->load_administration_settings();
4334 // Print empty navigation node, if needed.
4335 if ($SESSION->load_navigation_admin
&& !$isadminpage) {
4336 if ($adminsettings) {
4337 // Do not print settings tree on pages that do not need it, this helps with performance.
4338 $adminsettings->remove();
4339 $adminsettings = false;
4341 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4342 self
::TYPE_SITE_ADMIN
, null, 'siteadministration');
4343 $siteadminnode->id
= 'expandable_branch_' . $siteadminnode->type
. '_' .
4344 clean_param($siteadminnode->key
, PARAM_ALPHANUMEXT
);
4345 $siteadminnode->requiresajaxloading
= 'true';
4350 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $adminsettings) {
4351 $adminsettings->force_open();
4352 } else if ($context->contextlevel
== CONTEXT_USER
&& $usersettings) {
4353 $usersettings->force_open();
4356 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4357 $this->load_local_plugin_settings();
4359 foreach ($this->children
as $key=>$node) {
4360 if ($node->nodetype
== self
::NODETYPE_BRANCH
&& $node->children
->count() == 0) {
4361 // Site administration is shown as link.
4362 if (!empty($SESSION->load_navigation_admin
) && ($node->type
=== self
::TYPE_SITE_ADMIN
)) {
4368 $this->initialised
= true;
4371 * Override the parent function so that we can add preceeding hr's and set a
4372 * root node class against all first level element
4374 * It does this by first calling the parent's add method {@link navigation_node::add()}
4375 * and then proceeds to use the key to set class and hr
4377 * @param string $text text to be used for the link.
4378 * @param string|moodle_url $url url for the new node
4379 * @param int $type the type of node navigation_node::TYPE_*
4380 * @param string $shorttext
4381 * @param string|int $key a key to access the node by.
4382 * @param pix_icon $icon An icon that appears next to the node.
4383 * @return navigation_node with the new node added to it.
4385 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4386 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
4387 $node->add_class('root_node');
4392 * This function allows the user to add something to the start of the settings
4393 * navigation, which means it will be at the top of the settings navigation block
4395 * @param string $text text to be used for the link.
4396 * @param string|moodle_url $url url for the new node
4397 * @param int $type the type of node navigation_node::TYPE_*
4398 * @param string $shorttext
4399 * @param string|int $key a key to access the node by.
4400 * @param pix_icon $icon An icon that appears next to the node.
4401 * @return navigation_node $node with the new node added to it.
4403 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4404 $children = $this->children
;
4405 $childrenclass = get_class($children);
4406 $this->children
= new $childrenclass;
4407 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4408 foreach ($children as $child) {
4409 $this->children
->add($child);
4415 * Does this page require loading of full admin tree or is
4416 * it enough rely on AJAX?
4420 protected function is_admin_tree_needed() {
4421 if (self
::$loadadmintree) {
4422 // Usually external admin page or settings page.
4426 if ($this->page
->pagelayout
=== 'admin' or strpos($this->page
->pagetype
, 'admin-') === 0) {
4427 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4428 if ($this->page
->context
->contextlevel
!= CONTEXT_SYSTEM
) {
4438 * Load the site administration tree
4440 * This function loads the site administration tree by using the lib/adminlib library functions
4442 * @param navigation_node $referencebranch A reference to a branch in the settings
4444 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4445 * tree and start at the beginning
4446 * @return mixed A key to access the admin tree by
4448 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
4451 // Check if we are just starting to generate this navigation.
4452 if ($referencebranch === null) {
4454 // Require the admin lib then get an admin structure
4455 if (!function_exists('admin_get_root')) {
4456 require_once($CFG->dirroot
.'/lib/adminlib.php');
4458 $adminroot = admin_get_root(false, false);
4459 // This is the active section identifier
4460 $this->adminsection
= $this->page
->url
->param('section');
4462 // Disable the navigation from automatically finding the active node
4463 navigation_node
::$autofindactive = false;
4464 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self
::TYPE_SITE_ADMIN
, null, 'root');
4465 foreach ($adminroot->children
as $adminbranch) {
4466 $this->load_administration_settings($referencebranch, $adminbranch);
4468 navigation_node
::$autofindactive = true;
4470 // Use the admin structure to locate the active page
4471 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
4472 $currentnode = $this;
4473 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
4474 $currentnode = $currentnode->get($pathkey);
4477 $currentnode->make_active();
4480 $this->scan_for_active_node($referencebranch);
4482 return $referencebranch;
4483 } else if ($adminbranch->check_access()) {
4484 // We have a reference branch that we can access and is not hidden `hurrah`
4485 // Now we need to display it and any children it may have
4489 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page
) {
4490 if (empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
4493 $url = $adminbranch->get_settings_page_url();
4498 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
4500 if ($adminbranch->is_hidden()) {
4501 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
4502 $reference->add_class('hidden');
4504 $reference->display
= false;
4508 // Check if we are generating the admin notifications and whether notificiations exist
4509 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
4510 $reference->add_class('criticalnotification');
4512 // Check if this branch has children
4513 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
4514 foreach ($adminbranch->children
as $branch) {
4515 // Generate the child branches as well now using this branch as the reference
4516 $this->load_administration_settings($reference, $branch);
4519 $reference->icon
= new pix_icon('i/settings', '');
4525 * This function recursivily scans nodes until it finds the active node or there
4526 * are no more nodes.
4527 * @param navigation_node $node
4529 protected function scan_for_active_node(navigation_node
$node) {
4530 if (!$node->check_if_active() && $node->children
->count()>0) {
4531 foreach ($node->children
as &$child) {
4532 $this->scan_for_active_node($child);
4538 * Gets a navigation node given an array of keys that represent the path to
4541 * @param array $path
4542 * @return navigation_node|false
4544 protected function get_by_path(array $path) {
4545 $node = $this->get(array_shift($path));
4546 foreach ($path as $key) {
4553 * This function loads the course settings that are available for the user
4555 * @param bool $forceopen If set to true the course node will be forced open
4556 * @return navigation_node|false
4558 protected function load_course_settings($forceopen = false) {
4560 require_once($CFG->dirroot
. '/course/lib.php');
4562 $course = $this->page
->course
;
4563 $coursecontext = context_course
::instance($course->id
);
4564 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4566 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4568 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
4570 $coursenode->force_open();
4574 if ($adminoptions->update
) {
4575 // Add the course settings link
4576 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
4577 $coursenode->add(get_string('settings'), $url, self
::TYPE_SETTING
, null,
4578 'editsettings', new pix_icon('i/settings', ''));
4581 if ($adminoptions->editcompletion
) {
4582 // Add the course completion settings link
4583 $url = new moodle_url('/course/completion.php', array('id' => $course->id
));
4584 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self
::TYPE_SETTING
, null, 'coursecompletion',
4585 new pix_icon('i/settings', ''));
4588 if (!$adminoptions->update
&& $adminoptions->tags
) {
4589 $url = new moodle_url('/course/tags.php', array('id' => $course->id
));
4590 $coursenode->add(get_string('coursetags', 'tag'), $url, self
::TYPE_SETTING
, null, 'coursetags', new pix_icon('i/settings', ''));
4591 $coursenode->get('coursetags')->set_force_into_more_menu();
4595 enrol_add_course_navigation($coursenode, $course);
4598 if ($adminoptions->filters
) {
4599 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4600 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
,
4601 null, 'filtermanagement', new pix_icon('i/filter', ''));
4604 // View course reports.
4605 if ($adminoptions->reports
) {
4606 $reportnav = $coursenode->add(get_string('reports'),
4607 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid
]),
4608 self
::TYPE_CONTAINER
, null, 'coursereports', new pix_icon('i/stats', ''));
4609 $coursereports = core_component
::get_plugin_list('coursereport');
4610 foreach ($coursereports as $report => $dir) {
4611 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
4612 if (file_exists($libfile)) {
4613 require_once($libfile);
4614 $reportfunction = $report.'_report_extend_navigation';
4615 if (function_exists($report.'_report_extend_navigation')) {
4616 $reportfunction($reportnav, $course, $coursecontext);
4621 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4622 foreach ($reports as $reportfunction) {
4623 $reportfunction($reportnav, $course, $coursecontext);
4627 // Check if we can view the gradebook's setup page.
4628 if ($adminoptions->gradebook
) {
4629 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id
));
4630 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self
::TYPE_SETTING
,
4631 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4634 // Add the context locking node.
4635 $this->add_context_locking_node($coursenode, $coursecontext);
4637 // Add outcome if permitted
4638 if ($adminoptions->outcomes
) {
4639 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
4640 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
4643 //Add badges navigation
4644 if ($adminoptions->badges
) {
4645 require_once($CFG->libdir
.'/badgeslib.php');
4646 badges_add_course_navigation($coursenode, $course);
4649 // Import data from other courses.
4650 if ($adminoptions->import
) {
4651 $url = new moodle_url('/backup/import.php', array('id' => $course->id
));
4652 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/import', ''));
4655 // Backup this course
4656 if ($adminoptions->backup
) {
4657 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4658 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
4661 // Restore to this course
4662 if ($adminoptions->restore
) {
4663 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4664 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
4667 // Copy this course.
4668 if ($adminoptions->copy
) {
4669 $url = new moodle_url('/backup/copy.php', array('id' => $course->id
));
4670 $coursenode->add(get_string('copycourse'), $url, self
::TYPE_SETTING
, null, 'copy', new pix_icon('t/copy', ''));
4673 // Reset this course
4674 if ($adminoptions->reset
) {
4675 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
4676 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, 'reset', new pix_icon('i/return', ''));
4680 require_once($CFG->libdir
. '/questionlib.php');
4681 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4683 if ($adminoptions->update
) {
4684 // Repository Instances
4685 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
4686 require_once($CFG->dirroot
. '/repository/lib.php');
4687 $editabletypes = repository
::get_editable_types($coursecontext);
4688 $haseditabletypes = !empty($editabletypes);
4689 unset($editabletypes);
4690 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
4692 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
4694 if ($haseditabletypes) {
4695 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
4696 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
4701 if ($adminoptions->files
) {
4702 // hidden in new courses and courses where legacy files were turned off
4703 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
4704 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/folder', ''));
4708 // Let plugins hook into course navigation.
4709 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4710 foreach ($pluginsfunction as $plugintype => $plugins) {
4711 // Ignore the report plugin as it was already loaded above.
4712 if ($plugintype == 'report') {
4715 foreach ($plugins as $pluginfunction) {
4716 $pluginfunction($coursenode, $course, $coursecontext);
4720 // Prepare data for course content download functionality if it is enabled.
4721 // Will only be included here if the action menu is already in use, otherwise a button will be added to the UI elsewhere.
4722 if (\core\content
::can_export_context($coursecontext, $USER) && !empty($coursenode->get_children_key_list())) {
4723 $linkattr = \core_course\output\content_export_link
::get_attributes($coursecontext);
4724 $actionlink = new action_link($linkattr->url
, $linkattr->displaystring
, null, $linkattr->elementattributes
);
4726 $coursenode->add($linkattr->displaystring
, $actionlink, self
::TYPE_SETTING
, null, 'download',
4727 new pix_icon('t/download', ''));
4728 $coursenode->get('download')->set_force_into_more_menu();
4731 // Return we are done
4736 * Get the moodle_page object associated to the current settings navigation.
4738 * @return moodle_page
4740 public function get_page(): moodle_page
{
4745 * This function calls the module function to inject module settings into the
4746 * settings navigation tree.
4748 * This only gets called if there is a corrosponding function in the modules
4751 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4753 * @return navigation_node|false
4755 protected function load_module_settings() {
4758 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
4759 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
4760 $this->page
->set_cm($cm, $this->page
->course
);
4763 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
4764 if (file_exists($file)) {
4765 require_once($file);
4768 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
), null, self
::TYPE_SETTING
, null, 'modulesettings');
4769 $modulenode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
4770 $modulenode->force_open();
4772 // Settings for the module
4773 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
4774 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => 1));
4775 $modulenode->add(get_string('settings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
4777 // Assign local roles
4778 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
4779 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
4780 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
4783 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
4784 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
4785 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
4787 // Check role permissions
4788 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
4789 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
4790 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
4793 // Add the context locking node.
4794 $this->add_context_locking_node($modulenode, $this->page
->cm
->context
);
4797 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
4798 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
4799 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
4802 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4803 foreach ($reports as $reportfunction) {
4804 $reportfunction($modulenode, $this->page
->cm
);
4806 // Add a backup link
4807 $featuresfunc = $this->page
->activityname
.'_supports';
4808 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
4809 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
4810 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
4813 // Restore this activity
4814 $featuresfunc = $this->page
->activityname
.'_supports';
4815 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
4816 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
4817 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
4820 // Allow the active advanced grading method plugin to append its settings
4821 $featuresfunc = $this->page
->activityname
.'_supports';
4822 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
4823 require_once($CFG->dirroot
.'/grade/grading/lib.php');
4824 $gradingman = get_grading_manager($this->page
->cm
->context
, 'mod_'.$this->page
->activityname
);
4825 $gradingman->extend_settings_navigation($this, $modulenode);
4828 $function = $this->page
->activityname
.'_extend_settings_navigation';
4829 if (function_exists($function)) {
4830 $function($this, $modulenode);
4833 // Remove the module node if there are no children.
4834 if ($modulenode->children
->count() <= 0) {
4835 $modulenode->remove();
4842 * Loads the user settings block of the settings nav
4844 * This function is simply works out the userid and whether we need to load
4845 * just the current users profile settings, or the current user and the user the
4846 * current user is viewing.
4848 * This function has some very ugly code to work out the user, if anyone has
4849 * any bright ideas please feel free to intervene.
4851 * @param int $courseid The course id of the current course
4852 * @return navigation_node|false
4854 protected function load_user_settings($courseid = SITEID
) {
4857 if (isguestuser() ||
!isloggedin()) {
4861 $navusers = $this->page
->navigation
->get_extending_users();
4863 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
4865 foreach ($this->userstoextendfor
as $userid) {
4866 if ($userid == $USER->id
) {
4869 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4870 if (is_null($usernode)) {
4874 foreach ($navusers as $user) {
4875 if ($user->id
== $USER->id
) {
4878 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
4879 if (is_null($usernode)) {
4883 $this->generate_user_settings($courseid, $USER->id
);
4885 $usernode = $this->generate_user_settings($courseid, $USER->id
);
4891 * Extends the settings navigation for the given user.
4893 * Note: This method gets called automatically if you call
4894 * $PAGE->navigation->extend_for_user($userid)
4896 * @param int $userid
4898 public function extend_for_user($userid) {
4901 if (!in_array($userid, $this->userstoextendfor
)) {
4902 $this->userstoextendfor
[] = $userid;
4903 if ($this->initialised
) {
4904 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
4905 $children = array();
4906 foreach ($this->children
as $child) {
4907 $children[] = $child;
4909 array_unshift($children, array_pop($children));
4910 $this->children
= new navigation_node_collection();
4911 foreach ($children as $child) {
4912 $this->children
->add($child);
4919 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4920 * what can be shown/done
4922 * @param int $courseid The current course' id
4923 * @param int $userid The user id to load for
4924 * @param string $gstitle The string to pass to get_string for the branch title
4925 * @return navigation_node|false
4927 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4928 global $DB, $CFG, $USER, $SITE;
4930 if ($courseid != $SITE->id
) {
4931 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
4932 $course = $this->page
->course
;
4934 $select = context_helper
::get_preload_record_columns_sql('ctx');
4935 $sql = "SELECT c.*, $select
4937 JOIN {context} ctx ON c.id = ctx.instanceid
4938 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4939 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
4940 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
4941 context_helper
::preload_from_record($course);
4947 $coursecontext = context_course
::instance($course->id
); // Course context
4948 $systemcontext = context_system
::instance();
4949 $currentuser = ($USER->id
== $userid);
4953 $usercontext = context_user
::instance($user->id
); // User context
4955 $select = context_helper
::get_preload_record_columns_sql('ctx');
4956 $sql = "SELECT u.*, $select
4958 JOIN {context} ctx ON u.id = ctx.instanceid
4959 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4960 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
4961 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
4965 context_helper
::preload_from_record($user);
4967 // Check that the user can view the profile
4968 $usercontext = context_user
::instance($user->id
); // User context
4969 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4971 if ($course->id
== $SITE->id
) {
4972 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4973 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4977 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4978 $userisenrolled = is_enrolled($coursecontext, $user->id
, '', true);
4979 if ((!$canviewusercourse && !$canviewuser) ||
!$userisenrolled) {
4982 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4983 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
&& !$canviewuser) {
4984 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4985 if ($courseid == $this->page
->course
->id
) {
4986 $mygroups = get_fast_modinfo($this->page
->course
)->groups
;
4988 $mygroups = groups_get_user_groups($courseid);
4990 $usergroups = groups_get_user_groups($courseid, $userid);
4991 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
4998 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
5001 $prefurl = new moodle_url('/user/preferences.php');
5002 if ($gstitle != 'usercurrentsettings') {
5004 $prefurl->param('userid', $userid);
5007 // Add a user setting branch.
5008 if ($gstitle == 'usercurrentsettings') {
5009 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_CONTAINER
, null, 'dashboard');
5010 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
5012 $dashboard->display
= false;
5013 $homepage = get_home_page();
5014 if (($homepage == HOMEPAGE_MY ||
$homepage == HOMEPAGE_MYCOURSES
)) {
5015 $dashboard->mainnavonly
= true;
5018 $iscurrentuser = ($user->id
== $USER->id
);
5020 $baseargs = array('id' => $user->id
);
5021 if ($course->id
!= $SITE->id
&& !$iscurrentuser) {
5022 $baseargs['course'] = $course->id
;
5023 $issitecourse = false;
5025 // Load all categories and get the context for the system.
5026 $issitecourse = true;
5029 // Add the user profile to the dashboard.
5030 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
5031 array('id' => $user->id
)), self
::TYPE_SETTING
, null, 'myprofile');
5033 if (!empty($CFG->navadduserpostslinks
)) {
5034 // Add nodes for forum posts and discussions if the user can view either or both
5035 // There are no capability checks here as the content of the page is based
5036 // purely on the forums the current user has access too.
5037 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
5038 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
5039 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
5040 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
5044 if (!empty($CFG->enableblogs
)) {
5045 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
5046 require_once($CFG->dirroot
.'/blog/lib.php');
5047 // Get all options for the user.
5048 $options = blog_get_options_for_user($user);
5049 $this->cache
->set('userblogoptions'.$user->id
, $options);
5051 $options = $this->cache
->{'userblogoptions'.$user->id
};
5054 if (count($options) > 0) {
5055 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
5056 foreach ($options as $type => $option) {
5057 if ($type == "rss") {
5058 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, null,
5059 new pix_icon('i/rss', ''));
5061 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, 'blog' . $type);
5067 // Add the messages link.
5068 // It is context based so can appear in the user's profile and in course participants information.
5069 if (!empty($CFG->messaging
)) {
5070 $messageargs = array('user1' => $USER->id
);
5071 if ($USER->id
!= $user->id
) {
5072 $messageargs['user2'] = $user->id
;
5074 $url = new moodle_url('/message/index.php', $messageargs);
5075 $dashboard->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
5078 // Add the "My private files" link.
5079 // This link doesn't have a unique display for course context so only display it under the user's profile.
5080 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
5081 $url = new moodle_url('/user/files.php');
5082 $dashboard->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
5085 // Add a node to view the users notes if permitted.
5086 if (!empty($CFG->enablenotes
) &&
5087 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
5088 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
5089 if ($coursecontext->instanceid
!= SITEID
) {
5090 $url->param('course', $coursecontext->instanceid
);
5092 $profilenode->add(get_string('notes', 'notes'), $url);
5095 // Show the grades node.
5096 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
5097 require_once($CFG->dirroot
. '/user/lib.php');
5098 // Set the grades node to link to the "Grades" page.
5099 if ($course->id
== SITEID
) {
5100 $url = user_mygrades_url($user->id
, $course->id
);
5101 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5102 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
5104 $dashboard->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'mygrades');
5107 // Let plugins hook into user navigation.
5108 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5109 foreach ($pluginsfunction as $plugintype => $plugins) {
5110 if ($plugintype != 'report') {
5111 foreach ($plugins as $pluginfunction) {
5112 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5117 $usersetting = navigation_node
::create(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
5118 $dashboard->add_node($usersetting);
5120 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
5121 $usersetting->display
= false;
5123 $usersetting->id
= 'usersettings';
5125 // Check if the user has been deleted.
5126 if ($user->deleted
) {
5127 if (!has_capability('moodle/user:update', $coursecontext)) {
5128 // We can't edit the user so just show the user deleted message.
5129 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
5131 // We can edit the user so show the user deleted message and link it to the profile.
5132 if ($course->id
== $SITE->id
) {
5133 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
5135 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
5137 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
5142 $userauthplugin = false;
5143 if (!empty($user->auth
)) {
5144 $userauthplugin = get_auth_plugin($user->auth
);
5147 $useraccount = $usersetting->add(get_string('useraccount'), null, self
::TYPE_CONTAINER
, null, 'useraccount');
5149 // Add the profile edit link.
5150 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5151 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) &&
5152 has_capability('moodle/user:update', $systemcontext)) {
5153 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
5154 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
5155 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5156 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5157 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5158 $url = $userauthplugin->edit_profile_url();
5160 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
5162 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
5167 // Change password link.
5168 if ($userauthplugin && $currentuser && !\core\session\manager
::is_loggedinas() && !isguestuser() &&
5169 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5170 $passwordchangeurl = $userauthplugin->change_password_url();
5171 if (empty($passwordchangeurl)) {
5172 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
5174 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
, null, 'changepassword');
5177 // Default homepage.
5178 $defaulthomepageuser = (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_USER
));
5179 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5180 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5181 has_capability('moodle/user:editprofile', $usercontext)) {
5182 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id
]);
5183 $useraccount->add(get_string('defaulthomepageuser'), $url, self
::TYPE_SETTING
, null, 'defaulthomepageuser');
5187 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5188 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5189 has_capability('moodle/user:editprofile', $usercontext)) {
5190 $url = new moodle_url('/user/language.php', array('id' => $user->id
, 'course' => $course->id
));
5191 $useraccount->add(get_string('preferredlanguage'), $url, self
::TYPE_SETTING
, null, 'preferredlanguage');
5194 $pluginmanager = core_plugin_manager
::instance();
5195 $enabled = $pluginmanager->get_enabled_plugins('mod');
5196 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5197 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5198 has_capability('moodle/user:editprofile', $usercontext)) {
5199 $url = new moodle_url('/user/forum.php', array('id' => $user->id
, 'course' => $course->id
));
5200 $useraccount->add(get_string('forumpreferences'), $url, self
::TYPE_SETTING
);
5203 $editors = editors_get_enabled();
5204 if (count($editors) > 1) {
5205 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5206 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5207 has_capability('moodle/user:editprofile', $usercontext)) {
5208 $url = new moodle_url('/user/editor.php', array('id' => $user->id
, 'course' => $course->id
));
5209 $useraccount->add(get_string('editorpreferences'), $url, self
::TYPE_SETTING
);
5214 // Add "Calendar preferences" link.
5215 if (isloggedin() && !isguestuser($user)) {
5216 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5217 has_capability('moodle/user:editprofile', $usercontext)) {
5218 $url = new moodle_url('/user/calendar.php', array('id' => $user->id
));
5219 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self
::TYPE_SETTING
, null, 'preferredcalendar');
5223 // Add "Content bank preferences" link.
5224 if (isloggedin() && !isguestuser($user)) {
5225 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5226 has_capability('moodle/user:editprofile', $usercontext)) {
5227 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id
]);
5228 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self
::TYPE_SETTING
,
5229 null, 'contentbankpreferences');
5233 // View the roles settings.
5234 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5235 'moodle/role:manage'], $usercontext)) {
5236 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
5238 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id
, 'courseid' => $course->id
]);
5239 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
5241 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
5243 if (!empty($assignableroles)) {
5244 $url = new moodle_url('/admin/roles/assign.php',
5245 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5246 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
5249 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
5250 $url = new moodle_url('/admin/roles/permissions.php',
5251 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5252 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
5255 $url = new moodle_url('/admin/roles/check.php',
5256 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5257 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
5261 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
5262 require_once($CFG->dirroot
. '/repository/lib.php');
5263 $editabletypes = repository
::get_editable_types($usercontext);
5264 $haseditabletypes = !empty($editabletypes);
5265 unset($editabletypes);
5266 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
5268 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
5270 if ($haseditabletypes) {
5271 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self
::TYPE_SETTING
);
5272 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5273 array('contextid' => $usercontext->id
)));
5277 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
5278 require_once($CFG->libdir
. '/portfoliolib.php');
5279 if (portfolio_has_visible_instances()) {
5280 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
5282 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
5283 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
5285 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
5286 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
5290 $enablemanagetokens = false;
5291 if (!empty($CFG->enablerssfeeds
)) {
5292 $enablemanagetokens = true;
5293 } else if (!is_siteadmin($USER->id
)
5294 && !empty($CFG->enablewebservices
)
5295 && has_capability('moodle/webservice:createtoken', context_system
::instance()) ) {
5296 $enablemanagetokens = true;
5299 if ($currentuser && $enablemanagetokens) {
5300 $url = new moodle_url('/user/managetoken.php');
5301 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
5305 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) &&
5306 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
5307 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id
));
5308 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id
));
5309 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self
::TYPE_SETTING
);
5310 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self
::TYPE_SETTING
);
5314 if ($currentuser && !empty($CFG->enableblogs
)) {
5315 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
5316 if (has_capability('moodle/blog:view', $systemcontext)) {
5317 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5318 navigation_node
::TYPE_SETTING
);
5320 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 &&
5321 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5322 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5323 navigation_node
::TYPE_SETTING
);
5324 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5325 navigation_node
::TYPE_SETTING
);
5327 // Remove the blog node if empty.
5328 $blog->trim_if_empty();
5332 if ($currentuser && !empty($CFG->enablebadges
)) {
5333 $badges = $usersetting->add(get_string('badges'), null, navigation_node
::TYPE_CONTAINER
, null, 'badges');
5334 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5335 $url = new moodle_url('/badges/mybadges.php');
5336 $badges->add(get_string('managebadges', 'badges'), $url, self
::TYPE_SETTING
);
5338 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5339 navigation_node
::TYPE_SETTING
);
5340 if (!empty($CFG->badges_allowexternalbackpack
)) {
5341 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5342 navigation_node
::TYPE_SETTING
);
5346 // Let plugins hook into user settings navigation.
5347 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5348 foreach ($pluginsfunction as $plugintype => $plugins) {
5349 foreach ($plugins as $pluginfunction) {
5350 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5354 return $usersetting;
5358 * Loads block specific settings in the navigation
5360 * @return navigation_node
5362 protected function load_block_settings() {
5365 $blocknode = $this->add($this->context
->get_context_name(), null, self
::TYPE_SETTING
, null, 'blocksettings');
5366 $blocknode->force_open();
5368 // Assign local roles
5369 if (get_assignable_roles($this->context
, ROLENAME_ORIGINAL
)) {
5370 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $this->context
->id
));
5371 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null,
5372 'roles', new pix_icon('i/assignroles', ''));
5376 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
5377 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
5378 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null,
5379 'permissions', new pix_icon('i/permissions', ''));
5381 // Check role permissions
5382 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
5383 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
5384 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null,
5385 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5388 // Add the context locking node.
5389 $this->add_context_locking_node($blocknode, $this->context
);
5395 * Loads category specific settings in the navigation
5397 * @return navigation_node
5399 protected function load_category_settings() {
5402 // We can land here while being in the context of a block, in which case we
5403 // should get the parent context which should be the category one. See self::initialise().
5404 if ($this->context
->contextlevel
== CONTEXT_BLOCK
) {
5405 $catcontext = $this->context
->get_parent_context();
5407 $catcontext = $this->context
;
5410 // Let's make sure that we always have the right context when getting here.
5411 if ($catcontext->contextlevel
!= CONTEXT_COURSECAT
) {
5412 throw new coding_exception('Unexpected context while loading category settings.');
5415 $categorynodetype = navigation_node
::TYPE_CONTAINER
;
5416 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5417 $categorynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
5418 $categorynode->force_open();
5420 if (can_edit_in_category($catcontext->instanceid
)) {
5421 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid
));
5422 $editstring = get_string('managecategorythis');
5423 $node = $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, 'managecategory', new pix_icon('i/edit', ''));
5424 $node->set_show_in_secondary_navigation(false);
5427 if (has_capability('moodle/category:manage', $catcontext)) {
5428 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid
));
5429 $categorynode->add(get_string('settings'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
5431 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid
));
5432 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null,
5433 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false);
5436 // Assign local roles
5437 $assignableroles = get_assignable_roles($catcontext);
5438 if (!empty($assignableroles)) {
5439 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $catcontext->id
));
5440 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
5444 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5445 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid' => $catcontext->id
));
5446 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
5448 // Check role permissions
5449 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5450 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5451 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid' => $catcontext->id
));
5452 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck', new pix_icon('i/checkpermissions', ''));
5455 // Add the context locking node.
5456 $this->add_context_locking_node($categorynode, $catcontext);
5459 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5460 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5461 array('contextid' => $catcontext->id
)), self
::TYPE_SETTING
, null, 'cohort', new pix_icon('i/cohort', ''));
5465 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5466 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id
));
5467 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
5471 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5472 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id
));
5473 $categorynode->add(get_string('restorecourse', 'admin'), $url, self
::TYPE_SETTING
, null, 'restorecourse', new pix_icon('i/restore', ''));
5476 // Let plugins hook into category settings navigation.
5477 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5478 foreach ($pluginsfunction as $plugintype => $plugins) {
5479 foreach ($plugins as $pluginfunction) {
5480 $pluginfunction($categorynode, $catcontext);
5484 $cb = new contentbank();
5485 if ($cb->is_context_allowed($catcontext)
5486 && has_capability('moodle/contentbank:access', $catcontext)) {
5487 $url = new \
moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id
]);
5488 $categorynode->add(get_string('contentbank'), $url, self
::TYPE_CUSTOM
, null,
5489 'contentbank', new \
pix_icon('i/contentbank', ''));
5492 return $categorynode;
5496 * Determine whether the user is assuming another role
5498 * This function checks to see if the user is assuming another role by means of
5499 * role switching. In doing this we compare each RSW key (context path) against
5500 * the current context path. This ensures that we can provide the switching
5501 * options against both the course and any page shown under the course.
5503 * @return bool|int The role(int) if the user is in another role, false otherwise
5505 protected function in_alternative_role() {
5507 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
5508 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
5509 return $USER->access
['rsw'][$this->page
->context
->path
];
5511 foreach ($USER->access
['rsw'] as $key=>$role) {
5512 if (strpos($this->context
->path
,$key)===0) {
5521 * This function loads all of the front page settings into the settings navigation.
5522 * This function is called when the user is on the front page, or $COURSE==$SITE
5523 * @param bool $forceopen (optional)
5524 * @return navigation_node
5526 protected function load_front_page_settings($forceopen = false) {
5528 require_once($CFG->dirroot
. '/course/lib.php');
5530 $course = clone($SITE);
5531 $coursecontext = context_course
::instance($course->id
); // Course context
5532 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5534 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
5536 $frontpage->force_open();
5538 $frontpage->id
= 'frontpagesettings';
5540 if ($this->page
->user_allowed_editing() && !$this->page
->theme
->haseditswitch
) {
5542 // Add the turn on/off settings
5543 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
5544 if ($this->page
->user_is_editing()) {
5545 $url->param('edit', 'off');
5546 $editstring = get_string('turneditingoff');
5548 $url->param('edit', 'on');
5549 $editstring = get_string('turneditingon');
5551 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5554 if ($adminoptions->update
) {
5555 // Add the course settings link
5556 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5557 $frontpage->add(get_string('settings'), $url, self
::TYPE_SETTING
, null,
5558 'editsettings', new pix_icon('i/settings', ''));
5562 enrol_add_course_navigation($frontpage, $course);
5565 if ($adminoptions->filters
) {
5566 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
5567 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
,
5568 null, 'filtermanagement', new pix_icon('i/filter', ''));
5571 // View course reports.
5572 if ($adminoptions->reports
) {
5573 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php',
5574 ['courseid' => $coursecontext->instanceid
]),
5575 self
::TYPE_CONTAINER
, null, 'coursereports',
5576 new pix_icon('i/stats', ''));
5577 $coursereports = core_component
::get_plugin_list('coursereport');
5578 foreach ($coursereports as $report=>$dir) {
5579 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
5580 if (file_exists($libfile)) {
5581 require_once($libfile);
5582 $reportfunction = $report.'_report_extend_navigation';
5583 if (function_exists($report.'_report_extend_navigation')) {
5584 $reportfunction($frontpagenav, $course, $coursecontext);
5589 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5590 foreach ($reports as $reportfunction) {
5591 $reportfunction($frontpagenav, $course, $coursecontext);
5595 // Backup this course
5596 if ($adminoptions->backup
) {
5597 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
5598 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
5601 // Restore to this course
5602 if ($adminoptions->restore
) {
5603 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
5604 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
5608 require_once($CFG->libdir
. '/questionlib.php');
5609 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5612 if ($adminoptions->files
) {
5613 //hiden in new installs
5614 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
5615 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/folder', ''));
5618 // Let plugins hook into frontpage navigation.
5619 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5620 foreach ($pluginsfunction as $plugintype => $plugins) {
5621 foreach ($plugins as $pluginfunction) {
5622 $pluginfunction($frontpage, $course, $coursecontext);
5630 * This function gives local plugins an opportunity to modify the settings navigation.
5632 protected function load_local_plugin_settings() {
5634 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5635 $function($this, $this->context
);
5640 * This function marks the cache as volatile so it is cleared during shutdown
5642 public function clear_cache() {
5643 $this->cache
->volatile();
5647 * Checks to see if there are child nodes available in the specific user's preference node.
5648 * If so, then they have the appropriate permissions view this user's preferences.
5650 * @since Moodle 2.9.3
5651 * @param int $userid The user's ID.
5652 * @return bool True if child nodes exist to view, otherwise false.
5654 public function can_view_user_preferences($userid) {
5655 if (is_siteadmin()) {
5658 // See if any nodes are present in the preferences section for this user.
5659 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5660 if ($preferencenode && $preferencenode->has_children()) {
5661 // Run through each child node.
5662 foreach ($preferencenode->children
as $childnode) {
5663 // If the child node has children then this user has access to a link in the preferences page.
5664 if ($childnode->has_children()) {
5669 // No links found for the user to access on the preferences page.
5675 * Class used to populate site admin navigation for ajax.
5678 * @category navigation
5679 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5682 class settings_navigation_ajax
extends settings_navigation
{
5684 * Constructs the navigation for use in an AJAX request
5686 * @param moodle_page $page
5688 public function __construct(moodle_page
&$page) {
5689 $this->page
= $page;
5690 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
5691 $this->children
= new navigation_node_collection();
5692 $this->initialise();
5696 * Initialise the site admin navigation.
5698 * @return array An array of the expandable nodes
5700 public function initialise() {
5701 if ($this->initialised ||
during_initial_install()) {
5704 $this->context
= $this->page
->context
;
5705 $this->load_administration_settings();
5707 // Check if local plugins is adding node to site admin.
5708 $this->load_local_plugin_settings();
5710 $this->initialised
= true;
5715 * Simple class used to output a navigation branch in XML
5718 * @category navigation
5719 * @copyright 2009 Sam Hemelryk
5720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5722 class navigation_json
{
5723 /** @var array An array of different node types */
5724 protected $nodetype = array('node','branch');
5725 /** @var array An array of node keys and types */
5726 protected $expandable = array();
5728 * Turns a branch and all of its children into XML
5730 * @param navigation_node $branch
5731 * @return string XML string
5733 public function convert($branch) {
5734 $xml = $this->convert_child($branch);
5738 * Set the expandable items in the array so that we have enough information
5739 * to attach AJAX events
5740 * @param array $expandable
5742 public function set_expandable($expandable) {
5743 foreach ($expandable as $node) {
5744 $this->expandable
[$node['key'].':'.$node['type']] = $node;
5748 * Recusively converts a child node and its children to XML for output
5750 * @param navigation_node $child The child to convert
5751 * @param int $depth Pointlessly used to track the depth of the XML structure
5752 * @return string JSON
5754 protected function convert_child($child, $depth=1) {
5755 if (!$child->display
) {
5758 $attributes = array();
5759 $attributes['id'] = $child->id
;
5760 $attributes['name'] = (string)$child->text
; // This can be lang_string object so typecast it.
5761 $attributes['type'] = $child->type
;
5762 $attributes['key'] = $child->key
;
5763 $attributes['class'] = $child->get_css_type();
5764 $attributes['requiresajaxloading'] = $child->requiresajaxloading
;
5766 if ($child->icon
instanceof pix_icon
) {
5767 $attributes['icon'] = array(
5768 'component' => $child->icon
->component
,
5769 'pix' => $child->icon
->pix
,
5771 foreach ($child->icon
->attributes
as $key=>$value) {
5772 if ($key == 'class') {
5773 $attributes['icon']['classes'] = explode(' ', $value);
5774 } else if (!array_key_exists($key, $attributes['icon'])) {
5775 $attributes['icon'][$key] = $value;
5779 } else if (!empty($child->icon
)) {
5780 $attributes['icon'] = (string)$child->icon
;
5783 if ($child->forcetitle ||
$child->title
!== $child->text
) {
5784 $attributes['title'] = htmlentities($child->title
, ENT_QUOTES
, 'UTF-8');
5786 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
5787 $attributes['expandable'] = $child->key
;
5788 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
5791 if (count($child->classes
)>0) {
5792 $attributes['class'] .= ' '.join(' ',$child->classes
);
5794 if (is_string($child->action
)) {
5795 $attributes['link'] = $child->action
;
5796 } else if ($child->action
instanceof moodle_url
) {
5797 $attributes['link'] = $child->action
->out();
5798 } else if ($child->action
instanceof action_link
) {
5799 $attributes['link'] = $child->action
->url
->out();
5801 $attributes['hidden'] = ($child->hidden
);
5802 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
5803 $attributes['haschildren'] = $attributes['haschildren'] ||
$child->type
== navigation_node
::TYPE_MY_CATEGORY
;
5805 if ($child->children
->count() > 0) {
5806 $attributes['children'] = array();
5807 foreach ($child->children
as $subchild) {
5808 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
5815 return json_encode($attributes);
5821 * The cache class used by global navigation and settings navigation.
5823 * It is basically an easy access point to session with a bit of smarts to make
5824 * sure that the information that is cached is valid still.
5828 * if (!$cache->viewdiscussion()) {
5829 * // Code to do stuff and produce cachable content
5830 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5832 * $content = $cache->viewdiscussion;
5836 * @category navigation
5837 * @copyright 2009 Sam Hemelryk
5838 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5840 class navigation_cache
{
5841 /** @var int represents the time created */
5842 protected $creation;
5843 /** @var array An array of session keys */
5846 * The string to use to segregate this particular cache. It can either be
5847 * unique to start a fresh cache or if you want to share a cache then make
5848 * it the string used in the original cache.
5852 /** @var int a time that the information will time out */
5854 /** @var stdClass The current context */
5855 protected $currentcontext;
5856 /** @var int cache time information */
5857 const CACHETIME
= 0;
5858 /** @var int cache user id */
5859 const CACHEUSERID
= 1;
5860 /** @var int cache value */
5861 const CACHEVALUE
= 2;
5862 /** @var null|array An array of navigation cache areas to expire on shutdown */
5863 public static $volatilecaches;
5866 * Contructor for the cache. Requires two arguments
5868 * @param string $area The string to use to segregate this particular cache
5869 * it can either be unique to start a fresh cache or if you want
5870 * to share a cache then make it the string used in the original
5872 * @param int $timeout The number of seconds to time the information out after
5874 public function __construct($area, $timeout=1800) {
5875 $this->creation
= time();
5876 $this->area
= $area;
5877 $this->timeout
= time() - $timeout;
5878 if (rand(0,100) === 0) {
5879 $this->garbage_collection();
5884 * Used to set up the cache within the SESSION.
5886 * This is called for each access and ensure that we don't put anything into the session before
5889 protected function ensure_session_cache_initialised() {
5891 if (empty($this->session
)) {
5892 if (!isset($SESSION->navcache
)) {
5893 $SESSION->navcache
= new stdClass
;
5895 if (!isset($SESSION->navcache
->{$this->area
})) {
5896 $SESSION->navcache
->{$this->area
} = array();
5898 $this->session
= &$SESSION->navcache
->{$this->area
}; // pointer to array, =& is correct here
5903 * Magic Method to retrieve something by simply calling using = cache->key
5905 * @param mixed $key The identifier for the information you want out again
5906 * @return void|mixed Either void or what ever was put in
5908 public function __get($key) {
5909 if (!$this->cached($key)) {
5912 $information = $this->session
[$key][self
::CACHEVALUE
];
5913 return unserialize($information);
5917 * Magic method that simply uses {@link set();} to store something in the cache
5919 * @param string|int $key
5920 * @param mixed $information
5922 public function __set($key, $information) {
5923 $this->set($key, $information);
5927 * Sets some information against the cache (session) for later retrieval
5929 * @param string|int $key
5930 * @param mixed $information
5932 public function set($key, $information) {
5934 $this->ensure_session_cache_initialised();
5935 $information = serialize($information);
5936 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
5939 * Check the existence of the identifier in the cache
5941 * @param string|int $key
5944 public function cached($key) {
5946 $this->ensure_session_cache_initialised();
5947 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
) {
5953 * Compare something to it's equivilant in the cache
5955 * @param string $key
5956 * @param mixed $value
5957 * @param bool $serialise Whether to serialise the value before comparison
5958 * this should only be set to false if the value is already
5960 * @return bool If the value is the same false if it is not set or doesn't match
5962 public function compare($key, $value, $serialise = true) {
5963 if ($this->cached($key)) {
5965 $value = serialize($value);
5967 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
5974 * Wipes the entire cache, good to force regeneration
5976 public function clear() {
5978 unset($SESSION->navcache
);
5979 $this->session
= null;
5982 * Checks all cache entries and removes any that have expired, good ole cleanup
5984 protected function garbage_collection() {
5985 if (empty($this->session
)) {
5988 foreach ($this->session
as $key=>$cachedinfo) {
5989 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
5990 unset($this->session
[$key]);
5996 * Marks the cache as being volatile (likely to change)
5998 * Any caches marked as volatile will be destroyed at the on shutdown by
5999 * {@link navigation_node::destroy_volatile_caches()} which is registered
6000 * as a shutdown function if any caches are marked as volatile.
6002 * @param bool $setting True to destroy the cache false not too
6004 public function volatile($setting = true) {
6005 if (self
::$volatilecaches===null) {
6006 self
::$volatilecaches = array();
6007 core_shutdown_manager
::register_function(array('navigation_cache','destroy_volatile_caches'));
6011 self
::$volatilecaches[$this->area
] = $this->area
;
6012 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
6013 unset(self
::$volatilecaches[$this->area
]);
6018 * Destroys all caches marked as volatile
6020 * This function is static and works in conjunction with the static volatilecaches
6021 * property of navigation cache.
6022 * Because this function is static it manually resets the cached areas back to an
6025 public static function destroy_volatile_caches() {
6027 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
6028 foreach (self
::$volatilecaches as $area) {
6029 $SESSION->navcache
->{$area} = array();
6032 $SESSION->navcache
= new stdClass
;