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