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