navigation MDL-14632 Gave user branches a more useful key
[moodle.git] / lib / navigationlib.php
CommitLineData
7d2a0492 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This file contains classes used to manage the navigation structures in Moodle
20 * and was introduced as part of the changes occuring in Moodle 2.0
21 *
22 * @since 2.0
23 * @package moodlecore
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29if (!function_exists('get_all_sections')) {
30 /** Include course lib for its functions */
31 require_once($CFG->dirroot.'/course/lib.php');
32}
33
f5b5a822 34/**
2561c4e9 35 * The name that will be used to separate the navigation cache within SESSION
f5b5a822 36 */
37define('NAVIGATION_CACHE_NAME', 'navigation');
38
7d2a0492 39/**
40 * This class is used to represent a node in a navigation tree
41 *
42 * This class is used to represent a node in a navigation tree within Moodle,
43 * the tree could be one of global navigation, settings navigation, or the navbar.
44 * Each node can be one of two types either a Leaf (default) or a branch.
45 * When a node is first created it is created as a leaf, when/if children are added
46 * the node then becomes a branch.
47 *
48 * @package moodlecore
babb3911 49 * @subpackage navigation
7d2a0492 50 * @copyright 2009 Sam Hemelryk
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 */
3406acde
SH
53class navigation_node implements renderable {
54 /** @var int Used to identify this node a leaf (default) 0 */
507a7a9a 55 const NODETYPE_LEAF = 0;
3406acde 56 /** @var int Used to identify this node a branch, happens with children 1 */
7d2a0492 57 const NODETYPE_BRANCH = 1;
3406acde 58 /** @var null Unknown node type null */
7d2a0492 59 const TYPE_UNKNOWN = null;
3406acde
SH
60 /** @var int System node type 0 */
61 const TYPE_ROOTNODE = 0;
62 /** @var int System node type 1 */
63 const TYPE_SYSTEM = 1;
64 /** @var int Category node type 10 */
7d2a0492 65 const TYPE_CATEGORY = 10;
3406acde 66 /** @var int Course node type 20 */
7d2a0492 67 const TYPE_COURSE = 20;
3406acde 68 /** @var int Course Structure node type 30 */
507a7a9a 69 const TYPE_SECTION = 30;
3406acde 70 /** @var int Activity node type, e.g. Forum, Quiz 40 */
7d2a0492 71 const TYPE_ACTIVITY = 40;
3406acde 72 /** @var int Resource node type, e.g. Link to a file, or label 50 */
7d2a0492 73 const TYPE_RESOURCE = 50;
3406acde 74 /** @var int A custom node type, default when adding without specifing type 60 */
7d2a0492 75 const TYPE_CUSTOM = 60;
3406acde 76 /** @var int Setting node type, used only within settings nav 70 */
7d2a0492 77 const TYPE_SETTING = 70;
3406acde 78 /** @var int Setting node type, used only within settings nav 80 */
507a7a9a 79 const TYPE_USER = 80;
3406acde
SH
80 /** @var int Setting node type, used for containers of no importance 90 */
81 const TYPE_CONTAINER = 90;
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;
3406acde
SH
123 /** @var navigation_node A reference to the node parent */
124 public $parent = null;
493a48f3
SH
125 /** @var bool Override to not display the icon even if one is provided **/
126 public $hideicon = false;
7d2a0492 127 /** @var array */
b14ae498 128 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
7d2a0492 129 /** @var moodle_url */
130 protected static $fullmeurl = null;
d9d2817a
SH
131 /** @var bool toogles auto matching of active node */
132 public static $autofindactive = true;
7d2a0492 133
134 /**
3406acde 135 * Constructs a new navigation_node
7d2a0492 136 *
3406acde
SH
137 * @param array|string $properties Either an array of properties or a string to use
138 * as the text for the node
7d2a0492 139 */
140 public function __construct($properties) {
7d2a0492 141 if (is_array($properties)) {
3406acde
SH
142 // Check the array for each property that we allow to set at construction.
143 // text - The main content for the node
144 // shorttext - A short text if required for the node
145 // icon - The icon to display for the node
146 // type - The type of the node
147 // key - The key to use to identify the node
148 // parent - A reference to the nodes parent
149 // action - The action to attribute to this node, usually a URL to link to
7d2a0492 150 if (array_key_exists('text', $properties)) {
151 $this->text = $properties['text'];
152 }
153 if (array_key_exists('shorttext', $properties)) {
154 $this->shorttext = $properties['shorttext'];
155 }
7081714d
SH
156 if (!array_key_exists('icon', $properties)) {
157 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
158 }
159 $this->icon = $properties['icon'];
160 if ($this->icon instanceof pix_icon) {
161 if (empty($this->icon->attributes['class'])) {
162 $this->icon->attributes['class'] = 'navicon';
163 } else {
164 $this->icon->attributes['class'] .= ' navicon';
7da3a799 165 }
7d2a0492 166 }
167 if (array_key_exists('type', $properties)) {
168 $this->type = $properties['type'];
169 } else {
170 $this->type = self::TYPE_CUSTOM;
171 }
172 if (array_key_exists('key', $properties)) {
173 $this->key = $properties['key'];
174 }
3406acde
SH
175 if (array_key_exists('parent', $properties)) {
176 $this->parent = $properties['parent'];
177 }
178 // This needs to happen last because of the check_if_active call that occurs
179 if (array_key_exists('action', $properties)) {
180 $this->action = $properties['action'];
181 if (is_string($this->action)) {
182 $this->action = new moodle_url($this->action);
183 }
184 if (self::$autofindactive) {
185 $this->check_if_active();
186 }
187 }
7d2a0492 188 } else if (is_string($properties)) {
189 $this->text = $properties;
190 }
191 if ($this->text === null) {
192 throw new coding_exception('You must set the text for the node when you create it.');
193 }
3406acde 194 // Default the title to the text
7d2a0492 195 $this->title = $this->text;
3406acde
SH
196 // Instantiate a new navigation node collection for this nodes children
197 $this->children = new navigation_node_collection();
7d2a0492 198 }
199
95b97515 200 /**
3406acde 201 * Checks if this node is the active node.
0baa5d46 202 *
3406acde
SH
203 * This is determined by comparing the action for the node against the
204 * defined URL for the page. A match will see this node marked as active.
0baa5d46 205 *
3406acde
SH
206 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
207 * @return bool
7d2a0492 208 */
bf6c37c7 209 public function check_if_active($strength=URL_MATCH_EXACT) {
210 global $FULLME, $PAGE;
3406acde 211 // Set fullmeurl if it hasn't already been set
7d2a0492 212 if (self::$fullmeurl == null) {
bf6c37c7 213 if ($PAGE->has_set_url()) {
3406acde 214 self::override_active_url(new moodle_url($PAGE->url));
bf6c37c7 215 } else {
3406acde 216 self::override_active_url(new moodle_url($FULLME));
7d2a0492 217 }
218 }
bf6c37c7 219
3406acde 220 // Compare the action of this node against the fullmeurl
bf6c37c7 221 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
7d2a0492 222 $this->make_active();
223 return true;
7d2a0492 224 }
225 return false;
226 }
3406acde 227
7d2a0492 228 /**
3406acde 229 * Overrides the fullmeurl variable providing
7d2a0492 230 *
3406acde
SH
231 * @param moodle_url $url The url to use for the fullmeurl.
232 */
233 public static function override_active_url(moodle_url $url) {
234 self::$fullmeurl = $url;
235 }
236
237 /**
238 * Adds a navigation node as a child of this node.
435a512e 239 *
3406acde
SH
240 * @param string $text
241 * @param moodle_url|action_link $action
242 * @param int $type
243 * @param string $shorttext
244 * @param string|int $key
245 * @param pix_icon $icon
246 * @return navigation_node
7d2a0492 247 */
3406acde
SH
248 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
249 // First convert the nodetype for this node to a branch as it will now have children
7d2a0492 250 if ($this->nodetype !== self::NODETYPE_BRANCH) {
251 $this->nodetype = self::NODETYPE_BRANCH;
252 }
3406acde
SH
253 // Properties array used when creating the new navigation node
254 $itemarray = array(
255 'text' => $text,
256 'type' => $type
257 );
258 // Set the action if one was provided
7d2a0492 259 if ($action!==null) {
260 $itemarray['action'] = $action;
261 }
3406acde 262 // Set the shorttext if one was provided
7d2a0492 263 if ($shorttext!==null) {
264 $itemarray['shorttext'] = $shorttext;
265 }
3406acde 266 // Set the icon if one was provided
7d2a0492 267 if ($icon!==null) {
268 $itemarray['icon'] = $icon;
269 }
3406acde
SH
270 // Default the key to the number of children if not provided
271 if ($key === null) {
272 $key = $this->children->count();
7d2a0492 273 }
3406acde 274 // Set the key
7d2a0492 275 $itemarray['key'] = $key;
3406acde
SH
276 // Set the parent to this node
277 $itemarray['parent'] = $this;
278 // Add the child using the navigation_node_collections add method
279 $node = $this->children->add(new navigation_node($itemarray));
280 // If the node is a category node or the user is logged in and its a course
281 // then mark this node as a branch (makes it expandable by AJAX)
c73e37e0 282 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
3406acde 283 $node->nodetype = self::NODETYPE_BRANCH;
7d2a0492 284 }
3406acde 285 // If this node is hidden mark it's children as hidden also
7d2a0492 286 if ($this->hidden) {
3406acde 287 $node->hidden = true;
7d2a0492 288 }
3406acde
SH
289 // Return the node (reference returned by $this->children->add()
290 return $node;
7d2a0492 291 }
292
293 /**
3406acde 294 * Searches for a node of the given type with the given key.
7d2a0492 295 *
3406acde
SH
296 * This searches this node plus all of its children, and their children....
297 * If you know the node you are looking for is a child of this node then please
298 * use the get method instead.
299 *
300 * @param int|string $key The key of the node we are looking for
301 * @param int $type One of navigation_node::TYPE_*
302 * @return navigation_node|false
7d2a0492 303 */
3406acde
SH
304 public function find($key, $type) {
305 return $this->children->find($key, $type);
306 }
307
308 /**
309 * Get ths child of this node that has the given key + (optional) type.
310 *
311 * If you are looking for a node and want to search all children + thier children
312 * then please use the find method instead.
313 *
314 * @param int|string $key The key of the node we are looking for
315 * @param int $type One of navigation_node::TYPE_*
316 * @return navigation_node|false
317 */
318 public function get($key, $type=null) {
319 return $this->children->get($key, $type);
320 }
321
322 /**
323 * Removes this node.
324 *
325 * @return bool
326 */
327 public function remove() {
328 return $this->parent->children->remove($this->key, $this->type);
329 }
330
331 /**
332 * Checks if this node has or could have any children
333 *
334 * @return bool Returns true if it has children or could have (by AJAX expansion)
335 */
336 public function has_children() {
337 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
338 }
339
340 /**
341 * Marks this node as active and forces it open.
342 */
343 public function make_active() {
344 $this->isactive = true;
345 $this->add_class('active_tree_node');
346 $this->force_open();
347 if ($this->parent !== null) {
348 $this->parent->make_inactive();
349 }
350 }
351
352 /**
353 * Marks a node as inactive and recusised back to the base of the tree
354 * doing the same to all parents.
355 */
356 public function make_inactive() {
357 $this->isactive = false;
358 $this->remove_class('active_tree_node');
359 if ($this->parent !== null) {
360 $this->parent->make_inactive();
7d2a0492 361 }
362 }
363
364 /**
3406acde
SH
365 * Forces this node to be open and at the same time forces open all
366 * parents until the root node.
117bd748 367 *
3406acde
SH
368 * Recursive.
369 */
370 public function force_open() {
371 $this->forceopen = true;
372 if ($this->parent !== null) {
373 $this->parent->force_open();
374 }
375 }
376
377 /**
378 * Adds a CSS class to this node.
379 *
380 * @param string $class
381 * @return bool
7d2a0492 382 */
383 public function add_class($class) {
384 if (!in_array($class, $this->classes)) {
385 $this->classes[] = $class;
386 }
387 return true;
388 }
389
390 /**
3406acde 391 * Removes a CSS class from this node.
7d2a0492 392 *
393 * @param string $class
3406acde 394 * @return bool True if the class was successfully removed.
7d2a0492 395 */
396 public function remove_class($class) {
397 if (in_array($class, $this->classes)) {
398 $key = array_search($class,$this->classes);
399 if ($key!==false) {
400 unset($this->classes[$key]);
401 return true;
402 }
403 }
404 return false;
405 }
406
407 /**
3406acde
SH
408 * Sets the title for this node and forces Moodle to utilise it.
409 * @param string $title
410 */
411 public function title($title) {
412 $this->title = $title;
413 $this->forcetitle = true;
414 }
415
416 /**
417 * Resets the page specific information on this node if it is being unserialised.
418 */
419 public function __wakeup(){
420 $this->forceopen = false;
421 $this->isactive = false;
422 $this->remove_class('active_tree_node');
423 }
424
425 /**
426 * Checks if this node or any of its children contain the active node.
435a512e 427 *
3406acde 428 * Recursive.
7d2a0492 429 *
3406acde 430 * @return bool
7d2a0492 431 */
3406acde
SH
432 public function contains_active_node() {
433 if ($this->isactive) {
7d2a0492 434 return true;
435 } else {
3406acde
SH
436 foreach ($this->children as $child) {
437 if ($child->isactive || $child->contains_active_node()) {
438 return true;
439 }
440 }
7d2a0492 441 }
3406acde 442 return false;
7d2a0492 443 }
444
445 /**
3406acde
SH
446 * Finds the active node.
447 *
448 * Searches this nodes children plus all of the children for the active node
449 * and returns it if found.
7d2a0492 450 *
3406acde
SH
451 * Recursive.
452 *
453 * @return navigation_node|false
7d2a0492 454 */
3406acde
SH
455 public function find_active_node() {
456 if ($this->isactive) {
457 return $this;
458 } else {
7d2a0492 459 foreach ($this->children as &$child) {
3406acde
SH
460 $outcome = $child->find_active_node();
461 if ($outcome !== false) {
462 return $outcome;
7d2a0492 463 }
464 }
7d2a0492 465 }
3406acde 466 return false;
7d2a0492 467 }
468
7c4efe3b
SH
469 /**
470 * Searches all children for the best matching active node
471 * @return navigation_node|false
472 */
473 public function search_for_active_node() {
474 if ($this->check_if_active(URL_MATCH_BASE)) {
475 return $this;
476 } else {
477 foreach ($this->children as &$child) {
478 $outcome = $child->search_for_active_node();
479 if ($outcome !== false) {
480 return $outcome;
481 }
482 }
483 }
484 return false;
485 }
486
7d2a0492 487 /**
3406acde 488 * Gets the content for this node.
7d2a0492 489 *
3406acde
SH
490 * @param bool $shorttext If true shorttext is used rather than the normal text
491 * @return string
7d2a0492 492 */
3406acde 493 public function get_content($shorttext=false) {
7d2a0492 494 if ($shorttext && $this->shorttext!==null) {
3406acde 495 return format_string($this->shorttext);
7d2a0492 496 } else {
3406acde 497 return format_string($this->text);
1c4eef57 498 }
3406acde 499 }
1c4eef57 500
3406acde
SH
501 /**
502 * Gets the title to use for this node.
435a512e 503 *
3406acde
SH
504 * @return string
505 */
506 public function get_title() {
bbfa9be0 507 if ($this->forcetitle || $this->action != null){
3406acde
SH
508 return $this->title;
509 } else {
9bf16314
PS
510 return '';
511 }
7d2a0492 512 }
117bd748 513
7d2a0492 514 /**
3406acde 515 * Gets the CSS class to add to this node to describe its type
435a512e 516 *
7d2a0492 517 * @return string
518 */
519 public function get_css_type() {
520 if (array_key_exists($this->type, $this->namedtypes)) {
521 return 'type_'.$this->namedtypes[$this->type];
522 }
523 return 'type_unknown';
524 }
525
526 /**
3406acde 527 * Finds all nodes that are expandable by AJAX
7d2a0492 528 *
3406acde 529 * @param array $expandable An array by reference to populate with expandable nodes.
7d2a0492 530 */
3406acde 531 public function find_expandable(array &$expandable) {
4766a50c
SH
532 $isloggedin = (isloggedin() && !isguestuser());
533 if (!$isloggedin && $this->type > self::TYPE_CATEGORY) {
3406acde
SH
534 return;
535 }
536 foreach ($this->children as &$child) {
4766a50c
SH
537 if (!$isloggedin && $child->type > self::TYPE_CATEGORY) {
538 continue;
539 }
88f77c3c 540 if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count()==0 && $child->display) {
3406acde
SH
541 $child->id = 'expandable_branch_'.(count($expandable)+1);
542 $this->add_class('canexpand');
543 $expandable[] = array('id'=>$child->id,'branchid'=>$child->key,'type'=>$child->type);
7d2a0492 544 }
3406acde 545 $child->find_expandable($expandable);
7d2a0492 546 }
7d2a0492 547 }
88f77c3c 548
4766a50c
SH
549 /**
550 * Finds all nodes of a given type (recursive)
551 *
552 * @param int $type On of navigation_node::TYPE_*
553 * @return array
554 */
88f77c3c
SH
555 public function find_all_of_type($type) {
556 $nodes = $this->children->type($type);
557 foreach ($this->children as &$node) {
558 $childnodes = $node->find_all_of_type($type);
559 $nodes = array_merge($nodes, $childnodes);
560 }
561 return $nodes;
562 }
56ed242b
SH
563
564 /**
565 * Removes this node if it is empty
566 */
567 public function trim_if_empty() {
568 if ($this->children->count() == 0) {
569 $this->remove();
570 }
571 }
572
573 /**
574 * Creates a tab representation of this nodes children that can be used
575 * with print_tabs to produce the tabs on a page.
576 *
577 * call_user_func_array('print_tabs', $node->get_tabs_array());
578 *
579 * @param array $inactive
580 * @param bool $return
581 * @return array Array (tabs, selected, inactive, activated, return)
582 */
583 public function get_tabs_array(array $inactive=array(), $return=false) {
584 $tabs = array();
585 $rows = array();
586 $selected = null;
587 $activated = array();
588 foreach ($this->children as $node) {
589 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
590 if ($node->contains_active_node()) {
591 if ($node->children->count() > 0) {
592 $activated[] = $node->key;
593 foreach ($node->children as $child) {
594 if ($child->contains_active_node()) {
595 $selected = $child->key;
596 }
597 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
598 }
599 } else {
600 $selected = $node->key;
601 }
602 }
603 }
604 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
605 }
3406acde 606}
7d2a0492 607
3406acde
SH
608/**
609 * Navigation node collection
610 *
611 * This class is responsible for managing a collection of navigation nodes.
612 * It is required because a node's unique identifier is a combination of both its
613 * key and its type.
614 *
615 * Originally an array was used with a string key that was a combination of the two
616 * however it was decided that a better solution would be to use a class that
617 * implements the standard IteratorAggregate interface.
618 *
619 * @package moodlecore
620 * @subpackage navigation
621 * @copyright 2010 Sam Hemelryk
622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
623 */
624class navigation_node_collection implements IteratorAggregate {
7d2a0492 625 /**
3406acde
SH
626 * A multidimensional array to where the first key is the type and the second
627 * key is the nodes key.
628 * @var array
7d2a0492 629 */
3406acde 630 protected $collection = array();
7d2a0492 631 /**
3406acde
SH
632 * An array that contains references to nodes in the same order they were added.
633 * This is maintained as a progressive array.
634 * @var array
7d2a0492 635 */
3406acde 636 protected $orderedcollection = array();
da3ab9c4 637 /**
3406acde
SH
638 * A reference to the last node that was added to the collection
639 * @var navigation_node
da3ab9c4 640 */
3406acde 641 protected $last = null;
6644741d 642 /**
3406acde
SH
643 * The total number of items added to this array.
644 * @var int
6644741d 645 */
3406acde 646 protected $count = 0;
7d2a0492 647 /**
3406acde 648 * Adds a navigation node to the collection
7d2a0492 649 *
3406acde
SH
650 * @param navigation_node $node
651 * @return navigation_node
7d2a0492 652 */
3406acde
SH
653 public function add(navigation_node $node) {
654 global $CFG;
655 $key = $node->key;
656 $type = $node->type;
657 // First check we have a 2nd dimension for this type
658 if (!array_key_exists($type, $this->orderedcollection)) {
659 $this->orderedcollection[$type] = array();
7d2a0492 660 }
3406acde
SH
661 // Check for a collision and report if debugging is turned on
662 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
663 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
7d2a0492 664 }
3406acde
SH
665 // Add the node to the appropriate place in the ordered structure.
666 $this->orderedcollection[$type][$key] = $node;
667 // Add a reference to the node to the progressive collection.
668 $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
669 // Update the last property to a reference to this new node.
670 $this->last = &$this->orderedcollection[$type][$key];
671 $this->count++;
672 // Return the reference to the now added node
673 return $this->last;
7d2a0492 674 }
675
676 /**
3406acde 677 * Fetches a node from this collection.
7d2a0492 678 *
3406acde
SH
679 * @param string|int $key The key of the node we want to find.
680 * @param int $type One of navigation_node::TYPE_*.
681 * @return navigation_node|null
7d2a0492 682 */
3406acde
SH
683 public function get($key, $type=null) {
684 if ($type !== null) {
685 // If the type is known then we can simply check and fetch
686 if (!empty($this->orderedcollection[$type][$key])) {
687 return $this->orderedcollection[$type][$key];
688 }
689 } else {
690 // Because we don't know the type we look in the progressive array
691 foreach ($this->collection as $node) {
692 if ($node->key === $key) {
693 return $node;
7d2a0492 694 }
695 }
696 }
697 return false;
698 }
7d2a0492 699 /**
3406acde 700 * Searches for a node with matching key and type.
7d2a0492 701 *
3406acde
SH
702 * This function searches both the nodes in this collection and all of
703 * the nodes in each collection belonging to the nodes in this collection.
7d2a0492 704 *
3406acde 705 * Recursive.
7d2a0492 706 *
3406acde
SH
707 * @param string|int $key The key of the node we want to find.
708 * @param int $type One of navigation_node::TYPE_*.
709 * @return navigation_node|null
7d2a0492 710 */
3406acde
SH
711 public function find($key, $type=null) {
712 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
713 return $this->orderedcollection[$type][$key];
714 } else {
715 $nodes = $this->getIterator();
716 // Search immediate children first
717 foreach ($nodes as &$node) {
718 if ($node->key == $key && ($type == null || $type === $node->type)) {
719 return $node;
d926f4b1 720 }
3406acde
SH
721 }
722 // Now search each childs children
723 foreach ($nodes as &$node) {
724 $result = $node->children->find($key, $type);
725 if ($result !== false) {
726 return $result;
d926f4b1 727 }
7d2a0492 728 }
729 }
730 return false;
731 }
732
d926f4b1 733 /**
3406acde 734 * Fetches the last node that was added to this collection
435a512e 735 *
3406acde 736 * @return navigation_node
d926f4b1 737 */
3406acde
SH
738 public function last() {
739 return $this->last;
740 }
741 /**
742 * Fetches all nodes of a given type from this collection
743 */
744 public function type($type) {
745 if (!array_key_exists($type, $this->orderedcollection)) {
746 $this->orderedcollection[$type] = array();
d926f4b1 747 }
3406acde 748 return $this->orderedcollection[$type];
d926f4b1 749 }
7d2a0492 750 /**
3406acde 751 * Removes the node with the given key and type from the collection
7d2a0492 752 *
3406acde
SH
753 * @param string|int $key
754 * @param int $type
755 * @return bool
7d2a0492 756 */
3406acde
SH
757 public function remove($key, $type=null) {
758 $child = $this->get($key, $type);
759 if ($child !== false) {
760 foreach ($this->collection as $colkey => $node) {
761 if ($node->key == $key && $node->type == $type) {
762 unset($this->collection[$colkey]);
763 break;
764 }
7d2a0492 765 }
3406acde
SH
766 unset($this->orderedcollection[$child->type][$child->key]);
767 $this->count--;
768 return true;
7d2a0492 769 }
3406acde 770 return false;
7d2a0492 771 }
772
9da1ec27 773 /**
3406acde
SH
774 * Gets the number of nodes in this collection
775 * @return int
7d2a0492 776 */
3406acde
SH
777 public function count() {
778 return count($this->collection);
7d2a0492 779 }
7d2a0492 780 /**
3406acde 781 * Gets an array iterator for the collection.
7d2a0492 782 *
3406acde
SH
783 * This is required by the IteratorAggregator interface and is used by routines
784 * such as the foreach loop.
7d2a0492 785 *
3406acde 786 * @return ArrayIterator
7d2a0492 787 */
3406acde
SH
788 public function getIterator() {
789 return new ArrayIterator($this->collection);
7d2a0492 790 }
791}
792
793/**
794 * The global navigation class used for... the global navigation
795 *
796 * This class is used by PAGE to store the global navigation for the site
797 * and is then used by the settings nav and navbar to save on processing and DB calls
798 *
799 * See
800 * <ul>
801 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
802 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
803 * </ul>
804 *
805 * @package moodlecore
babb3911 806 * @subpackage navigation
7d2a0492 807 * @copyright 2009 Sam Hemelryk
808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
809 */
810class global_navigation extends navigation_node {
3406acde
SH
811 /**
812 * The Moodle page this navigation object belongs to.
813 * @var moodle_page
814 */
815 protected $page;
7d2a0492 816 /** @var bool */
817 protected $initialised = false;
3406acde
SH
818 /** @var array */
819 protected $mycourses = array();
820 /** @var array */
821 protected $rootnodes = array();
7d2a0492 822 /** @var bool */
3406acde
SH
823 protected $showemptysections = false;
824 /** @var array */
7a7e209d 825 protected $extendforuser = array();
3406acde
SH
826 /** @var navigation_cache */
827 protected $cache;
828 /** @var array */
829 protected $addedcourses = array();
88f77c3c
SH
830 /** @var int */
831 protected $expansionlimit = 0;
832
7d2a0492 833 /**
3406acde
SH
834 * Constructs a new global navigation
835 *
3406acde 836 * @param moodle_page $page The page this navigation object belongs to
7d2a0492 837 */
3406acde 838 public function __construct(moodle_page $page) {
4766a50c 839 global $CFG, $SITE, $USER;
3406acde 840
7d2a0492 841 if (during_initial_install()) {
3406acde 842 return;
7d2a0492 843 }
3406acde 844
4766a50c
SH
845 if (get_home_page() == HOMEPAGE_SITE) {
846 // We are using the site home for the root element
847 $properties = array(
848 'key' => 'home',
849 'type' => navigation_node::TYPE_SYSTEM,
850 'text' => get_string('home'),
851 'action' => new moodle_url('/')
852 );
853 } else {
854 // We are using the users my moodle for the root element
855 $properties = array(
856 'key' => 'myhome',
857 'type' => navigation_node::TYPE_SYSTEM,
858 'text' => get_string('myhome'),
859 'action' => new moodle_url('/my/')
860 );
dd8e5011 861 }
4766a50c
SH
862
863 // Use the parents consturctor.... good good reuse
3406acde
SH
864 parent::__construct($properties);
865
866 // Initalise and set defaults
867 $this->page = $page;
7d2a0492 868 $this->forceopen = true;
f5b5a822 869 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3406acde
SH
870
871 // Check if we need to clear the cache
7d2a0492 872 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
3406acde 873 if ($regenerate === 'navigation') {
7d2a0492 874 $this->cache->clear();
875 }
876 }
877
878 /**
3406acde 879 * Initialises the navigation object.
7d2a0492 880 *
3406acde
SH
881 * This causes the navigation object to look at the current state of the page
882 * that it is associated with and then load the appropriate content.
7d2a0492 883 *
3406acde
SH
884 * This should only occur the first time that the navigation structure is utilised
885 * which will normally be either when the navbar is called to be displayed or
886 * when a block makes use of it.
7d2a0492 887 *
3406acde 888 * @return bool
7d2a0492 889 */
3406acde 890 public function initialise() {
4766a50c 891 global $CFG, $SITE, $USER, $DB;
3406acde 892 // Check if it has alread been initialised
7d2a0492 893 if ($this->initialised || during_initial_install()) {
894 return true;
895 }
3406acde
SH
896
897 // Set up the five base root nodes. These are nodes where we will put our
898 // content and are as follows:
899 // site: Navigation for the front page.
900 // myprofile: User profile information goes here.
901 // mycourses: The users courses get added here.
902 // courses: Additional courses are added here.
903 // users: Other users information loaded here.
904 $this->rootnodes = array();
4766a50c 905 if (get_home_page() == HOMEPAGE_SITE) {
3f9ccf85 906 // The home element should be my moodle because the root element is the site
b9d4c7d3 907 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
3f9ccf85
MD
908 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
909 }
4766a50c
SH
910 } else {
911 // The home element should be the site because the root node is my moodle
912 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
913 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
914 // We need to stop automatic redirection
915 $this->rootnodes['home']->action->param('redirect', '0');
916 }
917 }
3406acde
SH
918 $this->rootnodes['site'] = $this->add_course($SITE);
919 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
920 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
921 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
922 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
923
924 // Fetch all of the users courses.
4766a50c
SH
925 $limit = 20;
926 if (!empty($CFG->navcourselimit)) {
927 $limit = $CFG->navcourselimit;
928 }
929
9a18a77e
SH
930 if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') == 1) {
931 // There is only one category so we don't want to show categories
932 $CFG->navshowcategories = false;
933 }
934
4766a50c 935 $this->mycourses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', null, false, $limit);
ba2789c1
SH
936 $showallcourses = (count($this->mycourses) == 0 || !empty($CFG->navshowallcourses));
937 $showcategories = ($showallcourses && !empty($CFG->navshowcategories));
938
3406acde
SH
939 // Check if any courses were returned.
940 if (count($this->mycourses) > 0) {
941 // Add all of the users courses to the navigation
942 foreach ($this->mycourses as &$course) {
4766a50c 943 $course->coursenode = $this->add_course($course);
3406acde 944 }
4766a50c
SH
945 }
946
4766a50c
SH
947 if ($showcategories) {
948 // Load all categories (ensures we get the base categories)
949 $this->load_all_categories();
ba2789c1
SH
950 } else if ($showallcourses) {
951 // Load all courses
952 $this->load_all_courses();
3406acde
SH
953 }
954
955 // Next load context specific content into the navigation
956 switch ($this->page->context->contextlevel) {
957 case CONTEXT_SYSTEM :
958 case CONTEXT_COURSECAT :
959 // Load the front page course navigation
7c4efe3b
SH
960 $coursenode = $this->load_course($SITE);
961 $this->add_front_page_course_essentials($coursenode, $SITE);
7d2a0492 962 break;
3406acde
SH
963 case CONTEXT_BLOCK :
964 case CONTEXT_COURSE :
965 // Load the course associated with the page into the navigation
966 $course = $this->page->course;
967 $coursenode = $this->load_course($course);
3406acde
SH
968 // Add the essentials such as reports etc...
969 $this->add_course_essentials($coursenode, $course);
970 if ($this->format_display_course_content($course->format)) {
971 // Load the course sections
972 $sections = $this->load_course_sections($course, $coursenode);
973 }
7c4efe3b
SH
974 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
975 $coursenode->make_active();
976 }
7d2a0492 977 break;
3406acde
SH
978 case CONTEXT_MODULE :
979 $course = $this->page->course;
980 $cm = $this->page->cm;
981 // Load the course associated with the page into the navigation
982 $coursenode = $this->load_course($course);
983 $this->add_course_essentials($coursenode, $course);
984 // Load the course sections into the page
985 $sections = $this->load_course_sections($course, $coursenode);
986 if ($course->id !== SITEID) {
987 // Find the section for the $CM associated with the page and collect
988 // its section number.
989 foreach ($sections as $section) {
990 if ($section->id == $cm->section) {
991 $cm->sectionnumber = $section->section;
992 break;
993 }
994 }
995
996 // Load all of the section activities for the section the cm belongs to.
997 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
3406acde
SH
998 } else {
999 $activities = array();
1000 $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1001 }
91eab03d 1002 // Finally load the cm specific navigaton information
3406acde 1003 $this->load_activity($cm, $course, $activities[$cm->id]);
7c4efe3b
SH
1004 // Check if we have an active ndoe
1005 if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1006 // And make the activity node active.
1007 $activities[$cm->id]->make_active();
1008 }
7d2a0492 1009 break;
3406acde
SH
1010 case CONTEXT_USER :
1011 $course = $this->page->course;
1012 if ($course->id != SITEID) {
1013 // Load the course associated with the user into the navigation
1014 $coursenode = $this->load_course($course);
1015 $this->add_course_essentials($coursenode, $course);
1016 $sections = $this->load_course_sections($course, $coursenode);
7a7e209d 1017 }
7d2a0492 1018 break;
1019 }
7a7e209d 1020
ba2789c1
SH
1021 $limit = 20;
1022 if (!empty($CFG->navcourselimit)) {
1023 $limit = $CFG->navcourselimit;
1024 }
1025 if ($showcategories) {
1026 $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1027 foreach ($categories as &$category) {
1028 if ($category->children->count() >= $limit) {
1029 $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1030 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1031 }
1032 }
1033 } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1034 $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1035 }
1036
3406acde
SH
1037 // Load for the current user
1038 $this->load_for_user();
25ad1f47 1039 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
87c215de
SH
1040 $this->load_for_user(null, true);
1041 }
7a7e209d
SH
1042 // Load each extending user into the navigation.
1043 foreach ($this->extendforuser as $user) {
1044 if ($user->id !== $USER->id) {
1045 $this->load_for_user($user);
1046 }
1047 }
7a7e209d 1048
a683da3c
SH
1049 // Give the local plugins a chance to include some navigation if they want.
1050 foreach (get_list_of_plugins('local') as $plugin) {
1051 if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1052 continue;
1053 }
1054 require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1055 $function = $plugin.'_extends_navigation';
1056 if (function_exists($function)) {
1057 $function($this);
1058 }
1059 }
1060
3406acde
SH
1061 // Remove any empty root nodes
1062 foreach ($this->rootnodes as $node) {
4766a50c
SH
1063 // Dont remove the home node
1064 if ($node->key !== 'home' && !$node->has_children()) {
3406acde
SH
1065 $node->remove();
1066 }
1067 }
1068
7c4efe3b
SH
1069 if (!$this->contains_active_node()) {
1070 $this->search_for_active_node();
1071 }
1072
3406acde
SH
1073 // If the user is not logged in modify the navigation structure as detailed
1074 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1075 if (!isloggedin()) {
1076 $activities = clone($this->rootnodes['site']->children);
1077 $this->rootnodes['site']->remove();
1078 $children = clone($this->children);
1079 $this->children = new navigation_node_collection();
1080 foreach ($activities as $child) {
1081 $this->children->add($child);
1082 }
1083 foreach ($children as $child) {
1084 $this->children->add($child);
1085 }
3406acde
SH
1086 }
1087
7d2a0492 1088 $this->initialised = true;
1089 return true;
1090 }
1091 /**
3406acde
SH
1092 * Checks the course format to see whether it wants the navigation to load
1093 * additional information for the course.
1094 *
1095 * This function utilises a callback that can exist within the course format lib.php file
1096 * The callback should be a function called:
1097 * callback_{formatname}_display_content()
1098 * It doesn't get any arguments and should return true if additional content is
1099 * desired. If the callback doesn't exist we assume additional content is wanted.
1100 *
3406acde
SH
1101 * @param string $format The course format
1102 * @return bool
1103 */
1104 protected function format_display_course_content($format) {
1105 global $CFG;
1106 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1107 if (file_exists($formatlib)) {
1108 require_once($formatlib);
1109 $displayfunc = 'callback_'.$format.'_display_content';
1110 if (function_exists($displayfunc) && !$displayfunc()) {
1111 return $displayfunc();
1112 }
1113 }
1114 return true;
1115 }
1116
1117 /**
1118 * Loads of the the courses in Moodle into the navigation.
1119 *
4766a50c 1120 * @param string|array $categoryids Either a string or array of category ids to load courses for
3406acde
SH
1121 * @return array An array of navigation_node
1122 */
4766a50c
SH
1123 protected function load_all_courses($categoryids=null) {
1124 global $CFG, $DB, $USER;
1125
1126 if ($categoryids !== null) {
1127 if (is_array($categoryids)) {
1128 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1129 } else {
1130 $select = '= ?';
1131 $params = array($categoryids);
1132 }
1133 array_unshift($params, SITEID);
1134 $select = ' AND c.category '.$select;
1135 } else {
1136 $params = array(SITEID);
1137 $select = '';
1138 }
435a512e 1139
3406acde
SH
1140 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1141 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1142 FROM {course} c
1143 $ccjoin
1144 LEFT JOIN {course_categories} cat ON cat.id=c.category
4766a50c 1145 WHERE c.id <> ?$select
3406acde 1146 ORDER BY c.sortorder ASC";
4766a50c
SH
1147 $limit = 20;
1148 if (!empty($CFG->navcourselimit)) {
1149 $limit = $CFG->navcourselimit;
1150 }
1151 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1152
3406acde
SH
1153 $coursenodes = array();
1154 foreach ($courses as $course) {
1155 context_instance_preload($course);
1156 $coursenodes[$course->id] = $this->add_course($course);
1157 }
1158 return $coursenodes;
1159 }
1160
4766a50c
SH
1161 /**
1162 * Loads all categories (top level or if an id is specified for that category)
1163 *
1164 * @param int $categoryid
1165 * @return void
1166 */
1167 protected function load_all_categories($categoryid=null) {
1168 global $DB;
1169 if ($categoryid == null) {
1170 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1171 } else {
1172 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
1173 $wantedids = explode('/', trim($category->path, '/'));
1174 list($select, $params) = $DB->get_in_or_equal($wantedids);
1175 $select = 'id '.$select.' OR parent '.$select;
1176 $params = array_merge($params, $params);
1177 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1178 }
1179 $structured = array();
1180 $categoriestoload = array();
1181 foreach ($categories as $category) {
1182 if ($category->parent == '0') {
1183 $structured[$category->id] = array('category'=>$category, 'children'=>array());
1184 } else {
1185 if ($category->parent == $categoryid) {
1186 $categoriestoload[] = $category->id;
1187 }
1188 $parents = array();
1189 $id = $category->parent;
1190 while ($id != '0') {
1191 $parents[] = $id;
1192 if (!array_key_exists($id, $categories)) {
1193 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST);
1194 }
1195 $id = $categories[$id]->parent;
1196 }
1197 $parents = array_reverse($parents);
1198 $parentref = &$structured[array_shift($parents)];
1199 foreach ($parents as $parent) {
1200 if (!array_key_exists($parent, $parentref['children'])) {
1201 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1202 }
1203 $parentref = &$parentref['children'][$parent];
1204 }
1205 if (!array_key_exists($category->id, $parentref['children'])) {
1206 $parentref['children'][$category->id] = array('category'=>$category, 'children'=>array());
1207 }
1208 }
1209 }
1210
1211 foreach ($structured as $category) {
1212 $this->add_category($category, $this->rootnodes['courses']);
1213 }
1214
1215 if ($categoryid !== null && count($wantedids)) {
1216 foreach ($wantedids as $catid) {
1217 $this->load_all_courses($catid);
1218 }
1219 }
1220 }
1221
1222 /**
1223 * Adds a structured category to the navigation in the correct order/place
1224 *
1225 * @param object $cat
435a512e 1226 * @param navigation_node $parent
4766a50c
SH
1227 */
1228 protected function add_category($cat, navigation_node $parent) {
1229 $category = $parent->get($cat['category']->id, navigation_node::TYPE_CATEGORY);
1230 if (!$category) {
1231 $category = $cat['category'];
1232 $url = new moodle_url('/course/category.php', array('id'=>$category->id));
1233 $category = $parent->add($category->name, null, self::TYPE_CATEGORY, $category->name, $category->id);
1234 }
1235 foreach ($cat['children'] as $child) {
1236 $this->add_category($child, $category);
1237 }
1238 }
1239
3406acde
SH
1240 /**
1241 * Loads the given course into the navigation
7d2a0492 1242 *
3406acde
SH
1243 * @param stdClass $course
1244 * @return navigation_node
1245 */
1246 protected function load_course(stdClass $course) {
1247 if ($course->id == SITEID) {
1248 $coursenode = $this->rootnodes['site'];
1249 } else if (array_key_exists($course->id, $this->mycourses)) {
1250 if (!isset($this->mycourses[$course->id]->coursenode)) {
1251 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
1252 }
1253 $coursenode = $this->mycourses[$course->id]->coursenode;
1254 } else {
1255 $coursenode = $this->add_course($course);
1256 }
1257 return $coursenode;
1258 }
1259
1260 /**
1261 * Loads all of the courses section into the navigation.
1262 *
1263 * This function utilisies a callback that can be implemented within the course
1264 * formats lib.php file to customise the navigation that is generated at this
1265 * point for the course.
1266 *
1267 * By default (if not defined) the method {@see load_generic_course_sections} is
1268 * called instead.
1269 *
3406acde
SH
1270 * @param stdClass $course Database record for the course
1271 * @param navigation_node $coursenode The course node within the navigation
1272 * @return array Array of navigation nodes for the section with key = section id
1273 */
1274 protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1275 global $CFG;
1276 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1277 $structurefunc = 'callback_'.$course->format.'_load_content';
1278 if (function_exists($structurefunc)) {
1279 return $structurefunc($this, $course, $coursenode);
1280 } else if (file_exists($structurefile)) {
1281 require_once $structurefile;
1282 if (function_exists($structurefunc)) {
1283 return $structurefunc($this, $course, $coursenode);
1284 } else {
0f4ab67d 1285 return $this->load_generic_course_sections($course, $coursenode);
3406acde
SH
1286 }
1287 } else {
0f4ab67d 1288 return $this->load_generic_course_sections($course, $coursenode);
3406acde
SH
1289 }
1290 }
1291
1292 /**
1293 * Generically loads the course sections into the course's navigation.
1294 *
1295 * @param stdClass $course
1296 * @param navigation_node $coursenode
1297 * @param string $name The string that identifies each section. e.g Topic, or Week
1298 * @param string $activeparam The url used to identify the active section
1299 * @return array An array of course section nodes
1300 */
0f4ab67d
SH
1301 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1302 global $DB, $USER;
435a512e 1303
3406acde
SH
1304 $modinfo = get_fast_modinfo($course);
1305 $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1306 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1307
0f4ab67d
SH
1308 if (isloggedin() && !isguestuser()) {
1309 $activesection = $DB->get_field("course_display", "display", array("userid"=>$USER->id, "course"=>$course->id));
1310 } else {
1311 $activesection = null;
1312 }
1313
1314 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1315 $namingfunctionexists = (function_exists($namingfunction));
435a512e 1316
0f4ab67d
SH
1317 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1318 if (function_exists($activeparamfunction)) {
1319 $activeparam = $activeparamfunction();
1320 } else {
1321 $activeparam = 'section';
dc076831 1322 }
7487c856
SH
1323 $navigationsections = array();
1324 foreach ($sections as $sectionid=>$section) {
1325 $section = clone($section);
3406acde
SH
1326 if ($course->id == SITEID) {
1327 $this->load_section_activities($coursenode, $section->section, $modinfo);
1328 } else {
1329 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1330 continue;
1331 }
0f4ab67d
SH
1332 if ($namingfunctionexists) {
1333 $sectionname = $namingfunction($course, $section, $sections);
3406acde 1334 } else {
0f4ab67d 1335 $sectionname = get_string('section').' '.$section->section;
3406acde
SH
1336 }
1337 $url = new moodle_url('/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1338 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1339 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1340 $sectionnode->hidden = (!$section->visible);
91eab03d 1341 if ($this->page->context->contextlevel != CONTEXT_MODULE && ($sectionnode->isactive || ($activesection != null && $section->section == $activesection))) {
0f4ab67d 1342 $sectionnode->force_open();
3406acde
SH
1343 $this->load_section_activities($sectionnode, $section->section, $modinfo);
1344 }
1345 $section->sectionnode = $sectionnode;
7487c856 1346 $navigationsections[$sectionid] = $section;
3406acde
SH
1347 }
1348 }
7487c856 1349 return $navigationsections;
3406acde
SH
1350 }
1351 /**
1352 * Loads all of the activities for a section into the navigation structure.
1353 *
1354 * @param navigation_node $sectionnode
1355 * @param int $sectionnumber
1356 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1357 * @return array Array of activity nodes
1358 */
1359 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1360 if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1361 return true;
1362 }
1363
1364 $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page->context);
1365
1366 $activities = array();
1367
1368 foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1369 $cm = $modinfo->cms[$cmid];
1370 if (!$viewhiddenactivities && !$cm->visible) {
1371 continue;
1372 }
1373 if ($cm->icon) {
1374 $icon = new pix_icon($cm->icon, '', $cm->iconcomponent);
1375 } else {
1376 $icon = new pix_icon('icon', '', $cm->modname);
1377 }
1378 $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1379 $activitynode = $sectionnode->add($cm->name, $url, navigation_node::TYPE_ACTIVITY, $cm->name, $cm->id, $icon);
1380 $activitynode->title(get_string('modulename', $cm->modname));
1381 $activitynode->hidden = (!$cm->visible);
1382 if ($this->module_extends_navigation($cm->modname)) {
8f57314b 1383 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
3406acde
SH
1384 }
1385 $activities[$cmid] = $activitynode;
1386 }
1387
1388 return $activities;
1389 }
1390 /**
1391 * Loads the navigation structure for the given activity into the activities node.
1392 *
1393 * This method utilises a callback within the modules lib.php file to load the
1394 * content specific to activity given.
1395 *
1396 * The callback is a method: {modulename}_extend_navigation()
1397 * Examples:
1398 * * {@see forum_extend_navigation()}
1399 * * {@see workshop_extend_navigation()}
1400 *
3406acde
SH
1401 * @param stdClass $cm
1402 * @param stdClass $course
1403 * @param navigation_node $activity
1404 * @return bool
1405 */
1406 protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1407 global $CFG, $DB;
1408
1409 $activity->make_active();
1410 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1411 $function = $cm->modname.'_extend_navigation';
1412
1413 if (file_exists($file)) {
1414 require_once($file);
1415 if (function_exists($function)) {
1416 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1417 $function($activity, $course, $activtyrecord, $cm);
1418 return true;
1419 }
1420 }
1421 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1422 return false;
1423 }
1424 /**
1425 * Loads user specific information into the navigation in the appopriate place.
1426 *
1427 * If no user is provided the current user is assumed.
1428 *
3406acde
SH
1429 * @param stdClass $user
1430 * @return bool
7a7e209d 1431 */
87c215de 1432 protected function load_for_user($user=null, $forceforcontext=false) {
3406acde 1433 global $DB, $CFG, $USER;
4f0c2d00 1434
7a7e209d
SH
1435 $iscurrentuser = false;
1436 if ($user === null) {
1437 // We can't require login here but if the user isn't logged in we don't
1438 // want to show anything
b9d4c7d3 1439 if (!isloggedin() || isguestuser()) {
7a7e209d
SH
1440 return false;
1441 }
1442 $user = $USER;
1443 $iscurrentuser = true;
1444 } else if (!is_object($user)) {
1445 // If the user is not an object then get them from the database
1446 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1447 }
507a7a9a 1448 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
7a7e209d
SH
1449
1450 // Get the course set against the page, by default this will be the site
3406acde
SH
1451 $course = $this->page->course;
1452 $baseargs = array('id'=>$user->id);
87c215de 1453 if ($course->id !== SITEID && (!$iscurrentuser || $forceforcontext)) {
3406acde
SH
1454 if (array_key_exists($course->id, $this->mycourses)) {
1455 $coursenode = $this->mycourses[$course->id]->coursenode;
1456 } else {
1457 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1458 if (!$coursenode) {
1459 $coursenode = $this->load_course($course);
1460 }
1461 }
7a7e209d 1462 $baseargs['course'] = $course->id;
3406acde 1463 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
7a7e209d 1464 $issitecourse = false;
7d2a0492 1465 } else {
7a7e209d 1466 // Load all categories and get the context for the system
507a7a9a 1467 $coursecontext = get_context_instance(CONTEXT_SYSTEM);
7a7e209d
SH
1468 $issitecourse = true;
1469 }
1470
1471 // Create a node to add user information under.
87c215de 1472 if ($iscurrentuser && !$forceforcontext) {
3406acde
SH
1473 // If it's the current user the information will go under the profile root node
1474 $usernode = $this->rootnodes['myprofile'];
7a7e209d
SH
1475 } else {
1476 if (!$issitecourse) {
1477 // Not the current user so add it to the participants node for the current course
3406acde 1478 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
7a7e209d
SH
1479 } else {
1480 // This is the site so add a users node to the root branch
3406acde
SH
1481 $usersnode = $this->rootnodes['users'];
1482 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
7a7e209d
SH
1483 }
1484 // Add a branch for the current user
25aad2c4 1485 $usernode = $usersnode->add(fullname($user, true), null, self::TYPE_USER, null, $user->id);
3406acde
SH
1486 }
1487
1488 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1489 $usernode->force_open();
7a7e209d
SH
1490 }
1491
1492 // If the user is the current user or has permission to view the details of the requested
1493 // user than add a view profile link.
507a7a9a 1494 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
87c215de 1495 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
03d9401e
MD
1496 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1497 } else {
1498 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1499 }
7a7e209d
SH
1500 }
1501
1502 // Add nodes for forum posts and discussions if the user can view either or both
507a7a9a
SH
1503 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1504 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
7a7e209d
SH
1505 if ($canviewposts || $canviewdiscussions) {
1506 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
7a7e209d 1507 if ($canviewposts) {
a6855934 1508 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
7a7e209d
SH
1509 }
1510 if ($canviewdiscussions) {
03d9401e 1511 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions', 'course'=>$course->id))));
7a7e209d
SH
1512 }
1513 }
1514
27bad0a6
SH
1515 // Add blog nodes
1516 if (!empty($CFG->bloglevel)) {
1517 require_once($CFG->dirroot.'/blog/lib.php');
1518 // Get all options for the user
1519 $options = blog_get_options_for_user($user);
1520 if (count($options) > 0) {
1521 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1522 foreach ($options as $option) {
1523 $blogs->add($option['string'], $option['link']);
1524 }
1525 }
1526 }
1527
7a7e209d 1528 // Add a node to view the users notes if permitted
507a7a9a 1529 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
3406acde
SH
1530 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1531 if ($coursecontext->instanceid) {
1532 $url->param('course', $coursecontext->instanceid);
1533 }
1534 $usernode->add(get_string('notes', 'notes'), $url);
7a7e209d
SH
1535 }
1536
1537 // Add a reports tab and then add reports the the user has permission to see.
507a7a9a 1538 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
7a7e209d 1539 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser));
03d9401e
MD
1540 if ($viewreports) {
1541 $reporttab = $usernode->add(get_string('activityreports'));
1542 $reportargs = array('user'=>$user->id);
1543 if (!empty($course->id)) {
1544 $reportargs['id'] = $course->id;
1545 } else {
1546 $reportargs['id'] = SITEID;
1547 }
1548 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1549 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1550 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1551 }
4f0c2d00 1552
03d9401e
MD
1553 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1554 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1555 }
7a7e209d 1556
03d9401e
MD
1557 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1558 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1559 }
7a7e209d 1560
03d9401e
MD
1561 if (!empty($CFG->enablestats)) {
1562 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1563 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1564 }
7a7e209d 1565 }
7a7e209d 1566
03d9401e
MD
1567 $gradeaccess = false;
1568 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1569 //ok - can view all course grades
7a7e209d 1570 $gradeaccess = true;
03d9401e
MD
1571 } else if ($course->showgrades) {
1572 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1573 //ok - can view own grades
1574 $gradeaccess = true;
1575 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1576 // ok - can view grades of this user - parent most probably
1577 $gradeaccess = true;
1578 } else if ($anyreport) {
1579 // ok - can view grades of this user - parent most probably
1580 $gradeaccess = true;
1581 }
1582 }
1583 if ($gradeaccess) {
1584 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
7a7e209d 1585 }
7a7e209d 1586
03d9401e
MD
1587 // Check the number of nodes in the report node... if there are none remove
1588 // the node
1589 if (count($reporttab->children)===0) {
1590 $usernode->remove_child($reporttab);
1591 }
7a7e209d
SH
1592 }
1593
03d9401e 1594
7a7e209d
SH
1595 // If the user is the current user add the repositories for the current user
1596 if ($iscurrentuser) {
1597 require_once($CFG->dirroot . '/repository/lib.php');
507a7a9a 1598 $editabletypes = repository::get_editable_types($usercontext);
7a7e209d 1599 if (!empty($editabletypes)) {
ad70376c 1600 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
7a7e209d
SH
1601 }
1602 }
1603 return true;
1604 }
1605
1606 /**
3406acde 1607 * This method simply checks to see if a given module can extend the navigation.
7d2a0492 1608 *
1609 * @param string $modname
1610 * @return bool
1611 */
1612 protected function module_extends_navigation($modname) {
1613 global $CFG;
1614 if ($this->cache->cached($modname.'_extends_navigation')) {
1615 return $this->cache->{$modname.'_extends_navigation'};
1616 }
1617 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1618 $function = $modname.'_extend_navigation';
1619 if (function_exists($function)) {
1620 $this->cache->{$modname.'_extends_navigation'} = true;
1621 return true;
1622 } else if (file_exists($file)) {
1623 require_once($file);
1624 if (function_exists($function)) {
1625 $this->cache->{$modname.'_extends_navigation'} = true;
1626 return true;
1627 }
1628 }
1629 $this->cache->{$modname.'_extends_navigation'} = false;
1630 return false;
1631 }
1632 /**
3406acde 1633 * Extends the navigation for the given user.
435a512e 1634 *
3406acde 1635 * @param stdClass $user A user from the database
7d2a0492 1636 */
3406acde
SH
1637 public function extend_for_user($user) {
1638 $this->extendforuser[] = $user;
87c215de 1639 $this->page->settingsnav->extend_for_user($user->id);
7d2a0492 1640 }
7d2a0492 1641 /**
3406acde 1642 * Adds the given course to the navigation structure.
7d2a0492 1643 *
3406acde
SH
1644 * @param stdClass $course
1645 * @return navigation_node
7d2a0492 1646 */
4766a50c
SH
1647 public function add_course(stdClass $course, $forcegeneric = false) {
1648 global $CFG;
3406acde
SH
1649 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1650 if ($course->id !== SITEID && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1651 return false;
7d2a0492 1652 }
7d2a0492 1653
4766a50c
SH
1654 $issite = ($course->id == SITEID);
1655 $ismycourse = (array_key_exists($course->id, $this->mycourses) && !$forcegeneric);
1656 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories));
1657
1658 if ($issite) {
3406acde 1659 $parent = $this;
4766a50c
SH
1660 $url = null;
1661 $course->shortname = get_string('sitepages');
1662 } else if ($ismycourse) {
3406acde
SH
1663 $parent = $this->rootnodes['mycourses'];
1664 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7a7e209d 1665 } else {
3406acde 1666 $parent = $this->rootnodes['courses'];
a6855934 1667 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7d2a0492 1668 }
4766a50c
SH
1669
1670 if ($displaycategories) {
1671 // We need to load the category structure for this course
1672 $categoryfound = false;
1673 if (!empty($course->categorypath)) {
1674 $categories = explode('/', trim($course->categorypath, '/'));
1675 $category = $parent;
1676 while ($category && $categoryid = array_shift($categories)) {
1677 $category = $category->get($categoryid, self::TYPE_CATEGORY);
1678 }
1679 if ($category instanceof navigation_node) {
1680 $parent = $category;
1681 $categoryfound = true;
1682 }
1683 if (!$categoryfound && $forcegeneric) {
1684 $this->load_all_categories($course->category);
1685 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1686 $parent = $category;
1687 $categoryfound = true;
1688 }
1689 }
1690 } else if (!empty($course->category)) {
1691 $this->load_all_categories($course->category);
1692 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1693 $parent = $category;
1694 $categoryfound = true;
1695 }
1696 if (!$categoryfound && !$forcegeneric) {
1697 $this->load_all_categories($course->category);
1698 if ($category = $parent->find($course->category, self::TYPE_CATEGORY)) {
1699 $parent = $category;
1700 $categoryfound = true;
1701 }
1702 }
1703 }
1704 }
1705
1706 // We found the course... we can return it now :)
1707 if ($coursenode = $parent->get($course->id, self::TYPE_COURSE)) {
1708 return $coursenode;
1709 }
1710
d59a3f28 1711 $coursenode = $parent->add($course->shortname, $url, self::TYPE_COURSE, $course->shortname, $course->id);
3406acde
SH
1712 $coursenode->nodetype = self::NODETYPE_BRANCH;
1713 $coursenode->hidden = (!$course->visible);
4766a50c 1714 $coursenode->title($course->fullname);
3406acde 1715 $this->addedcourses[$course->id] = &$coursenode;
4766a50c
SH
1716 if ($ismycourse && !empty($CFG->navshowallcourses)) {
1717 // We need to add this course to the general courses node as well as the
1718 // my courses node, rerun the function with the kill param
1719 $genericcourse = $this->add_course($course, true);
1720 if ($genericcourse->isactive) {
1721 $genericcourse->make_inactive();
1722 $genericcourse->collapse = true;
1723 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
1724 $parent = $genericcourse->parent;
1725 while ($parent && $parent->type == self::TYPE_CATEGORY) {
1726 $parent->collapse = true;
1727 $parent = $parent->parent;
1728 }
1729 }
1730 }
1731 }
3406acde 1732 return $coursenode;
7d2a0492 1733 }
1734 /**
3406acde 1735 * Adds essential course nodes to the navigation for the given course.
7d2a0492 1736 *
3406acde 1737 * This method adds nodes such as reports, blogs and participants
7d2a0492 1738 *
3406acde
SH
1739 * @param navigation_node $coursenode
1740 * @param stdClass $course
7d2a0492 1741 * @return bool
1742 */
3406acde
SH
1743 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1744 global $CFG;
7d2a0492 1745
4766a50c 1746 if ($course->id == SITEID) {
3406acde 1747 return $this->add_front_page_course_essentials($coursenode, $course);
7d2a0492 1748 }
7d2a0492 1749
3406acde
SH
1750 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1751 return true;
7d2a0492 1752 }
7d2a0492 1753
3406acde
SH
1754 //Participants
1755 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1756 require_once($CFG->dirroot.'/blog/lib.php');
1757 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1758 $currentgroup = groups_get_course_group($course, true);
1759 if ($course->id == SITEID) {
1760 $filterselect = '';
1761 } else if ($course->id && !$currentgroup) {
1762 $filterselect = $course->id;
1763 } else {
1764 $filterselect = $currentgroup;
1765 }
1766 $filterselect = clean_param($filterselect, PARAM_INT);
1767 if ($CFG->bloglevel >= 3) {
1768 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1769 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1770 }
1771 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1772 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1773 }
533299cb 1774 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
3406acde
SH
1775 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1776 }
1777
1778 // View course reports
1779 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1780 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1781 $coursereports = get_plugin_list('coursereport');
1782 foreach ($coursereports as $report=>$dir) {
1783 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1784 if (file_exists($libfile)) {
1785 require_once($libfile);
1786 $reportfunction = $report.'_report_extend_navigation';
1787 if (function_exists($report.'_report_extend_navigation')) {
1788 $reportfunction($reportnav, $course, $this->page->context);
7d2a0492 1789 }
1790 }
1791 }
1792 }
1793 return true;
1794 }
1795
3406acde
SH
1796 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1797 global $CFG;
7d2a0492 1798
3406acde
SH
1799 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1800 return true;
7a7e209d
SH
1801 }
1802
3406acde
SH
1803 //Participants
1804 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
3406acde
SH
1805 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1806 }
435a512e 1807
3406acde
SH
1808 $currentgroup = groups_get_course_group($course, true);
1809 if ($course->id == SITEID) {
1810 $filterselect = '';
1811 } else if ($course->id && !$currentgroup) {
1812 $filterselect = $course->id;
7d2a0492 1813 } else {
3406acde 1814 $filterselect = $currentgroup;
7d2a0492 1815 }
3406acde 1816 $filterselect = clean_param($filterselect, PARAM_INT);
593270c6
MD
1817
1818 // Blogs
1819 if (has_capability('moodle/blog:view', $this->page->context)) {
1820 require_once($CFG->dirroot.'/blog/lib.php');
1821 if (blog_is_enabled_for_user()) {
1822 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1823 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1824 }
7d2a0492 1825 }
593270c6
MD
1826
1827 // Notes
3406acde
SH
1828 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1829 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1830 }
593270c6
MD
1831
1832 // Tags
1833 if (!empty($CFG->usetags) && isloggedin()) {
3406acde 1834 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
7d2a0492 1835 }
6644741d 1836
6644741d 1837
3406acde
SH
1838 // View course reports
1839 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1840 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1841 $coursereports = get_plugin_list('coursereport');
1842 foreach ($coursereports as $report=>$dir) {
1843 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1844 if (file_exists($libfile)) {
1845 require_once($libfile);
1846 $reportfunction = $report.'_report_extend_navigation';
1847 if (function_exists($report.'_report_extend_navigation')) {
1848 $reportfunction($reportnav, $course, $this->page->context);
1849 }
6644741d 1850 }
6644741d 1851 }
1852 }
3406acde 1853 return true;
6644741d 1854 }
da3ab9c4 1855
3406acde
SH
1856 /**
1857 * Clears the navigation cache
1858 */
1859 public function clear_cache() {
1860 $this->cache->clear();
da3ab9c4 1861 }
88f77c3c
SH
1862
1863 public function set_expansion_limit($type) {
1864 $nodes = $this->find_all_of_type($type);
1865 foreach ($nodes as &$node) {
1866 foreach ($node->children as &$child) {
1867 $child->display = false;
1868 }
1869 }
1870 return true;
1871 }
7d2a0492 1872}
1873
1874/**
1875 * The limited global navigation class used for the AJAX extension of the global
1876 * navigation class.
1877 *
1878 * The primary methods that are used in the global navigation class have been overriden
1879 * to ensure that only the relevant branch is generated at the root of the tree.
1880 * This can be done because AJAX is only used when the backwards structure for the
1881 * requested branch exists.
1882 * This has been done only because it shortens the amounts of information that is generated
1883 * which of course will speed up the response time.. because no one likes laggy AJAX.
1884 *
1885 * @package moodlecore
babb3911 1886 * @subpackage navigation
7d2a0492 1887 * @copyright 2009 Sam Hemelryk
1888 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1889 */
507a7a9a 1890class global_navigation_for_ajax extends global_navigation {
3406acde
SH
1891
1892 /** @var array */
1893 protected $expandable = array();
1894
7d2a0492 1895 /**
3406acde 1896 * Constructs the navigation for use in AJAX request
3406acde 1897 */
4766a50c 1898 public function __construct($page) {
3406acde 1899 global $SITE;
4766a50c 1900 $this->page = $page;
3406acde
SH
1901 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1902 $this->children = new navigation_node_collection();
1903 $this->rootnodes = array();
1aa1e9b5 1904 $this->rootnodes['site'] = $this->add_course($SITE);
3406acde
SH
1905 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1906 }
1907 /**
1908 * Initialise the navigation given the type and id for the branch to expand.
7d2a0492 1909 *
3406acde
SH
1910 * @param int $branchtype One of navigation_node::TYPE_*
1911 * @param int $id
1912 * @return array The expandable nodes
7d2a0492 1913 */
507a7a9a 1914 public function initialise($branchtype, $id) {
4766a50c 1915 global $CFG, $DB, $PAGE;
507a7a9a 1916
7d2a0492 1917 if ($this->initialised || during_initial_install()) {
95b97515 1918 return $this->expandable;
7d2a0492 1919 }
507a7a9a
SH
1920
1921 // Branchtype will be one of navigation_node::TYPE_*
1922 switch ($branchtype) {
4766a50c
SH
1923 case self::TYPE_CATEGORY :
1924 $this->load_all_categories($id);
1925 $limit = 20;
1926 if (!empty($CFG->navcourselimit)) {
1927 $limit = (int)$CFG->navcourselimit;
1928 }
1929 $courses = $DB->get_records('course', array('category' => $id), 'sortorder','*', 0, $limit);
1930 foreach ($courses as $course) {
1931 $this->add_course($course);
1932 }
1933 break;
507a7a9a
SH
1934 case self::TYPE_COURSE :
1935 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
1936 require_course_login($course);
3406acde 1937 $this->page = $PAGE;
87c215de 1938 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
3406acde
SH
1939 $coursenode = $this->add_course($course);
1940 $this->add_course_essentials($coursenode, $course);
1941 if ($this->format_display_course_content($course->format)) {
1942 $this->load_course_sections($course, $coursenode);
1943 }
7d2a0492 1944 break;
507a7a9a 1945 case self::TYPE_SECTION :
3406acde 1946 $sql = 'SELECT c.*, cs.section AS sectionnumber
507a7a9a
SH
1947 FROM {course} c
1948 LEFT JOIN {course_sections} cs ON cs.course = c.id
1949 WHERE cs.id = ?';
1950 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
1951 require_course_login($course);
3406acde 1952 $this->page = $PAGE;
87c215de 1953 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
3406acde
SH
1954 $coursenode = $this->add_course($course);
1955 $this->add_course_essentials($coursenode, $course);
1956 $sections = $this->load_course_sections($course, $coursenode);
1957 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
7d2a0492 1958 break;
507a7a9a
SH
1959 case self::TYPE_ACTIVITY :
1960 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
1961 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1962 require_course_login($course, true, $cm);
3406acde 1963 $this->page = $PAGE;
87c215de 1964 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
3406acde
SH
1965 $coursenode = $this->load_course($course);
1966 $sections = $this->load_course_sections($course, $coursenode);
1967 foreach ($sections as $section) {
1968 if ($section->id == $cm->section) {
1969 $cm->sectionnumber = $section->section;
1970 break;
1971 }
1972 }
1aa1e9b5
SH
1973 if ($course->id == SITEID) {
1974 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
1975 } else {
1976 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1977 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
1978 }
7d2a0492 1979 break;
507a7a9a 1980 default:
3406acde 1981 throw new Exception('Unknown type');
507a7a9a 1982 return $this->expandable;
7d2a0492 1983 }
507a7a9a 1984 $this->find_expandable($this->expandable);
507a7a9a 1985 return $this->expandable;
7d2a0492 1986 }
7d2a0492 1987}
1988
1989/**
1990 * Navbar class
1991 *
1992 * This class is used to manage the navbar, which is initialised from the navigation
1993 * object held by PAGE
1994 *
1995 * @package moodlecore
babb3911 1996 * @subpackage navigation
7d2a0492 1997 * @copyright 2009 Sam Hemelryk
1998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1999 */
2000class navbar extends navigation_node {
2001 /** @var bool */
2002 protected $initialised = false;
2003 /** @var mixed */
2004 protected $keys = array();
2005 /** @var null|string */
2006 protected $content = null;
3406acde 2007 /** @var moodle_page object */
7d2a0492 2008 protected $page;
2009 /** @var bool */
31759089 2010 protected $ignoreactive = false;
2011 /** @var bool */
7d2a0492 2012 protected $duringinstall = false;
7a7e209d
SH
2013 /** @var bool */
2014 protected $hasitems = false;
3406acde
SH
2015 /** @var array */
2016 protected $items;
2017 /** @var array */
2018 public $children = array();
4d5059d4
SH
2019 /** @var bool */
2020 public $includesettingsbase = false;
7d2a0492 2021 /**
2022 * The almighty constructor
3406acde
SH
2023 *
2024 * @param moodle_page $page
7d2a0492 2025 */
3406acde 2026 public function __construct(moodle_page $page) {
507a7a9a 2027 global $CFG;
7d2a0492 2028 if (during_initial_install()) {
2029 $this->duringinstall = true;
2030 return false;
2031 }
2032 $this->page = $page;
2033 $this->text = get_string('home');
2034 $this->shorttext = get_string('home');
2035 $this->action = new moodle_url($CFG->wwwroot);
2036 $this->nodetype = self::NODETYPE_BRANCH;
2037 $this->type = self::TYPE_SYSTEM;
2038 }
2039
2040 /**
2041 * Quick check to see if the navbar will have items in.
2042 *
2043 * @return bool Returns true if the navbar will have items, false otherwise
2044 */
2045 public function has_items() {
2046 if ($this->duringinstall) {
2047 return false;
7a7e209d
SH
2048 } else if ($this->hasitems !== false) {
2049 return true;
7d2a0492 2050 }
3406acde 2051 $this->page->navigation->initialise($this->page);
bf6c37c7 2052
7a7e209d 2053 $activenodefound = ($this->page->navigation->contains_active_node() ||
3406acde 2054 $this->page->settingsnav->contains_active_node());
bf6c37c7 2055
3406acde 2056 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
7a7e209d 2057 $this->hasitems = $outcome;
bf6c37c7 2058 return $outcome;
31759089 2059 }
2060
3406acde
SH
2061 /**
2062 * Turn on/off ignore active
2063 *
2064 * @param bool $setting
2065 */
31759089 2066 public function ignore_active($setting=true) {
2067 $this->ignoreactive = ($setting);
7d2a0492 2068 }
3406acde
SH
2069 public function get($key, $type = null) {
2070 foreach ($this->children as &$child) {
2071 if ($child->key === $key && ($type == null || $type == $child->type)) {
2072 return $child;
2073 }
2074 }
2075 return false;
2076 }
7d2a0492 2077 /**
3406acde 2078 * Returns an array of navigation_node's that make up the navbar.
435a512e 2079 *
3406acde 2080 * @return array
7d2a0492 2081 */
3406acde
SH
2082 public function get_items() {
2083 $items = array();
7d2a0492 2084 // Make sure that navigation is initialised
7a7e209d 2085 if (!$this->has_items()) {
3406acde 2086 return $items;
7a7e209d 2087 }
3406acde
SH
2088 if ($this->items !== null) {
2089 return $this->items;
7d2a0492 2090 }
2091
3406acde
SH
2092 if (count($this->children) > 0) {
2093 // Add the custom children
2094 $items = array_reverse($this->children);
2095 }
117bd748 2096
3406acde
SH
2097 $navigationactivenode = $this->page->navigation->find_active_node();
2098 $settingsactivenode = $this->page->settingsnav->find_active_node();
0b29477b 2099
7d2a0492 2100 // Check if navigation contains the active node
0b29477b 2101 if (!$this->ignoreactive) {
435a512e 2102
3406acde 2103 if ($navigationactivenode && $settingsactivenode) {
0b29477b 2104 // Parse a combined navigation tree
3406acde
SH
2105 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2106 if (!$settingsactivenode->mainnavonly) {
2107 $items[] = $settingsactivenode;
2108 }
2109 $settingsactivenode = $settingsactivenode->parent;
2110 }
4d5059d4
SH
2111 if (!$this->includesettingsbase) {
2112 // Removes the first node from the settings (root node) from the list
2113 array_pop($items);
2114 }
3406acde
SH
2115 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2116 if (!$navigationactivenode->mainnavonly) {
2117 $items[] = $navigationactivenode;
2118 }
2119 $navigationactivenode = $navigationactivenode->parent;
0b29477b 2120 }
3406acde 2121 } else if ($navigationactivenode) {
0b29477b 2122 // Parse the navigation tree to get the active node
3406acde
SH
2123 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2124 if (!$navigationactivenode->mainnavonly) {
2125 $items[] = $navigationactivenode;
2126 }
2127 $navigationactivenode = $navigationactivenode->parent;
2128 }
2129 } else if ($settingsactivenode) {
0b29477b 2130 // Parse the settings navigation to get the active node
3406acde
SH
2131 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2132 if (!$settingsactivenode->mainnavonly) {
2133 $items[] = $settingsactivenode;
2134 }
2135 $settingsactivenode = $settingsactivenode->parent;
2136 }
0b29477b 2137 }
7d2a0492 2138 }
a3bbac8b 2139
3406acde
SH
2140 $items[] = new navigation_node(array(
2141 'text'=>$this->page->navigation->text,
2142 'shorttext'=>$this->page->navigation->shorttext,
2143 'key'=>$this->page->navigation->key,
2144 'action'=>$this->page->navigation->action
2145 ));
a3bbac8b 2146
3406acde
SH
2147 $this->items = array_reverse($items);
2148 return $this->items;
7d2a0492 2149 }
507a7a9a 2150
7d2a0492 2151 /**
3406acde 2152 * Add a new navigation_node to the navbar, overrides parent::add
7d2a0492 2153 *
2154 * This function overrides {@link navigation_node::add()} so that we can change
2155 * the way nodes get added to allow us to simply call add and have the node added to the
2156 * end of the navbar
2157 *
2158 * @param string $text
7d2a0492 2159 * @param string|moodle_url $action
d972bad1 2160 * @param int $type
2161 * @param string|int $key
2162 * @param string $shorttext
7d2a0492 2163 * @param string $icon
3406acde 2164 * @return navigation_node
7d2a0492 2165 */
f9fc1461 2166 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3406acde
SH
2167 if ($this->content !== null) {
2168 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2169 }
435a512e 2170
3406acde
SH
2171 // Properties array used when creating the new navigation node
2172 $itemarray = array(
2173 'text' => $text,
2174 'type' => $type
2175 );
2176 // Set the action if one was provided
2177 if ($action!==null) {
2178 $itemarray['action'] = $action;
2179 }
2180 // Set the shorttext if one was provided
2181 if ($shorttext!==null) {
2182 $itemarray['shorttext'] = $shorttext;
2183 }
2184 // Set the icon if one was provided
2185 if ($icon!==null) {
2186 $itemarray['icon'] = $icon;
7d2a0492 2187 }
3406acde
SH
2188 // Default the key to the number of children if not provided
2189 if ($key === null) {
2190 $key = count($this->children);
7d2a0492 2191 }
3406acde
SH
2192 // Set the key
2193 $itemarray['key'] = $key;
2194 // Set the parent to this node
2195 $itemarray['parent'] = $this;
2196 // Add the child using the navigation_node_collections add method
2197 $this->children[] = new navigation_node($itemarray);
2198 return $this;
7d2a0492 2199 }
2200}
2201
2202/**
2203 * Class used to manage the settings option for the current page
2204 *
2205 * This class is used to manage the settings options in a tree format (recursively)
2206 * and was created initially for use with the settings blocks.
2207 *
2208 * @package moodlecore
babb3911 2209 * @subpackage navigation
7d2a0492 2210 * @copyright 2009 Sam Hemelryk
2211 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2212 */
2213class settings_navigation extends navigation_node {
2214 /** @var stdClass */
2215 protected $context;
3406acde 2216 /** @var navigation_cache */
7d2a0492 2217 protected $cache;
3406acde 2218 /** @var moodle_page */
7d2a0492 2219 protected $page;
3406acde 2220 /** @var string */
d9d2817a 2221 protected $adminsection;
4766a50c
SH
2222 /** @var bool */
2223 protected $initialised = false;
87c215de
SH
2224 /** @var array */
2225 protected $userstoextendfor = array();
4766a50c 2226
7d2a0492 2227 /**
2228 * Sets up the object with basic settings and preparse it for use
435a512e 2229 *
3406acde 2230 * @param moodle_page $page
7d2a0492 2231 */
507a7a9a 2232 public function __construct(moodle_page &$page) {
7d2a0492 2233 if (during_initial_install()) {
2234 return false;
2235 }
7d2a0492 2236 $this->page = $page;
2237 // Initialise the main navigation. It is most important that this is done
2238 // before we try anything
2239 $this->page->navigation->initialise();
2240 // Initialise the navigation cache
f5b5a822 2241 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3406acde 2242 $this->children = new navigation_node_collection();
7d2a0492 2243 }
2244 /**
2245 * Initialise the settings navigation based on the current context
2246 *
2247 * This function initialises the settings navigation tree for a given context
2248 * by calling supporting functions to generate major parts of the tree.
3406acde 2249 *
7d2a0492 2250 */
2251 public function initialise() {
0b29477b 2252 global $DB;
4f0c2d00 2253
7d2a0492 2254 if (during_initial_install()) {
2255 return false;
4766a50c
SH
2256 } else if ($this->initialised) {
2257 return true;
7d2a0492 2258 }
2259 $this->id = 'settingsnav';
2260 $this->context = $this->page->context;
0b29477b
SH
2261
2262 $context = $this->context;
2263 if ($context->contextlevel == CONTEXT_BLOCK) {
2264 $this->load_block_settings();
2265 $context = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid));
2266 }
2267
2268 switch ($context->contextlevel) {
7d2a0492 2269 case CONTEXT_SYSTEM:
0b29477b
SH
2270 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2271 $this->load_front_page_settings(($context->id == $this->context->id));
2272 }
7d2a0492 2273 break;
2274 case CONTEXT_COURSECAT:
0b29477b 2275 $this->load_category_settings();
7d2a0492 2276 break;
2277 case CONTEXT_COURSE:
0b29477b
SH
2278 if ($this->page->course->id != SITEID) {
2279 $this->load_course_settings(($context->id == $this->context->id));
7d2a0492 2280 } else {
0b29477b 2281 $this->load_front_page_settings(($context->id == $this->context->id));
7d2a0492 2282 }
2283 break;
2284 case CONTEXT_MODULE:
0b29477b
SH
2285 $this->load_module_settings();
2286 $this->load_course_settings();
7d2a0492 2287 break;
2288 case CONTEXT_USER:
0b29477b
SH
2289 if ($this->page->course->id != SITEID) {
2290 $this->load_course_settings();
7d2a0492 2291 }
7d2a0492 2292 break;
2293 }
2294
3406acde
SH
2295 $settings = $this->load_user_settings($this->page->course->id);
2296 $admin = $this->load_administration_settings();
0b29477b 2297
3406acde
SH
2298 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2299 $admin->force_open();
2300 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2301 $settings->force_open();
0b29477b
SH
2302 }
2303
7d2a0492 2304 // Check if the user is currently logged in as another user
2305 if (session_is_loggedinas()) {
2306 // Get the actual user, we need this so we can display an informative return link
2307 $realuser = session_get_realuser();
2308 // Add the informative return to original user link
a6855934 2309 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
f9fc1461 2310 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
7d2a0492 2311 }
2312
2313 // Make sure the first child doesnt have proceed with hr set to true
7d2a0492 2314
3406acde
SH
2315 foreach ($this->children as $key=>$node) {
2316 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2317 $node->remove();
2318 }
2319 }
4766a50c 2320 $this->initialised = true;
7d2a0492 2321 }
2322 /**
2323 * Override the parent function so that we can add preceeding hr's and set a
2324 * root node class against all first level element
2325 *
2326 * It does this by first calling the parent's add method {@link navigation_node::add()}
117bd748 2327 * and then proceeds to use the key to set class and hr
7d2a0492 2328 *
2329 * @param string $text
91152a35 2330 * @param sting|moodle_url $url
7d2a0492 2331 * @param string $shorttext
2332 * @param string|int $key
2333 * @param int $type
7d2a0492 2334 * @param string $icon
3406acde 2335 * @return navigation_node
7d2a0492 2336 */
f9fc1461 2337 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3406acde
SH
2338 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2339 $node->add_class('root_node');
2340 return $node;
7d2a0492 2341 }
a6e34701 2342
2343 /**
2344 * This function allows the user to add something to the start of the settings
2345 * navigation, which means it will be at the top of the settings navigation block
2346 *
2347 * @param string $text
2348 * @param sting|moodle_url $url
2349 * @param string $shorttext
2350 * @param string|int $key
2351 * @param int $type
2352 * @param string $icon
3406acde 2353 * @return navigation_node
a6e34701 2354 */
f9fc1461 2355 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
a6e34701 2356 $children = $this->children;
b499db57
SH
2357 $childrenclass = get_class($children);
2358 $this->children = new $childrenclass;
3406acde
SH
2359 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2360 foreach ($children as $child) {
2361 $this->children->add($child);
a6e34701 2362 }
3406acde 2363 return $node;
a6e34701 2364 }
7d2a0492 2365 /**
2366 * Load the site administration tree
2367 *
2368 * This function loads the site administration tree by using the lib/adminlib library functions
2369 *
3406acde 2370 * @param navigation_node $referencebranch A reference to a branch in the settings
7d2a0492 2371 * navigation tree
3406acde 2372 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
7d2a0492 2373 * tree and start at the beginning
2374 * @return mixed A key to access the admin tree by
2375 */
0e3eee62 2376 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
507a7a9a 2377 global $CFG;
0e3eee62 2378
7d2a0492 2379 // Check if we are just starting to generate this navigation.
2380 if ($referencebranch === null) {
0e3eee62 2381
d9d2817a 2382 // Require the admin lib then get an admin structure
0e3eee62
SH
2383 if (!function_exists('admin_get_root')) {
2384 require_once($CFG->dirroot.'/lib/adminlib.php');
2385 }
2386 $adminroot = admin_get_root(false, false);
d9d2817a
SH
2387 // This is the active section identifier
2388 $this->adminsection = $this->page->url->param('section');
4f0c2d00 2389
d9d2817a
SH
2390 // Disable the navigation from automatically finding the active node
2391 navigation_node::$autofindactive = false;
3406acde 2392 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
0e3eee62
SH
2393 foreach ($adminroot->children as $adminbranch) {
2394 $this->load_administration_settings($referencebranch, $adminbranch);
2395 }
d9d2817a 2396 navigation_node::$autofindactive = true;
0e3eee62 2397
d9d2817a 2398 // Use the admin structure to locate the active page
3406acde
SH
2399 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2400 $currentnode = $this;
2401 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2402 $currentnode = $currentnode->get($pathkey);
2403 }
2404 if ($currentnode) {
2405 $currentnode->make_active();
7d2a0492 2406 }
25b550d2
SH
2407 } else {
2408 $this->scan_for_active_node($referencebranch);
0e3eee62 2409 }
3406acde 2410 return $referencebranch;
8140c440 2411 } else if ($adminbranch->check_access()) {
7d2a0492 2412 // We have a reference branch that we can access and is not hidden `hurrah`
2413 // Now we need to display it and any children it may have
2414 $url = null;
2415 $icon = null;
2416 if ($adminbranch instanceof admin_settingpage) {
a6855934 2417 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
7d2a0492 2418 } else if ($adminbranch instanceof admin_externalpage) {
2419 $url = $adminbranch->url;
2420 }
2421
2422 // Add the branch
3406acde 2423 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
8140c440 2424
2425 if ($adminbranch->is_hidden()) {
d9d2817a
SH
2426 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2427 $reference->add_class('hidden');
2428 } else {
2429 $reference->display = false;
2430 }
8140c440 2431 }
2432
7d2a0492 2433 // Check if we are generating the admin notifications and whether notificiations exist
2434 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2435 $reference->add_class('criticalnotification');
2436 }
2437 // Check if this branch has children
2438 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2439 foreach ($adminbranch->children as $branch) {
2440 // Generate the child branches as well now using this branch as the reference
459e384e 2441 $this->load_administration_settings($reference, $branch);
7d2a0492 2442 }
2443 } else {
f9fc1461 2444 $reference->icon = new pix_icon('i/settings', '');
7d2a0492 2445 }
2446 }
2447 }
2448
25b550d2
SH
2449 /**
2450 * This function recursivily scans nodes until it finds the active node or there
2451 * are no more nodes.
2452 * @param navigation_node $node
2453 */
2454 protected function scan_for_active_node(navigation_node $node) {
2455 if (!$node->check_if_active() && $node->children->count()>0) {
2456 foreach ($node->children as &$child) {
2457 $this->scan_for_active_node($child);
2458 }
2459 }
2460 }
2461
3406acde
SH
2462 /**
2463 * Gets a navigation node given an array of keys that represent the path to
2464 * the desired node.
2465 *
2466 * @param array $path
2467 * @return navigation_node|false
2468 */
2469 protected function get_by_path(array $path) {
2470 $node = $this->get(array_shift($path));
2471 foreach ($path as $key) {
2472 $node->get($key);
2473 }
2474 return $node;
2475 }
2476
7d2a0492 2477 /**
2478 * Generate the list of modules for the given course.
2479 *
2480 * The array of resources and activities that can be added to a course is then
2481 * stored in the cache so that we can access it for anywhere.
2482 * It saves us generating it all the time
2483 *
2484 * <code php>
2485 * // To get resources:
2486 * $this->cache->{'course'.$courseid.'resources'}
2487 * // To get activities:
2488 * $this->cache->{'course'.$courseid.'activities'}
2489 * </code>
2490 *
2491 * @param stdClass $course The course to get modules for
2492 */
2493 protected function get_course_modules($course) {
2494 global $CFG;
2495 $mods = $modnames = $modnamesplural = $modnamesused = array();
2496 // This function is included when we include course/lib.php at the top
2497 // of this file
2498 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2499 $resources = array();
2500 $activities = array();
2501 foreach($modnames as $modname=>$modnamestr) {
2502 if (!course_allowed_module($course, $modname)) {
2503 continue;
2504 }
2505
2506 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2507 if (!file_exists($libfile)) {
2508 continue;
2509 }
2510 include_once($libfile);
2511 $gettypesfunc = $modname.'_get_types';
2512 if (function_exists($gettypesfunc)) {
2513 $types = $gettypesfunc();
2514 foreach($types as $type) {
2515 if (!isset($type->modclass) || !isset($type->typestr)) {
2516 debugging('Incorrect activity type in '.$modname);
2517 continue;
2518 }
2519 if ($type->modclass == MOD_CLASS_RESOURCE) {
2520 $resources[html_entity_decode($type->type)] = $type->typestr;
2521 } else {
2522 $activities[html_entity_decode($type->type)] = $type->typestr;
2523 }
2524 }
2525 } else {
2526 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2527 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2528 $resources[$modname] = $modnamestr;
2529 } else {
2530 // all other archetypes are considered activity
2531 $activities[$modname] = $modnamestr;
2532 }
2533 }
2534 }
2535 $this->cache->{'course'.$course->id.'resources'} = $resources;
2536 $this->cache->{'course'.$course->id.'activities'} = $activities;
2537 }
2538
2539 /**
2540 * This function loads the course settings that are available for the user
2541 *
0b29477b 2542 * @param bool $forceopen If set to true the course node will be forced open
3406acde 2543 * @return navigation_node|false
7d2a0492 2544 */
0b29477b 2545 protected function load_course_settings($forceopen = false) {
4f0c2d00 2546 global $CFG, $USER, $SESSION, $OUTPUT;
7d2a0492 2547
2548 $course = $this->page->course;
4f0c2d00 2549 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
7d2a0492 2550 if (!$this->cache->cached('canviewcourse'.$course->id)) {
4f0c2d00 2551 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
7d2a0492 2552 }
2553 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2554 return false;
2555 }
2556
3406acde
SH
2557 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2558 if ($forceopen) {
2559 $coursenode->force_open();
2560 }
117bd748 2561
4f0c2d00 2562 if (has_capability('moodle/course:update', $coursecontext)) {
7d2a0492 2563 // Add the turn on/off settings
a6855934 2564 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
7d2a0492 2565 if ($this->page->user_is_editing()) {
2566 $url->param('edit', 'off');
2567 $editstring = get_string('turneditingoff');
2568 } else {
2569 $url->param('edit', 'on');
2570 $editstring = get_string('turneditingon');
2571 }
f9fc1461 2572 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
7d2a0492 2573
7d2a0492 2574 if ($this->page->user_is_editing()) {
2575 // Add `add` resources|activities branches
2576 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2577 if (file_exists($structurefile)) {
2578 require_once($structurefile);
2579 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2580 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2581 } else {
2582 $formatstring = get_string('topic');
2583 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2584 }
7487c856
SH
2585
2586 $sections = get_all_sections($course->id);
117bd748 2587
3406acde
SH
2588 $addresource = $this->add(get_string('addresource'));
2589 $addactivity = $this->add(get_string('addactivity'));
7d2a0492 2590 if ($formatidentifier!==0) {
3406acde
SH
2591 $addresource->force_open();
2592 $addactivity->force_open();
7d2a0492 2593 }
2594
2595 if (!$this->cache->cached('course'.$course->id.'resources')) {
459e384e 2596 $this->get_course_modules($course);
7d2a0492 2597 }
2598 $resources = $this->cache->{'course'.$course->id.'resources'};
2599 $activities = $this->cache->{'course'.$course->id.'activities'};
117bd748 2600
9cf45d02
SH
2601 $textlib = textlib_get_instance();
2602
7d2a0492 2603 foreach ($sections as $section) {
2604 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2605 continue;
2606 }
a6855934 2607 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
7d2a0492 2608 if ($section->section == 0) {
d972bad1 2609 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2610 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
7d2a0492 2611 } else {
d972bad1 2612 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2613 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
7d2a0492 2614 }
2615 foreach ($resources as $value=>$resource) {
a6855934 2616 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2617 $pos = strpos($value, '&type=');
2618 if ($pos!==false) {
9cf45d02
SH
2619 $url->param('add', $textlib->substr($value, 0,$pos));
2620 $url->param('type', $textlib->substr($value, $pos+6));
7d2a0492 2621 } else {
2622 $url->param('add', $value);
2623 }
3406acde 2624 $sectionresources->add($resource, $url, self::TYPE_SETTING);
7d2a0492 2625 }
2626 $subbranch = false;
2627 foreach ($activities as $activityname=>$activity) {
2628 if ($activity==='--') {
2629 $subbranch = false;
2630 continue;
2631 }
2632 if (strpos($activity, '--')===0) {
aac0dc92 2633 $subbranch = $sectionactivities->add(trim($activity, '-'));
7d2a0492 2634 continue;
2635 }
a6855934 2636 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2637 $pos = strpos($activityname, '&type=');
2638 if ($pos!==false) {
9cf45d02
SH
2639 $url->param('add', $textlib->substr($activityname, 0,$pos));
2640 $url->param('type', $textlib->substr($activityname, $pos+6));
7d2a0492 2641 } else {
2642 $url->param('add', $activityname);
2643 }
2644 if ($subbranch !== false) {
3406acde 2645 $subbranch->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2646 } else {
aac0dc92 2647 $sectionactivities->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2648 }
2649 }
2650 }
2651 }
2652
2653 // Add the course settings link
a6855934 2654 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
f9fc1461 2655 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2be4d090
MD
2656
2657 // Add the course completion settings link
2658 if ($CFG->enablecompletion && $course->enablecompletion) {
2659 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2660 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2661 }
7d2a0492 2662 }
117bd748 2663
4f0c2d00 2664 if (has_capability('moodle/role:assign', $coursecontext)) {
0b29477b 2665 // Add assign or override roles if allowed
4f0c2d00 2666 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
f9fc1461 2667 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
0b29477b 2668 // Override roles
4f0c2d00
PS
2669 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2670 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
8a556fdd 2671 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/permissions', ''));
0b29477b
SH
2672 }
2673 // Check role permissions
4f0c2d00
PS
2674 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2675 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
8a556fdd 2676 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/checkpermissions', ''));
0b29477b
SH
2677 }
2678 // Manage filters
4f0c2d00
PS
2679 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2680 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2681 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2682 }
7d2a0492 2683 }
2684
2685 // Add view grade report is permitted
2686 $reportavailable = false;
4f0c2d00 2687 if (has_capability('moodle/grade:viewall', $coursecontext)) {
7d2a0492 2688 $reportavailable = true;
2689 } else if (!empty($course->showgrades)) {
2690 $reports = get_plugin_list('gradereport');
2691 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2692 arsort($reports); // user is last, we want to test it first
2693 foreach ($reports as $plugin => $plugindir) {
4f0c2d00 2694 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
7d2a0492 2695 //stop when the first visible plugin is found
2696 $reportavailable = true;
2697 break;
2698 }
2699 }
2700 }
2701 }
2702 if ($reportavailable) {
a6855934 2703 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
b499db57 2704 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
7d2a0492 2705 }
2706
2707 // Add outcome if permitted
4f0c2d00 2708 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
a6855934 2709 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
d6d07a68 2710 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
7d2a0492 2711 }
2712
2713 // Add meta course links
2714 if ($course->metacourse) {
4f0c2d00 2715 if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
a6855934 2716 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
f9fc1461 2717 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
4f0c2d00 2718 } else if (has_capability('moodle/role:assign', $coursecontext)) {
3406acde
SH
2719 $roleassign = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2720 $roleassign->hidden = true;
7d2a0492 2721 }
2722 }
2723
2724 // Manage groups in this course
4f0c2d00 2725 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
a6855934 2726 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
d6d07a68 2727 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
7d2a0492 2728 }
2729
7d2a0492 2730 // Backup this course
4f0c2d00 2731 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
a6855934 2732 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
d6d07a68 2733 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
7d2a0492 2734 }
2735
2736 // Restore to this course
4f0c2d00 2737 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
a6855934 2738 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
530fa981 2739 $url = null; // Disabled until restore is implemented. MDL-21432
d6d07a68 2740 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
7d2a0492 2741 }
2742
2743 // Import data from other courses
4f0c2d00 2744 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
a6855934 2745 $url = new moodle_url('/course/import.php', array('id'=>$course->id));
530fa981 2746 $url = null; // Disabled until restore is implemented. MDL-21432
d6d07a68 2747 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
7d2a0492 2748 }
2749
07ab0c80 2750 // Publish course on a hub
2751 if (has_capability('moodle/course:publish', $coursecontext)) {
2752 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
d6d07a68 2753 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
07ab0c80 2754 }
2755
7d2a0492 2756 // Reset this course
4f0c2d00 2757 if (has_capability('moodle/course:reset', $coursecontext)) {
a6855934 2758 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
f9fc1461 2759 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
7d2a0492 2760 }
7d2a0492 2761
56ed242b
SH
2762 // Questions
2763 require_once($CFG->dirroot.'/question/editlib.php');
2764 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
7d2a0492 2765
2766 // Repository Instances
2767 require_once($CFG->dirroot.'/repository/lib.php');
76046fa8
SH
2768 $editabletypes = repository::get_editable_types($coursecontext);
2769 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2770 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id));
f9fc1461 2771 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
7d2a0492 2772 }
2773
2774 // Manage files
bf34822b 2775 if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
76046fa8
SH
2776 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id, 'itemid'=>0, 'filearea'=>'course_content'));
2777 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
7d2a0492 2778 }
2779
2780 // Authorize hooks
2781 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2782 require_once($CFG->dirroot.'/enrol/authorize/const.php');
a6855934 2783 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
f9fc1461 2784 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2785 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2786 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2787 if ($cnt) {
a6855934 2788 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
f9fc1461 2789 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2790 }
2791 }
2792 }
2793
2794 // Unenrol link
4f0c2d00
PS
2795 if (empty($course->metacourse) && ($course->id!==SITEID)) {
2796 if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2797 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
2798 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2799 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2800 }
2801
2802 } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2803 // inspector, manager, etc. - do not show anything
2804 } else {
2805 // access because otherwise they would not get into this course at all
2806 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2807 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
7d2a0492 2808 }
2809 }
2810
7d2a0492 2811 // Switch roles
2812 $roles = array();
2813 $assumedrole = $this->in_alternative_role();
2814 if ($assumedrole!==false) {
2815 $roles[0] = get_string('switchrolereturn');
2816 }
76046fa8
SH
2817 if (has_capability('moodle/role:switchroles', $coursecontext)) {
2818 $availableroles = get_switchable_roles($coursecontext);
7d2a0492 2819 if (is_array($availableroles)) {
2820 foreach ($availableroles as $key=>$role) {
2821 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2822 continue;
2823 }
2824 $roles[$key] = $role;
2825 }
2826 }
2827 }
2828 if (is_array($roles) && count($roles)>0) {
3406acde 2829 $switchroles = $this->add(get_string('switchroleto'));
7d2a0492 2830 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3406acde 2831 $switchroles->force_open();
7d2a0492 2832 }
2833 $returnurl = $this->page->url;
2834 $returnurl->param('sesskey', sesskey());
2835 $SESSION->returnurl = serialize($returnurl);
2836 foreach ($roles as $key=>$name) {
a6855934 2837 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
3406acde 2838 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
7d2a0492 2839 }
2840 }
2841 // Return we are done
3406acde 2842 return $coursenode;
7d2a0492 2843 }
2844
2845 /**
2846 * This function calls the module function to inject module settings into the
2847 * settings navigation tree.
2848 *
2849 * This only gets called if there is a corrosponding function in the modules
2850 * lib file.
2851 *
2852 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2853 *
3406acde 2854 * @return navigation_node|false
7d2a0492 2855 */
2856 protected function load_module_settings() {
507a7a9a 2857 global $CFG;
4dd5bce8 2858
2859 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
0b29477b 2860 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
507a7a9a 2861 $this->page->set_cm($cm, $this->page->course);
4dd5bce8 2862 }
2863
3406acde
SH
2864 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2865 $modulenode->force_open();
4f0c2d00 2866
0b29477b
SH
2867 // Settings for the module
2868 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2869 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2870 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2871 }
2872 // Assign local roles
2873 if (count(get_assignable_roles($this->page->cm->context))>0) {
2874 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2875 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2876 }
2877 // Override roles
2878 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2879 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2880 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2881 }
2882 // Check role permissions
2883 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2884 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2885 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2886 }
2887 // Manage filters
2888 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2889 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2890 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2891 }
4f0c2d00 2892
18ddfc1e
SH
2893 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $this->page->cm->course))) {
2894 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page->cm->course,'modid'=>$this->page->cm->id));
2895 $modulenode->add(get_string('logs'), $url, self::TYPE_SETTING);
2896 }
2897
59c7680f
SH
2898 // Add a backup link
2899 $featuresfunc = $this->page->activityname.'_supports';
2900 if ($featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
2901 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
2902 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
2903 }
2904
507a7a9a
SH
2905 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2906 $function = $this->page->activityname.'_extend_settings_navigation';
117bd748 2907
7d2a0492 2908 if (file_exists($file)) {
2909 require_once($file);
2910 }
2911 if (!function_exists($function)) {
3406acde 2912 return $modulenode;
7d2a0492 2913 }
0b29477b
SH
2914
2915 $function($this, $modulenode);
2916
2917 // Remove the module node if there are no children
2918 if (empty($modulenode->children)) {
3406acde 2919 $modulenode->remove();
0b29477b
SH
2920 }
2921
3406acde 2922 return $modulenode;
7d2a0492 2923 }
2924
2925 /**
2926 * Loads the user settings block of the settings nav
117bd748 2927 *
7d2a0492 2928 * This function is simply works out the userid and whether we need to load
117bd748 2929 * just the current users profile settings, or the current user and the user the
7d2a0492 2930 * current user is viewing.
117bd748 2931 *
7d2a0492 2932 * This function has some very ugly code to work out the user, if anyone has
2933 * any bright ideas please feel free to intervene.
2934 *
2935 * @param int $courseid The course id of the current course
3406acde 2936 * @return navigation_node|false
7d2a0492 2937 */
2938 protected function load_user_settings($courseid=SITEID) {
0b29477b 2939 global $USER, $FULLME, $CFG;
7d2a0492 2940
2941 if (isguestuser() || !isloggedin()) {
2942 return false;
2943 }
435a512e 2944
87c215de
SH
2945 if (count($this->userstoextendfor) > 0) {
2946 $usernode = null;
2947 foreach ($this->userstoextendfor as $userid) {
2948 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
2949 if (is_null($usernode)) {
2950 $usernode = $node;
2951 }
2952 }
0b29477b 2953 $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2954 } else {
3406acde 2955 $usernode = $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2956 }
3406acde 2957 return $usernode;
7d2a0492 2958 }
2959
87c215de
SH
2960 public function extend_for_user($userid) {
2961 global $CFG;
2962
2963 if (!in_array($userid, $this->userstoextendfor)) {
2964 $this->userstoextendfor[] = $userid;
2965 if ($this->initialised) {
2966 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
2967 $children = array();
2968 foreach ($this->children as $child) {
2969 $children[] = $child;
2970 }
2971 array_unshift($children, array_pop($children));
2972 $this->children = new navigation_node_collection();
2973 foreach ($children as $child) {
2974 $this->children->add($child);
2975 }
2976 }
2977 }
2978 }
2979
7d2a0492 2980 /**
2981 * This function gets called by {@link load_user_settings()} and actually works out
2982 * what can be shown/done
2983 *
2984 * @param int $courseid The current course' id
2985 * @param int $userid The user id to load for
2986 * @param string $gstitle The string to pass to get_string for the branch title
3406acde 2987 * @return navigation_node|false
7d2a0492 2988 */
2989 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
507a7a9a 2990 global $DB, $CFG, $USER, $SITE;
7d2a0492 2991
507a7a9a
SH
2992 if ($courseid != SITEID) {
2993 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
2994 $course = $this->page->course;
2995 } else {
2996 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
2997 }
2998 } else {
2999 $course = $SITE;
7d2a0492 3000 }
3001
3002 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
507a7a9a 3003 $systemcontext = get_system_context();
7d2a0492 3004 $currentuser = ($USER->id == $userid);
4f0c2d00 3005
7d2a0492 3006 if ($currentuser) {
3007 $user = $USER;
3008 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3009 } else {
7a7e209d 3010 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
7d2a0492 3011 return false;
3012 }
3013 // Check that the user can view the profile
3014 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3015 if ($course->id==SITEID) {
4f0c2d00 3016 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
7d2a0492 3017 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3018 return false;
3019 }
3020 } else {
4f0c2d00 3021 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
7d2a0492 3022 return false;
3023 }
3024 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3025 // If groups are in use, make sure we can see that group
3026 return false;
3027 }
3028 }
3029 }
3030
3031 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3032
3033 // Add a user setting branch
25b550d2 3034 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $gstitle);
7d2a0492 3035 $usersetting->id = 'usersettings';
3036
7d2a0492 3037 // Check if the user has been deleted
3038 if ($user->deleted) {
3039 if (!has_capability('moodle/user:update', $coursecontext)) {
3040 // We can't edit the user so just show the user deleted message
d972bad1 3041 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
7d2a0492 3042 } else {
3043 // We can edit the user so show the user deleted message and link it to the profile
03d9401e
MD
3044 if ($course->id == SITEID) {
3045 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3046 } else {
3047 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3048 }
d972bad1 3049 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
7d2a0492 3050 }
3051 return true;
3052 }
3053
7d2a0492 3054 // Add the profile edit link
3055 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
7a7e209d 3056 if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
a6855934 3057 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
7a7e209d 3058 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 3059 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
a6855934 3060 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 3061 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 3062 }
3063 }
3064
3065 // Change password link
3066 if (!empty($user->auth)) {
3067 $userauth = get_auth_plugin($user->auth);
3068 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3069 $passwordchangeurl = $userauth->change_password_url();
3070 if (!$passwordchangeurl) {
3071 if (empty($CFG->loginhttps)) {
3072 $wwwroot = $CFG->wwwroot;
3073 } else {
3074 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
3075 }
a6855934 3076 $passwordchangeurl = new moodle_url('/login/change_password.php');
7d2a0492 3077 } else {
3078 $urlbits = explode($passwordchangeurl. '?', 1);
3079 $passwordchangeurl = new moodle_url($urlbits[0]);
3080 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
3081 foreach ($matches as $pair) {
3082 $fullmeurl->param($pair[1],$pair[2]);
3083 }
3084 }
3085 }
3086 $passwordchangeurl->param('id', $course->id);
d972bad1 3087 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
7d2a0492 3088 }
3089 }
3090
3091 // View the roles settings
3092 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3406acde 3093 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
7d2a0492 3094
a6855934 3095 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3406acde 3096 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3097
3098 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
7d2a0492 3099
3100 if (!empty($assignableroles)) {
a6855934 3101 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 3102 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3103 }
3104
0b29477b
SH
3105 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3106 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 3107 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3108 }
3109
a6855934 3110 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 3111 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3112 }
3113
3114 // Portfolio
7a7e209d 3115 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
24ba58ee
PL
3116 require_once($CFG->libdir . '/portfoliolib.php');
3117 if (portfolio_instances(true, false)) {
3406acde
SH
3118 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3119 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
3120 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
24ba58ee 3121 }
7d2a0492 3122 }
3123
4dfdeb76
AD
3124 $enablemanagetokens = false;
3125 if (!empty($CFG->enablerssfeeds)) {
3126 $enablemanagetokens = true;
3127 } else if (!is_siteadmin($USER->id)
3128 && !empty($CFG->enablewebservices)
3129 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3130 $enablemanagetokens = true;
3131 }
94e90ab7 3132 // Security keys
4dfdeb76 3133 if ($currentuser && $enablemanagetokens) {
a6855934 3134 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
94e90ab7 3135 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5eacbd4b 3136 }
3137
7d2a0492 3138 // Repository
3139 if (!$currentuser) {
3140 require_once($CFG->dirroot . '/repository/lib.php');
3141 $editabletypes = repository::get_editable_types($usercontext);
3142 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
a6855934 3143 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
d972bad1 3144 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
7d2a0492 3145 }
3146 }
3147
3148 // Messaging
03d9401e 3149 // TODO this is adding itself to the messaging settings for other people based on one's own setting
7a7e209d 3150 if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
a6855934 3151 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 3152 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
7d2a0492 3153 }
3154
2713c6bd
SH
3155 // Blogs
3156 if (!empty($CFG->bloglevel)) {
3157 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3158 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
435a512e 3159 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
2713c6bd
SH
3160 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3161 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3162 }
3163 }
3164
03d9401e
MD
3165 // Login as ...
3166 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3167 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3168 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3169 }
3170
3406acde 3171 return $usersetting;
7d2a0492 3172 }
3173
0b29477b
SH
3174 /**
3175 * Loads block specific settings in the navigation
4f0c2d00 3176 *
3406acde 3177 * @return navigation_node
0b29477b
SH
3178 */