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