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