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 $navcontext = \context_helper
::get_navigation_filter_context(null);
683 $options = !empty($navcontext) ?
['context' => $navcontext] : null;
685 if ($shorttext && $this->shorttext
!==null) {
686 return format_string($this->shorttext
, null, $options);
688 return format_string($this->text
, null, $options);
693 * Gets the title to use for this node.
697 public function get_title() {
698 if ($this->forcetitle ||
$this->action
!= null){
706 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
710 public function has_action() {
711 return !empty($this->action
);
715 * Used to easily determine if the action is an internal link.
719 public function has_internal_action(): bool {
721 if ($this->has_action()) {
722 $url = $this->action();
723 if ($this->action() instanceof \action_link
) {
724 $url = $this->action()->url
;
727 if (($url->out() === $CFG->wwwroot
) ||
(strpos($url->out(), $CFG->wwwroot
.'/') === 0)) {
735 * Used to easily determine if this link in the breadcrumbs is hidden.
739 public function is_hidden() {
740 return $this->hidden
;
744 * Gets the CSS class to add to this node to describe its type
748 public function get_css_type() {
749 if (array_key_exists($this->type
, $this->namedtypes
)) {
750 return 'type_'.$this->namedtypes
[$this->type
];
752 return 'type_unknown';
756 * Finds all nodes that are expandable by AJAX
758 * @param array $expandable An array by reference to populate with expandable nodes.
760 public function find_expandable(array &$expandable) {
761 foreach ($this->children
as &$child) {
762 if ($child->display
&& $child->has_children() && $child->children
->count() == 0) {
763 $child->id
= 'expandable_branch_'.$child->type
.'_'.clean_param($child->key
, PARAM_ALPHANUMEXT
);
764 $this->add_class('canexpand');
765 $child->requiresajaxloading
= true;
766 $expandable[] = array('id' => $child->id
, 'key' => $child->key
, 'type' => $child->type
);
768 $child->find_expandable($expandable);
773 * Finds all nodes of a given type (recursive)
775 * @param int $type One of navigation_node::TYPE_*
778 public function find_all_of_type($type) {
779 $nodes = $this->children
->type($type);
780 foreach ($this->children
as &$node) {
781 $childnodes = $node->find_all_of_type($type);
782 $nodes = array_merge($nodes, $childnodes);
788 * Removes this node if it is empty
790 public function trim_if_empty() {
791 if ($this->children
->count() == 0) {
797 * Creates a tab representation of this nodes children that can be used
798 * with print_tabs to produce the tabs on a page.
800 * call_user_func_array('print_tabs', $node->get_tabs_array());
802 * @param array $inactive
803 * @param bool $return
804 * @return array Array (tabs, selected, inactive, activated, return)
806 public function get_tabs_array(array $inactive=array(), $return=false) {
810 $activated = array();
811 foreach ($this->children
as $node) {
812 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
813 if ($node->contains_active_node()) {
814 if ($node->children
->count() > 0) {
815 $activated[] = $node->key
;
816 foreach ($node->children
as $child) {
817 if ($child->contains_active_node()) {
818 $selected = $child->key
;
820 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
823 $selected = $node->key
;
827 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
831 * Sets the parent for this node and if this node is active ensures that the tree is properly
834 * @param navigation_node $parent
836 public function set_parent(navigation_node
$parent) {
837 // Set the parent (thats the easy part)
838 $this->parent
= $parent;
839 // Check if this node is active (this is checked during construction)
840 if ($this->isactive
) {
841 // Force all of the parent nodes open so you can see this node
842 $this->parent
->force_open();
843 // Make all parents inactive so that its clear where we are.
844 $this->parent
->make_inactive();
849 * Hides the node and any children it has.
852 * @param array $typestohide Optional. An array of node types that should be hidden.
853 * If null all nodes will be hidden.
854 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
855 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
857 public function hide(array $typestohide = null) {
858 if ($typestohide === null ||
in_array($this->type
, $typestohide)) {
859 $this->display
= false;
860 if ($this->has_children()) {
861 foreach ($this->children
as $child) {
862 $child->hide($typestohide);
869 * Get the action url for this navigation node.
870 * Called from templates.
874 public function action() {
875 if ($this->action
instanceof moodle_url
) {
876 return $this->action
;
877 } else if ($this->action
instanceof action_link
) {
878 return $this->action
->url
;
880 return $this->action
;
884 * Return an array consisting of the additional attributes for the action url.
886 * @return array Formatted array to parse in a template
888 public function actionattributes() {
889 if ($this->action
instanceof action_link
) {
890 return array_map(function($key, $value) {
895 }, array_keys($this->action
->attributes
), $this->action
->attributes
);
902 * Check whether the node's action is of type action_link.
906 public function is_action_link() {
907 return $this->action
instanceof action_link
;
911 * Return an array consisting of the actions for the action link.
913 * @return array Formatted array to parse in a template
915 public function action_link_actions() {
918 if (!$this->is_action_link()) {
922 $actionid = $this->action
->attributes
['id'];
923 $actionsdata = array_map(function($action) use ($PAGE, $actionid) {
924 $data = $action->export_for_template($PAGE->get_renderer('core'));
925 $data->id
= $actionid;
927 }, !empty($this->action
->actions
) ?
$this->action
->actions
: []);
929 return ['actions' => $actionsdata];
933 * Sets whether the node and its children should be added into a "more" menu whenever possible.
935 * @param bool $forceintomoremenu
937 public function set_force_into_more_menu(bool $forceintomoremenu = false) {
938 $this->forceintomoremenu
= $forceintomoremenu;
939 foreach ($this->children
as $child) {
940 $child->set_force_into_more_menu($forceintomoremenu);
945 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable.
949 public function set_show_in_secondary_navigation(bool $show = true) {
950 $this->showinsecondarynavigation
= $show;
951 foreach ($this->children
as $child) {
952 $child->set_show_in_secondary_navigation($show);
957 * Add the menu item to handle locking and unlocking of a conext.
959 * @param \navigation_node $node Node to add
960 * @param \context $context The context to be locked
962 protected function add_context_locking_node(\navigation_node
$node, \context
$context) {
964 // Manage context locking.
965 if (!empty($CFG->contextlocking
) && has_capability('moodle/site:managecontextlocks', $context)) {
966 $parentcontext = $context->get_parent_context();
967 if (empty($parentcontext) ||
!$parentcontext->locked
) {
968 if ($context->locked
) {
969 $lockicon = 'i/unlock';
970 $lockstring = get_string('managecontextunlock', 'admin');
972 $lockicon = 'i/lock';
973 $lockstring = get_string('managecontextlock', 'admin');
980 'id' => $context->id
,
986 new pix_icon($lockicon, '')
995 * Navigation node collection
997 * This class is responsible for managing a collection of navigation nodes.
998 * It is required because a node's unique identifier is a combination of both its
1001 * Originally an array was used with a string key that was a combination of the two
1002 * however it was decided that a better solution would be to use a class that
1003 * implements the standard IteratorAggregate interface.
1006 * @category navigation
1007 * @copyright 2010 Sam Hemelryk
1008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1010 class navigation_node_collection
implements IteratorAggregate
, Countable
{
1012 * A multidimensional array to where the first key is the type and the second
1013 * key is the nodes key.
1016 protected $collection = array();
1018 * An array that contains references to nodes in the same order they were added.
1019 * This is maintained as a progressive array.
1022 protected $orderedcollection = array();
1024 * A reference to the last node that was added to the collection
1025 * @var navigation_node
1027 protected $last = null;
1029 * The total number of items added to this array.
1032 protected $count = 0;
1035 * Label for collection of nodes.
1038 protected $collectionlabel = '';
1041 * Adds a navigation node to the collection
1043 * @param navigation_node $node Node to add
1044 * @param string $beforekey If specified, adds before a node with this key,
1045 * otherwise adds at end
1046 * @return navigation_node Added node
1048 public function add(navigation_node
$node, $beforekey=null) {
1051 $type = $node->type
;
1053 // First check we have a 2nd dimension for this type
1054 if (!array_key_exists($type, $this->orderedcollection
)) {
1055 $this->orderedcollection
[$type] = array();
1057 // Check for a collision and report if debugging is turned on
1058 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
1059 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
1062 // Find the key to add before
1063 $newindex = $this->count
;
1065 if ($beforekey !== null) {
1066 foreach ($this->collection
as $index => $othernode) {
1067 if ($othernode->key
=== $beforekey) {
1073 if ($newindex === $this->count
) {
1074 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
1075 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER
);
1079 // Add the node to the appropriate place in the by-type structure (which
1080 // is not ordered, despite the variable name)
1081 $this->orderedcollection
[$type][$key] = $node;
1083 // Update existing references in the ordered collection (which is the
1084 // one that isn't called 'ordered') to shuffle them along if required
1085 for ($oldindex = $this->count
; $oldindex > $newindex; $oldindex--) {
1086 $this->collection
[$oldindex] = $this->collection
[$oldindex - 1];
1089 // Add a reference to the node to the progressive collection.
1090 $this->collection
[$newindex] = $this->orderedcollection
[$type][$key];
1091 // Update the last property to a reference to this new node.
1092 $this->last
= $this->orderedcollection
[$type][$key];
1094 // Reorder the array by index if needed
1096 ksort($this->collection
);
1099 // Return the reference to the now added node
1104 * Return a list of all the keys of all the nodes.
1105 * @return array the keys.
1107 public function get_key_list() {
1109 foreach ($this->collection
as $node) {
1110 $keys[] = $node->key
;
1116 * Set a label for this collection.
1118 * @param string $label
1120 public function set_collectionlabel($label) {
1121 $this->collectionlabel
= $label;
1125 * Return a label for this collection.
1129 public function get_collectionlabel() {
1130 return $this->collectionlabel
;
1134 * Fetches a node from this collection.
1136 * @param string|int $key The key of the node we want to find.
1137 * @param int $type One of navigation_node::TYPE_*.
1138 * @return navigation_node|null
1140 public function get($key, $type=null) {
1141 if ($type !== null) {
1142 // If the type is known then we can simply check and fetch
1143 if (!empty($this->orderedcollection
[$type][$key])) {
1144 return $this->orderedcollection
[$type][$key];
1147 // Because we don't know the type we look in the progressive array
1148 foreach ($this->collection
as $node) {
1149 if ($node->key
=== $key) {
1158 * Searches for a node with matching key and type.
1160 * This function searches both the nodes in this collection and all of
1161 * the nodes in each collection belonging to the nodes in this collection.
1165 * @param string|int $key The key of the node we want to find.
1166 * @param int $type One of navigation_node::TYPE_*.
1167 * @return navigation_node|null
1169 public function find($key, $type=null) {
1170 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
1171 return $this->orderedcollection
[$type][$key];
1173 $nodes = $this->getIterator();
1174 // Search immediate children first
1175 foreach ($nodes as &$node) {
1176 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
1180 // Now search each childs children
1181 foreach ($nodes as &$node) {
1182 $result = $node->children
->find($key, $type);
1183 if ($result !== false) {
1192 * Fetches the last node that was added to this collection
1194 * @return navigation_node
1196 public function last() {
1201 * Fetches all nodes of a given type from this collection
1203 * @param string|int $type node type being searched for.
1204 * @return array ordered collection
1206 public function type($type) {
1207 if (!array_key_exists($type, $this->orderedcollection
)) {
1208 $this->orderedcollection
[$type] = array();
1210 return $this->orderedcollection
[$type];
1213 * Removes the node with the given key and type from the collection
1215 * @param string|int $key The key of the node we want to find.
1219 public function remove($key, $type=null) {
1220 $child = $this->get($key, $type);
1221 if ($child !== false) {
1222 foreach ($this->collection
as $colkey => $node) {
1223 if ($node->key
=== $key && (is_null($type) ||
$node->type
== $type)) {
1224 unset($this->collection
[$colkey]);
1225 $this->collection
= array_values($this->collection
);
1229 unset($this->orderedcollection
[$child->type
][$child->key
]);
1237 * Gets the number of nodes in this collection
1239 * This option uses an internal count rather than counting the actual options to avoid
1240 * a performance hit through the count function.
1244 public function count() {
1245 return $this->count
;
1248 * Gets an array iterator for the collection.
1250 * This is required by the IteratorAggregator interface and is used by routines
1251 * such as the foreach loop.
1253 * @return ArrayIterator
1255 public function getIterator() {
1256 return new ArrayIterator($this->collection
);
1261 * The global navigation class used for... the global navigation
1263 * This class is used by PAGE to store the global navigation for the site
1264 * and is then used by the settings nav and navbar to save on processing and DB calls
1267 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
1268 * {@link lib/ajax/getnavbranch.php} Called by ajax
1271 * @category navigation
1272 * @copyright 2009 Sam Hemelryk
1273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1275 class global_navigation
extends navigation_node
{
1276 /** @var moodle_page The Moodle page this navigation object belongs to. */
1278 /** @var bool switch to let us know if the navigation object is initialised*/
1279 protected $initialised = false;
1280 /** @var array An array of course information */
1281 protected $mycourses = array();
1282 /** @var navigation_node[] An array for containing root navigation nodes */
1283 protected $rootnodes = array();
1284 /** @var bool A switch for whether to show empty sections in the navigation */
1285 protected $showemptysections = true;
1286 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
1287 protected $showcategories = null;
1288 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1289 protected $showmycategories = null;
1290 /** @var array An array of stdClasses for users that the navigation is extended for */
1291 protected $extendforuser = array();
1292 /** @var navigation_cache */
1294 /** @var array An array of course ids that are present in the navigation */
1295 protected $addedcourses = array();
1297 protected $allcategoriesloaded = false;
1298 /** @var array An array of category ids that are included in the navigation */
1299 protected $addedcategories = array();
1300 /** @var int expansion limit */
1301 protected $expansionlimit = 0;
1302 /** @var int userid to allow parent to see child's profile page navigation */
1303 protected $useridtouseforparentchecks = 0;
1304 /** @var cache_session A cache that stores information on expanded courses */
1305 protected $cacheexpandcourse = null;
1307 /** Used when loading categories to load all top level categories [parent = 0] **/
1308 const LOAD_ROOT_CATEGORIES
= 0;
1309 /** Used when loading categories to load all categories **/
1310 const LOAD_ALL_CATEGORIES
= -1;
1313 * Constructs a new global navigation
1315 * @param moodle_page $page The page this navigation object belongs to
1317 public function __construct(moodle_page
$page) {
1318 global $CFG, $SITE, $USER;
1320 if (during_initial_install()) {
1324 $homepage = get_home_page();
1325 if ($homepage == HOMEPAGE_SITE
) {
1326 // We are using the site home for the root element.
1327 $properties = array(
1329 'type' => navigation_node
::TYPE_SYSTEM
,
1330 'text' => get_string('home'),
1331 'action' => new moodle_url('/'),
1332 'icon' => new pix_icon('i/home', '')
1334 } else if ($homepage == HOMEPAGE_MYCOURSES
) {
1335 // We are using the user's course summary page for the root element.
1336 $properties = array(
1337 'key' => 'mycourses',
1338 'type' => navigation_node
::TYPE_SYSTEM
,
1339 'text' => get_string('mycourses'),
1340 'action' => new moodle_url('/my/courses.php'),
1341 'icon' => new pix_icon('i/course', '')
1344 // We are using the users my moodle for the root element.
1345 $properties = array(
1347 'type' => navigation_node
::TYPE_SYSTEM
,
1348 'text' => get_string('myhome'),
1349 'action' => new moodle_url('/my/'),
1350 'icon' => new pix_icon('i/dashboard', '')
1354 // Use the parents constructor.... good good reuse
1355 parent
::__construct($properties);
1356 $this->showinflatnavigation
= true;
1358 // Initalise and set defaults
1359 $this->page
= $page;
1360 $this->forceopen
= true;
1361 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
1365 * Mutator to set userid to allow parent to see child's profile
1366 * page navigation. See MDL-25805 for initial issue. Linked to it
1367 * is an issue explaining why this is a REALLY UGLY HACK thats not
1370 * @param int $userid userid of profile page that parent wants to navigate around.
1372 public function set_userid_for_parent_checks($userid) {
1373 $this->useridtouseforparentchecks
= $userid;
1378 * Initialises the navigation object.
1380 * This causes the navigation object to look at the current state of the page
1381 * that it is associated with and then load the appropriate content.
1383 * This should only occur the first time that the navigation structure is utilised
1384 * which will normally be either when the navbar is called to be displayed or
1385 * when a block makes use of it.
1389 public function initialise() {
1390 global $CFG, $SITE, $USER;
1391 // Check if it has already been initialised
1392 if ($this->initialised ||
during_initial_install()) {
1395 $this->initialised
= true;
1397 // Set up the five base root nodes. These are nodes where we will put our
1398 // content and are as follows:
1399 // site: Navigation for the front page.
1400 // myprofile: User profile information goes here.
1401 // currentcourse: The course being currently viewed.
1402 // mycourses: The users courses get added here.
1403 // courses: Additional courses are added here.
1404 // users: Other users information loaded here.
1405 $this->rootnodes
= array();
1406 $defaulthomepage = get_home_page();
1407 if ($defaulthomepage == HOMEPAGE_SITE
) {
1408 // The home element should be my moodle because the root element is the site
1409 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
1410 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1411 self
::TYPE_SETTING
, null, 'myhome', new pix_icon('i/dashboard', ''));
1412 $this->rootnodes
['home']->showinflatnavigation
= true;
1415 // The home element should be the site because the root node is my moodle
1416 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1417 self
::TYPE_SETTING
, null, 'home', new pix_icon('i/home', ''));
1418 $this->rootnodes
['home']->showinflatnavigation
= true;
1419 if (!empty($CFG->defaulthomepage
) &&
1420 ($CFG->defaulthomepage
== HOMEPAGE_MY ||
$CFG->defaulthomepage
== HOMEPAGE_MYCOURSES
)) {
1421 // We need to stop automatic redirection
1422 $this->rootnodes
['home']->action
->param('redirect', '0');
1425 $this->rootnodes
['site'] = $this->add_course($SITE);
1426 $this->rootnodes
['myprofile'] = $this->add(get_string('profile'), null, self
::TYPE_USER
, null, 'myprofile');
1427 $this->rootnodes
['currentcourse'] = $this->add(get_string('currentcourse'), null, self
::TYPE_ROOTNODE
, null, 'currentcourse');
1428 $this->rootnodes
['mycourses'] = $this->add(
1429 get_string('mycourses'),
1430 new moodle_url('/my/courses.php'),
1431 self
::TYPE_ROOTNODE
,
1434 new pix_icon('i/course', '')
1436 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses.
1437 // It will be automatically handled by the breadcrumb generator.
1438 if ($defaulthomepage == HOMEPAGE_MYCOURSES
) {
1439 $this->rootnodes
['mycourses']->mainnavonly
= true;
1442 $this->rootnodes
['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self
::TYPE_ROOTNODE
, null, 'courses');
1443 if (!core_course_category
::user_top()) {
1444 $this->rootnodes
['courses']->hide();
1446 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
1448 // We always load the frontpage course to ensure it is available without
1449 // JavaScript enabled.
1450 $this->add_front_page_course_essentials($this->rootnodes
['site'], $SITE);
1451 $this->load_course_sections($SITE, $this->rootnodes
['site']);
1453 $course = $this->page
->course
;
1454 $this->load_courses_enrolled();
1456 // $issite gets set to true if the current pages course is the sites frontpage course
1457 $issite = ($this->page
->course
->id
== $SITE->id
);
1459 // Determine if the user is enrolled in any course.
1460 $enrolledinanycourse = enrol_user_sees_own_courses();
1462 $this->rootnodes
['currentcourse']->mainnavonly
= true;
1463 if ($enrolledinanycourse) {
1464 $this->rootnodes
['mycourses']->isexpandable
= true;
1465 $this->rootnodes
['mycourses']->showinflatnavigation
= true;
1466 if ($CFG->navshowallcourses
) {
1467 // When we show all courses we need to show both the my courses and the regular courses branch.
1468 $this->rootnodes
['courses']->isexpandable
= true;
1471 $this->rootnodes
['courses']->isexpandable
= true;
1473 $this->rootnodes
['mycourses']->forceopen
= true;
1475 $canviewcourseprofile = true;
1477 // Next load context specific content into the navigation
1478 switch ($this->page
->context
->contextlevel
) {
1479 case CONTEXT_SYSTEM
:
1480 // Nothing left to do here I feel.
1482 case CONTEXT_COURSECAT
:
1483 // This is essential, we must load categories.
1484 $this->load_all_categories($this->page
->context
->instanceid
, true);
1486 case CONTEXT_BLOCK
:
1487 case CONTEXT_COURSE
:
1489 // Nothing left to do here.
1493 // Load the course associated with the current page into the navigation.
1494 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1495 // If the course wasn't added then don't try going any further.
1497 $canviewcourseprofile = false;
1501 // If the user is not enrolled then we only want to show the
1502 // course node and not populate it.
1504 // Not enrolled, can't view, and hasn't switched roles
1505 if (!can_access_course($course, null, '', true)) {
1506 if ($coursenode->isexpandable
=== true) {
1507 // Obviously the situation has changed, update the cache and adjust the node.
1508 // This occurs if the user access to a course has been revoked (one way or another) after
1509 // initially logging in for this session.
1510 $this->get_expand_course_cache()->set($course->id
, 1);
1511 $coursenode->isexpandable
= true;
1512 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1514 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1515 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1516 if (!$this->current_user_is_parent_role()) {
1517 $coursenode->make_active();
1518 $canviewcourseprofile = false;
1521 } else if ($coursenode->isexpandable
=== false) {
1522 // Obviously the situation has changed, update the cache and adjust the node.
1523 // This occurs if the user has been granted access to a course (one way or another) after initially
1524 // logging in for this session.
1525 $this->get_expand_course_cache()->set($course->id
, 1);
1526 $coursenode->isexpandable
= true;
1527 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1530 // Add the essentials such as reports etc...
1531 $this->add_course_essentials($coursenode, $course);
1532 // Extend course navigation with it's sections/activities
1533 $this->load_course_sections($course, $coursenode);
1534 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1535 $coursenode->make_active();
1539 case CONTEXT_MODULE
:
1541 // If this is the site course then most information will have
1542 // already been loaded.
1543 // However we need to check if there is more content that can
1544 // yet be loaded for the specific module instance.
1545 $activitynode = $this->rootnodes
['site']->find($this->page
->cm
->id
, navigation_node
::TYPE_ACTIVITY
);
1546 if ($activitynode) {
1547 $this->load_activity($this->page
->cm
, $this->page
->course
, $activitynode);
1552 $course = $this->page
->course
;
1553 $cm = $this->page
->cm
;
1555 // Load the course associated with the page into the navigation
1556 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1558 // If the course wasn't added then don't try going any further.
1560 $canviewcourseprofile = false;
1564 // If the user is not enrolled then we only want to show the
1565 // course node and not populate it.
1566 if (!can_access_course($course, null, '', true)) {
1567 $coursenode->make_active();
1568 $canviewcourseprofile = false;
1572 $this->add_course_essentials($coursenode, $course);
1574 // Load the course sections into the page
1575 $this->load_course_sections($course, $coursenode, null, $cm);
1576 $activity = $coursenode->find($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1577 if (!empty($activity)) {
1578 // Finally load the cm specific navigaton information
1579 $this->load_activity($cm, $course, $activity);
1580 // Check if we have an active ndoe
1581 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1582 // And make the activity node active.
1583 $activity->make_active();
1589 // The users profile information etc is already loaded
1590 // for the front page.
1593 $course = $this->page
->course
;
1594 // Load the course associated with the user into the navigation
1595 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
1597 // If the course wasn't added then don't try going any further.
1599 $canviewcourseprofile = false;
1603 // If the user is not enrolled then we only want to show the
1604 // course node and not populate it.
1605 if (!can_access_course($course, null, '', true)) {
1606 $coursenode->make_active();
1607 $canviewcourseprofile = false;
1610 $this->add_course_essentials($coursenode, $course);
1611 $this->load_course_sections($course, $coursenode);
1615 // Load for the current user
1616 $this->load_for_user();
1617 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
&& $canviewcourseprofile) {
1618 $this->load_for_user(null, true);
1620 // Load each extending user into the navigation.
1621 foreach ($this->extendforuser
as $user) {
1622 if ($user->id
!= $USER->id
) {
1623 $this->load_for_user($user);
1627 // Give the local plugins a chance to include some navigation if they want.
1628 $this->load_local_plugin_navigation();
1630 // Remove any empty root nodes
1631 foreach ($this->rootnodes
as $node) {
1632 // Dont remove the home node
1633 /** @var navigation_node $node */
1634 if (!in_array($node->key
, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive
) {
1639 if (!$this->contains_active_node()) {
1640 $this->search_for_active_node();
1643 // If the user is not logged in modify the navigation structure as detailed
1644 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1645 if (!isloggedin()) {
1646 $activities = clone($this->rootnodes
['site']->children
);
1647 $this->rootnodes
['site']->remove();
1648 $children = clone($this->children
);
1649 $this->children
= new navigation_node_collection();
1650 foreach ($activities as $child) {
1651 $this->children
->add($child);
1653 foreach ($children as $child) {
1654 $this->children
->add($child);
1661 * This function gives local plugins an opportunity to modify navigation.
1663 protected function load_local_plugin_navigation() {
1664 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1670 * Returns true if the current user is a parent of the user being currently viewed.
1672 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1673 * other user being viewed this function returns false.
1674 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1679 protected function current_user_is_parent_role() {
1681 if ($this->useridtouseforparentchecks
&& $this->useridtouseforparentchecks
!= $USER->id
) {
1682 $usercontext = context_user
::instance($this->useridtouseforparentchecks
, MUST_EXIST
);
1683 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1686 if ($DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
))) {
1694 * Returns true if courses should be shown within categories on the navigation.
1696 * @param bool $ismycourse Set to true if you are calculating this for a course.
1699 protected function show_categories($ismycourse = false) {
1702 return $this->show_my_categories();
1704 if ($this->showcategories
=== null) {
1706 if ($this->page
->context
->contextlevel
== CONTEXT_COURSECAT
) {
1708 } else if (!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') > 1) {
1711 $this->showcategories
= $show;
1713 return $this->showcategories
;
1717 * Returns true if we should show categories in the My Courses branch.
1720 protected function show_my_categories() {
1722 if ($this->showmycategories
=== null) {
1723 $this->showmycategories
= !empty($CFG->navshowmycoursecategories
) && !core_course_category
::is_simple_site();
1725 return $this->showmycategories
;
1729 * Loads the courses in Moodle into the navigation.
1731 * @global moodle_database $DB
1732 * @param string|array $categoryids An array containing categories to load courses
1733 * for, OR null to load courses for all categories.
1734 * @return array An array of navigation_nodes one for each course
1736 protected function load_all_courses($categoryids = null) {
1737 global $CFG, $DB, $SITE;
1739 // Work out the limit of courses.
1741 if (!empty($CFG->navcourselimit
)) {
1742 $limit = $CFG->navcourselimit
;
1745 $toload = (empty($CFG->navshowallcourses
))?self
::LOAD_ROOT_CATEGORIES
:self
::LOAD_ALL_CATEGORIES
;
1747 // If we are going to show all courses AND we are showing categories then
1748 // to save us repeated DB calls load all of the categories now
1749 if ($this->show_categories()) {
1750 $this->load_all_categories($toload);
1753 // Will be the return of our efforts
1754 $coursenodes = array();
1756 // Check if we need to show categories.
1757 if ($this->show_categories()) {
1758 // Hmmm we need to show categories... this is going to be painful.
1759 // We now need to fetch up to $limit courses for each category to
1761 if ($categoryids !== null) {
1762 if (!is_array($categoryids)) {
1763 $categoryids = array($categoryids);
1765 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cc');
1766 $categorywhere = 'WHERE cc.id '.$categorywhere;
1767 } else if ($toload == self
::LOAD_ROOT_CATEGORIES
) {
1768 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1769 $categoryparams = array();
1771 $categorywhere = '';
1772 $categoryparams = array();
1775 // First up we are going to get the categories that we are going to
1776 // need so that we can determine how best to load the courses from them.
1777 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1778 FROM {course_categories} cc
1779 LEFT JOIN {course} c ON c.category = cc.id
1782 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1783 $fullfetch = array();
1784 $partfetch = array();
1785 foreach ($categories as $category) {
1786 if (!$this->can_add_more_courses_to_category($category->id
)) {
1789 if ($category->coursecount
> $limit * 5) {
1790 $partfetch[] = $category->id
;
1791 } else if ($category->coursecount
> 0) {
1792 $fullfetch[] = $category->id
;
1795 $categories->close();
1797 if (count($fullfetch)) {
1798 // First up fetch all of the courses in categories where we know that we are going to
1799 // need the majority of courses.
1800 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED
, 'lcategory');
1801 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1802 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1803 $categoryparams['contextlevel'] = CONTEXT_COURSE
;
1804 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1807 WHERE c.category {$categoryids}
1808 ORDER BY c.sortorder ASC";
1809 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1810 foreach ($coursesrs as $course) {
1811 if ($course->id
== $SITE->id
) {
1812 // This should not be necessary, frontpage is not in any category.
1815 if (array_key_exists($course->id
, $this->addedcourses
)) {
1816 // It is probably better to not include the already loaded courses
1817 // directly in SQL because inequalities may confuse query optimisers
1818 // and may interfere with query caching.
1821 if (!$this->can_add_more_courses_to_category($course->category
)) {
1824 context_helper
::preload_from_record($course);
1825 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1828 $coursenodes[$course->id
] = $this->add_course($course);
1830 $coursesrs->close();
1833 if (count($partfetch)) {
1834 // Next we will work our way through the categories where we will likely only need a small
1835 // proportion of the courses.
1836 foreach ($partfetch as $categoryid) {
1837 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1838 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1839 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1842 WHERE c.category = :categoryid
1843 ORDER BY c.sortorder ASC";
1844 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE
);
1845 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1846 foreach ($coursesrs as $course) {
1847 if ($course->id
== $SITE->id
) {
1848 // This should not be necessary, frontpage is not in any category.
1851 if (array_key_exists($course->id
, $this->addedcourses
)) {
1852 // It is probably better to not include the already loaded courses
1853 // directly in SQL because inequalities may confuse query optimisers
1854 // and may interfere with query caching.
1855 // This also helps to respect expected $limit on repeated executions.
1858 if (!$this->can_add_more_courses_to_category($course->category
)) {
1861 context_helper
::preload_from_record($course);
1862 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1865 $coursenodes[$course->id
] = $this->add_course($course);
1867 $coursesrs->close();
1871 // Prepare the SQL to load the courses and their contexts
1872 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses
), SQL_PARAMS_NAMED
, 'lc', false);
1873 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1874 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1875 $courseparams['contextlevel'] = CONTEXT_COURSE
;
1876 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1879 WHERE c.id {$courseids}
1880 ORDER BY c.sortorder ASC";
1881 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1882 foreach ($coursesrs as $course) {
1883 if ($course->id
== $SITE->id
) {
1884 // frotpage is not wanted here
1887 if ($this->page
->course
&& ($this->page
->course
->id
== $course->id
)) {
1888 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1891 context_helper
::preload_from_record($course);
1892 if (!$course->visible
&& !is_role_switched($course->id
) && !has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1895 $coursenodes[$course->id
] = $this->add_course($course);
1896 if (count($coursenodes) >= $limit) {
1900 $coursesrs->close();
1903 return $coursenodes;
1907 * Returns true if more courses can be added to the provided category.
1909 * @param int|navigation_node|stdClass $category
1912 protected function can_add_more_courses_to_category($category) {
1915 if (!empty($CFG->navcourselimit
)) {
1916 $limit = (int)$CFG->navcourselimit
;
1918 if (is_numeric($category)) {
1919 if (!array_key_exists($category, $this->addedcategories
)) {
1922 $coursecount = count($this->addedcategories
[$category]->children
->type(self
::TYPE_COURSE
));
1923 } else if ($category instanceof navigation_node
) {
1924 if (($category->type
!= self
::TYPE_CATEGORY
) ||
($category->type
!= self
::TYPE_MY_CATEGORY
)) {
1927 $coursecount = count($category->children
->type(self
::TYPE_COURSE
));
1928 } else if (is_object($category) && property_exists($category,'id')) {
1929 $coursecount = count($this->addedcategories
[$category->id
]->children
->type(self
::TYPE_COURSE
));
1931 return ($coursecount <= $limit);
1935 * Loads all categories (top level or if an id is specified for that category)
1937 * @param int $categoryid The category id to load or null/0 to load all base level categories
1938 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1939 * as the requested category and any parent categories.
1940 * @return navigation_node|void returns a navigation node if a category has been loaded.
1942 protected function load_all_categories($categoryid = self
::LOAD_ROOT_CATEGORIES
, $showbasecategories = false) {
1945 // Check if this category has already been loaded
1946 if ($this->allcategoriesloaded ||
($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1950 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
1951 $sqlselect = "SELECT cc.*, $catcontextsql
1952 FROM {course_categories} cc
1953 JOIN {context} ctx ON cc.id = ctx.instanceid";
1954 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
;
1955 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1958 $categoriestoload = array();
1959 if ($categoryid == self
::LOAD_ALL_CATEGORIES
) {
1960 // We are going to load all categories regardless... prepare to fire
1961 // on the database server!
1962 } else if ($categoryid == self
::LOAD_ROOT_CATEGORIES
) { // can be 0
1963 // We are going to load all of the first level categories (categories without parents)
1964 $sqlwhere .= " AND cc.parent = 0";
1965 } else if (array_key_exists($categoryid, $this->addedcategories
)) {
1966 // The category itself has been loaded already so we just need to ensure its subcategories
1968 $addedcategories = $this->addedcategories
;
1969 unset($addedcategories[$categoryid]);
1970 if (count($addedcategories) > 0) {
1971 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED
, 'parent', false);
1972 if ($showbasecategories) {
1973 // We need to include categories with parent = 0 as well
1974 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1976 // All we need is categories that match the parent
1977 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1980 $params['categoryid'] = $categoryid;
1982 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1983 // and load this category plus all its parents and subcategories
1984 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST
);
1985 $categoriestoload = explode('/', trim($category->path
, '/'));
1986 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1987 // We are going to use select twice so double the params
1988 $params = array_merge($params, $params);
1989 $basecategorysql = ($showbasecategories)?
' OR cc.depth = 1':'';
1990 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1993 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1994 $categories = array();
1995 foreach ($categoriesrs as $category) {
1996 // Preload the context.. we'll need it when adding the category in order
1997 // to format the category name.
1998 context_helper
::preload_from_record($category);
1999 if (array_key_exists($category->id
, $this->addedcategories
)) {
2000 // Do nothing, its already been added.
2001 } else if ($category->parent
== '0') {
2002 // This is a root category lets add it immediately
2003 $this->add_category($category, $this->rootnodes
['courses']);
2004 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
2005 // This categories parent has already been added we can add this immediately
2006 $this->add_category($category, $this->addedcategories
[$category->parent
]);
2008 $categories[] = $category;
2011 $categoriesrs->close();
2013 // Now we have an array of categories we need to add them to the navigation.
2014 while (!empty($categories)) {
2015 $category = reset($categories);
2016 if (array_key_exists($category->id
, $this->addedcategories
)) {
2018 } else if ($category->parent
== '0') {
2019 $this->add_category($category, $this->rootnodes
['courses']);
2020 } else if (array_key_exists($category->parent
, $this->addedcategories
)) {
2021 $this->add_category($category, $this->addedcategories
[$category->parent
]);
2023 // This category isn't in the navigation and niether is it's parent (yet).
2024 // We need to go through the category path and add all of its components in order.
2025 $path = explode('/', trim($category->path
, '/'));
2026 foreach ($path as $catid) {
2027 if (!array_key_exists($catid, $this->addedcategories
)) {
2028 // This category isn't in the navigation yet so add it.
2029 $subcategory = $categories[$catid];
2030 if ($subcategory->parent
== '0') {
2031 // Yay we have a root category - this likely means we will now be able
2032 // to add categories without problems.
2033 $this->add_category($subcategory, $this->rootnodes
['courses']);
2034 } else if (array_key_exists($subcategory->parent
, $this->addedcategories
)) {
2035 // The parent is in the category (as we'd expect) so add it now.
2036 $this->add_category($subcategory, $this->addedcategories
[$subcategory->parent
]);
2037 // Remove the category from the categories array.
2038 unset($categories[$catid]);
2040 // We should never ever arrive here - if we have then there is a bigger
2042 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
2047 // Remove the category from the categories array now that we know it has been added.
2048 unset($categories[$category->id
]);
2050 if ($categoryid === self
::LOAD_ALL_CATEGORIES
) {
2051 $this->allcategoriesloaded
= true;
2053 // Check if there are any categories to load.
2054 if (count($categoriestoload) > 0) {
2055 $readytoloadcourses = array();
2056 foreach ($categoriestoload as $category) {
2057 if ($this->can_add_more_courses_to_category($category)) {
2058 $readytoloadcourses[] = $category;
2061 if (count($readytoloadcourses)) {
2062 $this->load_all_courses($readytoloadcourses);
2066 // Look for all categories which have been loaded
2067 if (!empty($this->addedcategories
)) {
2068 $categoryids = array();
2069 foreach ($this->addedcategories
as $category) {
2070 if ($this->can_add_more_courses_to_category($category)) {
2071 $categoryids[] = $category->key
;
2075 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
);
2076 $params['limit'] = (!empty($CFG->navcourselimit
))?
$CFG->navcourselimit
:20;
2077 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
2078 FROM {course_categories} cc
2079 JOIN {course} c ON c.category = cc.id
2080 WHERE cc.id {$categoriessql}
2082 HAVING COUNT(c.id) > :limit";
2083 $excessivecategories = $DB->get_records_sql($sql, $params);
2084 foreach ($categories as &$category) {
2085 if (array_key_exists($category->key
, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
2086 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key
));
2087 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
2095 * Adds a structured category to the navigation in the correct order/place
2097 * @param stdClass $category category to be added in navigation.
2098 * @param navigation_node $parent parent navigation node
2099 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2102 protected function add_category(stdClass
$category, navigation_node
$parent, $nodetype = self
::TYPE_CATEGORY
) {
2104 if (array_key_exists($category->id
, $this->addedcategories
)) {
2107 $canview = core_course_category
::can_view_category($category);
2108 $url = $canview ?
new moodle_url('/course/index.php', array('categoryid' => $category->id
)) : null;
2109 $context = \context_helper
::get_navigation_filter_context(context_coursecat
::instance($category->id
));
2110 $categoryname = $canview ?
format_string($category->name
, true, ['context' => $context]) :
2111 get_string('categoryhidden');
2112 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id
);
2114 // User does not have required capabilities to view category.
2115 $categorynode->display
= false;
2116 } else if (!$category->visible
) {
2117 // Category is hidden but user has capability to view hidden categories.
2118 $categorynode->hidden
= true;
2120 $this->addedcategories
[$category->id
] = $categorynode;
2124 * Loads the given course into the navigation
2126 * @param stdClass $course
2127 * @return navigation_node
2129 protected function load_course(stdClass
$course) {
2131 if ($course->id
== $SITE->id
) {
2132 // This is always loaded during initialisation
2133 return $this->rootnodes
['site'];
2134 } else if (array_key_exists($course->id
, $this->addedcourses
)) {
2135 // The course has already been loaded so return a reference
2136 return $this->addedcourses
[$course->id
];
2139 return $this->add_course($course);
2144 * Loads all of the courses section into the navigation.
2146 * This function calls method from current course format, see
2147 * core_courseformat\base::extend_course_navigation()
2148 * If course module ($cm) is specified but course format failed to create the node,
2149 * the activity node is created anyway.
2151 * By default course formats call the method global_navigation::load_generic_course_sections()
2153 * @param stdClass $course Database record for the course
2154 * @param navigation_node $coursenode The course node within the navigation
2155 * @param null|int $sectionnum If specified load the contents of section with this relative number
2156 * @param null|cm_info $cm If specified make sure that activity node is created (either
2157 * in containg section or by calling load_stealth_activity() )
2159 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode, $sectionnum = null, $cm = null) {
2161 require_once($CFG->dirroot
.'/course/lib.php');
2162 if (isset($cm->sectionnum
)) {
2163 $sectionnum = $cm->sectionnum
;
2165 if ($sectionnum !== null) {
2166 $this->includesectionnum
= $sectionnum;
2168 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2169 if (isset($cm->id
)) {
2170 $activity = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
2171 if (empty($activity)) {
2172 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2178 * Generates an array of sections and an array of activities for the given course.
2180 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2182 * @param stdClass $course
2183 * @return array Array($sections, $activities)
2185 protected function generate_sections_and_activities(stdClass
$course) {
2187 require_once($CFG->dirroot
.'/course/lib.php');
2189 $modinfo = get_fast_modinfo($course);
2190 $sections = $modinfo->get_section_info_all();
2192 // For course formats using 'numsections' trim the sections list
2193 $courseformatoptions = course_get_format($course)->get_format_options();
2194 if (isset($courseformatoptions['numsections'])) {
2195 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+
1, true);
2198 $activities = array();
2200 foreach ($sections as $key => $section) {
2201 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
2202 $sections[$key] = clone($section);
2203 unset($sections[$key]->summary
);
2204 $sections[$key]->hasactivites
= false;
2205 if (!array_key_exists($section->section
, $modinfo->sections
)) {
2208 foreach ($modinfo->sections
[$section->section
] as $cmid) {
2209 $cm = $modinfo->cms
[$cmid];
2210 $activity = new stdClass
;
2211 $activity->id
= $cm->id
;
2212 $activity->course
= $course->id
;
2213 $activity->section
= $section->section
;
2214 $activity->name
= $cm->name
;
2215 $activity->icon
= $cm->icon
;
2216 $activity->iconcomponent
= $cm->iconcomponent
;
2217 $activity->hidden
= (!$cm->visible
);
2218 $activity->modname
= $cm->modname
;
2219 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2220 $activity->onclick
= $cm->onclick
;
2223 $activity->url
= null;
2224 $activity->display
= false;
2226 $activity->url
= $url->out();
2227 $activity->display
= $cm->is_visible_on_course_page() ?
true : false;
2228 if (self
::module_extends_navigation($cm->modname
)) {
2229 $activity->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2232 $activities[$cmid] = $activity;
2233 if ($activity->display
) {
2234 $sections[$key]->hasactivites
= true;
2239 return array($sections, $activities);
2243 * Generically loads the course sections into the course's navigation.
2245 * @param stdClass $course
2246 * @param navigation_node $coursenode
2247 * @return array An array of course section nodes
2249 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode) {
2250 global $CFG, $DB, $USER, $SITE;
2251 require_once($CFG->dirroot
.'/course/lib.php');
2253 list($sections, $activities) = $this->generate_sections_and_activities($course);
2255 $navigationsections = array();
2256 foreach ($sections as $sectionid => $section) {
2257 $section = clone($section);
2258 if ($course->id
== $SITE->id
) {
2259 $this->load_section_activities($coursenode, $section->section
, $activities);
2261 if (!$section->uservisible ||
(!$this->showemptysections
&&
2262 !$section->hasactivites
&& $this->includesectionnum
!== $section->section
)) {
2266 $sectionname = get_section_name($course, $section);
2267 $url = course_get_url($course, $section->section
, array('navigation' => true));
2269 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
,
2270 null, $section->id
, new pix_icon('i/section', ''));
2271 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2272 $sectionnode->hidden
= (!$section->visible ||
!$section->available
);
2273 if ($this->includesectionnum
!== false && $this->includesectionnum
== $section->section
) {
2274 $this->load_section_activities($sectionnode, $section->section
, $activities);
2276 $section->sectionnode
= $sectionnode;
2277 $navigationsections[$sectionid] = $section;
2280 return $navigationsections;
2284 * Loads all of the activities for a section into the navigation structure.
2286 * @param navigation_node $sectionnode
2287 * @param int $sectionnumber
2288 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
2289 * @param stdClass $course The course object the section and activities relate to.
2290 * @return array Array of activity nodes
2292 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, array $activities, $course = null) {
2294 // A static counter for JS function naming
2295 static $legacyonclickcounter = 0;
2297 $activitynodes = array();
2298 if (empty($activities)) {
2299 return $activitynodes;
2302 if (!is_object($course)) {
2303 $activity = reset($activities);
2304 $courseid = $activity->course
;
2306 $courseid = $course->id
;
2308 $showactivities = ($courseid != $SITE->id ||
!empty($CFG->navshowfrontpagemods
));
2310 foreach ($activities as $activity) {
2311 if ($activity->section
!= $sectionnumber) {
2314 if ($activity->icon
) {
2315 $icon = new pix_icon($activity->icon
, get_string('modulename', $activity->modname
), $activity->iconcomponent
);
2317 $icon = new pix_icon('icon', get_string('modulename', $activity->modname
), $activity->modname
);
2320 // Prepare the default name and url for the node
2321 $displaycontext = \context_helper
::get_navigation_filter_context(context_module
::instance($activity->id
));
2322 $activityname = format_string($activity->name
, true, ['context' => $displaycontext]);
2323 $action = new moodle_url($activity->url
);
2325 // Check if the onclick property is set (puke!)
2326 if (!empty($activity->onclick
)) {
2327 // Increment the counter so that we have a unique number.
2328 $legacyonclickcounter++
;
2329 // Generate the function name we will use
2330 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2331 $propogrationhandler = '';
2332 // Check if we need to cancel propogation. Remember inline onclick
2333 // events would return false if they wanted to prevent propogation and the
2335 if (strpos($activity->onclick
, 'return false')) {
2336 $propogrationhandler = 'e.halt();';
2338 // Decode the onclick - it has already been encoded for display (puke)
2339 $onclick = htmlspecialchars_decode($activity->onclick
, ENT_QUOTES
);
2340 // Build the JS function the click event will call
2341 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
2342 $this->page
->requires
->js_amd_inline($jscode);
2343 // Override the default url with the new action link
2344 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2347 $activitynode = $sectionnode->add($activityname, $action, navigation_node
::TYPE_ACTIVITY
, null, $activity->id
, $icon);
2348 $activitynode->title(get_string('modulename', $activity->modname
));
2349 $activitynode->hidden
= $activity->hidden
;
2350 $activitynode->display
= $showactivities && $activity->display
;
2351 $activitynode->nodetype
= $activity->nodetype
;
2352 $activitynodes[$activity->id
] = $activitynode;
2355 return $activitynodes;
2358 * Loads a stealth module from unavailable section
2359 * @param navigation_node $coursenode
2360 * @param stdClass $modinfo
2361 * @return navigation_node or null if not accessible
2363 protected function load_stealth_activity(navigation_node
$coursenode, $modinfo) {
2364 if (empty($modinfo->cms
[$this->page
->cm
->id
])) {
2367 $cm = $modinfo->cms
[$this->page
->cm
->id
];
2369 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
2371 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
2374 $activitynode = $coursenode->add(format_string($cm->name
), $url, navigation_node
::TYPE_ACTIVITY
, null, $cm->id
, $icon);
2375 $activitynode->title(get_string('modulename', $cm->modname
));
2376 $activitynode->hidden
= (!$cm->visible
);
2377 if (!$cm->is_visible_on_course_page()) {
2378 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2379 // Also there may be no exception at all in case when teacher is logged in as student.
2380 $activitynode->display
= false;
2382 // Don't show activities that don't have links!
2383 $activitynode->display
= false;
2384 } else if (self
::module_extends_navigation($cm->modname
)) {
2385 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
2387 return $activitynode;
2390 * Loads the navigation structure for the given activity into the activities node.
2392 * This method utilises a callback within the modules lib.php file to load the
2393 * content specific to activity given.
2395 * The callback is a method: {modulename}_extend_navigation()
2397 * * {@link forum_extend_navigation()}
2398 * * {@link workshop_extend_navigation()}
2400 * @param cm_info|stdClass $cm
2401 * @param stdClass $course
2402 * @param navigation_node $activity
2405 protected function load_activity($cm, stdClass
$course, navigation_node
$activity) {
2408 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2409 if (!($cm instanceof cm_info
)) {
2410 $modinfo = get_fast_modinfo($course);
2411 $cm = $modinfo->get_cm($cm->id
);
2413 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
2414 $activity->make_active();
2415 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
2416 $function = $cm->modname
.'_extend_navigation';
2418 if (file_exists($file)) {
2419 require_once($file);
2420 if (function_exists($function)) {
2421 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
2422 $function($activity, $course, $activtyrecord, $cm);
2426 // Allow the active advanced grading method plugin to append module navigation
2427 $featuresfunc = $cm->modname
.'_supports';
2428 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
)) {
2429 require_once($CFG->dirroot
.'/grade/grading/lib.php');
2430 $gradingman = get_grading_manager($cm->context
, 'mod_'.$cm->modname
);
2431 $gradingman->extend_navigation($this, $activity);
2434 return $activity->has_children();
2437 * Loads user specific information into the navigation in the appropriate place.
2439 * If no user is provided the current user is assumed.
2441 * @param stdClass $user
2442 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2445 protected function load_for_user($user=null, $forceforcontext=false) {
2446 global $DB, $CFG, $USER, $SITE;
2448 require_once($CFG->dirroot
. '/course/lib.php');
2450 if ($user === null) {
2451 // We can't require login here but if the user isn't logged in we don't
2452 // want to show anything
2453 if (!isloggedin() ||
isguestuser()) {
2457 } else if (!is_object($user)) {
2458 // If the user is not an object then get them from the database
2459 $select = context_helper
::get_preload_record_columns_sql('ctx');
2460 $sql = "SELECT u.*, $select
2462 JOIN {context} ctx ON u.id = ctx.instanceid
2463 WHERE u.id = :userid AND
2464 ctx.contextlevel = :contextlevel";
2465 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER
), MUST_EXIST
);
2466 context_helper
::preload_from_record($user);
2469 $iscurrentuser = ($user->id
== $USER->id
);
2471 $usercontext = context_user
::instance($user->id
);
2473 // Get the course set against the page, by default this will be the site
2474 $course = $this->page
->course
;
2475 $baseargs = array('id'=>$user->id
);
2476 if ($course->id
!= $SITE->id
&& (!$iscurrentuser ||
$forceforcontext)) {
2477 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
2478 $baseargs['course'] = $course->id
;
2479 $coursecontext = context_course
::instance($course->id
);
2480 $issitecourse = false;
2482 // Load all categories and get the context for the system
2483 $coursecontext = context_system
::instance();
2484 $issitecourse = true;
2487 // Create a node to add user information under.
2489 if (!$issitecourse) {
2490 // Not the current user so add it to the participants node for the current course.
2491 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
2492 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2493 } else if ($USER->id
!= $user->id
) {
2494 // This is the site so add a users node to the root branch.
2495 $usersnode = $this->rootnodes
['users'];
2496 if (course_can_view_participants($coursecontext)) {
2497 $usersnode->action
= new moodle_url('/user/index.php', array('id' => $course->id
));
2499 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2502 // We should NEVER get here, if the course hasn't been populated
2503 // with a participants node then the navigaiton either wasn't generated
2504 // for it (you are missing a require_login or set_context call) or
2505 // you don't have access.... in the interests of no leaking informatin
2506 // we simply quit...
2509 // Add a branch for the current user.
2510 // Only reveal user details if $user is the current user, or a user to which the current user has access.
2511 $viewprofile = true;
2512 if (!$iscurrentuser) {
2513 require_once($CFG->dirroot
. '/user/lib.php');
2514 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& !has_capability('moodle/user:viewdetails', $usercontext) ) {
2515 $viewprofile = false;
2516 } else if ($this->page
->context
->contextlevel
!= CONTEXT_USER
&& !user_can_view_profile($user, $course, $usercontext)) {
2517 $viewprofile = false;
2519 if (!$viewprofile) {
2520 $viewprofile = user_can_view_profile($user, null, $usercontext);
2524 // Now, conditionally add the user node.
2526 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2527 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self
::TYPE_USER
, null, 'user' . $user->id
);
2529 $usernode = $usersnode->add(get_string('user'));
2532 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
2533 $usernode->make_active();
2536 // Add user information to the participants or user node.
2537 if ($issitecourse) {
2539 // If the user is the current user or has permission to view the details of the requested
2540 // user than add a view profile link.
2541 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
2542 has_capability('moodle/user:viewdetails', $usercontext)) {
2543 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
2544 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
2546 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
2550 if (!empty($CFG->navadduserpostslinks
)) {
2551 // Add nodes for forum posts and discussions if the user can view either or both
2552 // There are no capability checks here as the content of the page is based
2553 // purely on the forums the current user has access too.
2554 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2555 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2556 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
2557 array_merge($baseargs, array('mode' => 'discussions'))));
2561 if (!empty($CFG->enableblogs
)) {
2562 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
2563 require_once($CFG->dirroot
.'/blog/lib.php');
2564 // Get all options for the user.
2565 $options = blog_get_options_for_user($user);
2566 $this->cache
->set('userblogoptions'.$user->id
, $options);
2568 $options = $this->cache
->{'userblogoptions'.$user->id
};
2571 if (count($options) > 0) {
2572 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
2573 foreach ($options as $type => $option) {
2574 if ($type == "rss") {
2575 $blogs->add($option['string'], $option['link'], settings_navigation
::TYPE_SETTING
, null, null,
2576 new pix_icon('i/rss', ''));
2578 $blogs->add($option['string'], $option['link']);
2584 // Add the messages link.
2585 // It is context based so can appear in the user's profile and in course participants information.
2586 if (!empty($CFG->messaging
)) {
2587 $messageargs = array('user1' => $USER->id
);
2588 if ($USER->id
!= $user->id
) {
2589 $messageargs['user2'] = $user->id
;
2591 $url = new moodle_url('/message/index.php', $messageargs);
2592 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
2595 // Add the "My private files" link.
2596 // This link doesn't have a unique display for course context so only display it under the user's profile.
2597 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2598 $url = new moodle_url('/user/files.php');
2599 $usernode->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
2602 // Add a node to view the users notes if permitted.
2603 if (!empty($CFG->enablenotes
) &&
2604 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2605 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
2606 if ($coursecontext->instanceid
!= SITEID
) {
2607 $url->param('course', $coursecontext->instanceid
);
2609 $usernode->add(get_string('notes', 'notes'), $url);
2612 // Show the grades node.
2613 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
2614 require_once($CFG->dirroot
. '/user/lib.php');
2615 // Set the grades node to link to the "Grades" page.
2616 if ($course->id
== SITEID
) {
2617 $url = user_mygrades_url($user->id
, $course->id
);
2618 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2619 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
2621 if ($USER->id
!= $user->id
) {
2622 $usernode->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'usergrades');
2624 $usernode->add(get_string('grades', 'grades'), $url);
2628 // If the user is the current user add the repositories for the current user.
2629 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
2630 if (!$iscurrentuser &&
2631 $course->id
== $SITE->id
&&
2632 has_capability('moodle/user:viewdetails', $usercontext) &&
2633 (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2635 // Add view grade report is permitted.
2636 $reports = core_component
::get_plugin_list('gradereport');
2637 arsort($reports); // User is last, we want to test it first.
2639 $userscourses = enrol_get_users_courses($user->id
, false, '*');
2640 $userscoursesnode = $usernode->add(get_string('courses'));
2643 foreach ($userscourses as $usercourse) {
2644 if ($count === (int)$CFG->navcourselimit
) {
2645 $url = new moodle_url('/user/profile.php', array('id' => $user->id
, 'showallcourses' => 1));
2646 $userscoursesnode->add(get_string('showallcourses'), $url);
2650 $usercoursecontext = context_course
::instance($usercourse->id
);
2651 $usercourseshortname = format_string($usercourse->shortname
, true, array('context' => $usercoursecontext));
2652 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
2653 array('id' => $user->id
, 'course' => $usercourse->id
)), self
::TYPE_CONTAINER
);
2655 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
2656 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
2657 foreach ($reports as $plugin => $plugindir) {
2658 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2659 // Stop when the first visible plugin is found.
2660 $gradeavailable = true;
2666 if ($gradeavailable) {
2667 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id
));
2668 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null,
2669 new pix_icon('i/grades', ''));
2672 // Add a node to view the users notes if permitted.
2673 if (!empty($CFG->enablenotes
) &&
2674 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2675 $url = new moodle_url('/notes/index.php', array('user' => $user->id
, 'course' => $usercourse->id
));
2676 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
2679 if (can_access_course($usercourse, $user->id
, '', true)) {
2680 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
2681 array('id' => $usercourse->id
)), self
::TYPE_SETTING
, null, null, new pix_icon('i/course', ''));
2684 $reporttab = $usercoursenode->add(get_string('activityreports'));
2686 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2687 foreach ($reportfunctions as $reportfunction) {
2688 $reportfunction($reporttab, $user, $usercourse);
2691 $reporttab->trim_if_empty();
2695 // Let plugins hook into user navigation.
2696 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2697 foreach ($pluginsfunction as $plugintype => $plugins) {
2698 if ($plugintype != 'report') {
2699 foreach ($plugins as $pluginfunction) {
2700 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2709 * This method simply checks to see if a given module can extend the navigation.
2711 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2713 * @param string $modname
2716 public static function module_extends_navigation($modname) {
2718 static $extendingmodules = array();
2719 if (!array_key_exists($modname, $extendingmodules)) {
2720 $extendingmodules[$modname] = false;
2721 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
2722 if (file_exists($file)) {
2723 $function = $modname.'_extend_navigation';
2724 require_once($file);
2725 $extendingmodules[$modname] = (function_exists($function));
2728 return $extendingmodules[$modname];
2731 * Extends the navigation for the given user.
2733 * @param stdClass $user A user from the database
2735 public function extend_for_user($user) {
2736 $this->extendforuser
[] = $user;
2740 * Returns all of the users the navigation is being extended for
2742 * @return array An array of extending users.
2744 public function get_extending_users() {
2745 return $this->extendforuser
;
2748 * Adds the given course to the navigation structure.
2750 * @param stdClass $course
2751 * @param bool $forcegeneric
2752 * @param bool $ismycourse
2753 * @return navigation_node
2755 public function add_course(stdClass
$course, $forcegeneric = false, $coursetype = self
::COURSE_OTHER
) {
2758 // We found the course... we can return it now :)
2759 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2760 return $this->addedcourses
[$course->id
];
2763 $coursecontext = context_course
::instance($course->id
);
2765 if ($coursetype != self
::COURSE_MY
&& $coursetype != self
::COURSE_CURRENT
&& $course->id
!= $SITE->id
) {
2766 if (is_role_switched($course->id
)) {
2767 // user has to be able to access course in order to switch, let's skip the visibility test here
2768 } else if (!core_course_category
::can_view_course_info($course)) {
2773 $issite = ($course->id
== $SITE->id
);
2774 $displaycontext = \context_helper
::get_navigation_filter_context($coursecontext);
2775 $shortname = format_string($course->shortname
, true, ['context' => $displaycontext]);
2776 $fullname = format_string($course->fullname
, true, ['context' => $displaycontext]);
2777 // This is the name that will be shown for the course.
2778 $coursename = empty($CFG->navshowfullcoursenames
) ?
$shortname : $fullname;
2780 if ($coursetype == self
::COURSE_CURRENT
) {
2781 if ($coursenode = $this->rootnodes
['mycourses']->find($course->id
, self
::TYPE_COURSE
)) {
2784 $coursetype = self
::COURSE_OTHER
;
2788 // Can the user expand the course to see its content.
2789 $canexpandcourse = true;
2793 if (empty($CFG->usesitenameforsitepages
)) {
2794 $coursename = get_string('sitepages');
2796 } else if ($coursetype == self
::COURSE_CURRENT
) {
2797 $parent = $this->rootnodes
['currentcourse'];
2798 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2799 $canexpandcourse = $this->can_expand_course($course);
2800 } else if ($coursetype == self
::COURSE_MY
&& !$forcegeneric) {
2801 if (!empty($CFG->navshowmycoursecategories
) && ($parent = $this->rootnodes
['mycourses']->find($course->category
, self
::TYPE_MY_CATEGORY
))) {
2802 // Nothing to do here the above statement set $parent to the category within mycourses.
2804 $parent = $this->rootnodes
['mycourses'];
2806 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2808 $parent = $this->rootnodes
['courses'];
2809 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
2810 // They can only expand the course if they can access it.
2811 $canexpandcourse = $this->can_expand_course($course);
2812 if (!empty($course->category
) && $this->show_categories($coursetype == self
::COURSE_MY
)) {
2813 if (!$this->is_category_fully_loaded($course->category
)) {
2814 // We need to load the category structure for this course
2815 $this->load_all_categories($course->category
, false);
2817 if (array_key_exists($course->category
, $this->addedcategories
)) {
2818 $parent = $this->addedcategories
[$course->category
];
2819 // This could lead to the course being created so we should check whether it is the case again
2820 if (!$forcegeneric && array_key_exists($course->id
, $this->addedcourses
)) {
2821 return $this->addedcourses
[$course->id
];
2827 $coursenode = $parent->add($coursename, $url, self
::TYPE_COURSE
, $shortname, $course->id
, new pix_icon('i/course', ''));
2828 $coursenode->showinflatnavigation
= $coursetype == self
::COURSE_MY
;
2830 $coursenode->hidden
= (!$course->visible
);
2831 $coursenode->title(format_string($course->fullname
, true, ['context' => $displaycontext, 'escape' => false]));
2832 if ($canexpandcourse) {
2833 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2834 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
2835 $coursenode->isexpandable
= true;
2837 $coursenode->nodetype
= self
::NODETYPE_LEAF
;
2838 $coursenode->isexpandable
= false;
2840 if (!$forcegeneric) {
2841 $this->addedcourses
[$course->id
] = $coursenode;
2848 * Returns a cache instance to use for the expand course cache.
2849 * @return cache_session
2851 protected function get_expand_course_cache() {
2852 if ($this->cacheexpandcourse
=== null) {
2853 $this->cacheexpandcourse
= cache
::make('core', 'navigation_expandcourse');
2855 return $this->cacheexpandcourse
;
2859 * Checks if a user can expand a course in the navigation.
2861 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2862 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2863 * permits stale data.
2864 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2866 * It is brought up to date in only one of two ways.
2867 * 1. The user logs out and in again.
2868 * 2. The user browses to the course they've just being given access to.
2870 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2872 * @param stdClass $course
2875 protected function can_expand_course($course) {
2876 $cache = $this->get_expand_course_cache();
2877 $canexpand = $cache->get($course->id
);
2878 if ($canexpand === false) {
2879 $canexpand = isloggedin() && can_access_course($course, null, '', true);
2880 $canexpand = (int)$canexpand;
2881 $cache->set($course->id
, $canexpand);
2883 return ($canexpand === 1);
2887 * Returns true if the category has already been loaded as have any child categories
2889 * @param int $categoryid
2892 protected function is_category_fully_loaded($categoryid) {
2893 return (array_key_exists($categoryid, $this->addedcategories
) && ($this->allcategoriesloaded ||
$this->addedcategories
[$categoryid]->children
->count() > 0));
2897 * Adds essential course nodes to the navigation for the given course.
2899 * This method adds nodes such as reports, blogs and participants
2901 * @param navigation_node $coursenode
2902 * @param stdClass $course
2903 * @return bool returns true on successful addition of a node.
2905 public function add_course_essentials($coursenode, stdClass
$course) {
2907 require_once($CFG->dirroot
. '/course/lib.php');
2909 if ($course->id
== $SITE->id
) {
2910 return $this->add_front_page_course_essentials($coursenode, $course);
2913 if ($coursenode == false ||
!($coursenode instanceof navigation_node
) ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
2917 $navoptions = course_get_user_navigation_options($this->page
->context
, $course);
2920 if ($navoptions->participants
) {
2921 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
),
2922 self
::TYPE_CONTAINER
, get_string('participants'), 'participants', new pix_icon('i/users', ''));
2924 if ($navoptions->blogs
) {
2925 $blogsurls = new moodle_url('/blog/index.php');
2926 if ($currentgroup = groups_get_course_group($course, true)) {
2927 $blogsurls->param('groupid', $currentgroup);
2929 $blogsurls->param('courseid', $course->id
);
2931 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self
::TYPE_SETTING
, null, 'courseblogs');
2934 if ($navoptions->notes
) {
2935 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id
)), self
::TYPE_SETTING
, null, 'currentcoursenotes');
2937 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
2938 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
2942 if ($navoptions->badges
) {
2943 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id
));
2945 $coursenode->add(get_string('coursebadges', 'badges'), $url,
2946 navigation_node
::TYPE_SETTING
, null, 'badgesview',
2947 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2950 // Check access to the course and competencies page.
2951 if ($navoptions->competencies
) {
2952 // Just a link to course competency.
2953 $title = get_string('competencies', 'core_competency');
2954 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id
));
2955 $coursenode->add($title, $path, navigation_node
::TYPE_SETTING
, null, 'competencies',
2956 new pix_icon('i/competencies', ''));
2958 if ($navoptions->grades
) {
2959 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
2960 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null,
2961 'grades', new pix_icon('i/grades', ''));
2962 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
2963 if ($this->page
->context
->contextlevel
< CONTEXT_MODULE
&& strpos($this->page
->pagetype
, 'grade-') === 0) {
2964 $gradenode->make_active();
2971 * This generates the structure of the course that won't be generated when
2972 * the modules and sections are added.
2974 * Things such as the reports branch, the participants branch, blogs... get
2975 * added to the course node by this method.
2977 * @param navigation_node $coursenode
2978 * @param stdClass $course
2979 * @return bool True for successfull generation
2981 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
2982 global $CFG, $USER, $COURSE, $SITE;
2983 require_once($CFG->dirroot
. '/course/lib.php');
2985 if ($coursenode == false ||
$coursenode->get('frontpageloaded', navigation_node
::TYPE_CUSTOM
)) {
2989 $systemcontext = context_system
::instance();
2990 $navoptions = course_get_user_navigation_options($systemcontext, $course);
2992 // Hidden node that we use to determine if the front page navigation is loaded.
2993 // This required as there are not other guaranteed nodes that may be loaded.
2994 $coursenode->add('frontpageloaded', null, self
::TYPE_CUSTOM
, null, 'frontpageloaded')->display
= false;
2996 // Add My courses to the site pages within the navigation structure so the block can read it.
2997 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self
::TYPE_CUSTOM
, null, 'mycourses');
3000 if ($navoptions->participants
) {
3001 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
),
3002 self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
3006 if ($navoptions->blogs
) {
3007 $blogsurls = new moodle_url('/blog/index.php');
3008 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self
::TYPE_SYSTEM
, null, 'siteblog');
3014 if ($navoptions->badges
) {
3015 $url = new moodle_url($CFG->wwwroot
. '/badges/view.php', array('type' => 1));
3016 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node
::TYPE_CUSTOM
);
3020 if ($navoptions->notes
) {
3021 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
3022 array('filtertype' => 'course', 'filterselect' => $filterselect)), self
::TYPE_SETTING
, null, 'notes');
3026 if ($navoptions->tags
) {
3027 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
3028 self
::TYPE_SETTING
, null, 'tags');
3032 if ($navoptions->search
) {
3033 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
3034 self
::TYPE_SETTING
, null, 'search');
3038 $usercontext = context_user
::instance($USER->id
);
3039 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
3040 $url = new moodle_url('/user/files.php');
3041 $node = $coursenode->add(get_string('privatefiles'), $url,
3042 self
::TYPE_SETTING
, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
3043 $node->display
= false;
3044 $node->showinflatnavigation
= true;
3049 $context = $this->page
->context
;
3050 switch ($context->contextlevel
) {
3051 case CONTEXT_COURSECAT
:
3052 // OK, expected context level.
3054 case CONTEXT_COURSE
:
3055 // OK, expected context level if not on frontpage.
3056 if ($COURSE->id
!= $SITE->id
) {
3060 // If this context is part of a course (excluding frontpage), use the course context.
3061 // Otherwise, use the system context.
3062 $coursecontext = $context->get_course_context(false);
3063 if ($coursecontext && $coursecontext->instanceid
!== $SITE->id
) {
3064 $context = $coursecontext;
3066 $context = $systemcontext;
3070 $params = ['contextid' => $context->id
];
3071 if (has_capability('moodle/contentbank:access', $context)) {
3072 $url = new moodle_url('/contentbank/index.php', $params);
3073 $node = $coursenode->add(get_string('contentbank'), $url,
3074 self
::TYPE_CUSTOM
, null, 'contentbank', new pix_icon('i/contentbank', ''));
3075 $node->showinflatnavigation
= true;
3083 * Clears the navigation cache
3085 public function clear_cache() {
3086 $this->cache
->clear();
3090 * Sets an expansion limit for the navigation
3092 * The expansion limit is used to prevent the display of content that has a type
3093 * greater than the provided $type.
3095 * Can be used to ensure things such as activities or activity content don't get
3096 * shown on the navigation.
3097 * They are still generated in order to ensure the navbar still makes sense.
3099 * @param int $type One of navigation_node::TYPE_*
3100 * @return bool true when complete.
3102 public function set_expansion_limit($type) {
3104 $nodes = $this->find_all_of_type($type);
3106 // We only want to hide specific types of nodes.
3107 // Only nodes that represent "structure" in the navigation tree should be hidden.
3108 // If we hide all nodes then we risk hiding vital information.
3109 $typestohide = array(
3110 self
::TYPE_CATEGORY
,
3116 foreach ($nodes as $node) {
3117 // We need to generate the full site node
3118 if ($type == self
::TYPE_COURSE
&& $node->key
== $SITE->id
) {
3121 foreach ($node->children
as $child) {
3122 $child->hide($typestohide);
3128 * Attempts to get the navigation with the given key from this nodes children.
3130 * This function only looks at this nodes children, it does NOT look recursivily.
3131 * If the node can't be found then false is returned.
3133 * If you need to search recursivily then use the {@link global_navigation::find()} method.
3135 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3136 * may be of more use to you.
3138 * @param string|int $key The key of the node you wish to receive.
3139 * @param int $type One of navigation_node::TYPE_*
3140 * @return navigation_node|false
3142 public function get($key, $type = null) {
3143 if (!$this->initialised
) {
3144 $this->initialise();
3146 return parent
::get($key, $type);
3150 * Searches this nodes children and their children to find a navigation node
3151 * with the matching key and type.
3153 * This method is recursive and searches children so until either a node is
3154 * found or there are no more nodes to search.
3156 * If you know that the node being searched for is a child of this node
3157 * then use the {@link global_navigation::get()} method instead.
3159 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
3160 * may be of more use to you.
3162 * @param string|int $key The key of the node you wish to receive.
3163 * @param int $type One of navigation_node::TYPE_*
3164 * @return navigation_node|false
3166 public function find($key, $type) {
3167 if (!$this->initialised
) {
3168 $this->initialise();
3170 if ($type == self
::TYPE_ROOTNODE
&& array_key_exists($key, $this->rootnodes
)) {
3171 return $this->rootnodes
[$key];
3173 return parent
::find($key, $type);
3177 * They've expanded the 'my courses' branch.
3179 protected function load_courses_enrolled() {
3182 $limit = (int) $CFG->navcourselimit
;
3184 $courses = enrol_get_my_courses('*');
3185 $flatnavcourses = [];
3187 // Go through the courses and see which ones we want to display in the flatnav.
3188 foreach ($courses as $course) {
3189 $classify = course_classify_for_timeline($course);
3191 if ($classify == COURSE_TIMELINE_INPROGRESS
) {
3192 $flatnavcourses[$course->id
] = $course;
3196 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3197 $numtotalcourses = count($courses);
3198 $numtotalflatnavcourses = count($flatnavcourses);
3200 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3201 $courses = array_slice($courses, 0, $limit, true);
3202 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3204 // Get the number of courses we are going to show for each.
3205 $numshowncourses = count($courses);
3206 $numshownflatnavcourses = count($flatnavcourses);
3207 if ($numshowncourses && $this->show_my_categories()) {
3208 // Generate an array containing unique values of all the courses' categories.
3209 $categoryids = array();
3210 foreach ($courses as $course) {
3211 if (in_array($course->category
, $categoryids)) {
3214 $categoryids[] = $course->category
;
3217 // Array of category IDs that include the categories of the user's courses and the related course categories.
3218 $fullpathcategoryids = [];
3219 // Get the course categories for the enrolled courses' category IDs.
3220 $mycoursecategories = core_course_category
::get_many($categoryids);
3221 // Loop over each of these categories and build the category tree using each category's path.
3222 foreach ($mycoursecategories as $mycoursecat) {
3223 $pathcategoryids = explode('/', $mycoursecat->path
);
3224 // First element of the exploded path is empty since paths begin with '/'.
3225 array_shift($pathcategoryids);
3226 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3227 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3230 // Fetch all of the categories related to the user's courses.
3231 $pathcategories = core_course_category
::get_many($fullpathcategoryids);
3232 // Loop over each of these categories and build the category tree.
3233 foreach ($pathcategories as $coursecat) {
3234 // No need to process categories that have already been added.
3235 if (isset($this->addedcategories
[$coursecat->id
])) {
3238 // Skip categories that are not visible.
3239 if (!$coursecat->is_uservisible()) {
3243 // Get this course category's parent node.
3245 if ($coursecat->parent
&& isset($this->addedcategories
[$coursecat->parent
])) {
3246 $parent = $this->addedcategories
[$coursecat->parent
];
3249 // If it has no parent, then it should be right under the My courses node.
3250 $parent = $this->rootnodes
['mycourses'];
3253 // Build the category object based from the coursecat object.
3254 $mycategory = new stdClass();
3255 $mycategory->id
= $coursecat->id
;
3256 $mycategory->name
= $coursecat->name
;
3257 $mycategory->visible
= $coursecat->visible
;
3259 // Add this category to the nav tree.
3260 $this->add_category($mycategory, $parent, self
::TYPE_MY_CATEGORY
);
3264 // Go through each course now and add it to the nav block, and the flatnav if applicable.
3265 foreach ($courses as $course) {
3266 $node = $this->add_course($course, false, self
::COURSE_MY
);
3268 $node->showinflatnavigation
= false;
3269 // Check if we should also add this to the flat nav as well.
3270 if (isset($flatnavcourses[$course->id
])) {
3271 $node->showinflatnavigation
= true;
3276 // Go through each course in the flatnav now.
3277 foreach ($flatnavcourses as $course) {
3278 // Check if we haven't already added it.
3279 if (!isset($courses[$course->id
])) {
3280 // Ok, add it to the flatnav only.
3281 $node = $this->add_course($course, false, self
::COURSE_MY
);
3282 $node->display
= false;
3283 $node->showinflatnavigation
= true;
3287 $showmorelinkinnav = $numtotalcourses > $numshowncourses;
3288 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses;
3289 // Show a link to the course page if there are more courses the user is enrolled in.
3290 if ($showmorelinkinnav ||
$showmorelinkinflatnav) {
3291 // Adding hash to URL so the link is not highlighted in the navigation when clicked.
3292 $url = new moodle_url('/my/');
3293 $parent = $this->rootnodes
['mycourses'];
3294 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self
::TYPE_CUSTOM
, null, self
::COURSE_INDEX_PAGE
);
3296 if ($showmorelinkinnav) {
3297 $coursenode->display
= true;
3300 if ($showmorelinkinflatnav) {
3301 $coursenode->showinflatnavigation
= true;
3308 * The global navigation class used especially for AJAX requests.
3310 * The primary methods that are used in the global navigation class have been overriden
3311 * to ensure that only the relevant branch is generated at the root of the tree.
3312 * This can be done because AJAX is only used when the backwards structure for the
3313 * requested branch exists.
3314 * This has been done only because it shortens the amounts of information that is generated
3315 * which of course will speed up the response time.. because no one likes laggy AJAX.
3318 * @category navigation
3319 * @copyright 2009 Sam Hemelryk
3320 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3322 class global_navigation_for_ajax
extends global_navigation
{
3324 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
3325 protected $branchtype;
3327 /** @var int the instance id */
3328 protected $instanceid;
3330 /** @var array Holds an array of expandable nodes */
3331 protected $expandable = array();
3334 * Constructs the navigation for use in an AJAX request
3336 * @param moodle_page $page moodle_page object
3337 * @param int $branchtype
3340 public function __construct($page, $branchtype, $id) {
3341 $this->page
= $page;
3342 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
3343 $this->children
= new navigation_node_collection();
3344 $this->branchtype
= $branchtype;
3345 $this->instanceid
= $id;
3346 $this->initialise();
3349 * Initialise the navigation given the type and id for the branch to expand.
3351 * @return array An array of the expandable nodes
3353 public function initialise() {
3356 if ($this->initialised ||
during_initial_install()) {
3357 return $this->expandable
;
3359 $this->initialised
= true;
3361 $this->rootnodes
= array();
3362 $this->rootnodes
['site'] = $this->add_course($SITE);
3363 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self
::TYPE_ROOTNODE
, null, 'mycourses');
3364 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
3365 // The courses branch is always displayed, and is always expandable (although may be empty).
3366 // This mimicks what is done during {@link global_navigation::initialise()}.
3367 $this->rootnodes
['courses']->isexpandable
= true;
3369 // Branchtype will be one of navigation_node::TYPE_*
3370 switch ($this->branchtype
) {
3372 if ($this->instanceid
=== 'mycourses') {
3373 $this->load_courses_enrolled();
3374 } else if ($this->instanceid
=== 'courses') {
3375 $this->load_courses_other();
3378 case self
::TYPE_CATEGORY
:
3379 $this->load_category($this->instanceid
);
3381 case self
::TYPE_MY_CATEGORY
:
3382 $this->load_category($this->instanceid
, self
::TYPE_MY_CATEGORY
);
3384 case self
::TYPE_COURSE
:
3385 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
3386 if (!can_access_course($course, null, '', true)) {
3387 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
3388 // add the course node and break. This leads to an empty node.
3389 $this->add_course($course);
3392 require_course_login($course, true, null, false, true);
3393 $this->page
->set_context(context_course
::instance($course->id
));
3394 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3395 $this->add_course_essentials($coursenode, $course);
3396 $this->load_course_sections($course, $coursenode);
3398 case self
::TYPE_SECTION
:
3399 $sql = 'SELECT c.*, cs.section AS sectionnumber
3401 LEFT JOIN {course_sections} cs ON cs.course = c.id
3403 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
3404 require_course_login($course, true, null, false, true);
3405 $this->page
->set_context(context_course
::instance($course->id
));
3406 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3407 $this->add_course_essentials($coursenode, $course);
3408 $this->load_course_sections($course, $coursenode, $course->sectionnumber
);
3410 case self
::TYPE_ACTIVITY
:
3413 JOIN {course_modules} cm ON cm.course = c.id
3414 WHERE cm.id = :cmid";
3415 $params = array('cmid' => $this->instanceid
);
3416 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
3417 $modinfo = get_fast_modinfo($course);
3418 $cm = $modinfo->get_cm($this->instanceid
);
3419 require_course_login($course, true, $cm, false, true);
3420 $this->page
->set_context(context_module
::instance($cm->id
));
3421 $coursenode = $this->add_course($course, false, self
::COURSE_CURRENT
);
3422 $this->load_course_sections($course, $coursenode, null, $cm);
3423 $activitynode = $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
);
3424 if ($activitynode) {
3425 $modulenode = $this->load_activity($cm, $course, $activitynode);
3429 throw new Exception('Unknown type');
3430 return $this->expandable
;
3433 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= $SITE->id
) {
3434 $this->load_for_user(null, true);
3437 // Give the local plugins a chance to include some navigation if they want.
3438 $this->load_local_plugin_navigation();
3440 $this->find_expandable($this->expandable
);
3441 return $this->expandable
;
3445 * They've expanded the general 'courses' branch.
3447 protected function load_courses_other() {
3448 $this->load_all_courses();
3452 * Loads a single category into the AJAX navigation.
3454 * This function is special in that it doesn't concern itself with the parent of
3455 * the requested category or its siblings.
3456 * This is because with the AJAX navigation we know exactly what is wanted and only need to
3459 * @global moodle_database $DB
3460 * @param int $categoryid id of category to load in navigation.
3461 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
3464 protected function load_category($categoryid, $nodetype = self
::TYPE_CATEGORY
) {
3468 if (!empty($CFG->navcourselimit
)) {
3469 $limit = (int)$CFG->navcourselimit
;
3472 $catcontextsql = context_helper
::get_preload_record_columns_sql('ctx');
3473 $sql = "SELECT cc.*, $catcontextsql
3474 FROM {course_categories} cc
3475 JOIN {context} ctx ON cc.id = ctx.instanceid
3476 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT
." AND
3477 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
3478 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
3479 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
3480 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
3481 $categorylist = array();
3482 $subcategories = array();
3483 $basecategory = null;
3484 foreach ($categories as $category) {
3485 $categorylist[] = $category->id
;
3486 context_helper
::preload_from_record($category);
3487 if ($category->id
== $categoryid) {
3488 $this->add_category($category, $this, $nodetype);
3489 $basecategory = $this->addedcategories
[$category->id
];
3491 $subcategories[$category->id
] = $category;
3494 $categories->close();
3497 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
3498 // else show all courses.
3499 if ($nodetype === self
::TYPE_MY_CATEGORY
) {
3500 $courses = enrol_get_my_courses('*');
3501 $categoryids = array();
3503 // Only search for categories if basecategory was found.
3504 if (!is_null($basecategory)) {
3505 // Get course parent category ids.
3506 foreach ($courses as $course) {
3507 $categoryids[] = $course->category
;
3510 // Get a unique list of category ids which a part of the path
3511 // to user's courses.
3512 $coursesubcategories = array();
3513 $addedsubcategories = array();
3515 list($sql, $params) = $DB->get_in_or_equal($categoryids);
3516 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
3518 foreach ($categories as $category){
3519 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path
, "/")));
3521 $categories->close();
3522 $coursesubcategories = array_unique($coursesubcategories);
3524 // Only add a subcategory if it is part of the path to user's course and
3525 // wasn't already added.
3526 foreach ($subcategories as $subid => $subcategory) {
3527 if (in_array($subid, $coursesubcategories) &&
3528 !in_array($subid, $addedsubcategories)) {
3529 $this->add_category($subcategory, $basecategory, $nodetype);
3530 $addedsubcategories[] = $subid;
3535 foreach ($courses as $course) {
3536 // Add course if it's in category.
3537 if (in_array($course->category
, $categorylist)) {
3538 $this->add_course($course, true, self
::COURSE_MY
);
3542 if (!is_null($basecategory)) {
3543 foreach ($subcategories as $key=>$category) {
3544 $this->add_category($category, $basecategory, $nodetype);
3547 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
3548 foreach ($courses as $course) {
3549 $this->add_course($course);
3556 * Returns an array of expandable nodes
3559 public function get_expandable() {
3560 return $this->expandable
;
3567 * This class is used to manage the navbar, which is initialised from the navigation
3568 * object held by PAGE
3571 * @category navigation
3572 * @copyright 2009 Sam Hemelryk
3573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3575 class navbar
extends navigation_node
{
3576 /** @var bool A switch for whether the navbar is initialised or not */
3577 protected $initialised = false;
3578 /** @var mixed keys used to reference the nodes on the navbar */
3579 protected $keys = array();
3580 /** @var null|string content of the navbar */
3581 protected $content = null;
3582 /** @var moodle_page object the moodle page that this navbar belongs to */
3584 /** @var bool A switch for whether to ignore the active navigation information */
3585 protected $ignoreactive = false;
3586 /** @var bool A switch to let us know if we are in the middle of an install */
3587 protected $duringinstall = false;
3588 /** @var bool A switch for whether the navbar has items */
3589 protected $hasitems = false;
3590 /** @var array An array of navigation nodes for the navbar */
3592 /** @var array An array of child node objects */
3593 public $children = array();
3594 /** @var bool A switch for whether we want to include the root node in the navbar */
3595 public $includesettingsbase = false;
3596 /** @var breadcrumb_navigation_node[] $prependchildren */
3597 protected $prependchildren = array();
3600 * The almighty constructor
3602 * @param moodle_page $page
3604 public function __construct(moodle_page
$page) {
3606 if (during_initial_install()) {
3607 $this->duringinstall
= true;
3610 $this->page
= $page;
3611 $this->text
= get_string('home');
3612 $this->shorttext
= get_string('home');
3613 $this->action
= new moodle_url($CFG->wwwroot
);
3614 $this->nodetype
= self
::NODETYPE_BRANCH
;
3615 $this->type
= self
::TYPE_SYSTEM
;
3619 * Quick check to see if the navbar will have items in.
3621 * @return bool Returns true if the navbar will have items, false otherwise
3623 public function has_items() {
3624 if ($this->duringinstall
) {
3626 } else if ($this->hasitems
!== false) {
3629 if (count($this->children
) > 0 ||
count($this->prependchildren
) > 0) {
3630 // There have been manually added items - there are definitely items.
3632 } else if (!$this->ignoreactive
) {
3633 // We will need to initialise the navigation structure to check if there are active items.
3634 $this->page
->navigation
->initialise($this->page
);
3635 $outcome = ($this->page
->navigation
->contains_active_node() ||
$this->page
->settingsnav
->contains_active_node());
3637 $this->hasitems
= $outcome;
3642 * Turn on/off ignore active
3644 * @param bool $setting
3646 public function ignore_active($setting=true) {
3647 $this->ignoreactive
= ($setting);
3651 * Gets a navigation node
3653 * @param string|int $key for referencing the navbar nodes
3654 * @param int $type breadcrumb_navigation_node::TYPE_*
3655 * @return breadcrumb_navigation_node|bool
3657 public function get($key, $type = null) {
3658 foreach ($this->children
as &$child) {
3659 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3663 foreach ($this->prependchildren
as &$child) {
3664 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
3671 * Returns an array of breadcrumb_navigation_nodes that make up the navbar.
3675 public function get_items() {
3678 // Make sure that navigation is initialised
3679 if (!$this->has_items()) {
3682 if ($this->items
!== null) {
3683 return $this->items
;
3686 if (count($this->children
) > 0) {
3687 // Add the custom children.
3688 $items = array_reverse($this->children
);
3691 // Check if navigation contains the active node
3692 if (!$this->ignoreactive
) {
3693 // We will need to ensure the navigation has been initialised.
3694 $this->page
->navigation
->initialise($this->page
);
3695 // Now find the active nodes on both the navigation and settings.
3696 $navigationactivenode = $this->page
->navigation
->find_active_node();
3697 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
3699 if ($navigationactivenode && $settingsactivenode) {
3700 // Parse a combined navigation tree
3701 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3702 if (!$settingsactivenode->mainnavonly
) {
3703 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3705 $settingsactivenode = $settingsactivenode->parent
;
3707 if (!$this->includesettingsbase
) {
3708 // Removes the first node from the settings (root node) from the list
3711 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3712 if (!$navigationactivenode->mainnavonly
) {
3713 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3715 if (!empty($CFG->navshowcategories
) &&
3716 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3717 $navigationactivenode->parent
->key
=== 'currentcourse') {
3718 foreach ($this->get_course_categories() as $item) {
3719 $items[] = new breadcrumb_navigation_node($item);
3722 $navigationactivenode = $navigationactivenode->parent
;
3724 } else if ($navigationactivenode) {
3725 // Parse the navigation tree to get the active node
3726 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
3727 if (!$navigationactivenode->mainnavonly
) {
3728 $items[] = new breadcrumb_navigation_node($navigationactivenode);
3730 if (!empty($CFG->navshowcategories
) &&
3731 $navigationactivenode->type
=== self
::TYPE_COURSE
&&
3732 $navigationactivenode->parent
->key
=== 'currentcourse') {
3733 foreach ($this->get_course_categories() as $item) {
3734 $items[] = new breadcrumb_navigation_node($item);
3737 $navigationactivenode = $navigationactivenode->parent
;
3739 } else if ($settingsactivenode) {
3740 // Parse the settings navigation to get the active node
3741 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
3742 if (!$settingsactivenode->mainnavonly
) {
3743 $items[] = new breadcrumb_navigation_node($settingsactivenode);
3745 $settingsactivenode = $settingsactivenode->parent
;
3750 $items[] = new breadcrumb_navigation_node(array(
3751 'text' => $this->page
->navigation
->text
,
3752 'shorttext' => $this->page
->navigation
->shorttext
,
3753 'key' => $this->page
->navigation
->key
,
3754 'action' => $this->page
->navigation
->action
3757 if (count($this->prependchildren
) > 0) {
3758 // Add the custom children
3759 $items = array_merge($items, array_reverse($this->prependchildren
));
3762 $last = reset($items);
3764 $last->set_last(true);
3766 $this->items
= array_reverse($items);
3767 return $this->items
;
3771 * Get the list of categories leading to this course.
3773 * This function is used by {@link navbar::get_items()} to add back the "courses"
3774 * node and category chain leading to the current course. Note that this is only ever
3775 * called for the current course, so we don't need to bother taking in any parameters.
3779 private function get_course_categories() {
3781 require_once($CFG->dirroot
.'/course/lib.php');
3783 $categories = array();
3784 $cap = 'moodle/category:viewhiddencategories';
3785 $showcategories = !core_course_category
::is_simple_site();
3787 if ($showcategories) {
3788 foreach ($this->page
->categories
as $category) {
3789 $context = context_coursecat
::instance($category->id
);
3790 if (!core_course_category
::can_view_category($category)) {
3794 $displaycontext = \context_helper
::get_navigation_filter_context($context);
3795 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id
]);
3796 $name = format_string($category->name
, true, ['context' => $displaycontext]);
3797 $categorynode = breadcrumb_navigation_node
::create($name, $url, self
::TYPE_CATEGORY
, null, $category->id
);
3798 if (!$category->visible
) {
3799 $categorynode->hidden
= true;
3801 $categories[] = $categorynode;
3805 // Don't show the 'course' node if enrolled in this course.
3806 $coursecontext = context_course
::instance($this->page
->course
->id
);
3807 if (!is_enrolled($coursecontext, null, '', true)) {
3808 $courses = $this->page
->navigation
->get('courses');
3810 // Courses node may not be present.
3811 $courses = breadcrumb_navigation_node
::create(
3812 get_string('courses'),
3813 new moodle_url('/course/index.php'),
3814 self
::TYPE_CONTAINER
3817 $categories[] = $courses;
3824 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add
3826 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change
3827 * the way nodes get added to allow us to simply call add and have the node added to the
3830 * @param string $text
3831 * @param string|moodle_url|action_link $action An action to associate with this node.
3832 * @param int $type One of navigation_node::TYPE_*
3833 * @param string $shorttext
3834 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3835 * @param pix_icon $icon An optional icon to use for this node.
3836 * @return navigation_node
3838 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3839 if ($this->content
!== null) {
3840 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3843 // Properties array used when creating the new navigation node
3848 // Set the action if one was provided
3849 if ($action!==null) {
3850 $itemarray['action'] = $action;
3852 // Set the shorttext if one was provided
3853 if ($shorttext!==null) {
3854 $itemarray['shorttext'] = $shorttext;
3856 // Set the icon if one was provided
3858 $itemarray['icon'] = $icon;
3860 // Default the key to the number of children if not provided
3861 if ($key === null) {
3862 $key = count($this->children
);
3865 $itemarray['key'] = $key;
3866 // Set the parent to this node
3867 $itemarray['parent'] = $this;
3868 // Add the child using the navigation_node_collections add method
3869 $this->children
[] = new breadcrumb_navigation_node($itemarray);
3874 * Prepends a new navigation_node to the start of the navbar
3876 * @param string $text
3877 * @param string|moodle_url|action_link $action An action to associate with this node.
3878 * @param int $type One of navigation_node::TYPE_*
3879 * @param string $shorttext
3880 * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3881 * @param pix_icon $icon An optional icon to use for this node.
3882 * @return navigation_node
3884 public function prepend($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
3885 if ($this->content
!== null) {
3886 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
3888 // Properties array used when creating the new navigation node.
3893 // Set the action if one was provided.
3894 if ($action!==null) {
3895 $itemarray['action'] = $action;
3897 // Set the shorttext if one was provided.
3898 if ($shorttext!==null) {
3899 $itemarray['shorttext'] = $shorttext;
3901 // Set the icon if one was provided.
3903 $itemarray['icon'] = $icon;
3905 // Default the key to the number of children if not provided.
3906 if ($key === null) {
3907 $key = count($this->children
);
3910 $itemarray['key'] = $key;
3911 // Set the parent to this node.
3912 $itemarray['parent'] = $this;
3913 // Add the child node to the prepend list.
3914 $this->prependchildren
[] = new breadcrumb_navigation_node($itemarray);
3920 * Subclass of navigation_node allowing different rendering for the breadcrumbs
3921 * in particular adding extra metadata for search engine robots to leverage.
3924 * @category navigation
3925 * @copyright 2015 Brendan Heywood
3926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3928 class breadcrumb_navigation_node
extends navigation_node
{
3930 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
3931 private $last = false;
3934 * A proxy constructor
3936 * @param mixed $navnode A navigation_node or an array
3938 public function __construct($navnode) {
3939 if (is_array($navnode)) {
3940 parent
::__construct($navnode);
3941 } else if ($navnode instanceof navigation_node
) {
3943 // Just clone everything.
3944 $objvalues = get_object_vars($navnode);
3945 foreach ($objvalues as $key => $value) {
3946 $this->$key = $value;
3949 throw new coding_exception('Not a valid breadcrumb_navigation_node');
3957 public function is_last() {
3963 * @param $val boolean
3965 public function set_last($val) {
3971 * Subclass of navigation_node allowing different rendering for the flat navigation
3972 * in particular allowing dividers and indents.
3975 * @category navigation
3976 * @copyright 2016 Damyon Wiese
3977 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3979 class flat_navigation_node
extends navigation_node
{
3981 /** @var $indent integer The indent level */
3982 private $indent = 0;
3984 /** @var $showdivider bool Show a divider before this element */
3985 private $showdivider = false;
3987 /** @var $collectionlabel string Label for a group of nodes */
3988 private $collectionlabel = '';
3991 * A proxy constructor
3993 * @param mixed $navnode A navigation_node or an array
3995 public function __construct($navnode, $indent) {
3996 if (is_array($navnode)) {
3997 parent
::__construct($navnode);
3998 } else if ($navnode instanceof navigation_node
) {
4000 // Just clone everything.
4001 $objvalues = get_object_vars($navnode);
4002 foreach ($objvalues as $key => $value) {
4003 $this->$key = $value;
4006 throw new coding_exception('Not a valid flat_navigation_node');
4008 $this->indent
= $indent;
4012 * Setter, a label is required for a flat navigation node that shows a divider.
4014 * @param string $label
4016 public function set_collectionlabel($label) {
4017 $this->collectionlabel
= $label;
4021 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one.
4025 public function get_collectionlabel() {
4026 if (!empty($this->collectionlabel
)) {
4027 return $this->collectionlabel
;
4029 if ($this->parent
&& ($this->parent
instanceof flat_navigation_node ||
$this->parent
instanceof flat_navigation
)) {
4030 return $this->parent
->get_collectionlabel();
4032 debugging('Navigation region requires a label', DEBUG_DEVELOPER
);
4037 * Does this node represent a course section link.
4040 public function is_section() {
4041 return $this->type
== navigation_node
::TYPE_SECTION
;
4045 * In flat navigation - sections are active if we are looking at activities in the section.
4048 public function isactive() {
4051 if ($this->is_section()) {
4052 $active = $PAGE->navigation
->find_active_node();
4054 while ($active = $active->parent
) {
4055 if ($active->key
== $this->key
&& $active->type
== $this->type
) {
4061 return $this->isactive
;
4065 * Getter for "showdivider"
4068 public function showdivider() {
4069 return $this->showdivider
;
4073 * Setter for "showdivider"
4074 * @param $val boolean
4075 * @param $label string Label for the group of nodes
4077 public function set_showdivider($val, $label = '') {
4078 $this->showdivider
= $val;
4079 if ($this->showdivider
&& empty($label)) {
4080 debugging('Navigation region requires a label', DEBUG_DEVELOPER
);
4082 $this->set_collectionlabel($label);
4087 * Getter for "indent"
4090 public function get_indent() {
4091 return $this->indent
;
4095 * Setter for "indent"
4096 * @param $val boolean
4098 public function set_indent($val) {
4099 $this->indent
= $val;
4104 * Class used to generate a collection of navigation nodes most closely related
4105 * to the current page.
4108 * @copyright 2016 Damyon Wiese
4109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4111 class flat_navigation
extends navigation_node_collection
{
4112 /** @var moodle_page the moodle page that the navigation belongs to */
4118 * @param moodle_page $page
4120 public function __construct(moodle_page
&$page) {
4121 if (during_initial_install()) {
4124 $this->page
= $page;
4128 * Build the list of navigation nodes based on the current navigation and settings trees.
4131 public function initialise() {
4132 global $PAGE, $USER, $OUTPUT, $CFG;
4133 if (during_initial_install()) {
4139 $course = $PAGE->course
;
4141 $this->page
->navigation
->initialise();
4143 // First walk the nav tree looking for "flat_navigation" nodes.
4144 if ($course->id
> 1) {
4145 // It's a real course.
4146 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
4148 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
4149 $displaycontext = \context_helper
::get_navigation_filter_context($coursecontext);
4150 // This is the name that will be shown for the course.
4151 $coursename = empty($CFG->navshowfullcoursenames
) ?
4152 format_string($course->shortname
, true, ['context' => $displaycontext]) :
4153 format_string($course->fullname
, true, ['context' => $displaycontext]);
4155 $flat = new flat_navigation_node(navigation_node
::create($coursename, $url), 0);
4156 $flat->set_collectionlabel($coursename);
4157 $flat->key
= 'coursehome';
4158 $flat->icon
= new pix_icon('i/course', '');
4160 $courseformat = course_get_format($course);
4161 $coursenode = $PAGE->navigation
->find_active_node();
4162 $targettype = navigation_node
::TYPE_COURSE
;
4164 // Single activity format has no course node - the course node is swapped for the activity node.
4165 if (!$courseformat->has_view_page()) {
4166 $targettype = navigation_node
::TYPE_ACTIVITY
;
4169 while (!empty($coursenode) && ($coursenode->type
!= $targettype)) {
4170 $coursenode = $coursenode->parent
;
4172 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
4173 // context at the same time. That page is broken but we need to handle it (hence the SITEID).
4174 if ($coursenode && $coursenode->key
!= SITEID
) {
4176 foreach ($coursenode->children
as $child) {
4177 if ($child->action
) {
4178 $flat = new flat_navigation_node($child, 0);
4184 $this->page
->navigation
->build_flat_navigation_list($this, true, get_string('site'));
4186 $this->page
->navigation
->build_flat_navigation_list($this, false, get_string('site'));
4189 $admin = $PAGE->settingsnav
->find('siteadministration', navigation_node
::TYPE_SITE_ADMIN
);
4191 // Try again - crazy nav tree!
4192 $admin = $PAGE->settingsnav
->find('root', navigation_node
::TYPE_SITE_ADMIN
);
4195 $flat = new flat_navigation_node($admin, 0);
4196 $flat->set_showdivider(true, get_string('sitesettings'));
4197 $flat->key
= 'sitesettings';
4198 $flat->icon
= new pix_icon('t/preferences', '');
4204 * Override the parent so we can set a label for this collection if it has not been set yet.
4206 * @param navigation_node $node Node to add
4207 * @param string $beforekey If specified, adds before a node with this key,
4208 * otherwise adds at end
4209 * @return navigation_node Added node
4211 public function add(navigation_node
$node, $beforekey=null) {
4212 $result = parent
::add($node, $beforekey);
4213 // Extend the parent to get a name for the collection of nodes if required.
4214 if (empty($this->collectionlabel
)) {
4215 if ($node instanceof flat_navigation_node
) {
4216 $this->set_collectionlabel($node->get_collectionlabel());
4225 * Class used to manage the settings option for the current page
4227 * This class is used to manage the settings options in a tree format (recursively)
4228 * and was created initially for use with the settings blocks.
4231 * @category navigation
4232 * @copyright 2009 Sam Hemelryk
4233 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4235 class settings_navigation
extends navigation_node
{
4236 /** @var stdClass the current context */
4238 /** @var moodle_page the moodle page that the navigation belongs to */
4240 /** @var string contains administration section navigation_nodes */
4241 protected $adminsection;
4242 /** @var bool A switch to see if the navigation node is initialised */
4243 protected $initialised = false;
4244 /** @var array An array of users that the nodes can extend for. */
4245 protected $userstoextendfor = array();
4246 /** @var navigation_cache **/
4250 * Sets up the object with basic settings and preparse it for use
4252 * @param moodle_page $page
4254 public function __construct(moodle_page
&$page) {
4255 if (during_initial_install()) {
4258 $this->page
= $page;
4259 // Initialise the main navigation. It is most important that this is done
4260 // before we try anything
4261 $this->page
->navigation
->initialise();
4262 // Initialise the navigation cache
4263 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
4264 $this->children
= new navigation_node_collection();
4268 * Initialise the settings navigation based on the current context
4270 * This function initialises the settings navigation tree for a given context
4271 * by calling supporting functions to generate major parts of the tree.
4274 public function initialise() {
4275 global $DB, $SESSION, $SITE;
4277 if (during_initial_install()) {
4279 } else if ($this->initialised
) {
4282 $this->id
= 'settingsnav';
4283 $this->context
= $this->page
->context
;
4285 $context = $this->context
;
4286 if ($context->contextlevel
== CONTEXT_BLOCK
) {
4287 $this->load_block_settings();
4288 $context = $context->get_parent_context();
4289 $this->context
= $context;
4291 switch ($context->contextlevel
) {
4292 case CONTEXT_SYSTEM
:
4293 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
4294 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4297 case CONTEXT_COURSECAT
:
4298 $this->load_category_settings();
4300 case CONTEXT_COURSE
:
4301 if ($this->page
->course
->id
!= $SITE->id
) {
4302 $this->load_course_settings(($context->id
== $this->context
->id
));
4304 $this->load_front_page_settings(($context->id
== $this->context
->id
));
4307 case CONTEXT_MODULE
:
4308 $this->load_module_settings();
4309 $this->load_course_settings();
4312 if ($this->page
->course
->id
!= $SITE->id
) {
4313 $this->load_course_settings();
4318 $usersettings = $this->load_user_settings($this->page
->course
->id
);
4320 $adminsettings = false;
4321 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin
) ||
$SESSION->load_navigation_admin
)) {
4322 $isadminpage = $this->is_admin_tree_needed();
4324 if (has_capability('moodle/site:configview', context_system
::instance())) {
4325 if (has_capability('moodle/site:config', context_system
::instance())) {
4326 // Make sure this works even if config capability changes on the fly
4327 // and also make it fast for admin right after login.
4328 $SESSION->load_navigation_admin
= 1;
4330 $adminsettings = $this->load_administration_settings();
4333 } else if (!isset($SESSION->load_navigation_admin
)) {
4334 $adminsettings = $this->load_administration_settings();
4335 $SESSION->load_navigation_admin
= (int)($adminsettings->children
->count() > 0);
4337 } else if ($SESSION->load_navigation_admin
) {
4339 $adminsettings = $this->load_administration_settings();
4343 // Print empty navigation node, if needed.
4344 if ($SESSION->load_navigation_admin
&& !$isadminpage) {
4345 if ($adminsettings) {
4346 // Do not print settings tree on pages that do not need it, this helps with performance.
4347 $adminsettings->remove();
4348 $adminsettings = false;
4350 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'),
4351 self
::TYPE_SITE_ADMIN
, null, 'siteadministration');
4352 $siteadminnode->id
= 'expandable_branch_' . $siteadminnode->type
. '_' .
4353 clean_param($siteadminnode->key
, PARAM_ALPHANUMEXT
);
4354 $siteadminnode->requiresajaxloading
= 'true';
4359 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $adminsettings) {
4360 $adminsettings->force_open();
4361 } else if ($context->contextlevel
== CONTEXT_USER
&& $usersettings) {
4362 $usersettings->force_open();
4365 // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
4366 $this->load_local_plugin_settings();
4368 foreach ($this->children
as $key=>$node) {
4369 if ($node->nodetype
== self
::NODETYPE_BRANCH
&& $node->children
->count() == 0) {
4370 // Site administration is shown as link.
4371 if (!empty($SESSION->load_navigation_admin
) && ($node->type
=== self
::TYPE_SITE_ADMIN
)) {
4377 $this->initialised
= true;
4380 * Override the parent function so that we can add preceeding hr's and set a
4381 * root node class against all first level element
4383 * It does this by first calling the parent's add method {@link navigation_node::add()}
4384 * and then proceeds to use the key to set class and hr
4386 * @param string $text text to be used for the link.
4387 * @param string|moodle_url $url url for the new node
4388 * @param int $type the type of node navigation_node::TYPE_*
4389 * @param string $shorttext
4390 * @param string|int $key a key to access the node by.
4391 * @param pix_icon $icon An icon that appears next to the node.
4392 * @return navigation_node with the new node added to it.
4394 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4395 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
4396 $node->add_class('root_node');
4401 * This function allows the user to add something to the start of the settings
4402 * navigation, which means it will be at the top of the settings navigation block
4404 * @param string $text text to be used for the link.
4405 * @param string|moodle_url $url url for the new node
4406 * @param int $type the type of node navigation_node::TYPE_*
4407 * @param string $shorttext
4408 * @param string|int $key a key to access the node by.
4409 * @param pix_icon $icon An icon that appears next to the node.
4410 * @return navigation_node $node with the new node added to it.
4412 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
4413 $children = $this->children
;
4414 $childrenclass = get_class($children);
4415 $this->children
= new $childrenclass;
4416 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
4417 foreach ($children as $child) {
4418 $this->children
->add($child);
4424 * Does this page require loading of full admin tree or is
4425 * it enough rely on AJAX?
4429 protected function is_admin_tree_needed() {
4430 if (self
::$loadadmintree) {
4431 // Usually external admin page or settings page.
4435 if ($this->page
->pagelayout
=== 'admin' or strpos($this->page
->pagetype
, 'admin-') === 0) {
4436 // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
4437 if ($this->page
->context
->contextlevel
!= CONTEXT_SYSTEM
) {
4447 * Load the site administration tree
4449 * This function loads the site administration tree by using the lib/adminlib library functions
4451 * @param navigation_node $referencebranch A reference to a branch in the settings
4453 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
4454 * tree and start at the beginning
4455 * @return mixed A key to access the admin tree by
4457 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
4460 // Check if we are just starting to generate this navigation.
4461 if ($referencebranch === null) {
4463 // Require the admin lib then get an admin structure
4464 if (!function_exists('admin_get_root')) {
4465 require_once($CFG->dirroot
.'/lib/adminlib.php');
4467 $adminroot = admin_get_root(false, false);
4468 // This is the active section identifier
4469 $this->adminsection
= $this->page
->url
->param('section');
4471 // Disable the navigation from automatically finding the active node
4472 navigation_node
::$autofindactive = false;
4473 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self
::TYPE_SITE_ADMIN
, null, 'root');
4474 foreach ($adminroot->children
as $adminbranch) {
4475 $this->load_administration_settings($referencebranch, $adminbranch);
4477 navigation_node
::$autofindactive = true;
4479 // Use the admin structure to locate the active page
4480 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
4481 $currentnode = $this;
4482 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
4483 $currentnode = $currentnode->get($pathkey);
4486 $currentnode->make_active();
4489 $this->scan_for_active_node($referencebranch);
4491 return $referencebranch;
4492 } else if ($adminbranch->check_access()) {
4493 // We have a reference branch that we can access and is not hidden `hurrah`
4494 // Now we need to display it and any children it may have
4498 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page
) {
4499 if (empty($CFG->linkadmincategories
) && $adminbranch instanceof admin_category
) {
4502 $url = $adminbranch->get_settings_page_url();
4507 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
4509 if ($adminbranch->is_hidden()) {
4510 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
4511 $reference->add_class('hidden');
4513 $reference->display
= false;
4517 // Check if we are generating the admin notifications and whether notificiations exist
4518 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
4519 $reference->add_class('criticalnotification');
4521 // Check if this branch has children
4522 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
4523 foreach ($adminbranch->children
as $branch) {
4524 // Generate the child branches as well now using this branch as the reference
4525 $this->load_administration_settings($reference, $branch);
4528 $reference->icon
= new pix_icon('i/settings', '');
4534 * This function recursivily scans nodes until it finds the active node or there
4535 * are no more nodes.
4536 * @param navigation_node $node
4538 protected function scan_for_active_node(navigation_node
$node) {
4539 if (!$node->check_if_active() && $node->children
->count()>0) {
4540 foreach ($node->children
as &$child) {
4541 $this->scan_for_active_node($child);
4547 * Gets a navigation node given an array of keys that represent the path to
4550 * @param array $path
4551 * @return navigation_node|false
4553 protected function get_by_path(array $path) {
4554 $node = $this->get(array_shift($path));
4555 foreach ($path as $key) {
4562 * This function loads the course settings that are available for the user
4564 * @param bool $forceopen If set to true the course node will be forced open
4565 * @return navigation_node|false
4567 protected function load_course_settings($forceopen = false) {
4569 require_once($CFG->dirroot
. '/course/lib.php');
4571 $course = $this->page
->course
;
4572 $coursecontext = context_course
::instance($course->id
);
4573 $adminoptions = course_get_user_administration_options($course, $coursecontext);
4575 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
4577 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
4579 $coursenode->force_open();
4583 if ($adminoptions->update
) {
4584 // Add the course settings link
4585 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
4586 $coursenode->add(get_string('settings'), $url, self
::TYPE_SETTING
, null,
4587 'editsettings', new pix_icon('i/settings', ''));
4590 if ($adminoptions->editcompletion
) {
4591 // Add the course completion settings link
4592 $url = new moodle_url('/course/completion.php', array('id' => $course->id
));
4593 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self
::TYPE_SETTING
, null, 'coursecompletion',
4594 new pix_icon('i/settings', ''));
4597 if (!$adminoptions->update
&& $adminoptions->tags
) {
4598 $url = new moodle_url('/course/tags.php', array('id' => $course->id
));
4599 $coursenode->add(get_string('coursetags', 'tag'), $url, self
::TYPE_SETTING
, null, 'coursetags', new pix_icon('i/settings', ''));
4600 $coursenode->get('coursetags')->set_force_into_more_menu();
4604 enrol_add_course_navigation($coursenode, $course);
4607 if ($adminoptions->filters
) {
4608 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
4609 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
,
4610 null, 'filtermanagement', new pix_icon('i/filter', ''));
4613 // View course reports.
4614 if ($adminoptions->reports
) {
4615 $reportnav = $coursenode->add(get_string('reports'),
4616 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid
]),
4617 self
::TYPE_CONTAINER
, null, 'coursereports', new pix_icon('i/stats', ''));
4618 $coursereports = core_component
::get_plugin_list('coursereport');
4619 foreach ($coursereports as $report => $dir) {
4620 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
4621 if (file_exists($libfile)) {
4622 require_once($libfile);
4623 $reportfunction = $report.'_report_extend_navigation';
4624 if (function_exists($report.'_report_extend_navigation')) {
4625 $reportfunction($reportnav, $course, $coursecontext);
4630 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
4631 foreach ($reports as $reportfunction) {
4632 $reportfunction($reportnav, $course, $coursecontext);
4636 // Check if we can view the gradebook's setup page.
4637 if ($adminoptions->gradebook
) {
4638 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id
));
4639 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self
::TYPE_SETTING
,
4640 null, 'gradebooksetup', new pix_icon('i/settings', ''));
4643 // Add the context locking node.
4644 $this->add_context_locking_node($coursenode, $coursecontext);
4646 // Add outcome if permitted
4647 if ($adminoptions->outcomes
) {
4648 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
4649 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
4652 //Add badges navigation
4653 if ($adminoptions->badges
) {
4654 require_once($CFG->libdir
.'/badgeslib.php');
4655 badges_add_course_navigation($coursenode, $course);
4658 // Import data from other courses.
4659 if ($adminoptions->import
) {
4660 $url = new moodle_url('/backup/import.php', array('id' => $course->id
));
4661 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/import', ''));
4664 // Backup this course
4665 if ($adminoptions->backup
) {
4666 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
4667 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
4670 // Restore to this course
4671 if ($adminoptions->restore
) {
4672 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
4673 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
4676 // Copy this course.
4677 if ($adminoptions->copy
) {
4678 $url = new moodle_url('/backup/copy.php', array('id' => $course->id
));
4679 $coursenode->add(get_string('copycourse'), $url, self
::TYPE_SETTING
, null, 'copy', new pix_icon('t/copy', ''));
4682 // Reset this course
4683 if ($adminoptions->reset
) {
4684 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
4685 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, 'reset', new pix_icon('i/return', ''));
4689 require_once($CFG->libdir
. '/questionlib.php');
4690 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
4692 if ($adminoptions->update
) {
4693 // Repository Instances
4694 if (!$this->cache
->cached('contexthasrepos'.$coursecontext->id
)) {
4695 require_once($CFG->dirroot
. '/repository/lib.php');
4696 $editabletypes = repository
::get_editable_types($coursecontext);
4697 $haseditabletypes = !empty($editabletypes);
4698 unset($editabletypes);
4699 $this->cache
->set('contexthasrepos'.$coursecontext->id
, $haseditabletypes);
4701 $haseditabletypes = $this->cache
->{'contexthasrepos'.$coursecontext->id
};
4703 if ($haseditabletypes) {
4704 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id
));
4705 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
4710 if ($adminoptions->files
) {
4711 // hidden in new courses and courses where legacy files were turned off
4712 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
4713 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/folder', ''));
4717 // Let plugins hook into course navigation.
4718 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php');
4719 foreach ($pluginsfunction as $plugintype => $plugins) {
4720 // Ignore the report plugin as it was already loaded above.
4721 if ($plugintype == 'report') {
4724 foreach ($plugins as $pluginfunction) {
4725 $pluginfunction($coursenode, $course, $coursecontext);
4729 // Prepare data for course content download functionality if it is enabled.
4730 // Will only be included here if the action menu is already in use, otherwise a button will be added to the UI elsewhere.
4731 if (\core\content
::can_export_context($coursecontext, $USER) && !empty($coursenode->get_children_key_list())) {
4732 $linkattr = \core_course\output\content_export_link
::get_attributes($coursecontext);
4733 $actionlink = new action_link($linkattr->url
, $linkattr->displaystring
, null, $linkattr->elementattributes
);
4735 $coursenode->add($linkattr->displaystring
, $actionlink, self
::TYPE_SETTING
, null, 'download',
4736 new pix_icon('t/download', ''));
4737 $coursenode->get('download')->set_force_into_more_menu();
4740 // Return we are done
4745 * Get the moodle_page object associated to the current settings navigation.
4747 * @return moodle_page
4749 public function get_page(): moodle_page
{
4754 * This function calls the module function to inject module settings into the
4755 * settings navigation tree.
4757 * This only gets called if there is a corrosponding function in the modules
4760 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
4762 * @return navigation_node|false
4764 protected function load_module_settings() {
4767 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
4768 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
4769 $this->page
->set_cm($cm, $this->page
->course
);
4772 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
4773 if (file_exists($file)) {
4774 require_once($file);
4777 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
), null, self
::TYPE_SETTING
, null, 'modulesettings');
4778 $modulenode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
4779 $modulenode->force_open();
4781 // Settings for the module
4782 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
4783 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => 1));
4784 $modulenode->add(get_string('settings'), $url, navigation_node
::TYPE_SETTING
, null, 'modedit');
4786 // Assign local roles
4787 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
4788 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
4789 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
, null, 'roleassign');
4792 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
4793 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
4794 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'roleoverride');
4796 // Check role permissions
4797 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
4798 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
4799 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck');
4802 // Add the context locking node.
4803 $this->add_context_locking_node($modulenode, $this->page
->cm
->context
);
4806 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
4807 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
4808 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filtermanage');
4811 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
4812 foreach ($reports as $reportfunction) {
4813 $reportfunction($modulenode, $this->page
->cm
);
4815 // Add a backup link
4816 $featuresfunc = $this->page
->activityname
.'_supports';
4817 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
4818 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
4819 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup');
4822 // Restore this activity
4823 $featuresfunc = $this->page
->activityname
.'_supports';
4824 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/restore:restoreactivity', $this->page
->cm
->context
)) {
4825 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page
->cm
->context
->id
));
4826 $modulenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore');
4829 // Allow the active advanced grading method plugin to append its settings
4830 $featuresfunc = $this->page
->activityname
.'_supports';
4831 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING
) && has_capability('moodle/grade:managegradingforms', $this->page
->cm
->context
)) {
4832 require_once($CFG->dirroot
.'/grade/grading/lib.php');
4833 $gradingman = get_grading_manager($this->page
->cm
->context
, 'mod_'.$this->page
->activityname
);
4834 $gradingman->extend_settings_navigation($this, $modulenode);
4837 $function = $this->page
->activityname
.'_extend_settings_navigation';
4838 if (function_exists($function)) {
4839 $function($this, $modulenode);
4842 // Remove the module node if there are no children.
4843 if ($modulenode->children
->count() <= 0) {
4844 $modulenode->remove();
4851 * Loads the user settings block of the settings nav
4853 * This function is simply works out the userid and whether we need to load
4854 * just the current users profile settings, or the current user and the user the
4855 * current user is viewing.
4857 * This function has some very ugly code to work out the user, if anyone has
4858 * any bright ideas please feel free to intervene.
4860 * @param int $courseid The course id of the current course
4861 * @return navigation_node|false
4863 protected function load_user_settings($courseid = SITEID
) {
4866 if (isguestuser() ||
!isloggedin()) {
4870 $navusers = $this->page
->navigation
->get_extending_users();
4872 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
4874 foreach ($this->userstoextendfor
as $userid) {
4875 if ($userid == $USER->id
) {
4878 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
4879 if (is_null($usernode)) {
4883 foreach ($navusers as $user) {
4884 if ($user->id
== $USER->id
) {
4887 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
4888 if (is_null($usernode)) {
4892 $this->generate_user_settings($courseid, $USER->id
);
4894 $usernode = $this->generate_user_settings($courseid, $USER->id
);
4900 * Extends the settings navigation for the given user.
4902 * Note: This method gets called automatically if you call
4903 * $PAGE->navigation->extend_for_user($userid)
4905 * @param int $userid
4907 public function extend_for_user($userid) {
4910 if (!in_array($userid, $this->userstoextendfor
)) {
4911 $this->userstoextendfor
[] = $userid;
4912 if ($this->initialised
) {
4913 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
4914 $children = array();
4915 foreach ($this->children
as $child) {
4916 $children[] = $child;
4918 array_unshift($children, array_pop($children));
4919 $this->children
= new navigation_node_collection();
4920 foreach ($children as $child) {
4921 $this->children
->add($child);
4928 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
4929 * what can be shown/done
4931 * @param int $courseid The current course' id
4932 * @param int $userid The user id to load for
4933 * @param string $gstitle The string to pass to get_string for the branch title
4934 * @return navigation_node|false
4936 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
4937 global $DB, $CFG, $USER, $SITE;
4939 if ($courseid != $SITE->id
) {
4940 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
4941 $course = $this->page
->course
;
4943 $select = context_helper
::get_preload_record_columns_sql('ctx');
4944 $sql = "SELECT c.*, $select
4946 JOIN {context} ctx ON c.id = ctx.instanceid
4947 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
4948 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE
);
4949 $course = $DB->get_record_sql($sql, $params, MUST_EXIST
);
4950 context_helper
::preload_from_record($course);
4956 $coursecontext = context_course
::instance($course->id
); // Course context
4957 $systemcontext = context_system
::instance();
4958 $currentuser = ($USER->id
== $userid);
4962 $usercontext = context_user
::instance($user->id
); // User context
4964 $select = context_helper
::get_preload_record_columns_sql('ctx');
4965 $sql = "SELECT u.*, $select
4967 JOIN {context} ctx ON u.id = ctx.instanceid
4968 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
4969 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER
);
4970 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING
);
4974 context_helper
::preload_from_record($user);
4976 // Check that the user can view the profile
4977 $usercontext = context_user
::instance($user->id
); // User context
4978 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
4980 if ($course->id
== $SITE->id
) {
4981 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
4982 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
4986 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
4987 $userisenrolled = is_enrolled($coursecontext, $user->id
, '', true);
4988 if ((!$canviewusercourse && !$canviewuser) ||
!$userisenrolled) {
4991 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
4992 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS
&& !$canviewuser) {
4993 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
4994 if ($courseid == $this->page
->course
->id
) {
4995 $mygroups = get_fast_modinfo($this->page
->course
)->groups
;
4997 $mygroups = groups_get_user_groups($courseid);
4999 $usergroups = groups_get_user_groups($courseid, $userid);
5000 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
5007 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
5010 $prefurl = new moodle_url('/user/preferences.php');
5011 if ($gstitle != 'usercurrentsettings') {
5013 $prefurl->param('userid', $userid);
5016 // Add a user setting branch.
5017 if ($gstitle == 'usercurrentsettings') {
5018 $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_CONTAINER
, null, 'dashboard');
5019 // This should be set to false as we don't want to show this to the user. It's only for generating the correct
5021 $dashboard->display
= false;
5022 $homepage = get_home_page();
5023 if (($homepage == HOMEPAGE_MY ||
$homepage == HOMEPAGE_MYCOURSES
)) {
5024 $dashboard->mainnavonly
= true;
5027 $iscurrentuser = ($user->id
== $USER->id
);
5029 $baseargs = array('id' => $user->id
);
5030 if ($course->id
!= $SITE->id
&& !$iscurrentuser) {
5031 $baseargs['course'] = $course->id
;
5032 $issitecourse = false;
5034 // Load all categories and get the context for the system.
5035 $issitecourse = true;
5038 // Add the user profile to the dashboard.
5039 $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php',
5040 array('id' => $user->id
)), self
::TYPE_SETTING
, null, 'myprofile');
5042 if (!empty($CFG->navadduserpostslinks
)) {
5043 // Add nodes for forum posts and discussions if the user can view either or both
5044 // There are no capability checks here as the content of the page is based
5045 // purely on the forums the current user has access too.
5046 $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
5047 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
5048 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
5049 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
5053 if (!empty($CFG->enableblogs
)) {
5054 if (!$this->cache
->cached('userblogoptions'.$user->id
)) {
5055 require_once($CFG->dirroot
.'/blog/lib.php');
5056 // Get all options for the user.
5057 $options = blog_get_options_for_user($user);
5058 $this->cache
->set('userblogoptions'.$user->id
, $options);
5060 $options = $this->cache
->{'userblogoptions'.$user->id
};
5063 if (count($options) > 0) {
5064 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
5065 foreach ($options as $type => $option) {
5066 if ($type == "rss") {
5067 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, null,
5068 new pix_icon('i/rss', ''));
5070 $blogs->add($option['string'], $option['link'], self
::TYPE_SETTING
, null, 'blog' . $type);
5076 // Add the messages link.
5077 // It is context based so can appear in the user's profile and in course participants information.
5078 if (!empty($CFG->messaging
)) {
5079 $messageargs = array('user1' => $USER->id
);
5080 if ($USER->id
!= $user->id
) {
5081 $messageargs['user2'] = $user->id
;
5083 $url = new moodle_url('/message/index.php', $messageargs);
5084 $dashboard->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
5087 // Add the "My private files" link.
5088 // This link doesn't have a unique display for course context so only display it under the user's profile.
5089 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
5090 $url = new moodle_url('/user/files.php');
5091 $dashboard->add(get_string('privatefiles'), $url, self
::TYPE_SETTING
, null, 'privatefiles');
5094 // Add a node to view the users notes if permitted.
5095 if (!empty($CFG->enablenotes
) &&
5096 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
5097 $url = new moodle_url('/notes/index.php', array('user' => $user->id
));
5098 if ($coursecontext->instanceid
!= SITEID
) {
5099 $url->param('course', $coursecontext->instanceid
);
5101 $profilenode->add(get_string('notes', 'notes'), $url);
5104 // Show the grades node.
5105 if (($issitecourse && $iscurrentuser) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
5106 require_once($CFG->dirroot
. '/user/lib.php');
5107 // Set the grades node to link to the "Grades" page.
5108 if ($course->id
== SITEID
) {
5109 $url = user_mygrades_url($user->id
, $course->id
);
5110 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
5111 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id
, 'user' => $user->id
));
5113 $dashboard->add(get_string('grades', 'grades'), $url, self
::TYPE_SETTING
, null, 'mygrades');
5116 // Let plugins hook into user navigation.
5117 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
5118 foreach ($pluginsfunction as $plugintype => $plugins) {
5119 if ($plugintype != 'report') {
5120 foreach ($plugins as $pluginfunction) {
5121 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
5126 $usersetting = navigation_node
::create(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
5127 $dashboard->add_node($usersetting);
5129 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self
::TYPE_CONTAINER
, null, $key);
5130 $usersetting->display
= false;
5132 $usersetting->id
= 'usersettings';
5134 // Check if the user has been deleted.
5135 if ($user->deleted
) {
5136 if (!has_capability('moodle/user:update', $coursecontext)) {
5137 // We can't edit the user so just show the user deleted message.
5138 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
5140 // We can edit the user so show the user deleted message and link it to the profile.
5141 if ($course->id
== $SITE->id
) {
5142 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
5144 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
5146 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
5151 $userauthplugin = false;
5152 if (!empty($user->auth
)) {
5153 $userauthplugin = get_auth_plugin($user->auth
);
5156 $useraccount = $usersetting->add(get_string('useraccount'), null, self
::TYPE_CONTAINER
, null, 'useraccount');
5158 // Add the profile edit link.
5159 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5160 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) &&
5161 has_capability('moodle/user:update', $systemcontext)) {
5162 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
5163 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
5164 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
5165 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
5166 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
5167 $url = $userauthplugin->edit_profile_url();
5169 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
5171 $useraccount->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
, null, 'editprofile');
5176 // Change password link.
5177 if ($userauthplugin && $currentuser && !\core\session\manager
::is_loggedinas() && !isguestuser() &&
5178 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
5179 $passwordchangeurl = $userauthplugin->change_password_url();
5180 if (empty($passwordchangeurl)) {
5181 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
5183 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
, null, 'changepassword');
5186 // Default homepage.
5187 $defaulthomepageuser = (!empty($CFG->defaulthomepage
) && ($CFG->defaulthomepage
== HOMEPAGE_USER
));
5188 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) {
5189 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5190 has_capability('moodle/user:editprofile', $usercontext)) {
5191 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id
]);
5192 $useraccount->add(get_string('defaulthomepageuser'), $url, self
::TYPE_SETTING
, null, 'defaulthomepageuser');
5196 if (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/language.php', array('id' => $user->id
, 'course' => $course->id
));
5200 $useraccount->add(get_string('preferredlanguage'), $url, self
::TYPE_SETTING
, null, 'preferredlanguage');
5203 $pluginmanager = core_plugin_manager
::instance();
5204 $enabled = $pluginmanager->get_enabled_plugins('mod');
5205 if (isset($enabled['forum']) && 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/forum.php', array('id' => $user->id
, 'course' => $course->id
));
5209 $useraccount->add(get_string('forumpreferences'), $url, self
::TYPE_SETTING
);
5212 $editors = editors_get_enabled();
5213 if (count($editors) > 1) {
5214 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
5215 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5216 has_capability('moodle/user:editprofile', $usercontext)) {
5217 $url = new moodle_url('/user/editor.php', array('id' => $user->id
, 'course' => $course->id
));
5218 $useraccount->add(get_string('editorpreferences'), $url, self
::TYPE_SETTING
);
5223 // Add "Calendar 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/calendar.php', array('id' => $user->id
));
5228 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self
::TYPE_SETTING
, null, 'preferredcalendar');
5232 // Add "Content bank preferences" link.
5233 if (isloggedin() && !isguestuser($user)) {
5234 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) ||
5235 has_capability('moodle/user:editprofile', $usercontext)) {
5236 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id
]);
5237 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self
::TYPE_SETTING
,
5238 null, 'contentbankpreferences');
5242 // View the roles settings.
5243 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override',
5244 'moodle/role:manage'], $usercontext)) {
5245 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
5247 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id
, 'courseid' => $course->id
]);
5248 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
5250 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
5252 if (!empty($assignableroles)) {
5253 $url = new moodle_url('/admin/roles/assign.php',
5254 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5255 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
5258 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
5259 $url = new moodle_url('/admin/roles/permissions.php',
5260 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5261 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
5264 $url = new moodle_url('/admin/roles/check.php',
5265 array('contextid' => $usercontext->id
, 'userid' => $user->id
, 'courseid' => $course->id
));
5266 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
5270 if (!$this->cache
->cached('contexthasrepos'.$usercontext->id
)) {
5271 require_once($CFG->dirroot
. '/repository/lib.php');
5272 $editabletypes = repository
::get_editable_types($usercontext);
5273 $haseditabletypes = !empty($editabletypes);
5274 unset($editabletypes);
5275 $this->cache
->set('contexthasrepos'.$usercontext->id
, $haseditabletypes);
5277 $haseditabletypes = $this->cache
->{'contexthasrepos'.$usercontext->id
};
5279 if ($haseditabletypes) {
5280 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self
::TYPE_SETTING
);
5281 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php',
5282 array('contextid' => $usercontext->id
)));
5286 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
5287 require_once($CFG->libdir
. '/portfoliolib.php');
5288 if (portfolio_has_visible_instances()) {
5289 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
5291 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
5292 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
5294 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
5295 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
5299 $enablemanagetokens = false;
5300 if (!empty($CFG->enablerssfeeds
)) {
5301 $enablemanagetokens = true;
5302 } else if (!is_siteadmin($USER->id
)
5303 && !empty($CFG->enablewebservices
)
5304 && has_capability('moodle/webservice:createtoken', context_system
::instance()) ) {
5305 $enablemanagetokens = true;
5308 if ($currentuser && $enablemanagetokens) {
5309 $url = new moodle_url('/user/managetoken.php');
5310 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
5314 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) &&
5315 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
5316 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id
));
5317 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id
));
5318 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self
::TYPE_SETTING
);
5319 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self
::TYPE_SETTING
);
5323 if ($currentuser && !empty($CFG->enableblogs
)) {
5324 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
5325 if (has_capability('moodle/blog:view', $systemcontext)) {
5326 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'),
5327 navigation_node
::TYPE_SETTING
);
5329 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 &&
5330 has_capability('moodle/blog:manageexternal', $systemcontext)) {
5331 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'),
5332 navigation_node
::TYPE_SETTING
);
5333 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'),
5334 navigation_node
::TYPE_SETTING
);
5336 // Remove the blog node if empty.
5337 $blog->trim_if_empty();
5341 if ($currentuser && !empty($CFG->enablebadges
)) {
5342 $badges = $usersetting->add(get_string('badges'), null, navigation_node
::TYPE_CONTAINER
, null, 'badges');
5343 if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
5344 $url = new moodle_url('/badges/mybadges.php');
5345 $badges->add(get_string('managebadges', 'badges'), $url, self
::TYPE_SETTING
);
5347 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'),
5348 navigation_node
::TYPE_SETTING
);
5349 if (!empty($CFG->badges_allowexternalbackpack
)) {
5350 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'),
5351 navigation_node
::TYPE_SETTING
);
5355 // Let plugins hook into user settings navigation.
5356 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
5357 foreach ($pluginsfunction as $plugintype => $plugins) {
5358 foreach ($plugins as $pluginfunction) {
5359 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
5363 return $usersetting;
5367 * Loads block specific settings in the navigation
5369 * @return navigation_node
5371 protected function load_block_settings() {
5374 $blocknode = $this->add($this->context
->get_context_name(), null, self
::TYPE_SETTING
, null, 'blocksettings');
5375 $blocknode->force_open();
5377 // Assign local roles
5378 if (get_assignable_roles($this->context
, ROLENAME_ORIGINAL
)) {
5379 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $this->context
->id
));
5380 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null,
5381 'roles', new pix_icon('i/assignroles', ''));
5385 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
5386 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
5387 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null,
5388 'permissions', new pix_icon('i/permissions', ''));
5390 // Check role permissions
5391 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
5392 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
5393 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null,
5394 'checkpermissions', new pix_icon('i/checkpermissions', ''));
5397 // Add the context locking node.
5398 $this->add_context_locking_node($blocknode, $this->context
);
5404 * Loads category specific settings in the navigation
5406 * @return navigation_node
5408 protected function load_category_settings() {
5411 // We can land here while being in the context of a block, in which case we
5412 // should get the parent context which should be the category one. See self::initialise().
5413 if ($this->context
->contextlevel
== CONTEXT_BLOCK
) {
5414 $catcontext = $this->context
->get_parent_context();
5416 $catcontext = $this->context
;
5419 // Let's make sure that we always have the right context when getting here.
5420 if ($catcontext->contextlevel
!= CONTEXT_COURSECAT
) {
5421 throw new coding_exception('Unexpected context while loading category settings.');
5424 $categorynodetype = navigation_node
::TYPE_CONTAINER
;
5425 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings');
5426 $categorynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
5427 $categorynode->force_open();
5429 if (can_edit_in_category($catcontext->instanceid
)) {
5430 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid
));
5431 $editstring = get_string('managecategorythis');
5432 $node = $categorynode->add($editstring, $url, self
::TYPE_SETTING
, null, 'managecategory', new pix_icon('i/edit', ''));
5433 $node->set_show_in_secondary_navigation(false);
5436 if (has_capability('moodle/category:manage', $catcontext)) {
5437 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid
));
5438 $categorynode->add(get_string('settings'), $editurl, self
::TYPE_SETTING
, null, 'edit', new pix_icon('i/edit', ''));
5440 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid
));
5441 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self
::TYPE_SETTING
, null,
5442 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false);
5445 // Assign local roles
5446 $assignableroles = get_assignable_roles($catcontext);
5447 if (!empty($assignableroles)) {
5448 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid' => $catcontext->id
));
5449 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
5453 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) {
5454 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid' => $catcontext->id
));
5455 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/permissions', ''));
5457 // Check role permissions
5458 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride',
5459 'moodle/role:override', 'moodle/role:assign'), $catcontext)) {
5460 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid' => $catcontext->id
));
5461 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
, null, 'rolecheck', new pix_icon('i/checkpermissions', ''));
5464 // Add the context locking node.
5465 $this->add_context_locking_node($categorynode, $catcontext);
5468 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) {
5469 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php',
5470 array('contextid' => $catcontext->id
)), self
::TYPE_SETTING
, null, 'cohort', new pix_icon('i/cohort', ''));
5474 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) {
5475 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id
));
5476 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, 'filters', new pix_icon('i/filter', ''));
5480 if (has_capability('moodle/restore:restorecourse', $catcontext)) {
5481 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id
));
5482 $categorynode->add(get_string('restorecourse', 'admin'), $url, self
::TYPE_SETTING
, null, 'restorecourse', new pix_icon('i/restore', ''));
5485 // Let plugins hook into category settings navigation.
5486 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php');
5487 foreach ($pluginsfunction as $plugintype => $plugins) {
5488 foreach ($plugins as $pluginfunction) {
5489 $pluginfunction($categorynode, $catcontext);
5493 $cb = new contentbank();
5494 if ($cb->is_context_allowed($catcontext)
5495 && has_capability('moodle/contentbank:access', $catcontext)) {
5496 $url = new \
moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id
]);
5497 $categorynode->add(get_string('contentbank'), $url, self
::TYPE_CUSTOM
, null,
5498 'contentbank', new \
pix_icon('i/contentbank', ''));
5501 return $categorynode;
5505 * Determine whether the user is assuming another role
5507 * This function checks to see if the user is assuming another role by means of
5508 * role switching. In doing this we compare each RSW key (context path) against
5509 * the current context path. This ensures that we can provide the switching
5510 * options against both the course and any page shown under the course.
5512 * @return bool|int The role(int) if the user is in another role, false otherwise
5514 protected function in_alternative_role() {
5516 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
5517 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
5518 return $USER->access
['rsw'][$this->page
->context
->path
];
5520 foreach ($USER->access
['rsw'] as $key=>$role) {
5521 if (strpos($this->context
->path
,$key)===0) {
5530 * This function loads all of the front page settings into the settings navigation.
5531 * This function is called when the user is on the front page, or $COURSE==$SITE
5532 * @param bool $forceopen (optional)
5533 * @return navigation_node
5535 protected function load_front_page_settings($forceopen = false) {
5537 require_once($CFG->dirroot
. '/course/lib.php');
5539 $course = clone($SITE);
5540 $coursecontext = context_course
::instance($course->id
); // Course context
5541 $adminoptions = course_get_user_administration_options($course, $coursecontext);
5543 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
5545 $frontpage->force_open();
5547 $frontpage->id
= 'frontpagesettings';
5549 if ($this->page
->user_allowed_editing() && !$this->page
->theme
->haseditswitch
) {
5551 // Add the turn on/off settings
5552 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
5553 if ($this->page
->user_is_editing()) {
5554 $url->param('edit', 'off');
5555 $editstring = get_string('turneditingoff');
5557 $url->param('edit', 'on');
5558 $editstring = get_string('turneditingon');
5560 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
5563 if ($adminoptions->update
) {
5564 // Add the course settings link
5565 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
5566 $frontpage->add(get_string('settings'), $url, self
::TYPE_SETTING
, null,
5567 'editsettings', new pix_icon('i/settings', ''));
5571 enrol_add_course_navigation($frontpage, $course);
5574 if ($adminoptions->filters
) {
5575 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
5576 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
,
5577 null, 'filtermanagement', new pix_icon('i/filter', ''));
5580 // View course reports.
5581 if ($adminoptions->reports
) {
5582 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php',
5583 ['courseid' => $coursecontext->instanceid
]),
5584 self
::TYPE_CONTAINER
, null, 'coursereports',
5585 new pix_icon('i/stats', ''));
5586 $coursereports = core_component
::get_plugin_list('coursereport');
5587 foreach ($coursereports as $report=>$dir) {
5588 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
5589 if (file_exists($libfile)) {
5590 require_once($libfile);
5591 $reportfunction = $report.'_report_extend_navigation';
5592 if (function_exists($report.'_report_extend_navigation')) {
5593 $reportfunction($frontpagenav, $course, $coursecontext);
5598 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
5599 foreach ($reports as $reportfunction) {
5600 $reportfunction($frontpagenav, $course, $coursecontext);
5604 // Backup this course
5605 if ($adminoptions->backup
) {
5606 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
5607 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
5610 // Restore to this course
5611 if ($adminoptions->restore
) {
5612 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
5613 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
5617 require_once($CFG->libdir
. '/questionlib.php');
5618 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
5621 if ($adminoptions->files
) {
5622 //hiden in new installs
5623 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
5624 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/folder', ''));
5627 // Let plugins hook into frontpage navigation.
5628 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php');
5629 foreach ($pluginsfunction as $plugintype => $plugins) {
5630 foreach ($plugins as $pluginfunction) {
5631 $pluginfunction($frontpage, $course, $coursecontext);
5639 * This function gives local plugins an opportunity to modify the settings navigation.
5641 protected function load_local_plugin_settings() {
5643 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) {
5644 $function($this, $this->context
);
5649 * This function marks the cache as volatile so it is cleared during shutdown
5651 public function clear_cache() {
5652 $this->cache
->volatile();
5656 * Checks to see if there are child nodes available in the specific user's preference node.
5657 * If so, then they have the appropriate permissions view this user's preferences.
5659 * @since Moodle 2.9.3
5660 * @param int $userid The user's ID.
5661 * @return bool True if child nodes exist to view, otherwise false.
5663 public function can_view_user_preferences($userid) {
5664 if (is_siteadmin()) {
5667 // See if any nodes are present in the preferences section for this user.
5668 $preferencenode = $this->find('userviewingsettings' . $userid, null);
5669 if ($preferencenode && $preferencenode->has_children()) {
5670 // Run through each child node.
5671 foreach ($preferencenode->children
as $childnode) {
5672 // If the child node has children then this user has access to a link in the preferences page.
5673 if ($childnode->has_children()) {
5678 // No links found for the user to access on the preferences page.
5684 * Class used to populate site admin navigation for ajax.
5687 * @category navigation
5688 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
5689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5691 class settings_navigation_ajax
extends settings_navigation
{
5693 * Constructs the navigation for use in an AJAX request
5695 * @param moodle_page $page
5697 public function __construct(moodle_page
&$page) {
5698 $this->page
= $page;
5699 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
5700 $this->children
= new navigation_node_collection();
5701 $this->initialise();
5705 * Initialise the site admin navigation.
5707 * @return array An array of the expandable nodes
5709 public function initialise() {
5710 if ($this->initialised ||
during_initial_install()) {
5713 $this->context
= $this->page
->context
;
5714 $this->load_administration_settings();
5716 // Check if local plugins is adding node to site admin.
5717 $this->load_local_plugin_settings();
5719 $this->initialised
= true;
5724 * Simple class used to output a navigation branch in XML
5727 * @category navigation
5728 * @copyright 2009 Sam Hemelryk
5729 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5731 class navigation_json
{
5732 /** @var array An array of different node types */
5733 protected $nodetype = array('node','branch');
5734 /** @var array An array of node keys and types */
5735 protected $expandable = array();
5737 * Turns a branch and all of its children into XML
5739 * @param navigation_node $branch
5740 * @return string XML string
5742 public function convert($branch) {
5743 $xml = $this->convert_child($branch);
5747 * Set the expandable items in the array so that we have enough information
5748 * to attach AJAX events
5749 * @param array $expandable
5751 public function set_expandable($expandable) {
5752 foreach ($expandable as $node) {
5753 $this->expandable
[$node['key'].':'.$node['type']] = $node;
5757 * Recusively converts a child node and its children to XML for output
5759 * @param navigation_node $child The child to convert
5760 * @param int $depth Pointlessly used to track the depth of the XML structure
5761 * @return string JSON
5763 protected function convert_child($child, $depth=1) {
5764 if (!$child->display
) {
5767 $attributes = array();
5768 $attributes['id'] = $child->id
;
5769 $attributes['name'] = (string)$child->text
; // This can be lang_string object so typecast it.
5770 $attributes['type'] = $child->type
;
5771 $attributes['key'] = $child->key
;
5772 $attributes['class'] = $child->get_css_type();
5773 $attributes['requiresajaxloading'] = $child->requiresajaxloading
;
5775 if ($child->icon
instanceof pix_icon
) {
5776 $attributes['icon'] = array(
5777 'component' => $child->icon
->component
,
5778 'pix' => $child->icon
->pix
,
5780 foreach ($child->icon
->attributes
as $key=>$value) {
5781 if ($key == 'class') {
5782 $attributes['icon']['classes'] = explode(' ', $value);
5783 } else if (!array_key_exists($key, $attributes['icon'])) {
5784 $attributes['icon'][$key] = $value;
5788 } else if (!empty($child->icon
)) {
5789 $attributes['icon'] = (string)$child->icon
;
5792 if ($child->forcetitle ||
$child->title
!== $child->text
) {
5793 $attributes['title'] = htmlentities($child->title
, ENT_QUOTES
, 'UTF-8');
5795 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
5796 $attributes['expandable'] = $child->key
;
5797 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
5800 if (count($child->classes
)>0) {
5801 $attributes['class'] .= ' '.join(' ',$child->classes
);
5803 if (is_string($child->action
)) {
5804 $attributes['link'] = $child->action
;
5805 } else if ($child->action
instanceof moodle_url
) {
5806 $attributes['link'] = $child->action
->out();
5807 } else if ($child->action
instanceof action_link
) {
5808 $attributes['link'] = $child->action
->url
->out();
5810 $attributes['hidden'] = ($child->hidden
);
5811 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
5812 $attributes['haschildren'] = $attributes['haschildren'] ||
$child->type
== navigation_node
::TYPE_MY_CATEGORY
;
5814 if ($child->children
->count() > 0) {
5815 $attributes['children'] = array();
5816 foreach ($child->children
as $subchild) {
5817 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
5824 return json_encode($attributes);
5830 * The cache class used by global navigation and settings navigation.
5832 * It is basically an easy access point to session with a bit of smarts to make
5833 * sure that the information that is cached is valid still.
5837 * if (!$cache->viewdiscussion()) {
5838 * // Code to do stuff and produce cachable content
5839 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
5841 * $content = $cache->viewdiscussion;
5845 * @category navigation
5846 * @copyright 2009 Sam Hemelryk
5847 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5849 class navigation_cache
{
5850 /** @var int represents the time created */
5851 protected $creation;
5852 /** @var array An array of session keys */
5855 * The string to use to segregate this particular cache. It can either be
5856 * unique to start a fresh cache or if you want to share a cache then make
5857 * it the string used in the original cache.
5861 /** @var int a time that the information will time out */
5863 /** @var stdClass The current context */
5864 protected $currentcontext;
5865 /** @var int cache time information */
5866 const CACHETIME
= 0;
5867 /** @var int cache user id */
5868 const CACHEUSERID
= 1;
5869 /** @var int cache value */
5870 const CACHEVALUE
= 2;
5871 /** @var null|array An array of navigation cache areas to expire on shutdown */
5872 public static $volatilecaches;
5875 * Contructor for the cache. Requires two arguments
5877 * @param string $area The string to use to segregate this particular cache
5878 * it can either be unique to start a fresh cache or if you want
5879 * to share a cache then make it the string used in the original
5881 * @param int $timeout The number of seconds to time the information out after
5883 public function __construct($area, $timeout=1800) {
5884 $this->creation
= time();
5885 $this->area
= $area;
5886 $this->timeout
= time() - $timeout;
5887 if (rand(0,100) === 0) {
5888 $this->garbage_collection();
5893 * Used to set up the cache within the SESSION.
5895 * This is called for each access and ensure that we don't put anything into the session before
5898 protected function ensure_session_cache_initialised() {
5900 if (empty($this->session
)) {
5901 if (!isset($SESSION->navcache
)) {
5902 $SESSION->navcache
= new stdClass
;
5904 if (!isset($SESSION->navcache
->{$this->area
})) {
5905 $SESSION->navcache
->{$this->area
} = array();
5907 $this->session
= &$SESSION->navcache
->{$this->area
}; // pointer to array, =& is correct here
5912 * Magic Method to retrieve something by simply calling using = cache->key
5914 * @param mixed $key The identifier for the information you want out again
5915 * @return void|mixed Either void or what ever was put in
5917 public function __get($key) {
5918 if (!$this->cached($key)) {
5921 $information = $this->session
[$key][self
::CACHEVALUE
];
5922 return unserialize($information);
5926 * Magic method that simply uses {@link set();} to store something in the cache
5928 * @param string|int $key
5929 * @param mixed $information
5931 public function __set($key, $information) {
5932 $this->set($key, $information);
5936 * Sets some information against the cache (session) for later retrieval
5938 * @param string|int $key
5939 * @param mixed $information
5941 public function set($key, $information) {
5943 $this->ensure_session_cache_initialised();
5944 $information = serialize($information);
5945 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
5948 * Check the existence of the identifier in the cache
5950 * @param string|int $key
5953 public function cached($key) {
5955 $this->ensure_session_cache_initialised();
5956 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
) {
5962 * Compare something to it's equivilant in the cache
5964 * @param string $key
5965 * @param mixed $value
5966 * @param bool $serialise Whether to serialise the value before comparison
5967 * this should only be set to false if the value is already
5969 * @return bool If the value is the same false if it is not set or doesn't match
5971 public function compare($key, $value, $serialise = true) {
5972 if ($this->cached($key)) {
5974 $value = serialize($value);
5976 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
5983 * Wipes the entire cache, good to force regeneration
5985 public function clear() {
5987 unset($SESSION->navcache
);
5988 $this->session
= null;
5991 * Checks all cache entries and removes any that have expired, good ole cleanup
5993 protected function garbage_collection() {
5994 if (empty($this->session
)) {
5997 foreach ($this->session
as $key=>$cachedinfo) {
5998 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
5999 unset($this->session
[$key]);
6005 * Marks the cache as being volatile (likely to change)
6007 * Any caches marked as volatile will be destroyed at the on shutdown by
6008 * {@link navigation_node::destroy_volatile_caches()} which is registered
6009 * as a shutdown function if any caches are marked as volatile.
6011 * @param bool $setting True to destroy the cache false not too
6013 public function volatile($setting = true) {
6014 if (self
::$volatilecaches===null) {
6015 self
::$volatilecaches = array();
6016 core_shutdown_manager
::register_function(array('navigation_cache','destroy_volatile_caches'));
6020 self
::$volatilecaches[$this->area
] = $this->area
;
6021 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
6022 unset(self
::$volatilecaches[$this->area
]);
6027 * Destroys all caches marked as volatile
6029 * This function is static and works in conjunction with the static volatilecaches
6030 * property of navigation cache.
6031 * Because this function is static it manually resets the cached areas back to an
6034 public static function destroy_volatile_caches() {
6036 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
6037 foreach (self
::$volatilecaches as $area) {
6038 $SESSION->navcache
->{$area} = array();
6041 $SESSION->navcache
= new stdClass
;