MDL-62142 navigation: accessibility
[moodle.git] / lib / navigationlib.php
CommitLineData
7d2a0492 1<?php
7d2a0492 2// This file is part of Moodle - http://moodle.org/
3//
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.
8//
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.
13//
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/>.
16
17/**
98556b23 18 * This file contains classes used to manage the navigation structures within Moodle.
7d2a0492 19 *
5bcfd504 20 * @since Moodle 2.0
78bfb562 21 * @package core
78bfb562
PS
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7d2a0492 24 */
25
78bfb562
PS
26defined('MOODLE_INTERNAL') || die();
27
f5b5a822 28/**
2561c4e9 29 * The name that will be used to separate the navigation cache within SESSION
f5b5a822 30 */
31define('NAVIGATION_CACHE_NAME', 'navigation');
5ab32c11 32define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
f5b5a822 33
7d2a0492 34/**
35 * This class is used to represent a node in a navigation tree
36 *
37 * This class is used to represent a node in a navigation tree within Moodle,
38 * the tree could be one of global navigation, settings navigation, or the navbar.
39 * Each node can be one of two types either a Leaf (default) or a branch.
40 * When a node is first created it is created as a leaf, when/if children are added
41 * the node then becomes a branch.
42 *
31fde54f
AG
43 * @package core
44 * @category navigation
7d2a0492 45 * @copyright 2009 Sam Hemelryk
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 */
3406acde
SH
48class navigation_node implements renderable {
49 /** @var int Used to identify this node a leaf (default) 0 */
507a7a9a 50 const NODETYPE_LEAF = 0;
3406acde 51 /** @var int Used to identify this node a branch, happens with children 1 */
7d2a0492 52 const NODETYPE_BRANCH = 1;
3406acde 53 /** @var null Unknown node type null */
7d2a0492 54 const TYPE_UNKNOWN = null;
3406acde
SH
55 /** @var int System node type 0 */
56 const TYPE_ROOTNODE = 0;
57 /** @var int System node type 1 */
58 const TYPE_SYSTEM = 1;
59 /** @var int Category node type 10 */
7d2a0492 60 const TYPE_CATEGORY = 10;
db47f68f
RT
61 /** var int Category displayed in MyHome navigation node */
62 const TYPE_MY_CATEGORY = 11;
3406acde 63 /** @var int Course node type 20 */
7d2a0492 64 const TYPE_COURSE = 20;
3406acde 65 /** @var int Course Structure node type 30 */
507a7a9a 66 const TYPE_SECTION = 30;
3406acde 67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
7d2a0492 68 const TYPE_ACTIVITY = 40;
3406acde 69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
7d2a0492 70 const TYPE_RESOURCE = 50;
3406acde 71 /** @var int A custom node type, default when adding without specifing type 60 */
7d2a0492 72 const TYPE_CUSTOM = 60;
3406acde 73 /** @var int Setting node type, used only within settings nav 70 */
7d2a0492 74 const TYPE_SETTING = 70;
5ab32c11
RT
75 /** @var int site admin branch node type, used only within settings nav 71 */
76 const TYPE_SITE_ADMIN = 71;
3406acde 77 /** @var int Setting node type, used only within settings nav 80 */
507a7a9a 78 const TYPE_USER = 80;
3406acde
SH
79 /** @var int Setting node type, used for containers of no importance 90 */
80 const TYPE_CONTAINER = 90;
6caf3f5c
ARN
81 /** var int Course the current user is not enrolled in */
82 const COURSE_OTHER = 0;
83 /** var int Course the current user is enrolled in but not viewing */
84 const COURSE_MY = 1;
85 /** var int Course the current user is currently viewing */
86 const COURSE_CURRENT = 2;
fa238237
MN
87 /** var string The course index page navigation node */
88 const COURSE_INDEX_PAGE = 'courseindexpage';
7d2a0492 89
90 /** @var int Parameter to aid the coder in tracking [optional] */
91 public $id = null;
92 /** @var string|int The identifier for the node, used to retrieve the node */
93 public $key = null;
94 /** @var string The text to use for the node */
95 public $text = null;
96 /** @var string Short text to use if requested [optional] */
97 public $shorttext = null;
98 /** @var string The title attribute for an action if one is defined */
99 public $title = null;
100 /** @var string A string that can be used to build a help button */
101 public $helpbutton = null;
3406acde 102 /** @var moodle_url|action_link|null An action for the node (link) */
7d2a0492 103 public $action = null;
f9fc1461 104 /** @var pix_icon The path to an icon to use for this node */
7d2a0492 105 public $icon = null;
106 /** @var int See TYPE_* constants defined for this class */
107 public $type = self::TYPE_UNKNOWN;
108 /** @var int See NODETYPE_* constants defined for this class */
109 public $nodetype = self::NODETYPE_LEAF;
110 /** @var bool If set to true the node will be collapsed by default */
111 public $collapse = false;
112 /** @var bool If set to true the node will be expanded by default */
113 public $forceopen = false;
3406acde 114 /** @var array An array of CSS classes for the node */
7d2a0492 115 public $classes = array();
3406acde 116 /** @var navigation_node_collection An array of child nodes */
7d2a0492 117 public $children = array();
118 /** @var bool If set to true the node will be recognised as active */
119 public $isactive = false;
3406acde 120 /** @var bool If set to true the node will be dimmed */
7d2a0492 121 public $hidden = false;
122 /** @var bool If set to false the node will not be displayed */
123 public $display = true;
124 /** @var bool If set to true then an HR will be printed before the node */
125 public $preceedwithhr = false;
126 /** @var bool If set to true the the navigation bar should ignore this node */
127 public $mainnavonly = false;
128 /** @var bool If set to true a title will be added to the action no matter what */
129 public $forcetitle = false;
d38a4849 130 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
3406acde 131 public $parent = null;
493a48f3
SH
132 /** @var bool Override to not display the icon even if one is provided **/
133 public $hideicon = false;
58b602da
SH
134 /** @var bool Set to true if we KNOW that this node can be expanded. */
135 public $isexpandable = false;
7d2a0492 136 /** @var array */
5d0cc05b
JD
137 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
138 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
139 90 => 'container');
7d2a0492 140 /** @var moodle_url */
141 protected static $fullmeurl = null;
d9d2817a
SH
142 /** @var bool toogles auto matching of active node */
143 public static $autofindactive = true;
61bb8c93
PS
144 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
145 protected static $loadadmintree = false;
d67e4821 146 /** @var mixed If set to an int, that section will be included even if it has no activities */
147 public $includesectionnum = false;
f8895446
JO
148 /** @var bool does the node need to be loaded via ajax */
149 public $requiresajaxloading = false;
99061152
DW
150 /** @var bool If set to true this node will be added to the "flat" navigation */
151 public $showinflatnavigation = false;
7d2a0492 152
153 /**
3406acde 154 * Constructs a new navigation_node
7d2a0492 155 *
3406acde
SH
156 * @param array|string $properties Either an array of properties or a string to use
157 * as the text for the node
7d2a0492 158 */
159 public function __construct($properties) {
7d2a0492 160 if (is_array($properties)) {
3406acde
SH
161 // Check the array for each property that we allow to set at construction.
162 // text - The main content for the node
163 // shorttext - A short text if required for the node
164 // icon - The icon to display for the node
165 // type - The type of the node
166 // key - The key to use to identify the node
167 // parent - A reference to the nodes parent
168 // action - The action to attribute to this node, usually a URL to link to
7d2a0492 169 if (array_key_exists('text', $properties)) {
170 $this->text = $properties['text'];
171 }
172 if (array_key_exists('shorttext', $properties)) {
173 $this->shorttext = $properties['shorttext'];
174 }
7081714d 175 if (!array_key_exists('icon', $properties)) {
775fe700 176 $properties['icon'] = new pix_icon('i/navigationitem', '');
7081714d
SH
177 }
178 $this->icon = $properties['icon'];
179 if ($this->icon instanceof pix_icon) {
180 if (empty($this->icon->attributes['class'])) {
181 $this->icon->attributes['class'] = 'navicon';
182 } else {
183 $this->icon->attributes['class'] .= ' navicon';
7da3a799 184 }
7d2a0492 185 }
186 if (array_key_exists('type', $properties)) {
187 $this->type = $properties['type'];
188 } else {
189 $this->type = self::TYPE_CUSTOM;
190 }
191 if (array_key_exists('key', $properties)) {
192 $this->key = $properties['key'];
193 }
3406acde
SH
194 // This needs to happen last because of the check_if_active call that occurs
195 if (array_key_exists('action', $properties)) {
196 $this->action = $properties['action'];
197 if (is_string($this->action)) {
198 $this->action = new moodle_url($this->action);
199 }
200 if (self::$autofindactive) {
201 $this->check_if_active();
202 }
203 }
d38a4849
SH
204 if (array_key_exists('parent', $properties)) {
205 $this->set_parent($properties['parent']);
206 }
7d2a0492 207 } else if (is_string($properties)) {
208 $this->text = $properties;
209 }
210 if ($this->text === null) {
211 throw new coding_exception('You must set the text for the node when you create it.');
212 }
3406acde
SH
213 // Instantiate a new navigation node collection for this nodes children
214 $this->children = new navigation_node_collection();
7d2a0492 215 }
216
95b97515 217 /**
3406acde 218 * Checks if this node is the active node.
0baa5d46 219 *
3406acde
SH
220 * This is determined by comparing the action for the node against the
221 * defined URL for the page. A match will see this node marked as active.
0baa5d46 222 *
3406acde
SH
223 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
224 * @return bool
7d2a0492 225 */
bf6c37c7 226 public function check_if_active($strength=URL_MATCH_EXACT) {
227 global $FULLME, $PAGE;
3406acde 228 // Set fullmeurl if it hasn't already been set
7d2a0492 229 if (self::$fullmeurl == null) {
bf6c37c7 230 if ($PAGE->has_set_url()) {
3406acde 231 self::override_active_url(new moodle_url($PAGE->url));
bf6c37c7 232 } else {
3406acde 233 self::override_active_url(new moodle_url($FULLME));
7d2a0492 234 }
235 }
bf6c37c7 236
3406acde 237 // Compare the action of this node against the fullmeurl
bf6c37c7 238 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
7d2a0492 239 $this->make_active();
240 return true;
7d2a0492 241 }
242 return false;
243 }
3406acde 244
99061152
DW
245 /**
246 * True if this nav node has siblings in the tree.
247 *
248 * @return bool
249 */
250 public function has_siblings() {
251 if (empty($this->parent) || empty($this->parent->children)) {
252 return false;
253 }
254 if ($this->parent->children instanceof navigation_node_collection) {
255 $count = $this->parent->children->count();
256 } else {
257 $count = count($this->parent->children);
258 }
259 return ($count > 1);
260 }
261
99061152
DW
262 /**
263 * Get a list of sibling navigation nodes at the same level as this one.
264 *
265 * @return bool|array of navigation_node
266 */
267 public function get_siblings() {
268 // Returns a list of the siblings of the current node for display in a flat navigation element. Either
269 // the in-page links or the breadcrumb links.
270 $siblings = false;
271
272 if ($this->has_siblings()) {
273 $siblings = [];
274 foreach ($this->parent->children as $child) {
275 if ($child->display) {
276 $siblings[] = $child;
277 }
278 }
279 }
280 return $siblings;
281 }
282
7d2a0492 283 /**
d0cfbab3
SH
284 * This sets the URL that the URL of new nodes get compared to when locating
285 * the active node.
286 *
287 * The active node is the node that matches the URL set here. By default this
288 * is either $PAGE->url or if that hasn't been set $FULLME.
7d2a0492 289 *
3406acde 290 * @param moodle_url $url The url to use for the fullmeurl.
61bb8c93 291 * @param bool $loadadmintree use true if the URL point to administration tree
3406acde 292 */
61bb8c93 293 public static function override_active_url(moodle_url $url, $loadadmintree = false) {
633c0843
TH
294 // Clone the URL, in case the calling script changes their URL later.
295 self::$fullmeurl = new moodle_url($url);
61bb8c93
PS
296 // True means we do not want AJAX loaded admin tree, required for all admin pages.
297 if ($loadadmintree) {
298 // Do not change back to false if already set.
299 self::$loadadmintree = true;
300 }
301 }
302
303 /**
304 * Use when page is linked from the admin tree,
305 * if not used navigation could not find the page using current URL
306 * because the tree is not fully loaded.
307 */
308 public static function require_admin_tree() {
309 self::$loadadmintree = true;
3406acde
SH
310 }
311
312 /**
188a8127 313 * Creates a navigation node, ready to add it as a child using add_node
314 * function. (The created node needs to be added before you can use it.)
3406acde
SH
315 * @param string $text
316 * @param moodle_url|action_link $action
317 * @param int $type
318 * @param string $shorttext
319 * @param string|int $key
320 * @param pix_icon $icon
321 * @return navigation_node
7d2a0492 322 */
188a8127 323 public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
324 $shorttext=null, $key=null, pix_icon $icon=null) {
3406acde
SH
325 // Properties array used when creating the new navigation node
326 $itemarray = array(
327 'text' => $text,
328 'type' => $type
329 );
330 // Set the action if one was provided
7d2a0492 331 if ($action!==null) {
332 $itemarray['action'] = $action;
333 }
3406acde 334 // Set the shorttext if one was provided
7d2a0492 335 if ($shorttext!==null) {
336 $itemarray['shorttext'] = $shorttext;
337 }
3406acde 338 // Set the icon if one was provided
7d2a0492 339 if ($icon!==null) {
340 $itemarray['icon'] = $icon;
341 }
3406acde 342 // Set the key
7d2a0492 343 $itemarray['key'] = $key;
188a8127 344 // Construct and return
345 return new navigation_node($itemarray);
346 }
347
348 /**
349 * Adds a navigation node as a child of this node.
350 *
351 * @param string $text
352 * @param moodle_url|action_link $action
353 * @param int $type
354 * @param string $shorttext
355 * @param string|int $key
356 * @param pix_icon $icon
357 * @return navigation_node
358 */
359 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
360 // Create child node
361 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
362
363 // Add the child to end and return
364 return $this->add_node($childnode);
365 }
366
367 /**
368 * Adds a navigation node as a child of this one, given a $node object
369 * created using the create function.
370 * @param navigation_node $childnode Node to add
31fde54f 371 * @param string $beforekey
188a8127 372 * @return navigation_node The added node
373 */
374 public function add_node(navigation_node $childnode, $beforekey=null) {
375 // First convert the nodetype for this node to a branch as it will now have children
376 if ($this->nodetype !== self::NODETYPE_BRANCH) {
377 $this->nodetype = self::NODETYPE_BRANCH;
378 }
3406acde 379 // Set the parent to this node
d38a4849 380 $childnode->set_parent($this);
188a8127 381
382 // Default the key to the number of children if not provided
383 if ($childnode->key === null) {
384 $childnode->key = $this->children->count();
385 }
386
3406acde 387 // Add the child using the navigation_node_collections add method
188a8127 388 $node = $this->children->add($childnode, $beforekey);
389
390 // If added node is a category node or the user is logged in and it's a course
391 // then mark added node as a branch (makes it expandable by AJAX)
392 $type = $childnode->type;
5ab32c11
RT
393 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
394 ($type === self::TYPE_SITE_ADMIN)) {
3406acde 395 $node->nodetype = self::NODETYPE_BRANCH;
7d2a0492 396 }
3406acde 397 // If this node is hidden mark it's children as hidden also
7d2a0492 398 if ($this->hidden) {
3406acde 399 $node->hidden = true;
7d2a0492 400 }
188a8127 401 // Return added node (reference returned by $this->children->add()
3406acde 402 return $node;
7d2a0492 403 }
404
0c2f94e0
TH
405 /**
406 * Return a list of all the keys of all the child nodes.
407 * @return array the keys.
408 */
409 public function get_children_key_list() {
410 return $this->children->get_key_list();
411 }
412
7d2a0492 413 /**
3406acde 414 * Searches for a node of the given type with the given key.
7d2a0492 415 *
3406acde
SH
416 * This searches this node plus all of its children, and their children....
417 * If you know the node you are looking for is a child of this node then please
418 * use the get method instead.
419 *
420 * @param int|string $key The key of the node we are looking for
421 * @param int $type One of navigation_node::TYPE_*
422 * @return navigation_node|false
7d2a0492 423 */
3406acde
SH
424 public function find($key, $type) {
425 return $this->children->find($key, $type);
426 }
427
99061152
DW
428 /**
429 * Walk the tree building up a list of all the flat navigation nodes.
430 *
431 * @param flat_navigation $nodes List of the found flat navigation nodes.
c9d6a047 432 * @param boolean $showdivider Show a divider before the first node.
9df03b19 433 * @param string $label A label for the collection of navigation links.
99061152 434 */
9df03b19 435 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') {
99061152
DW
436 if ($this->showinflatnavigation) {
437 $indent = 0;
e53a38c6 438 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) {
99061152
DW
439 $indent = 1;
440 }
c9d6a047 441 $flat = new flat_navigation_node($this, $indent);
9df03b19 442 $flat->set_showdivider($showdivider, $label);
c9d6a047 443 $nodes->add($flat);
99061152
DW
444 }
445 foreach ($this->children as $child) {
c9d6a047 446 $child->build_flat_navigation_list($nodes, false);
99061152
DW
447 }
448 }
449
3406acde 450 /**
31fde54f 451 * Get the child of this node that has the given key + (optional) type.
3406acde 452 *
f495187d 453 * If you are looking for a node and want to search all children + their children
3406acde
SH
454 * then please use the find method instead.
455 *
456 * @param int|string $key The key of the node we are looking for
457 * @param int $type One of navigation_node::TYPE_*
458 * @return navigation_node|false
459 */
460 public function get($key, $type=null) {
461 return $this->children->get($key, $type);
462 }
463
464 /**
465 * Removes this node.
466 *
467 * @return bool
468 */
469 public function remove() {
470 return $this->parent->children->remove($this->key, $this->type);
471 }
472
473 /**
474 * Checks if this node has or could have any children
475 *
476 * @return bool Returns true if it has children or could have (by AJAX expansion)
477 */
478 public function has_children() {
58b602da 479 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
3406acde
SH
480 }
481
482 /**
483 * Marks this node as active and forces it open.
d0cfbab3
SH
484 *
485 * Important: If you are here because you need to mark a node active to get
93123b17 486 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
d0cfbab3
SH
487 * You can use it to specify a different URL to match the active navigation node on
488 * rather than having to locate and manually mark a node active.
3406acde
SH
489 */
490 public function make_active() {
491 $this->isactive = true;
492 $this->add_class('active_tree_node');
493 $this->force_open();
494 if ($this->parent !== null) {
495 $this->parent->make_inactive();
496 }
497 }
498
499 /**
500 * Marks a node as inactive and recusised back to the base of the tree
501 * doing the same to all parents.
502 */
503 public function make_inactive() {
504 $this->isactive = false;
505 $this->remove_class('active_tree_node');
506 if ($this->parent !== null) {
507 $this->parent->make_inactive();
7d2a0492 508 }
509 }
510
511 /**
3406acde
SH
512 * Forces this node to be open and at the same time forces open all
513 * parents until the root node.
117bd748 514 *
3406acde
SH
515 * Recursive.
516 */
517 public function force_open() {
518 $this->forceopen = true;
519 if ($this->parent !== null) {
520 $this->parent->force_open();
521 }
522 }
523
524 /**
525 * Adds a CSS class to this node.
526 *
527 * @param string $class
528 * @return bool
7d2a0492 529 */
530 public function add_class($class) {
531 if (!in_array($class, $this->classes)) {
532 $this->classes[] = $class;
533 }
534 return true;
535 }
536
537 /**
3406acde 538 * Removes a CSS class from this node.
7d2a0492 539 *
540 * @param string $class
3406acde 541 * @return bool True if the class was successfully removed.
7d2a0492 542 */
543 public function remove_class($class) {
544 if (in_array($class, $this->classes)) {
545 $key = array_search($class,$this->classes);
546 if ($key!==false) {
547 unset($this->classes[$key]);
548 return true;
549 }
550 }
551 return false;
552 }
553
554 /**
3406acde
SH
555 * Sets the title for this node and forces Moodle to utilise it.
556 * @param string $title
557 */
558 public function title($title) {
559 $this->title = $title;
560 $this->forcetitle = true;
561 }
562
563 /**
564 * Resets the page specific information on this node if it is being unserialised.
565 */
566 public function __wakeup(){
567 $this->forceopen = false;
568 $this->isactive = false;
569 $this->remove_class('active_tree_node');
570 }
571
572 /**
573 * Checks if this node or any of its children contain the active node.
435a512e 574 *
3406acde 575 * Recursive.
7d2a0492 576 *
3406acde 577 * @return bool
7d2a0492 578 */
3406acde
SH
579 public function contains_active_node() {
580 if ($this->isactive) {
7d2a0492 581 return true;
582 } else {
3406acde
SH
583 foreach ($this->children as $child) {
584 if ($child->isactive || $child->contains_active_node()) {
585 return true;
586 }
587 }
7d2a0492 588 }
3406acde 589 return false;
7d2a0492 590 }
591
aad8c716
DW
592 /**
593 * To better balance the admin tree, we want to group all the short top branches together.
594 *
595 * This means < 8 nodes and no subtrees.
596 *
597 * @return bool
598 */
599 public function is_short_branch() {
600 $limit = 8;
601 if ($this->children->count() >= $limit) {
602 return false;
603 }
604 foreach ($this->children as $child) {
605 if ($child->has_children()) {
606 return false;
607 }
608 }
609 return true;
610 }
611
7d2a0492 612 /**
3406acde
SH
613 * Finds the active node.
614 *
615 * Searches this nodes children plus all of the children for the active node
616 * and returns it if found.
7d2a0492 617 *
3406acde
SH
618 * Recursive.
619 *
620 * @return navigation_node|false
7d2a0492 621 */
3406acde
SH
622 public function find_active_node() {
623 if ($this->isactive) {
624 return $this;
625 } else {
7d2a0492 626 foreach ($this->children as &$child) {
3406acde
SH
627 $outcome = $child->find_active_node();
628 if ($outcome !== false) {
629 return $outcome;
7d2a0492 630 }
631 }
7d2a0492 632 }
3406acde 633 return false;
7d2a0492 634 }
635
7c4efe3b
SH
636 /**
637 * Searches all children for the best matching active node
638 * @return navigation_node|false
639 */
640 public function search_for_active_node() {
641 if ($this->check_if_active(URL_MATCH_BASE)) {
642 return $this;
643 } else {
644 foreach ($this->children as &$child) {
645 $outcome = $child->search_for_active_node();
646 if ($outcome !== false) {
647 return $outcome;
648 }
649 }
650 }
651 return false;
652 }
653
7d2a0492 654 /**
3406acde 655 * Gets the content for this node.
7d2a0492 656 *
3406acde
SH
657 * @param bool $shorttext If true shorttext is used rather than the normal text
658 * @return string
7d2a0492 659 */
3406acde 660 public function get_content($shorttext=false) {
7d2a0492 661 if ($shorttext && $this->shorttext!==null) {
3406acde 662 return format_string($this->shorttext);
7d2a0492 663 } else {
3406acde 664 return format_string($this->text);
1c4eef57 665 }
3406acde 666 }
1c4eef57 667
3406acde
SH
668 /**
669 * Gets the title to use for this node.
435a512e 670 *
3406acde
SH
671 * @return string
672 */
673 public function get_title() {
bbfa9be0 674 if ($this->forcetitle || $this->action != null){
3406acde
SH
675 return $this->title;
676 } else {
9bf16314
PS
677 return '';
678 }
7d2a0492 679 }
117bd748 680
d893a411
DW
681 /**
682 * Used to easily determine if this link in the breadcrumbs has a valid action/url.
683 *
684 * @return boolean
685 */
686 public function has_action() {
687 return !empty($this->action);
688 }
689
8665cc33
FS
690 /**
691 * Used to easily determine if this link in the breadcrumbs is hidden.
692 *
693 * @return boolean
694 */
695 public function is_hidden() {
696 return $this->hidden;
697 }
698
7d2a0492 699 /**
3406acde 700 * Gets the CSS class to add to this node to describe its type
435a512e 701 *
7d2a0492 702 * @return string
703 */
704 public function get_css_type() {
705 if (array_key_exists($this->type, $this->namedtypes)) {
706 return 'type_'.$this->namedtypes[$this->type];
707 }
708 return 'type_unknown';
709 }
710
711 /**
3406acde 712 * Finds all nodes that are expandable by AJAX
7d2a0492 713 *
3406acde 714 * @param array $expandable An array by reference to populate with expandable nodes.
7d2a0492 715 */
3406acde 716 public function find_expandable(array &$expandable) {
3406acde 717 foreach ($this->children as &$child) {
58b602da 718 if ($child->display && $child->has_children() && $child->children->count() == 0) {
09da042b 719 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
3406acde 720 $this->add_class('canexpand');
f8895446 721 $child->requiresajaxloading = true;
8ad24c1a 722 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
7d2a0492 723 }
3406acde 724 $child->find_expandable($expandable);
7d2a0492 725 }
7d2a0492 726 }
88f77c3c 727
4766a50c
SH
728 /**
729 * Finds all nodes of a given type (recursive)
730 *
31fde54f 731 * @param int $type One of navigation_node::TYPE_*
4766a50c
SH
732 * @return array
733 */
88f77c3c
SH
734 public function find_all_of_type($type) {
735 $nodes = $this->children->type($type);
736 foreach ($this->children as &$node) {
737 $childnodes = $node->find_all_of_type($type);
738 $nodes = array_merge($nodes, $childnodes);
739 }
740 return $nodes;
741 }
56ed242b
SH
742
743 /**
744 * Removes this node if it is empty
745 */
746 public function trim_if_empty() {
747 if ($this->children->count() == 0) {
748 $this->remove();
749 }
750 }
751
752 /**
753 * Creates a tab representation of this nodes children that can be used
754 * with print_tabs to produce the tabs on a page.
755 *
756 * call_user_func_array('print_tabs', $node->get_tabs_array());
757 *
758 * @param array $inactive
759 * @param bool $return
760 * @return array Array (tabs, selected, inactive, activated, return)
761 */
762 public function get_tabs_array(array $inactive=array(), $return=false) {
763 $tabs = array();
764 $rows = array();
765 $selected = null;
766 $activated = array();
767 foreach ($this->children as $node) {
768 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
769 if ($node->contains_active_node()) {
770 if ($node->children->count() > 0) {
771 $activated[] = $node->key;
772 foreach ($node->children as $child) {
773 if ($child->contains_active_node()) {
774 $selected = $child->key;
775 }
776 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
777 }
778 } else {
779 $selected = $node->key;
780 }
781 }
782 }
783 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
784 }
d38a4849
SH
785
786 /**
787 * Sets the parent for this node and if this node is active ensures that the tree is properly
788 * adjusted as well.
789 *
790 * @param navigation_node $parent
791 */
792 public function set_parent(navigation_node $parent) {
793 // Set the parent (thats the easy part)
794 $this->parent = $parent;
795 // Check if this node is active (this is checked during construction)
796 if ($this->isactive) {
797 // Force all of the parent nodes open so you can see this node
798 $this->parent->force_open();
799 // Make all parents inactive so that its clear where we are.
800 $this->parent->make_inactive();
801 }
802 }
ba7b1ca5
SH
803
804 /**
805 * Hides the node and any children it has.
806 *
5bcfd504 807 * @since Moodle 2.5
8718ffba
SH
808 * @param array $typestohide Optional. An array of node types that should be hidden.
809 * If null all nodes will be hidden.
810 * If an array is given then nodes will only be hidden if their type mtatches an element in the array.
811 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
812 */
813 public function hide(array $typestohide = null) {
814 if ($typestohide === null || in_array($this->type, $typestohide)) {
815 $this->display = false;
816 if ($this->has_children()) {
817 foreach ($this->children as $child) {
818 $child->hide($typestohide);
819 }
ba7b1ca5
SH
820 }
821 }
822 }
88e709ae
DW
823
824 /**
825 * Get the action url for this navigation node.
826 * Called from templates.
827 *
828 * @since Moodle 3.2
829 */
830 public function action() {
831 if ($this->action instanceof moodle_url) {
832 return $this->action;
833 } else if ($this->action instanceof action_link) {
834 return $this->action->url;
835 }
836 return $this->action;
837 }
3a8cf5e6
AN
838
839 /**
840 * Add the menu item to handle locking and unlocking of a conext.
841 *
842 * @param \navigation_node $node Node to add
843 * @param \context $context The context to be locked
844 */
845 protected function add_context_locking_node(\navigation_node $node, \context $context) {
846 global $CFG;
847 // Manage context locking.
848 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) {
849 $parentcontext = $context->get_parent_context();
850 if (empty($parentcontext) || !$parentcontext->locked) {
851 if ($context->locked) {
852 $lockicon = 'i/unlock';
853 $lockstring = get_string('managecontextunlock', 'admin');
854 } else {
855 $lockicon = 'i/lock';
856 $lockstring = get_string('managecontextlock', 'admin');
857 }
858 $node->add(
859 $lockstring,
860 new moodle_url(
861 '/admin/lock.php',
862 [
863 'id' => $context->id,
864 ]
865 ),
866 self::TYPE_SETTING,
867 null,
868 'contextlocking',
869 new pix_icon($lockicon, '')
870 );
871 }
872 }
873
874 }
3406acde 875}
7d2a0492 876
3406acde
SH
877/**
878 * Navigation node collection
879 *
880 * This class is responsible for managing a collection of navigation nodes.
881 * It is required because a node's unique identifier is a combination of both its
882 * key and its type.
883 *
884 * Originally an array was used with a string key that was a combination of the two
885 * however it was decided that a better solution would be to use a class that
886 * implements the standard IteratorAggregate interface.
887 *
31fde54f
AG
888 * @package core
889 * @category navigation
3406acde
SH
890 * @copyright 2010 Sam Hemelryk
891 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
892 */
78da366b 893class navigation_node_collection implements IteratorAggregate, Countable {
7d2a0492 894 /**
3406acde
SH
895 * A multidimensional array to where the first key is the type and the second
896 * key is the nodes key.
897 * @var array
7d2a0492 898 */
3406acde 899 protected $collection = array();
7d2a0492 900 /**
3406acde
SH
901 * An array that contains references to nodes in the same order they were added.
902 * This is maintained as a progressive array.
903 * @var array
7d2a0492 904 */
3406acde 905 protected $orderedcollection = array();
da3ab9c4 906 /**
3406acde
SH
907 * A reference to the last node that was added to the collection
908 * @var navigation_node
da3ab9c4 909 */
3406acde 910 protected $last = null;
6644741d 911 /**
3406acde
SH
912 * The total number of items added to this array.
913 * @var int
6644741d 914 */
3406acde 915 protected $count = 0;
0c2f94e0 916
9df03b19
DW
917 /**
918 * Label for collection of nodes.
919 * @var string
920 */
921 protected $collectionlabel = '';
922
7d2a0492 923 /**
3406acde 924 * Adds a navigation node to the collection
7d2a0492 925 *
188a8127 926 * @param navigation_node $node Node to add
927 * @param string $beforekey If specified, adds before a node with this key,
928 * otherwise adds at end
929 * @return navigation_node Added node
7d2a0492 930 */
188a8127 931 public function add(navigation_node $node, $beforekey=null) {
3406acde
SH
932 global $CFG;
933 $key = $node->key;
934 $type = $node->type;
188a8127 935
3406acde
SH
936 // First check we have a 2nd dimension for this type
937 if (!array_key_exists($type, $this->orderedcollection)) {
938 $this->orderedcollection[$type] = array();
7d2a0492 939 }
3406acde
SH
940 // Check for a collision and report if debugging is turned on
941 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
942 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
7d2a0492 943 }
188a8127 944
945 // Find the key to add before
946 $newindex = $this->count;
947 $last = true;
948 if ($beforekey !== null) {
949 foreach ($this->collection as $index => $othernode) {
950 if ($othernode->key === $beforekey) {
951 $newindex = $index;
952 $last = false;
953 break;
954 }
955 }
956 if ($newindex === $this->count) {
188a8127 957 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
0c2f94e0 958 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
188a8127 959 }
960 }
961
962 // Add the node to the appropriate place in the by-type structure (which
963 // is not ordered, despite the variable name)
3406acde 964 $this->orderedcollection[$type][$key] = $node;
188a8127 965 if (!$last) {
966 // Update existing references in the ordered collection (which is the
967 // one that isn't called 'ordered') to shuffle them along if required
968 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
969 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
970 }
971 }
3406acde 972 // Add a reference to the node to the progressive collection.
082513ba 973 $this->collection[$newindex] = $this->orderedcollection[$type][$key];
3406acde 974 // Update the last property to a reference to this new node.
082513ba 975 $this->last = $this->orderedcollection[$type][$key];
5436561c 976
188a8127 977 // Reorder the array by index if needed
978 if (!$last) {
979 ksort($this->collection);
188a8127 980 }
3406acde
SH
981 $this->count++;
982 // Return the reference to the now added node
188a8127 983 return $node;
7d2a0492 984 }
985
0c2f94e0
TH
986 /**
987 * Return a list of all the keys of all the nodes.
988 * @return array the keys.
989 */
990 public function get_key_list() {
991 $keys = array();
992 foreach ($this->collection as $node) {
993 $keys[] = $node->key;
994 }
995 return $keys;
996 }
997
9df03b19
DW
998 /**
999 * Set a label for this collection.
1000 *
1001 * @param string $label
1002 */
1003 public function set_collectionlabel($label) {
1004 $this->collectionlabel = $label;
1005 }
1006
1007 /**
1008 * Return a label for this collection.
1009 *
1010 * @return string
1011 */
1012 public function get_collectionlabel() {
1013 return $this->collectionlabel;
1014 }
1015
7d2a0492 1016 /**
3406acde 1017 * Fetches a node from this collection.
7d2a0492 1018 *
3406acde
SH
1019 * @param string|int $key The key of the node we want to find.
1020 * @param int $type One of navigation_node::TYPE_*.
1021 * @return navigation_node|null
7d2a0492 1022 */
3406acde
SH
1023 public function get($key, $type=null) {
1024 if ($type !== null) {
1025 // If the type is known then we can simply check and fetch
1026 if (!empty($this->orderedcollection[$type][$key])) {
1027 return $this->orderedcollection[$type][$key];
1028 }
1029 } else {
1030 // Because we don't know the type we look in the progressive array
1031 foreach ($this->collection as $node) {
1032 if ($node->key === $key) {
1033 return $node;
7d2a0492 1034 }
1035 }
1036 }
1037 return false;
1038 }
0c2f94e0 1039
7d2a0492 1040 /**
3406acde 1041 * Searches for a node with matching key and type.
7d2a0492 1042 *
3406acde
SH
1043 * This function searches both the nodes in this collection and all of
1044 * the nodes in each collection belonging to the nodes in this collection.
7d2a0492 1045 *
3406acde 1046 * Recursive.
7d2a0492 1047 *
3406acde
SH
1048 * @param string|int $key The key of the node we want to find.
1049 * @param int $type One of navigation_node::TYPE_*.
1050 * @return navigation_node|null
7d2a0492 1051 */
3406acde
SH
1052 public function find($key, $type=null) {
1053 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
1054 return $this->orderedcollection[$type][$key];
1055 } else {
1056 $nodes = $this->getIterator();
1057 // Search immediate children first
1058 foreach ($nodes as &$node) {
d9219fc9 1059 if ($node->key === $key && ($type === null || $type === $node->type)) {
3406acde 1060 return $node;
d926f4b1 1061 }
3406acde
SH
1062 }
1063 // Now search each childs children
1064 foreach ($nodes as &$node) {
1065 $result = $node->children->find($key, $type);
1066 if ($result !== false) {
1067 return $result;
d926f4b1 1068 }
7d2a0492 1069 }
1070 }
1071 return false;
1072 }
1073
d926f4b1 1074 /**
3406acde 1075 * Fetches the last node that was added to this collection
435a512e 1076 *
3406acde 1077 * @return navigation_node
d926f4b1 1078 */
3406acde
SH
1079 public function last() {
1080 return $this->last;
1081 }
0c2f94e0 1082
3406acde
SH
1083 /**
1084 * Fetches all nodes of a given type from this collection
31fde54f
AG
1085 *
1086 * @param string|int $type node type being searched for.
1087 * @return array ordered collection
3406acde
SH
1088 */
1089 public function type($type) {
1090 if (!array_key_exists($type, $this->orderedcollection)) {
1091 $this->orderedcollection[$type] = array();
d926f4b1 1092 }
3406acde 1093 return $this->orderedcollection[$type];
d926f4b1 1094 }
7d2a0492 1095 /**
3406acde 1096 * Removes the node with the given key and type from the collection
7d2a0492 1097 *
31fde54f 1098 * @param string|int $key The key of the node we want to find.
3406acde
SH
1099 * @param int $type
1100 * @return bool
7d2a0492 1101 */
3406acde
SH
1102 public function remove($key, $type=null) {
1103 $child = $this->get($key, $type);
1104 if ($child !== false) {
1105 foreach ($this->collection as $colkey => $node) {
eb9a3e93 1106 if ($node->key === $key && (is_null($type) || $node->type == $type)) {
3406acde 1107 unset($this->collection[$colkey]);
5150c302 1108 $this->collection = array_values($this->collection);
3406acde
SH
1109 break;
1110 }
7d2a0492 1111 }
3406acde
SH
1112 unset($this->orderedcollection[$child->type][$child->key]);
1113 $this->count--;
1114 return true;
7d2a0492 1115 }
3406acde 1116 return false;
7d2a0492 1117 }
1118
9da1ec27 1119 /**
3406acde 1120 * Gets the number of nodes in this collection
e26507b3
SH
1121 *
1122 * This option uses an internal count rather than counting the actual options to avoid
1123 * a performance hit through the count function.
1124 *
3406acde 1125 * @return int
7d2a0492 1126 */
3406acde 1127 public function count() {
e26507b3 1128 return $this->count;
7d2a0492 1129 }
7d2a0492 1130 /**
3406acde 1131 * Gets an array iterator for the collection.
7d2a0492 1132 *
3406acde
SH
1133 * This is required by the IteratorAggregator interface and is used by routines
1134 * such as the foreach loop.
7d2a0492 1135 *
3406acde 1136 * @return ArrayIterator
7d2a0492 1137 */
3406acde
SH
1138 public function getIterator() {
1139 return new ArrayIterator($this->collection);
7d2a0492 1140 }
1141}
1142
1143/**
1144 * The global navigation class used for... the global navigation
1145 *
1146 * This class is used by PAGE to store the global navigation for the site
1147 * and is then used by the settings nav and navbar to save on processing and DB calls
1148 *
1149 * See
93123b17 1150 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
31fde54f 1151 * {@link lib/ajax/getnavbranch.php} Called by ajax
7d2a0492 1152 *
31fde54f
AG
1153 * @package core
1154 * @category navigation
7d2a0492 1155 * @copyright 2009 Sam Hemelryk
1156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1157 */
1158class global_navigation extends navigation_node {
31fde54f 1159 /** @var moodle_page The Moodle page this navigation object belongs to. */
3406acde 1160 protected $page;
31fde54f 1161 /** @var bool switch to let us know if the navigation object is initialised*/
7d2a0492 1162 protected $initialised = false;
31fde54f 1163 /** @var array An array of course information */
3406acde 1164 protected $mycourses = array();
aab6438c 1165 /** @var navigation_node[] An array for containing root navigation nodes */
3406acde 1166 protected $rootnodes = array();
31fde54f 1167 /** @var bool A switch for whether to show empty sections in the navigation */
fe221dd5 1168 protected $showemptysections = true;
31fde54f 1169 /** @var bool A switch for whether courses should be shown within categories on the navigation. */
9bf5af21 1170 protected $showcategories = null;
58b602da
SH
1171 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
1172 protected $showmycategories = null;
31fde54f 1173 /** @var array An array of stdClasses for users that the navigation is extended for */
7a7e209d 1174 protected $extendforuser = array();
3406acde
SH
1175 /** @var navigation_cache */
1176 protected $cache;
31fde54f 1177 /** @var array An array of course ids that are present in the navigation */
3406acde 1178 protected $addedcourses = array();
8e8de15f
SH
1179 /** @var bool */
1180 protected $allcategoriesloaded = false;
31fde54f 1181 /** @var array An array of category ids that are included in the navigation */
e26507b3 1182 protected $addedcategories = array();
31fde54f 1183 /** @var int expansion limit */
88f77c3c 1184 protected $expansionlimit = 0;
31fde54f 1185 /** @var int userid to allow parent to see child's profile page navigation */
870815fa 1186 protected $useridtouseforparentchecks = 0;
cbd063f4
SH
1187 /** @var cache_session A cache that stores information on expanded courses */
1188 protected $cacheexpandcourse = null;
88f77c3c 1189
8e8de15f
SH
1190 /** Used when loading categories to load all top level categories [parent = 0] **/
1191 const LOAD_ROOT_CATEGORIES = 0;
1192 /** Used when loading categories to load all categories **/
1193 const LOAD_ALL_CATEGORIES = -1;
1194
7d2a0492 1195 /**
3406acde
SH
1196 * Constructs a new global navigation
1197 *
3406acde 1198 * @param moodle_page $page The page this navigation object belongs to
7d2a0492 1199 */
3406acde 1200 public function __construct(moodle_page $page) {
4766a50c 1201 global $CFG, $SITE, $USER;
3406acde 1202
7d2a0492 1203 if (during_initial_install()) {
3406acde 1204 return;
7d2a0492 1205 }
3406acde 1206
4766a50c
SH
1207 if (get_home_page() == HOMEPAGE_SITE) {
1208 // We are using the site home for the root element
1209 $properties = array(
1210 'key' => 'home',
1211 'type' => navigation_node::TYPE_SYSTEM,
1212 'text' => get_string('home'),
45ae297f
KO
1213 'action' => new moodle_url('/'),
1214 'icon' => new pix_icon('i/home', '')
4766a50c
SH
1215 );
1216 } else {
1217 // We are using the users my moodle for the root element
1218 $properties = array(
1219 'key' => 'myhome',
1220 'type' => navigation_node::TYPE_SYSTEM,
1221 'text' => get_string('myhome'),
64448e1e
KO
1222 'action' => new moodle_url('/my/'),
1223 'icon' => new pix_icon('i/dashboard', '')
4766a50c 1224 );
dd8e5011 1225 }
4766a50c 1226
31fde54f 1227 // Use the parents constructor.... good good reuse
3406acde 1228 parent::__construct($properties);
99061152 1229 $this->showinflatnavigation = true;
3406acde
SH
1230
1231 // Initalise and set defaults
1232 $this->page = $page;
7d2a0492 1233 $this->forceopen = true;
f5b5a822 1234 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
7d2a0492 1235 }
1236
b9bcad24
AB
1237 /**
1238 * Mutator to set userid to allow parent to see child's profile
1239 * page navigation. See MDL-25805 for initial issue. Linked to it
1240 * is an issue explaining why this is a REALLY UGLY HACK thats not
1241 * for you to use!
1242 *
5607036a 1243 * @param int $userid userid of profile page that parent wants to navigate around.
b9bcad24 1244 */
870815fa
SH
1245 public function set_userid_for_parent_checks($userid) {
1246 $this->useridtouseforparentchecks = $userid;
b9bcad24
AB
1247 }
1248
1249
7d2a0492 1250 /**
3406acde 1251 * Initialises the navigation object.
7d2a0492 1252 *
3406acde
SH
1253 * This causes the navigation object to look at the current state of the page
1254 * that it is associated with and then load the appropriate content.
7d2a0492 1255 *
3406acde
SH
1256 * This should only occur the first time that the navigation structure is utilised
1257 * which will normally be either when the navbar is called to be displayed or
1258 * when a block makes use of it.
7d2a0492 1259 *
3406acde 1260 * @return bool
7d2a0492 1261 */
3406acde 1262 public function initialise() {
58b602da
SH
1263 global $CFG, $SITE, $USER;
1264 // Check if it has already been initialised
7d2a0492 1265 if ($this->initialised || during_initial_install()) {
1266 return true;
1267 }
e2b436d0 1268 $this->initialised = true;
3406acde
SH
1269
1270 // Set up the five base root nodes. These are nodes where we will put our
1271 // content and are as follows:
58b602da
SH
1272 // site: Navigation for the front page.
1273 // myprofile: User profile information goes here.
1274 // currentcourse: The course being currently viewed.
1275 // mycourses: The users courses get added here.
1276 // courses: Additional courses are added here.
1277 // users: Other users information loaded here.
3406acde 1278 $this->rootnodes = array();
4766a50c 1279 if (get_home_page() == HOMEPAGE_SITE) {
3f9ccf85 1280 // The home element should be my moodle because the root element is the site
b9d4c7d3 1281 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
45ae297f
KO
1282 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'),
1283 self::TYPE_SETTING, null, 'home', new pix_icon('i/dashboard', ''));
8a2ab5f7 1284 $this->rootnodes['home']->showinflatnavigation = true;
3f9ccf85 1285 }
4766a50c
SH
1286 } else {
1287 // The home element should be the site because the root node is my moodle
64448e1e
KO
1288 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'),
1289 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', ''));
8a2ab5f7 1290 $this->rootnodes['home']->showinflatnavigation = true;
ab6ec58a 1291 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
4766a50c
SH
1292 // We need to stop automatic redirection
1293 $this->rootnodes['home']->action->param('redirect', '0');
1294 }
1295 }
58b602da 1296 $this->rootnodes['site'] = $this->add_course($SITE);
4887d152 1297 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
6caf3f5c 1298 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
64448e1e 1299 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses', new pix_icon('i/course', ''));
58b602da
SH
1300 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1301 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
3406acde 1302
80c69522
SH
1303 // We always load the frontpage course to ensure it is available without
1304 // JavaScript enabled.
1305 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1306 $this->load_course_sections($SITE, $this->rootnodes['site']);
1307
58b602da 1308 $course = $this->page->course;
99061152 1309 $this->load_courses_enrolled();
58b602da 1310
8e8de15f 1311 // $issite gets set to true if the current pages course is the sites frontpage course
98556b23 1312 $issite = ($this->page->course->id == $SITE->id);
99061152 1313
58b602da
SH
1314 // Determine if the user is enrolled in any course.
1315 $enrolledinanycourse = enrol_user_sees_own_courses();
4766a50c 1316
58b602da
SH
1317 $this->rootnodes['currentcourse']->mainnavonly = true;
1318 if ($enrolledinanycourse) {
1319 $this->rootnodes['mycourses']->isexpandable = true;
99061152 1320 $this->rootnodes['mycourses']->showinflatnavigation = true;
58b602da
SH
1321 if ($CFG->navshowallcourses) {
1322 // When we show all courses we need to show both the my courses and the regular courses branch.
1323 $this->rootnodes['courses']->isexpandable = true;
8e8de15f 1324 }
58b602da
SH
1325 } else {
1326 $this->rootnodes['courses']->isexpandable = true;
3406acde 1327 }
8a2ab5f7 1328 $this->rootnodes['mycourses']->forceopen = true;
f87ce4e9 1329
cede87e0
SH
1330 $canviewcourseprofile = true;
1331
6a16e136
SH
1332 // Next load context specific content into the navigation
1333 switch ($this->page->context->contextlevel) {
1334 case CONTEXT_SYSTEM :
58b602da 1335 // Nothing left to do here I feel.
6a16e136
SH
1336 break;
1337 case CONTEXT_COURSECAT :
58b602da
SH
1338 // This is essential, we must load categories.
1339 $this->load_all_categories($this->page->context->instanceid, true);
6a16e136
SH
1340 break;
1341 case CONTEXT_BLOCK :
1342 case CONTEXT_COURSE :
1343 if ($issite) {
58b602da 1344 // Nothing left to do here.
56c062a4 1345 break;
6a16e136 1346 }
b9bcad24 1347
6caf3f5c 1348 // Load the course associated with the current page into the navigation.
6caf3f5c 1349 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
6a16e136
SH
1350 // If the course wasn't added then don't try going any further.
1351 if (!$coursenode) {
1352 $canviewcourseprofile = false;
1353 break;
1354 }
e26507b3 1355
6a16e136
SH
1356 // If the user is not enrolled then we only want to show the
1357 // course node and not populate it.
1358
1359 // Not enrolled, can't view, and hasn't switched roles
8b456850 1360 if (!can_access_course($course, null, '', true)) {
cbd063f4
SH
1361 if ($coursenode->isexpandable === true) {
1362 // Obviously the situation has changed, update the cache and adjust the node.
1363 // This occurs if the user access to a course has been revoked (one way or another) after
1364 // initially logging in for this session.
1365 $this->get_expand_course_cache()->set($course->id, 1);
1366 $coursenode->isexpandable = true;
1367 $coursenode->nodetype = self::NODETYPE_BRANCH;
1368 }
58b602da 1369 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
6a16e136 1370 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
58b602da 1371 if (!$this->current_user_is_parent_role()) {
56c062a4 1372 $coursenode->make_active();
6a16e136
SH
1373 $canviewcourseprofile = false;
1374 break;
1375 }
8b456850 1376 } else if ($coursenode->isexpandable === false) {
cbd063f4
SH
1377 // Obviously the situation has changed, update the cache and adjust the node.
1378 // This occurs if the user has been granted access to a course (one way or another) after initially
1379 // logging in for this session.
1380 $this->get_expand_course_cache()->set($course->id, 1);
1381 $coursenode->isexpandable = true;
1382 $coursenode->nodetype = self::NODETYPE_BRANCH;
1383 }
1384
6a16e136
SH
1385 // Add the essentials such as reports etc...
1386 $this->add_course_essentials($coursenode, $course);
ee7084e9
MG
1387 // Extend course navigation with it's sections/activities
1388 $this->load_course_sections($course, $coursenode);
6a16e136
SH
1389 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1390 $coursenode->make_active();
1391 }
6caf3f5c 1392
6a16e136
SH
1393 break;
1394 case CONTEXT_MODULE :
1395 if ($issite) {
1396 // If this is the site course then most information will have
1397 // already been loaded.
1398 // However we need to check if there is more content that can
1399 // yet be loaded for the specific module instance.
e010b850 1400 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
6a16e136
SH
1401 if ($activitynode) {
1402 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
56c062a4 1403 }
2027c10e 1404 break;
6a16e136 1405 }
2027c10e 1406
6a16e136
SH
1407 $course = $this->page->course;
1408 $cm = $this->page->cm;
cede87e0 1409
6a16e136 1410 // Load the course associated with the page into the navigation
58b602da 1411 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
56c062a4 1412
6a16e136
SH
1413 // If the course wasn't added then don't try going any further.
1414 if (!$coursenode) {
1415 $canviewcourseprofile = false;
1416 break;
1417 }
1418
1419 // If the user is not enrolled then we only want to show the
1420 // course node and not populate it.
8b456850 1421 if (!can_access_course($course, null, '', true)) {
6a16e136
SH
1422 $coursenode->make_active();
1423 $canviewcourseprofile = false;
1424 break;
1425 }
56c062a4 1426
6a16e136 1427 $this->add_course_essentials($coursenode, $course);
56c062a4 1428
6a16e136 1429 // Load the course sections into the page
e010b850
MG
1430 $this->load_course_sections($course, $coursenode, null, $cm);
1431 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
069c29b9
DM
1432 if (!empty($activity)) {
1433 // Finally load the cm specific navigaton information
1434 $this->load_activity($cm, $course, $activity);
1435 // Check if we have an active ndoe
1436 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1437 // And make the activity node active.
1438 $activity->make_active();
1439 }
6a16e136
SH
1440 }
1441 break;
1442 case CONTEXT_USER :
1443 if ($issite) {
1444 // The users profile information etc is already loaded
1445 // for the front page.
96e78552 1446 break;
6a16e136
SH
1447 }
1448 $course = $this->page->course;
6a16e136 1449 // Load the course associated with the user into the navigation
58b602da 1450 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2027c10e 1451
6a16e136
SH
1452 // If the course wasn't added then don't try going any further.
1453 if (!$coursenode) {
1454 $canviewcourseprofile = false;
1455 break;
1456 }
2027c10e 1457
6a16e136
SH
1458 // If the user is not enrolled then we only want to show the
1459 // course node and not populate it.
8b456850 1460 if (!can_access_course($course, null, '', true)) {
6a16e136
SH
1461 $coursenode->make_active();
1462 $canviewcourseprofile = false;
56c062a4 1463 break;
e52a5d3a 1464 }
6a16e136 1465 $this->add_course_essentials($coursenode, $course);
ee7084e9 1466 $this->load_course_sections($course, $coursenode);
6a16e136 1467 break;
7d2a0492 1468 }
7a7e209d 1469
3406acde
SH
1470 // Load for the current user
1471 $this->load_for_user();
98556b23 1472 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
87c215de
SH
1473 $this->load_for_user(null, true);
1474 }
7a7e209d
SH
1475 // Load each extending user into the navigation.
1476 foreach ($this->extendforuser as $user) {
44303ca6 1477 if ($user->id != $USER->id) {
7a7e209d
SH
1478 $this->load_for_user($user);
1479 }
1480 }
7a7e209d 1481
a683da3c 1482 // Give the local plugins a chance to include some navigation if they want.
a0ac16cb
MN
1483 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) {
1484 $function($this);
a683da3c
SH
1485 }
1486
3406acde
SH
1487 // Remove any empty root nodes
1488 foreach ($this->rootnodes as $node) {
4766a50c 1489 // Dont remove the home node
75eb202e
SH
1490 /** @var navigation_node $node */
1491 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
3406acde
SH
1492 $node->remove();
1493 }
1494 }
1495
7c4efe3b
SH
1496 if (!$this->contains_active_node()) {
1497 $this->search_for_active_node();
1498 }
1499
3406acde 1500 // If the user is not logged in modify the navigation structure as detailed
728ebac7 1501 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
3406acde
SH
1502 if (!isloggedin()) {
1503 $activities = clone($this->rootnodes['site']->children);
1504 $this->rootnodes['site']->remove();
1505 $children = clone($this->children);
1506 $this->children = new navigation_node_collection();
1507 foreach ($activities as $child) {
1508 $this->children->add($child);
1509 }
1510 foreach ($children as $child) {
1511 $this->children->add($child);
1512 }
3406acde 1513 }
7d2a0492 1514 return true;
1515 }
9bf5af21 1516
58b602da
SH
1517 /**
1518 * Returns true if the current user is a parent of the user being currently viewed.
1519 *
1520 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1521 * other user being viewed this function returns false.
1522 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1523 *
5bcfd504 1524 * @since Moodle 2.4
58b602da
SH
1525 * @return bool
1526 */
1527 protected function current_user_is_parent_role() {
1528 global $USER, $DB;
1529 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1530 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1531 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1532 return false;
1533 }
1534 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1535 return true;
1536 }
1537 }
1538 return false;
1539 }
1540
9bf5af21 1541 /**
31fde54f 1542 * Returns true if courses should be shown within categories on the navigation.
9bf5af21 1543 *
58b602da 1544 * @param bool $ismycourse Set to true if you are calculating this for a course.
9bf5af21
SH
1545 * @return bool
1546 */
58b602da 1547 protected function show_categories($ismycourse = false) {
9bf5af21 1548 global $CFG, $DB;
58b602da
SH
1549 if ($ismycourse) {
1550 return $this->show_my_categories();
1551 }
9bf5af21 1552 if ($this->showcategories === null) {
58b602da
SH
1553 $show = false;
1554 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1555 $show = true;
1556 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1557 $show = true;
1558 }
6a16e136 1559 $this->showcategories = $show;
9bf5af21
SH
1560 }
1561 return $this->showcategories;
1562 }
1563
58b602da
SH
1564 /**
1565 * Returns true if we should show categories in the My Courses branch.
1566 * @return bool
1567 */
1568 protected function show_my_categories() {
8aedc037 1569 global $CFG;
58b602da 1570 if ($this->showmycategories === null) {
442f12f8 1571 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && core_course_category::count_all() > 1;
58b602da
SH
1572 }
1573 return $this->showmycategories;
1574 }
1575
3406acde 1576 /**
31fde54f 1577 * Loads the courses in Moodle into the navigation.
3406acde 1578 *
8e8de15f
SH
1579 * @global moodle_database $DB
1580 * @param string|array $categoryids An array containing categories to load courses
1581 * for, OR null to load courses for all categories.
1582 * @return array An array of navigation_nodes one for each course
3406acde 1583 */
8e8de15f 1584 protected function load_all_courses($categoryids = null) {
98556b23 1585 global $CFG, $DB, $SITE;
4766a50c 1586
8e8de15f 1587 // Work out the limit of courses.
4766a50c
SH
1588 $limit = 20;
1589 if (!empty($CFG->navcourselimit)) {
1590 $limit = $CFG->navcourselimit;
1591 }
4766a50c 1592
8e8de15f
SH
1593 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1594
1595 // If we are going to show all courses AND we are showing categories then
1596 // to save us repeated DB calls load all of the categories now
1597 if ($this->show_categories()) {
1598 $this->load_all_categories($toload);
1599 }
1600
1601 // Will be the return of our efforts
3406acde 1602 $coursenodes = array();
8e8de15f 1603
f7ee4baa
SH
1604 // Check if we need to show categories.
1605 if ($this->show_categories()) {
1606 // Hmmm we need to show categories... this is going to be painful.
1607 // We now need to fetch up to $limit courses for each category to
1608 // be displayed.
1609 if ($categoryids !== null) {
1610 if (!is_array($categoryids)) {
1611 $categoryids = array($categoryids);
8e8de15f 1612 }
f7ee4baa
SH
1613 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1614 $categorywhere = 'WHERE cc.id '.$categorywhere;
1615 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1616 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1617 $categoryparams = array();
1618 } else {
1619 $categorywhere = '';
1620 $categoryparams = array();
1621 }
8e8de15f 1622
f7ee4baa
SH
1623 // First up we are going to get the categories that we are going to
1624 // need so that we can determine how best to load the courses from them.
1625 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1626 FROM {course_categories} cc
1627 LEFT JOIN {course} c ON c.category = cc.id
1628 {$categorywhere}
1629 GROUP BY cc.id";
1630 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1631 $fullfetch = array();
1632 $partfetch = array();
1633 foreach ($categories as $category) {
1634 if (!$this->can_add_more_courses_to_category($category->id)) {
1635 continue;
1636 }
1637 if ($category->coursecount > $limit * 5) {
1638 $partfetch[] = $category->id;
1639 } else if ($category->coursecount > 0) {
1640 $fullfetch[] = $category->id;
1641 }
1642 }
1643 $categories->close();
1644
1645 if (count($fullfetch)) {
1646 // First up fetch all of the courses in categories where we know that we are going to
1647 // need the majority of courses.
f7ee4baa 1648 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
2e4c0c91
FM
1649 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1650 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1651 $categoryparams['contextlevel'] = CONTEXT_COURSE;
f7ee4baa
SH
1652 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1653 FROM {course} c
1654 $ccjoin
fca2d3d7 1655 WHERE c.category {$categoryids}
f7ee4baa 1656 ORDER BY c.sortorder ASC";
fca2d3d7 1657 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
f7ee4baa 1658 foreach ($coursesrs as $course) {
fca2d3d7
PS
1659 if ($course->id == $SITE->id) {
1660 // This should not be necessary, frontpage is not in any category.
1661 continue;
1662 }
1663 if (array_key_exists($course->id, $this->addedcourses)) {
1664 // It is probably better to not include the already loaded courses
1665 // directly in SQL because inequalities may confuse query optimisers
1666 // and may interfere with query caching.
1667 continue;
1668 }
f7ee4baa 1669 if (!$this->can_add_more_courses_to_category($course->category)) {
8e8de15f
SH
1670 continue;
1671 }
db314f34 1672 context_helper::preload_from_record($course);
b0c6dc1c 1673 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
f7ee4baa 1674 continue;
8e8de15f 1675 }
f7ee4baa 1676 $coursenodes[$course->id] = $this->add_course($course);
8e8de15f 1677 }
f7ee4baa
SH
1678 $coursesrs->close();
1679 }
8e8de15f 1680
f7ee4baa
SH
1681 if (count($partfetch)) {
1682 // Next we will work our way through the categories where we will likely only need a small
1683 // proportion of the courses.
1684 foreach ($partfetch as $categoryid) {
2e4c0c91
FM
1685 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1686 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
8e8de15f 1687 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
f7ee4baa
SH
1688 FROM {course} c
1689 $ccjoin
fca2d3d7 1690 WHERE c.category = :categoryid
f7ee4baa 1691 ORDER BY c.sortorder ASC";
2e4c0c91 1692 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
f7ee4baa 1693 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
8e8de15f 1694 foreach ($coursesrs as $course) {
fca2d3d7
PS
1695 if ($course->id == $SITE->id) {
1696 // This should not be necessary, frontpage is not in any category.
1697 continue;
1698 }
1699 if (array_key_exists($course->id, $this->addedcourses)) {
1700 // It is probably better to not include the already loaded courses
1701 // directly in SQL because inequalities may confuse query optimisers
1702 // and may interfere with query caching.
1703 // This also helps to respect expected $limit on repeated executions.
1704 continue;
1705 }
8e8de15f 1706 if (!$this->can_add_more_courses_to_category($course->category)) {
f7ee4baa 1707 break;
8e8de15f 1708 }
db314f34 1709 context_helper::preload_from_record($course);
b0c6dc1c 1710 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
8e8de15f
SH
1711 continue;
1712 }
1713 $coursenodes[$course->id] = $this->add_course($course);
1714 }
1715 $coursesrs->close();
1716 }
8e8de15f 1717 }
8e8de15f 1718 } else {
8e8de15f 1719 // Prepare the SQL to load the courses and their contexts
f7ee4baa 1720 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
2e4c0c91
FM
1721 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1722 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1723 $courseparams['contextlevel'] = CONTEXT_COURSE;
8e8de15f 1724 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
f7ee4baa
SH
1725 FROM {course} c
1726 $ccjoin
1727 WHERE c.id {$courseids}
1728 ORDER BY c.sortorder ASC";
8e8de15f
SH
1729 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1730 foreach ($coursesrs as $course) {
fca2d3d7
PS
1731 if ($course->id == $SITE->id) {
1732 // frotpage is not wanted here
1733 continue;
1734 }
6caf3f5c
ARN
1735 if ($this->page->course && ($this->page->course->id == $course->id)) {
1736 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1737 continue;
1738 }
db314f34 1739 context_helper::preload_from_record($course);
b0c6dc1c 1740 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
f7ee4baa
SH
1741 continue;
1742 }
8e8de15f 1743 $coursenodes[$course->id] = $this->add_course($course);
f7ee4baa
SH
1744 if (count($coursenodes) >= $limit) {
1745 break;
1746 }
8e8de15f
SH
1747 }
1748 $coursesrs->close();
3406acde 1749 }
f7ee4baa 1750
3406acde
SH
1751 return $coursenodes;
1752 }
1753
8e8de15f
SH
1754 /**
1755 * Returns true if more courses can be added to the provided category.
1756 *
98556b23
SH
1757 * @param int|navigation_node|stdClass $category
1758 * @return bool
8e8de15f
SH
1759 */
1760 protected function can_add_more_courses_to_category($category) {
1761 global $CFG;
1762 $limit = 20;
1763 if (!empty($CFG->navcourselimit)) {
1764 $limit = (int)$CFG->navcourselimit;
1765 }
1766 if (is_numeric($category)) {
1767 if (!array_key_exists($category, $this->addedcategories)) {
1768 return true;
1769 }
1770 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1771 } else if ($category instanceof navigation_node) {
db47f68f 1772 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
8e8de15f
SH
1773 return false;
1774 }
1775 $coursecount = count($category->children->type(self::TYPE_COURSE));
1776 } else if (is_object($category) && property_exists($category,'id')) {
1777 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1778 }
d4bb6462 1779 return ($coursecount <= $limit);
8e8de15f
SH
1780 }
1781
4766a50c
SH
1782 /**
1783 * Loads all categories (top level or if an id is specified for that category)
1784 *
e26507b3
SH
1785 * @param int $categoryid The category id to load or null/0 to load all base level categories
1786 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1787 * as the requested category and any parent categories.
31fde54f 1788 * @return navigation_node|void returns a navigation node if a category has been loaded.
4766a50c 1789 */
8e8de15f 1790 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
58b602da 1791 global $CFG, $DB;
e26507b3
SH
1792
1793 // Check if this category has already been loaded
8e8de15f
SH
1794 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1795 return true;
e26507b3
SH
1796 }
1797
176b75b5
SH
1798 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1799 $sqlselect = "SELECT cc.*, $catcontextsql
1800 FROM {course_categories} cc
1801 JOIN {context} ctx ON cc.id = ctx.instanceid";
1802 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
957983b7 1803 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
176b75b5
SH
1804 $params = array();
1805
8e8de15f
SH
1806 $categoriestoload = array();
1807 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
176b75b5
SH
1808 // We are going to load all categories regardless... prepare to fire
1809 // on the database server!
8e8de15f 1810 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
e26507b3 1811 // We are going to load all of the first level categories (categories without parents)
176b75b5 1812 $sqlwhere .= " AND cc.parent = 0";
e26507b3
SH
1813 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1814 // The category itself has been loaded already so we just need to ensure its subcategories
1815 // have been loaded
85e59ac2
TP
1816 $addedcategories = $this->addedcategories;
1817 unset($addedcategories[$categoryid]);
6eb3da84
TP
1818 if (count($addedcategories) > 0) {
1819 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1820 if ($showbasecategories) {
1821 // We need to include categories with parent = 0 as well
1822 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1823 } else {
1824 // All we need is categories that match the parent
1825 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1826 }
e26507b3
SH
1827 }
1828 $params['categoryid'] = $categoryid;
4766a50c 1829 } else {
e26507b3
SH
1830 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1831 // and load this category plus all its parents and subcategories
3992a46e 1832 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
8e8de15f
SH
1833 $categoriestoload = explode('/', trim($category->path, '/'));
1834 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
176b75b5 1835 // We are going to use select twice so double the params
4766a50c 1836 $params = array_merge($params, $params);
d4bb6462
SH
1837 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1838 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
176b75b5
SH
1839 }
1840
1841 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1842 $categories = array();
1843 foreach ($categoriesrs as $category) {
1844 // Preload the context.. we'll need it when adding the category in order
1845 // to format the category name.
1846 context_helper::preload_from_record($category);
1847 if (array_key_exists($category->id, $this->addedcategories)) {
1848 // Do nothing, its already been added.
1849 } else if ($category->parent == '0') {
1850 // This is a root category lets add it immediately
1851 $this->add_category($category, $this->rootnodes['courses']);
1852 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1853 // This categories parent has already been added we can add this immediately
1854 $this->add_category($category, $this->addedcategories[$category->parent]);
1855 } else {
1856 $categories[] = $category;
1857 }
4766a50c 1858 }
176b75b5 1859 $categoriesrs->close();
e26507b3
SH
1860
1861 // Now we have an array of categories we need to add them to the navigation.
1862 while (!empty($categories)) {
1863 $category = reset($categories);
1864 if (array_key_exists($category->id, $this->addedcategories)) {
1865 // Do nothing
1866 } else if ($category->parent == '0') {
1867 $this->add_category($category, $this->rootnodes['courses']);
1868 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1869 $this->add_category($category, $this->addedcategories[$category->parent]);
4766a50c 1870 } else {
e26507b3
SH
1871 // This category isn't in the navigation and niether is it's parent (yet).
1872 // We need to go through the category path and add all of its components in order.
1873 $path = explode('/', trim($category->path, '/'));
1874 foreach ($path as $catid) {
1875 if (!array_key_exists($catid, $this->addedcategories)) {
1876 // This category isn't in the navigation yet so add it.
1877 $subcategory = $categories[$catid];
c4afcf84
SH
1878 if ($subcategory->parent == '0') {
1879 // Yay we have a root category - this likely means we will now be able
1880 // to add categories without problems.
1881 $this->add_category($subcategory, $this->rootnodes['courses']);
1882 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
e26507b3
SH
1883 // The parent is in the category (as we'd expect) so add it now.
1884 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1885 // Remove the category from the categories array.
1886 unset($categories[$catid]);
1887 } else {
1888 // We should never ever arrive here - if we have then there is a bigger
1889 // problem at hand.
5607036a 1890 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
e26507b3 1891 }
4766a50c 1892 }
4766a50c
SH
1893 }
1894 }
e26507b3
SH
1895 // Remove the category from the categories array now that we know it has been added.
1896 unset($categories[$category->id]);
4766a50c 1897 }
8e8de15f
SH
1898 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1899 $this->allcategoriesloaded = true;
1900 }
e26507b3 1901 // Check if there are any categories to load.
8e8de15f
SH
1902 if (count($categoriestoload) > 0) {
1903 $readytoloadcourses = array();
1904 foreach ($categoriestoload as $category) {
1905 if ($this->can_add_more_courses_to_category($category)) {
1906 $readytoloadcourses[] = $category;
1907 }
1908 }
1909 if (count($readytoloadcourses)) {
1910 $this->load_all_courses($readytoloadcourses);
1911 }
4766a50c 1912 }
58b602da
SH
1913
1914 // Look for all categories which have been loaded
1915 if (!empty($this->addedcategories)) {
1916 $categoryids = array();
1917 foreach ($this->addedcategories as $category) {
1918 if ($this->can_add_more_courses_to_category($category)) {
1919 $categoryids[] = $category->key;
1920 }
1921 }
bb900d13
PS
1922 if ($categoryids) {
1923 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1924 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1925 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1926 FROM {course_categories} cc
1927 JOIN {course} c ON c.category = cc.id
1928 WHERE cc.id {$categoriessql}
1929 GROUP BY cc.id
1930 HAVING COUNT(c.id) > :limit";
1931 $excessivecategories = $DB->get_records_sql($sql, $params);
1932 foreach ($categories as &$category) {
1933 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
30142c19 1934 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
bb900d13
PS
1935 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1936 }
58b602da
SH
1937 }
1938 }
1939 }
4766a50c
SH
1940 }
1941
1942 /**
1943 * Adds a structured category to the navigation in the correct order/place
1944 *
db47f68f
RT
1945 * @param stdClass $category category to be added in navigation.
1946 * @param navigation_node $parent parent navigation node
1947 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1948 * @return void.
4766a50c 1949 */
db47f68f 1950 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
e26507b3 1951 if (array_key_exists($category->id, $this->addedcategories)) {
563329e8 1952 return;
e26507b3 1953 }
30142c19 1954 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
b0c6dc1c 1955 $context = context_coursecat::instance($category->id);
63390481 1956 $categoryname = format_string($category->name, true, array('context' => $context));
db47f68f 1957 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
e26507b3 1958 if (empty($category->visible)) {
0601e0ee 1959 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
e26507b3
SH
1960 $categorynode->hidden = true;
1961 } else {
1962 $categorynode->display = false;
14337688 1963 }
4766a50c 1964 }
082513ba 1965 $this->addedcategories[$category->id] = $categorynode;
4766a50c
SH
1966 }
1967
3406acde
SH
1968 /**
1969 * Loads the given course into the navigation
7d2a0492 1970 *
3406acde
SH
1971 * @param stdClass $course
1972 * @return navigation_node
1973 */
1974 protected function load_course(stdClass $course) {
98556b23
SH
1975 global $SITE;
1976 if ($course->id == $SITE->id) {
80c69522 1977 // This is always loaded during initialisation
e26507b3
SH
1978 return $this->rootnodes['site'];
1979 } else if (array_key_exists($course->id, $this->addedcourses)) {
80c69522 1980 // The course has already been loaded so return a reference
e26507b3 1981 return $this->addedcourses[$course->id];
3406acde 1982 } else {
80c69522 1983 // Add the course
e26507b3 1984 return $this->add_course($course);
3406acde 1985 }
3406acde
SH
1986 }
1987
1988 /**
1989 * Loads all of the courses section into the navigation.
1990 *
e010b850
MG
1991 * This function calls method from current course format, see
1992 * {@link format_base::extend_course_navigation()}
1993 * If course module ($cm) is specified but course format failed to create the node,
1994 * the activity node is created anyway.
3406acde 1995 *
e010b850 1996 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
3406acde 1997 *
3406acde
SH
1998 * @param stdClass $course Database record for the course
1999 * @param navigation_node $coursenode The course node within the navigation
e010b850
MG
2000 * @param null|int $sectionnum If specified load the contents of section with this relative number
2001 * @param null|cm_info $cm If specified make sure that activity node is created (either
2002 * in containg section or by calling load_stealth_activity() )
3406acde 2003 */
e010b850
MG
2004 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
2005 global $CFG, $SITE;
ee7084e9 2006 require_once($CFG->dirroot.'/course/lib.php');
e010b850
MG
2007 if (isset($cm->sectionnum)) {
2008 $sectionnum = $cm->sectionnum;
2009 }
2010 if ($sectionnum !== null) {
2011 $this->includesectionnum = $sectionnum;
2012 }
2013 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
2014 if (isset($cm->id)) {
2015 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
2016 if (empty($activity)) {
2017 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
2018 }
2019 }
2020 }
3406acde 2021
e26507b3
SH
2022 /**
2023 * Generates an array of sections and an array of activities for the given course.
2024 *
2025 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
2026 *
2027 * @param stdClass $course
2028 * @return array Array($sections, $activities)
2029 */
2030 protected function generate_sections_and_activities(stdClass $course) {
2031 global $CFG;
2032 require_once($CFG->dirroot.'/course/lib.php');
2033
c18facf2 2034 $modinfo = get_fast_modinfo($course);
b5cf83f0 2035 $sections = $modinfo->get_section_info_all();
850acb35
MG
2036
2037 // For course formats using 'numsections' trim the sections list
2038 $courseformatoptions = course_get_format($course)->get_format_options();
2039 if (isset($courseformatoptions['numsections'])) {
2040 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
b5cf83f0 2041 }
850acb35 2042
c18facf2 2043 $activities = array();
e26507b3 2044
c18facf2 2045 foreach ($sections as $key => $section) {
2d9c0d11 2046 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
51591b2c
AO
2047 $sections[$key] = clone($section);
2048 unset($sections[$key]->summary);
c18facf2
SH
2049 $sections[$key]->hasactivites = false;
2050 if (!array_key_exists($section->section, $modinfo->sections)) {
2051 continue;
2052 }
2053 foreach ($modinfo->sections[$section->section] as $cmid) {
2054 $cm = $modinfo->cms[$cmid];
c18facf2
SH
2055 $activity = new stdClass;
2056 $activity->id = $cm->id;
2057 $activity->course = $course->id;
2058 $activity->section = $section->section;
2059 $activity->name = $cm->name;
2060 $activity->icon = $cm->icon;
2061 $activity->iconcomponent = $cm->iconcomponent;
2062 $activity->hidden = (!$cm->visible);
2063 $activity->modname = $cm->modname;
2064 $activity->nodetype = navigation_node::NODETYPE_LEAF;
73ee2fda
DP
2065 $activity->onclick = $cm->onclick;
2066 $url = $cm->url;
c18facf2
SH
2067 if (!$url) {
2068 $activity->url = null;
2069 $activity->display = false;
2070 } else {
73ee2fda 2071 $activity->url = $url->out();
8341055e 2072 $activity->display = $cm->is_visible_on_course_page() ? true : false;
c18facf2
SH
2073 if (self::module_extends_navigation($cm->modname)) {
2074 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
d67e4821 2075 }
e26507b3 2076 }
c18facf2
SH
2077 $activities[$cmid] = $activity;
2078 if ($activity->display) {
2079 $sections[$key]->hasactivites = true;
2080 }
e26507b3 2081 }
e26507b3 2082 }
c18facf2 2083
e26507b3
SH
2084 return array($sections, $activities);
2085 }
2086
3406acde
SH
2087 /**
2088 * Generically loads the course sections into the course's navigation.
2089 *
2090 * @param stdClass $course
2091 * @param navigation_node $coursenode
3406acde
SH
2092 * @return array An array of course section nodes
2093 */
ee7084e9 2094 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
98556b23 2095 global $CFG, $DB, $USER, $SITE;
df997f84 2096 require_once($CFG->dirroot.'/course/lib.php');
435a512e 2097
e26507b3 2098 list($sections, $activities) = $this->generate_sections_and_activities($course);
0f4ab67d 2099
7487c856 2100 $navigationsections = array();
e26507b3 2101 foreach ($sections as $sectionid => $section) {
7487c856 2102 $section = clone($section);
98556b23 2103 if ($course->id == $SITE->id) {
e26507b3 2104 $this->load_section_activities($coursenode, $section->section, $activities);
3406acde 2105 } else {
ce4dfd27 2106 if (!$section->uservisible || (!$this->showemptysections &&
d67e4821 2107 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
3406acde
SH
2108 continue;
2109 }
ce4dfd27 2110
ee7084e9
MG
2111 $sectionname = get_section_name($course, $section);
2112 $url = course_get_url($course, $section->section, array('navigation' => true));
ad470097 2113
64448e1e
KO
2114 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION,
2115 null, $section->id, new pix_icon('i/section', ''));
3406acde 2116 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
ce4dfd27 2117 $sectionnode->hidden = (!$section->visible || !$section->available);
e010b850 2118 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
e26507b3 2119 $this->load_section_activities($sectionnode, $section->section, $activities);
3406acde
SH
2120 }
2121 $section->sectionnode = $sectionnode;
7487c856 2122 $navigationsections[$sectionid] = $section;
3406acde
SH
2123 }
2124 }
7487c856 2125 return $navigationsections;
3406acde 2126 }
e010b850 2127
3406acde
SH
2128 /**
2129 * Loads all of the activities for a section into the navigation structure.
2130 *
2131 * @param navigation_node $sectionnode
2132 * @param int $sectionnumber
93123b17 2133 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1580cfdb 2134 * @param stdClass $course The course object the section and activities relate to.
3406acde
SH
2135 * @return array Array of activity nodes
2136 */
1580cfdb 2137 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
98556b23 2138 global $CFG, $SITE;
dee1a0fd
SH
2139 // A static counter for JS function naming
2140 static $legacyonclickcounter = 0;
3406acde 2141
e26507b3 2142 $activitynodes = array();
4037098e
SH
2143 if (empty($activities)) {
2144 return $activitynodes;
2145 }
2146
2147 if (!is_object($course)) {
2148 $activity = reset($activities);
2149 $courseid = $activity->course;
2150 } else {
2151 $courseid = $course->id;
2152 }
98556b23 2153 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
4037098e 2154
e26507b3
SH
2155 foreach ($activities as $activity) {
2156 if ($activity->section != $sectionnumber) {
3406acde
SH
2157 continue;
2158 }
e26507b3
SH
2159 if ($activity->icon) {
2160 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
3406acde 2161 } else {
e26507b3 2162 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
3406acde 2163 }
dee1a0fd
SH
2164
2165 // Prepare the default name and url for the node
b0c6dc1c 2166 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
dee1a0fd
SH
2167 $action = new moodle_url($activity->url);
2168
2169 // Check if the onclick property is set (puke!)
2170 if (!empty($activity->onclick)) {
2171 // Increment the counter so that we have a unique number.
2172 $legacyonclickcounter++;
2173 // Generate the function name we will use
2174 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
2175 $propogrationhandler = '';
2176 // Check if we need to cancel propogation. Remember inline onclick
2177 // events would return false if they wanted to prevent propogation and the
2178 // default action.
2179 if (strpos($activity->onclick, 'return false')) {
2180 $propogrationhandler = 'e.halt();';
2181 }
2182 // Decode the onclick - it has already been encoded for display (puke)
e5ad278a 2183 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
dee1a0fd
SH
2184 // Build the JS function the click event will call
2185 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
c41883f0 2186 $this->page->requires->js_amd_inline($jscode);
dee1a0fd
SH
2187 // Override the default url with the new action link
2188 $action = new action_link($action, $activityname, new component_action('click', $functionname));
2189 }
2190
2191 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
e26507b3
SH
2192 $activitynode->title(get_string('modulename', $activity->modname));
2193 $activitynode->hidden = $activity->hidden;
4037098e 2194 $activitynode->display = $showactivities && $activity->display;
e26507b3
SH
2195 $activitynode->nodetype = $activity->nodetype;
2196 $activitynodes[$activity->id] = $activitynode;
3406acde
SH
2197 }
2198
e26507b3 2199 return $activitynodes;
3406acde 2200 }
2a62743c
PS
2201 /**
2202 * Loads a stealth module from unavailable section
2203 * @param navigation_node $coursenode
2204 * @param stdClass $modinfo
2205 * @return navigation_node or null if not accessible
2206 */
2207 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2208 if (empty($modinfo->cms[$this->page->cm->id])) {
2209 return null;
2210 }
2211 $cm = $modinfo->cms[$this->page->cm->id];
2a62743c
PS
2212 if ($cm->icon) {
2213 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2214 } else {
2215 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2216 }
73ee2fda 2217 $url = $cm->url;
2a62743c
PS
2218 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2219 $activitynode->title(get_string('modulename', $cm->modname));
2220 $activitynode->hidden = (!$cm->visible);
8341055e 2221 if (!$cm->is_visible_on_course_page()) {
4fd2a16e
MG
2222 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2223 // Also there may be no exception at all in case when teacher is logged in as student.
2224 $activitynode->display = false;
2225 } else if (!$url) {
0d8b6a69 2226 // Don't show activities that don't have links!
2a62743c 2227 $activitynode->display = false;
e26507b3 2228 } else if (self::module_extends_navigation($cm->modname)) {
2a62743c
PS
2229 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2230 }
2231 return $activitynode;
2232 }
3406acde
SH
2233 /**
2234 * Loads the navigation structure for the given activity into the activities node.
2235 *
2236 * This method utilises a callback within the modules lib.php file to load the
2237 * content specific to activity given.
2238 *
2239 * The callback is a method: {modulename}_extend_navigation()
2240 * Examples:
93123b17
EL
2241 * * {@link forum_extend_navigation()}
2242 * * {@link workshop_extend_navigation()}
3406acde 2243 *
f0dcc212 2244 * @param cm_info|stdClass $cm
3406acde
SH
2245 * @param stdClass $course
2246 * @param navigation_node $activity
2247 * @return bool
2248 */
0d8b6a69 2249 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
3406acde 2250 global $CFG, $DB;
44303ca6 2251
f0dcc212
SH
2252 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2253 if (!($cm instanceof cm_info)) {
2254 $modinfo = get_fast_modinfo($course);
2255 $cm = $modinfo->get_cm($cm->id);
2256 }
577c8964 2257 $activity->nodetype = navigation_node::NODETYPE_LEAF;
3406acde
SH
2258 $activity->make_active();
2259 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2260 $function = $cm->modname.'_extend_navigation';
2261
2262 if (file_exists($file)) {
2263 require_once($file);
2264 if (function_exists($function)) {
2265 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2266 $function($activity, $course, $activtyrecord, $cm);
3406acde
SH
2267 }
2268 }
577c8964
MG
2269
2270 // Allow the active advanced grading method plugin to append module navigation
2271 $featuresfunc = $cm->modname.'_supports';
2272 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2273 require_once($CFG->dirroot.'/grade/grading/lib.php');
6cdfe1a8 2274 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname);
577c8964
MG
2275 $gradingman->extend_navigation($this, $activity);
2276 }
2277
2278 return $activity->has_children();
3406acde
SH
2279 }
2280 /**
4d00fded 2281 * Loads user specific information into the navigation in the appropriate place.
3406acde
SH
2282 *
2283 * If no user is provided the current user is assumed.
2284 *
3406acde 2285 * @param stdClass $user
4d00fded 2286 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
3406acde 2287 * @return bool
7a7e209d 2288 */
87c215de 2289 protected function load_for_user($user=null, $forceforcontext=false) {
98556b23 2290 global $DB, $CFG, $USER, $SITE;
4f0c2d00 2291
93b47710
MN
2292 require_once($CFG->dirroot . '/course/lib.php');
2293
7a7e209d
SH
2294 if ($user === null) {
2295 // We can't require login here but if the user isn't logged in we don't
2296 // want to show anything
b9d4c7d3 2297 if (!isloggedin() || isguestuser()) {
7a7e209d
SH
2298 return false;
2299 }
2300 $user = $USER;
7a7e209d
SH
2301 } else if (!is_object($user)) {
2302 // If the user is not an object then get them from the database
e141bc81
SH
2303 $select = context_helper::get_preload_record_columns_sql('ctx');
2304 $sql = "SELECT u.*, $select
2305 FROM {user} u
2306 JOIN {context} ctx ON u.id = ctx.instanceid
2307 WHERE u.id = :userid AND
2308 ctx.contextlevel = :contextlevel";
2309 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2310 context_helper::preload_from_record($user);
7a7e209d 2311 }
136ca7c8
SH
2312
2313 $iscurrentuser = ($user->id == $USER->id);
2314
b0c6dc1c 2315 $usercontext = context_user::instance($user->id);
7a7e209d
SH
2316
2317 // Get the course set against the page, by default this will be the site
3406acde
SH
2318 $course = $this->page->course;
2319 $baseargs = array('id'=>$user->id);
98556b23 2320 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
58b602da 2321 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
7a7e209d 2322 $baseargs['course'] = $course->id;
b0c6dc1c 2323 $coursecontext = context_course::instance($course->id);
7a7e209d 2324 $issitecourse = false;
7d2a0492 2325 } else {
7a7e209d 2326 // Load all categories and get the context for the system
b0c6dc1c 2327 $coursecontext = context_system::instance();
7a7e209d
SH
2328 $issitecourse = true;
2329 }
2330
2331 // Create a node to add user information under.
f495187d
AG
2332 $usersnode = null;
2333 if (!$issitecourse) {
2334 // Not the current user so add it to the participants node for the current course.
2335 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2336 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2337 } else if ($USER->id != $user->id) {
2338 // This is the site so add a users node to the root branch.
2339 $usersnode = $this->rootnodes['users'];
93b47710 2340 if (course_can_view_participants($coursecontext)) {
45367bdf 2341 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id));
f495187d
AG
2342 }
2343 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2344 }
2345 if (!$usersnode) {
2346 // We should NEVER get here, if the course hasn't been populated
2347 // with a participants node then the navigaiton either wasn't generated
2348 // for it (you are missing a require_login or set_context call) or
2349 // you don't have access.... in the interests of no leaking informatin
2350 // we simply quit...
2351 return false;
7a7e209d 2352 }
f495187d 2353 // Add a branch for the current user.
02e5a9d7 2354 // Only reveal user details if $user is the current user, or a user to which the current user has access.
01255549
JD
2355 $viewprofile = true;
2356 if (!$iscurrentuser) {
2357 require_once($CFG->dirroot . '/user/lib.php');
2358 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) {
2359 $viewprofile = false;
2360 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) {
2361 $viewprofile = false;
2362 }
2363 if (!$viewprofile) {
2364 $viewprofile = user_can_view_profile($user, null, $usercontext);
2365 }
2366 }
2367
2368 // Now, conditionally add the user node.
2369 if ($viewprofile) {
02e5a9d7
JD
2370 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2371 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id);
01255549
JD
2372 } else {
2373 $usernode = $usersnode->add(get_string('user'));
02e5a9d7 2374 }
01255549 2375
f495187d
AG
2376 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2377 $usernode->make_active();
7a7e209d
SH
2378 }
2379
f495187d
AG
2380 // Add user information to the participants or user node.
2381 if ($issitecourse) {
7a7e209d 2382
f495187d
AG
2383 // If the user is the current user or has permission to view the details of the requested
2384 // user than add a view profile link.
2385 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) ||
2386 has_capability('moodle/user:viewdetails', $usercontext)) {
2387 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
45367bdf 2388 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs));
f495187d 2389 } else {
45367bdf 2390 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs));
f495187d 2391 }
e26507b3
SH
2392 }
2393
f495187d
AG
2394 if (!empty($CFG->navadduserpostslinks)) {
2395 // Add nodes for forum posts and discussions if the user can view either or both
2396 // There are no capability checks here as the content of the page is based
2397 // purely on the forums the current user has access too.
2398 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2399 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2400 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php',
45367bdf 2401 array_merge($baseargs, array('mode' => 'discussions'))));
f495187d
AG
2402 }
2403
2404 // Add blog nodes.
2405 if (!empty($CFG->enableblogs)) {
2406 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2407 require_once($CFG->dirroot.'/blog/lib.php');
2408 // Get all options for the user.
2409 $options = blog_get_options_for_user($user);
2410 $this->cache->set('userblogoptions'.$user->id, $options);
2411 } else {
2412 $options = $this->cache->{'userblogoptions'.$user->id};
2413 }
2414
2415 if (count($options) > 0) {
2416 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2417 foreach ($options as $type => $option) {
2418 if ($type == "rss") {
2419 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null,
2420 new pix_icon('i/rss', ''));
2421 } else {
2422 $blogs->add($option['string'], $option['link']);
2423 }
c000545d 2424 }
27bad0a6
SH
2425 }
2426 }
27bad0a6 2427
f495187d 2428 // Add the messages link.
4887d152 2429 // It is context based so can appear in the user's profile and in course participants information.
f495187d
AG
2430 if (!empty($CFG->messaging)) {
2431 $messageargs = array('user1' => $USER->id);
2432 if ($USER->id != $user->id) {
2433 $messageargs['user2'] = $user->id;
2434 }
45367bdf 2435 $url = new moodle_url('/message/index.php', $messageargs);
f495187d 2436 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
5ac851fb 2437 }
78765507 2438
f495187d 2439 // Add the "My private files" link.
4887d152 2440 // This link doesn't have a unique display for course context so only display it under the user's profile.
f495187d
AG
2441 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
2442 $url = new moodle_url('/user/files.php');
27456a64 2443 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles');
f495187d 2444 }
27806552 2445
f495187d
AG
2446 // Add a node to view the users notes if permitted.
2447 if (!empty($CFG->enablenotes) &&
2448 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
45367bdf 2449 $url = new moodle_url('/notes/index.php', array('user' => $user->id));
f495187d
AG
2450 if ($coursecontext->instanceid != SITEID) {
2451 $url->param('course', $coursecontext->instanceid);
2452 }
2453 $usernode->add(get_string('notes', 'notes'), $url);
c9451960 2454 }
f495187d 2455
4887d152 2456 // Show the grades node.
f495187d
AG
2457 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) {
2458 require_once($CFG->dirroot . '/user/lib.php');
4887d152 2459 // Set the grades node to link to the "Grades" page.
f495187d
AG
2460 if ($course->id == SITEID) {
2461 $url = user_mygrades_url($user->id, $course->id);
2462 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
2463 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
2464 }
2465 if ($USER->id != $user->id) {
c78dbe03 2466 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades');
f495187d 2467 } else {
4887d152 2468 $usernode->add(get_string('grades', 'grades'), $url);
f495187d 2469 }
c9451960 2470 }
c9451960 2471
f495187d
AG
2472 // If the user is the current user add the repositories for the current user.
2473 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2474 if (!$iscurrentuser &&
2475 $course->id == $SITE->id &&
2476 has_capability('moodle/user:viewdetails', $usercontext) &&
2477 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
9acb8241 2478
f495187d
AG
2479 // Add view grade report is permitted.
2480 $reports = core_component::get_plugin_list('gradereport');
45367bdf 2481 arsort($reports); // User is last, we want to test it first.
9acb8241 2482
35b9bca0 2483 $userscourses = enrol_get_users_courses($user->id, false, '*');
f495187d 2484 $userscoursesnode = $usernode->add(get_string('courses'));
69816a5c 2485
f495187d
AG
2486 $count = 0;
2487 foreach ($userscourses as $usercourse) {
2488 if ($count === (int)$CFG->navcourselimit) {
2489 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
2490 $userscoursesnode->add(get_string('showallcourses'), $url);
2491 break;
2492 }
2493 $count++;
2494 $usercoursecontext = context_course::instance($usercourse->id);
2495 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2496 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php',
45367bdf 2497 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER);
f495187d 2498
d430a7c3 2499 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext);
f495187d
AG
2500 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2501 foreach ($reports as $plugin => $plugindir) {
2502 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
45367bdf 2503 // Stop when the first visible plugin is found.
f495187d
AG
2504 $gradeavailable = true;
2505 break;
2506 }
deaf04c7 2507 }
9acb8241 2508 }
9acb8241 2509
f495187d 2510 if ($gradeavailable) {
45367bdf 2511 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id));
f495187d
AG
2512 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null,
2513 new pix_icon('i/grades', ''));
2514 }
9acb8241 2515
f495187d
AG
2516 // Add a node to view the users notes if permitted.
2517 if (!empty($CFG->enablenotes) &&
2518 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
45367bdf 2519 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id));
f495187d
AG
2520 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2521 }
9acb8241 2522
8b456850 2523 if (can_access_course($usercourse, $user->id, '', true)) {
f495187d 2524 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php',
45367bdf 2525 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
f495187d 2526 }
9acb8241 2527
f495187d 2528 $reporttab = $usercoursenode->add(get_string('activityreports'));
4d00fded 2529
0b844a83
MG
2530 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2531 foreach ($reportfunctions as $reportfunction) {
f495187d
AG
2532 $reportfunction($reporttab, $user, $usercourse);
2533 }
4d00fded 2534
f495187d
AG
2535 $reporttab->trim_if_empty();
2536 }
9acb8241 2537 }
f495187d 2538
20dde5e6
JPG
2539 // Let plugins hook into user navigation.
2540 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
2541 foreach ($pluginsfunction as $plugintype => $plugins) {
2542 if ($plugintype != 'report') {
2543 foreach ($plugins as $pluginfunction) {
2544 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext);
2545 }
2546 }
2547 }
7a7e209d
SH
2548 }
2549 return true;
2550 }
2551
2552 /**
3406acde 2553 * This method simply checks to see if a given module can extend the navigation.
7d2a0492 2554 *
31fde54f 2555 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
e26507b3 2556 *
7d2a0492 2557 * @param string $modname
2558 * @return bool
2559 */
e010b850 2560 public static function module_extends_navigation($modname) {
7d2a0492 2561 global $CFG;
e26507b3
SH
2562 static $extendingmodules = array();
2563 if (!array_key_exists($modname, $extendingmodules)) {
2564 $extendingmodules[$modname] = false;
2565 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2566 if (file_exists($file)) {
2567 $function = $modname.'_extend_navigation';
2568 require_once($file);
2569 $extendingmodules[$modname] = (function_exists($function));
7d2a0492 2570 }
2571 }
e26507b3 2572 return $extendingmodules[$modname];
7d2a0492 2573 }
2574 /**
3406acde 2575 * Extends the navigation for the given user.
435a512e 2576 *
3406acde 2577 * @param stdClass $user A user from the database
7d2a0492 2578 */
3406acde
SH
2579 public function extend_for_user($user) {
2580 $this->extendforuser[] = $user;
5d07e957
SH
2581 }
2582
2583 /**
2584 * Returns all of the users the navigation is being extended for
2585 *
31fde54f 2586 * @return array An array of extending users.
5d07e957
SH
2587 */
2588 public function get_extending_users() {
2589 return $this->extendforuser;
7d2a0492 2590 }
7d2a0492 2591 /**
3406acde 2592 * Adds the given course to the navigation structure.
7d2a0492 2593 *
3406acde 2594 * @param stdClass $course
8e8de15f
SH
2595 * @param bool $forcegeneric
2596 * @param bool $ismycourse
3406acde 2597 * @return navigation_node
7d2a0492 2598 */
6caf3f5c 2599 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
98556b23 2600 global $CFG, $SITE;
44303ca6 2601
e26507b3
SH
2602 // We found the course... we can return it now :)
2603 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2604 return $this->addedcourses[$course->id];
2605 }
2606
b0c6dc1c 2607 $coursecontext = context_course::instance($course->id);
8ebbb06a 2608
98556b23 2609 if ($course->id != $SITE->id && !$course->visible) {
e26507b3
SH
2610 if (is_role_switched($course->id)) {
2611 // user has to be able to access course in order to switch, let's skip the visibility test here
8ebbb06a 2612 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
e26507b3 2613 return false;
44303ca6 2614 }
7d2a0492 2615 }
7d2a0492 2616
98556b23 2617 $issite = ($course->id == $SITE->id);
8ebbb06a 2618 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
d20337f1
SH
2619 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2620 // This is the name that will be shown for the course.
2621 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
4766a50c 2622
99061152
DW
2623 if ($coursetype == self::COURSE_CURRENT) {
2624 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) {
2625 return $coursenode;
2626 } else {
2627 $coursetype = self::COURSE_OTHER;
2628 }
2629 }
2630
cbd063f4
SH
2631 // Can the user expand the course to see its content.
2632 $canexpandcourse = true;
4766a50c 2633 if ($issite) {
3406acde 2634 $parent = $this;
4766a50c 2635 $url = null;
016ba638 2636 if (empty($CFG->usesitenameforsitepages)) {
d20337f1 2637 $coursename = get_string('sitepages');
016ba638 2638 }
6caf3f5c
ARN
2639 } else if ($coursetype == self::COURSE_CURRENT) {
2640 $parent = $this->rootnodes['currentcourse'];
2641 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
8b456850 2642 $canexpandcourse = $this->can_expand_course($course);
6caf3f5c 2643 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
db47f68f 2644 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
b0712163
SH
2645 // Nothing to do here the above statement set $parent to the category within mycourses.
2646 } else {
2647 $parent = $this->rootnodes['mycourses'];
2648 }
3406acde 2649 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7a7e209d 2650 } else {
3406acde 2651 $parent = $this->rootnodes['courses'];
a6855934 2652 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
cbd063f4
SH
2653 // They can only expand the course if they can access it.
2654 $canexpandcourse = $this->can_expand_course($course);
58b602da
SH
2655 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2656 if (!$this->is_category_fully_loaded($course->category)) {
8e8de15f 2657 // We need to load the category structure for this course
80c69522 2658 $this->load_all_categories($course->category, false);
8e8de15f
SH
2659 }
2660 if (array_key_exists($course->category, $this->addedcategories)) {
2661 $parent = $this->addedcategories[$course->category];
2662 // This could lead to the course being created so we should check whether it is the case again
2663 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2664 return $this->addedcourses[$course->id];
2665 }
3992a46e 2666 }
4766a50c
SH
2667 }
2668 }
2669
64448e1e 2670 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', ''));
3dabb083 2671 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY;
d07373f2 2672
3406acde 2673 $coursenode->hidden = (!$course->visible);
a530cb93 2674 $coursenode->title(format_string($course->fullname, true, array('context' => $coursecontext, 'escape' => false)));
cbd063f4
SH
2675 if ($canexpandcourse) {
2676 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
2677 $coursenode->nodetype = self::NODETYPE_BRANCH;
2678 $coursenode->isexpandable = true;
2679 } else {
2680 $coursenode->nodetype = self::NODETYPE_LEAF;
2681 $coursenode->isexpandable = false;
2682 }
e26507b3 2683 if (!$forcegeneric) {
082513ba 2684 $this->addedcourses[$course->id] = $coursenode;
e26507b3 2685 }
e26507b3 2686
3406acde 2687 return $coursenode;
7d2a0492 2688 }
8e8de15f 2689
cbd063f4
SH
2690 /**
2691 * Returns a cache instance to use for the expand course cache.
2692 * @return cache_session
2693 */
2694 protected function get_expand_course_cache() {
2695 if ($this->cacheexpandcourse === null) {
2696 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
2697 }
2698 return $this->cacheexpandcourse;
2699 }
2700
2701 /**
2702 * Checks if a user can expand a course in the navigation.
2703 *
2704 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
2705 * Because this functionality is basic + non-essential and because we lack good event triggering this cache
2706 * permits stale data.
2707 * In the situation the user is granted access to a course after we've initialised this session cache the cache
2708 * will be stale.
2709 * It is brought up to date in only one of two ways.
2710 * 1. The user logs out and in again.
2711 * 2. The user browses to the course they've just being given access to.
2712 *
2713 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
2714 *
2715 * @param stdClass $course
2716 * @return bool
2717 */
2718 protected function can_expand_course($course) {
2719 $cache = $this->get_expand_course_cache();
2720 $canexpand = $cache->get($course->id);
2721 if ($canexpand === false) {
8b456850 2722 $canexpand = isloggedin() && can_access_course($course, null, '', true);
cbd063f4
SH
2723 $canexpand = (int)$canexpand;
2724 $cache->set($course->id, $canexpand);
2725 }
2726 return ($canexpand === 1);
2727 }
2728
8e8de15f
SH
2729 /**
2730 * Returns true if the category has already been loaded as have any child categories
2731 *
2732 * @param int $categoryid
2733 * @return bool
2734 */
2735 protected function is_category_fully_loaded($categoryid) {
2736 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2737 }
2738
7d2a0492 2739 /**
3406acde 2740 * Adds essential course nodes to the navigation for the given course.
7d2a0492 2741 *
3406acde 2742 * This method adds nodes such as reports, blogs and participants
7d2a0492 2743 *
3406acde
SH
2744 * @param navigation_node $coursenode
2745 * @param stdClass $course
31fde54f 2746 * @return bool returns true on successful addition of a node.
7d2a0492 2747 */
2027c10e 2748 public function add_course_essentials($coursenode, stdClass $course) {
98556b23 2749 global $CFG, $SITE;
d6cd89b1 2750 require_once($CFG->dirroot . '/course/lib.php');
7d2a0492 2751
98556b23 2752 if ($course->id == $SITE->id) {
3406acde 2753 return $this->add_front_page_course_essentials($coursenode, $course);
7d2a0492 2754 }
7d2a0492 2755
2027c10e 2756 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
3406acde 2757 return true;
7d2a0492 2758 }
7d2a0492 2759
d430a7c3 2760 $navoptions = course_get_user_navigation_options($this->page->context, $course);
d6cd89b1 2761
3406acde 2762 //Participants
d6cd89b1 2763 if ($navoptions->participants) {
64448e1e
KO
2764 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id),
2765 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', ''));
d6cd89b1
JL
2766
2767 if ($navoptions->blogs) {
2768 $blogsurls = new moodle_url('/blog/index.php');
2769 if ($currentgroup = groups_get_course_group($course, true)) {
2770 $blogsurls->param('groupid', $currentgroup);
2771 } else {
2772 $blogsurls->param('courseid', $course->id);
24f4bfcf 2773 }
d6cd89b1 2774 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs');
3406acde 2775 }
d6cd89b1
JL
2776
2777 if ($navoptions->notes) {
327e68e6 2778 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes');
3406acde 2779 }
533299cb 2780 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
3406acde
SH
2781 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2782 }
2783
27806552 2784 // Badges.
d6cd89b1 2785 if ($navoptions->badges) {
1dcb9ff1 2786 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
27806552 2787
99061152 2788 $coursenode->add(get_string('coursebadges', 'badges'), $url,
27806552 2789 navigation_node::TYPE_SETTING, null, 'badgesview',
99061152
DW
2790 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
2791 }
2792
2793 // Check access to the course and competencies page.
2794 if ($navoptions->competencies) {
2795 // Just a link to course competency.
2796 $title = get_string('competencies', 'core_competency');
2797 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id));
f592063f
AB
2798 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies',
2799 new pix_icon('i/competencies', ''));
99061152
DW
2800 }
2801 if ($navoptions->grades) {
2802 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
f37c3ec8
KO
2803 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null,
2804 'grades', new pix_icon('i/grades', ''));
2805 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active.
fd2b5d5c 2806 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) {
f37c3ec8
KO
2807 $gradenode->make_active();
2808 }
27806552
YB
2809 }
2810
7d2a0492 2811 return true;
2812 }
deaf04c7 2813 /**
31fde54f 2814 * This generates the structure of the course that won't be generated when
deaf04c7
SH
2815 * the modules and sections are added.
2816 *
2817 * Things such as the reports branch, the participants branch, blogs... get
2818 * added to the course node by this method.
2819 *
2820 * @param navigation_node $coursenode
2821 * @param stdClass $course
2822 * @return bool True for successfull generation
2823 */
3406acde 2824 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
a5327e44 2825 global $CFG, $USER, $COURSE, $SITE;
d6cd89b1 2826 require_once($CFG->dirroot . '/course/lib.php');
7d2a0492 2827
1fa692ed 2828 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
3406acde 2829 return true;
7a7e209d
SH
2830 }
2831
ea9431eb 2832 $sitecontext = context_system::instance();
d6cd89b1 2833 $navoptions = course_get_user_navigation_options($sitecontext, $course);
ea9431eb 2834
1fa692ed
SH
2835 // Hidden node that we use to determine if the front page navigation is loaded.
2836 // This required as there are not other guaranteed nodes that may be loaded.
2837 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2838
ea9431eb 2839 // Participants.
d6cd89b1 2840 if ($navoptions->participants) {
3406acde
SH
2841 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2842 }
435a512e 2843
ea9431eb 2844 // Blogs.
d6cd89b1 2845 if ($navoptions->blogs) {
c1f97c77 2846 $blogsurls = new moodle_url('/blog/index.php');
45367bdf 2847 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog');
7d2a0492 2848 }
593270c6 2849
c1f97c77
DC
2850 $filterselect = 0;
2851
ea9431eb 2852 // Badges.
d6cd89b1 2853 if ($navoptions->badges) {
27806552
YB
2854 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2855 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2856 }
2857
ea9431eb 2858 // Notes.
d6cd89b1 2859 if ($navoptions->notes) {
45367bdf
AG
2860 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php',
2861 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes');
3406acde 2862 }
593270c6
MD
2863
2864 // Tags
d6cd89b1 2865 if ($navoptions->tags) {
45367bdf
AG
2866 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'),
2867 self::TYPE_SETTING, null, 'tags');
7d2a0492 2868 }
6644741d 2869
db48207e 2870 // Search.
d6cd89b1 2871 if ($navoptions->search) {
db48207e
DM
2872 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'),
2873 self::TYPE_SETTING, null, 'search');
2874 }
2875
d6cd89b1 2876 if ($navoptions->calendar) {
a5327e44
DW
2877 $courseid = $COURSE->id;
2878 $params = array('view' => 'month');
2879 if ($courseid != $SITE->id) {
2880 $params['course'] = $courseid;
2881 }
2882
e7f9b7ab 2883 // Calendar
a5327e44 2884 $calendarurl = new moodle_url('/calendar/view.php', $params);
64448e1e
KO
2885 $node = $coursenode->add(get_string('calendar', 'calendar'), $calendarurl,
2886 self::TYPE_CUSTOM, null, 'calendar', new pix_icon('i/calendar', ''));
99061152
DW
2887 $node->showinflatnavigation = true;
2888 }
2889
2890 if (isloggedin()) {
2891 $usercontext = context_user::instance($USER->id);
2892 if (has_capability('moodle/user:manageownfiles', $usercontext)) {
2893 $url = new moodle_url('/user/files.php');
64448e1e
KO
2894 $node = $coursenode->add(get_string('privatefiles'), $url,
2895 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', ''));
99061152
DW
2896 $node->display = false;
2897 $node->showinflatnavigation = true;
2898 }
e7f9b7ab 2899 }
6644741d 2900
3406acde 2901 return true;
6644741d 2902 }
da3ab9c4 2903
3406acde
SH
2904 /**
2905 * Clears the navigation cache
2906 */
2907 public function clear_cache() {
2908 $this->cache->clear();
da3ab9c4 2909 }
88f77c3c 2910
deaf04c7
SH
2911 /**
2912 * Sets an expansion limit for the navigation
2913 *
2914 * The expansion limit is used to prevent the display of content that has a type
2915 * greater than the provided $type.
2916 *
2917 * Can be used to ensure things such as activities or activity content don't get
2918 * shown on the navigation.
2919 * They are still generated in order to ensure the navbar still makes sense.
2920 *
2921 * @param int $type One of navigation_node::TYPE_*
31fde54f 2922 * @return bool true when complete.
deaf04c7 2923 */
88f77c3c 2924 public function set_expansion_limit($type) {
98556b23 2925 global $SITE;
88f77c3c 2926 $nodes = $this->find_all_of_type($type);
8718ffba
SH
2927
2928 // We only want to hide specific types of nodes.
2929 // Only nodes that represent "structure" in the navigation tree should be hidden.
2930 // If we hide all nodes then we risk hiding vital information.
2931 $typestohide = array(
2932 self::TYPE_CATEGORY,
2933 self::TYPE_COURSE,
2934 self::TYPE_SECTION,
2935 self::TYPE_ACTIVITY
2936 );
2937
ba7b1ca5 2938 foreach ($nodes as $node) {
1af67ecb 2939 // We need to generate the full site node
98556b23 2940 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
1af67ecb
SH
2941 continue;
2942 }
ba7b1ca5 2943 foreach ($node->children as $child) {
8718ffba 2944 $child->hide($typestohide);
88f77c3c
SH
2945 }
2946 }
2947 return true;
2948 }
deaf04c7
SH
2949 /**
2950 * Attempts to get the navigation with the given key from this nodes children.
2951 *
2952 * This function only looks at this nodes children, it does NOT look recursivily.
2953 * If the node can't be found then false is returned.
2954 *
93123b17 2955 * If you need to search recursivily then use the {@link global_navigation::find()} method.
deaf04c7 2956 *
93123b17 2957 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
deaf04c7
SH
2958 * may be of more use to you.
2959 *
2960 * @param string|int $key The key of the node you wish to receive.
2961 * @param int $type One of navigation_node::TYPE_*
2962 * @return navigation_node|false
2963 */
e2b436d0 2964 public function get($key, $type = null) {
246a9b05
SH
2965 if (!$this->initialised) {
2966 $this->initialise();
2967 }
54dc15ab 2968 return parent::get($key, $type);
e2b436d0
SH
2969 }
2970
deaf04c7 2971 /**
31fde54f 2972 * Searches this nodes children and their children to find a navigation node
deaf04c7
SH
2973 * with the matching key and type.
2974 *
2975 * This method is recursive and searches children so until either a node is
31fde54f 2976 * found or there are no more nodes to search.
deaf04c7
SH
2977 *
2978 * If you know that the node being searched for is a child of this node
93123b17 2979 * then use the {@link global_navigation::get()} method instead.
deaf04c7 2980 *
93123b17 2981 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
deaf04c7
SH
2982 * may be of more use to you.
2983 *
2984 * @param string|int $key The key of the node you wish to receive.
2985 * @param int $type One of navigation_node::TYPE_*
2986 * @return navigation_node|false
2987 */
e2b436d0 2988 public function find($key, $type) {
246a9b05
SH
2989 if (!$this->initialised) {
2990 $this->initialise();
2991 }
58b602da
SH
2992 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2993 return $this->rootnodes[$key];
2994 }
54dc15ab 2995 return parent::find($key, $type);
e2b436d0 2996 }
f87ce4e9
SH
2997
2998 /**
2999 * They've expanded the 'my courses' branch.
3000 */
3001 protected function load_courses_enrolled() {
8aedc037 3002 global $CFG;
fa238237
MN
3003
3004 $limit = (int) $CFG->navcourselimit;
3005
04985346 3006 $courses = enrol_get_my_courses('*');
3dabb083
MN
3007 $flatnavcourses = [];
3008
3009 // Go through the courses and see which ones we want to display in the flatnav.
3010 foreach ($courses as $course) {
3011 $classify = course_classify_for_timeline($course);
3012
3013 if ($classify == COURSE_TIMELINE_INPROGRESS) {
3014 $flatnavcourses[$course->id] = $course;
3015 }
3016 }
3017
3018 // Get the number of courses that can be displayed in the nav block and in the flatnav.
3019 $numtotalcourses = count($courses);
3020 $numtotalflatnavcourses = count($flatnavcourses);
3021
3022 // Reduce the size of the arrays to abide by the 'navcourselimit' setting.
3023 $courses = array_slice($courses, 0, $limit, true);
3024 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true);
3025
3026 // Get the number of courses we are going to show for each.
3027 $numshowncourses = count($courses);
3028 $numshownflatnavcourses = count($flatnavcourses);
3029 if ($numshowncourses && $this->show_my_categories()) {
8aedc037 3030 // Generate an array containing unique values of all the courses' categories.
f87ce4e9
SH
3031 $categoryids = array();
3032 foreach ($courses as $course) {
8aedc037
JP
3033 if (in_array($course->category, $categoryids)) {
3034 continue;
3035 }
f87ce4e9
SH
3036 $categoryids[] = $course->category;
3037 }
f87ce4e9 3038
8aedc037
JP
3039 // Array of category IDs that include the categories of the user's courses and the related course categories.
3040 $fullpathcategoryids = [];
3041 // Get the course categories for the enrolled courses' category IDs.
442f12f8 3042 $mycoursecategories = core_course_category::get_many($categoryids);
8aedc037
JP
3043 // Loop over each of these categories and build the category tree using each category's path.
3044 foreach ($mycoursecategories as $mycoursecat) {
3045 $pathcategoryids = explode('/', $mycoursecat->path);
3046 // First element of the exploded path is empty since paths begin with '/'.
3047 array_shift($pathcategoryids);
3048 // Merge the exploded category IDs into the full list of category IDs that we will fetch.
3049 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids);
3050 }
3051
3052 // Fetch all of the categories related to the user's courses.
442f12f8 3053 $pathcategories = core_course_category::get_many($fullpathcategoryids);
8aedc037
JP
3054 // Loop over each of these categories and build the category tree.
3055 foreach ($pathcategories as $coursecat) {
3056 // No need to process categories that have already been added.
3057 if (isset($this->addedcategories[$coursecat->id])) {
3058 continue;
3059 }
3060
3061 // Get this course category's parent node.
3062 $parent = null;
3063 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) {
3064 $parent = $this->addedcategories[$coursecat->parent];
3065 }
3066 if (!$parent) {
3067 // If it has no parent, then it should be right under the My courses node.
3068 $parent = $this->rootnodes['mycourses'];
3069 }
3070
3071 // Build the category object based from the coursecat object.
3072 $mycategory = new stdClass();
3073 $mycategory->id = $coursecat->id;
3074 $mycategory->name = $coursecat->name;
3075 $mycategory->visible = $coursecat->visible;
3076
3077 // Add this category to the nav tree.
3078 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY);
f87ce4e9
SH
3079 }
3080 }
3dabb083
MN
3081
3082 // Go through each course now and add it to the nav block, and the flatnav if applicable.
8aedc037 3083 foreach ($courses as $course) {
3dabb083
MN
3084 $node = $this->add_course($course, false, self::COURSE_MY);
3085 if ($node) {
3086 $node->showinflatnavigation = false;
3087 // Check if we should also add this to the flat nav as well.
3088 if (isset($flatnavcourses[$course->id])) {