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