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