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