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