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