Added id to uploaded file userfiles generalbox for specific styling
[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)) {
a6855934 1254 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
7a7e209d
SH
1255 }
1256
1257 // Add nodes for forum posts and discussions if the user can view either or both
507a7a9a
SH
1258 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1259 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
7a7e209d
SH
1260 if ($canviewposts || $canviewdiscussions) {
1261 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
7a7e209d 1262 if ($canviewposts) {
a6855934 1263 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
7a7e209d
SH
1264 }
1265 if ($canviewdiscussions) {
a6855934 1266 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
7a7e209d
SH
1267 }
1268 }
1269
27bad0a6
SH
1270 // Add blog nodes
1271 if (!empty($CFG->bloglevel)) {
1272 require_once($CFG->dirroot.'/blog/lib.php');
1273 // Get all options for the user
1274 $options = blog_get_options_for_user($user);
1275 if (count($options) > 0) {
1276 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1277 foreach ($options as $option) {
1278 $blogs->add($option['string'], $option['link']);
1279 }
1280 }
1281 }
1282
7a7e209d 1283 // Add a node to view the users notes if permitted
507a7a9a 1284 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
3406acde
SH
1285 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1286 if ($coursecontext->instanceid) {
1287 $url->param('course', $coursecontext->instanceid);
1288 }
1289 $usernode->add(get_string('notes', 'notes'), $url);
7a7e209d
SH
1290 }
1291
1292 // Add a reports tab and then add reports the the user has permission to see.
1293 $reporttab = $usernode->add(get_string('activityreports'));
507a7a9a 1294 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
7a7e209d
SH
1295 $viewreports = ($anyreport || ($course->showreports && $iscurrentuser));
1296 $reportargs = array('user'=>$user->id);
1297 if (!empty($course->id)) {
1298 $reportargs['id'] = $course->id;
1299 } else {
1300 $reportargs['id'] = SITEID;
1301 }
507a7a9a 1302 if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
a6855934
PS
1303 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1304 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
7a7e209d 1305 }
4f0c2d00 1306
507a7a9a 1307 if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
a6855934 1308 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
7a7e209d
SH
1309 }
1310
507a7a9a 1311 if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
a6855934 1312 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
7a7e209d
SH
1313 }
1314
1315 if (!empty($CFG->enablestats)) {
507a7a9a 1316 if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
a6855934 1317 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
7a7e209d
SH
1318 }
1319 }
1320
1321 $gradeaccess = false;
507a7a9a 1322 if (has_capability('moodle/grade:viewall', $coursecontext)) {
7a7e209d
SH
1323 //ok - can view all course grades
1324 $gradeaccess = true;
1325 } else if ($course->showgrades) {
507a7a9a 1326 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
7a7e209d
SH
1327 //ok - can view own grades
1328 $gradeaccess = true;
507a7a9a 1329 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
7a7e209d
SH
1330 // ok - can view grades of this user - parent most probably
1331 $gradeaccess = true;
1332 } else if ($anyreport) {
1333 // ok - can view grades of this user - parent most probably
1334 $gradeaccess = true;
1335 }
7d2a0492 1336 }
7a7e209d 1337 if ($gradeaccess) {
a6855934 1338 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
7a7e209d
SH
1339 }
1340
1341 // Check the number of nodes in the report node... if there are none remove
1342 // the node
1343 if (count($reporttab->children)===0) {
1344 $usernode->remove_child($reporttab);
1345 }
1346
1347 // If the user is the current user add the repositories for the current user
1348 if ($iscurrentuser) {
1349 require_once($CFG->dirroot . '/repository/lib.php');
507a7a9a 1350 $editabletypes = repository::get_editable_types($usercontext);
7a7e209d 1351 if (!empty($editabletypes)) {
ad70376c 1352 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
7a7e209d
SH
1353 }
1354 }
1355 return true;
1356 }
1357
1358 /**
3406acde 1359 * This method simply checks to see if a given module can extend the navigation.
7d2a0492 1360 *
1361 * @param string $modname
1362 * @return bool
1363 */
1364 protected function module_extends_navigation($modname) {
1365 global $CFG;
1366 if ($this->cache->cached($modname.'_extends_navigation')) {
1367 return $this->cache->{$modname.'_extends_navigation'};
1368 }
1369 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1370 $function = $modname.'_extend_navigation';
1371 if (function_exists($function)) {
1372 $this->cache->{$modname.'_extends_navigation'} = true;
1373 return true;
1374 } else if (file_exists($file)) {
1375 require_once($file);
1376 if (function_exists($function)) {
1377 $this->cache->{$modname.'_extends_navigation'} = true;
1378 return true;
1379 }
1380 }
1381 $this->cache->{$modname.'_extends_navigation'} = false;
1382 return false;
1383 }
1384 /**
3406acde
SH
1385 * Extends the navigation for the given user.
1386 *
1387 * @param stdClass $user A user from the database
7d2a0492 1388 */
3406acde
SH
1389 public function extend_for_user($user) {
1390 $this->extendforuser[] = $user;
7d2a0492 1391 }
7d2a0492 1392 /**
3406acde 1393 * Adds the given course to the navigation structure.
7d2a0492 1394 *
3406acde
SH
1395 * @param stdClass $course
1396 * @return navigation_node
7d2a0492 1397 */
3406acde
SH
1398 public function add_course(stdClass $course) {
1399 if (array_key_exists($course->id, $this->addedcourses)) {
1400 return $this->addedcourses[$course->id];
7d2a0492 1401 }
7d2a0492 1402
3406acde
SH
1403 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1404 if ($course->id !== SITEID && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1405 return false;
7d2a0492 1406 }
7d2a0492 1407
3406acde
SH
1408 if ($course->id == SITEID) {
1409 $parent = $this;
1410 $url = new moodle_url('/');
1411 } else if (array_key_exists($course->id, $this->mycourses)) {
1412 $parent = $this->rootnodes['mycourses'];
1413 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7a7e209d 1414 } else {
3406acde 1415 $parent = $this->rootnodes['courses'];
a6855934 1416 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7d2a0492 1417 }
3406acde
SH
1418 $coursenode = $parent->add($course->fullname, $url, self::TYPE_COURSE, $course->shortname, $course->id);
1419 $coursenode->nodetype = self::NODETYPE_BRANCH;
1420 $coursenode->hidden = (!$course->visible);
1421 $this->addedcourses[$course->id] = &$coursenode;
1422 return $coursenode;
7d2a0492 1423 }
1424 /**
3406acde 1425 * Adds essential course nodes to the navigation for the given course.
7d2a0492 1426 *
3406acde 1427 * This method adds nodes such as reports, blogs and participants
7d2a0492 1428 *
3406acde
SH
1429 * @param navigation_node $coursenode
1430 * @param stdClass $course
7d2a0492 1431 * @return bool
1432 */
3406acde
SH
1433 public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1434 global $CFG;
7d2a0492 1435
3406acde
SH
1436 if ($course->id === SITEID) {
1437 return $this->add_front_page_course_essentials($coursenode, $course);
7d2a0492 1438 }
7d2a0492 1439
3406acde
SH
1440 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1441 return true;
7d2a0492 1442 }
7d2a0492 1443
3406acde
SH
1444 //Participants
1445 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1446 require_once($CFG->dirroot.'/blog/lib.php');
1447 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1448 $currentgroup = groups_get_course_group($course, true);
1449 if ($course->id == SITEID) {
1450 $filterselect = '';
1451 } else if ($course->id && !$currentgroup) {
1452 $filterselect = $course->id;
1453 } else {
1454 $filterselect = $currentgroup;
1455 }
1456 $filterselect = clean_param($filterselect, PARAM_INT);
1457 if ($CFG->bloglevel >= 3) {
1458 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1459 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1460 }
1461 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1462 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1463 }
1464 } else if (count($this->extendforuser) > 0) {
1465 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1466 }
1467
1468 // View course reports
1469 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1470 $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', ''));
1471 $coursereports = get_plugin_list('coursereport');
1472 foreach ($coursereports as $report=>$dir) {
1473 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1474 if (file_exists($libfile)) {
1475 require_once($libfile);
1476 $reportfunction = $report.'_report_extend_navigation';
1477 if (function_exists($report.'_report_extend_navigation')) {
1478 $reportfunction($reportnav, $course, $this->page->context);
7d2a0492 1479 }
1480 }
1481 }
1482 }
1483 return true;
1484 }
1485
3406acde
SH
1486 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1487 global $CFG;
7d2a0492 1488
3406acde
SH
1489 if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1490 return true;
7a7e209d
SH
1491 }
1492
3406acde
SH
1493 //Participants
1494 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1495 require_once($CFG->dirroot.'/blog/lib.php');
1496 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1497 }
1498
1499 $currentgroup = groups_get_course_group($course, true);
1500 if ($course->id == SITEID) {
1501 $filterselect = '';
1502 } else if ($course->id && !$currentgroup) {
1503 $filterselect = $course->id;
7d2a0492 1504 } else {
3406acde 1505 $filterselect = $currentgroup;
7d2a0492 1506 }
3406acde
SH
1507 $filterselect = clean_param($filterselect, PARAM_INT);
1508 if ($CFG->bloglevel >= 3) {
1509 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1510 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
7d2a0492 1511 }
3406acde
SH
1512 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1513 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1514 }
1515 if (!empty($CFG->usetags)) {
1516 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
7d2a0492 1517 }
6644741d 1518
6644741d 1519
3406acde
SH
1520 // View course reports
1521 if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1522 $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', ''));
1523 $coursereports = get_plugin_list('coursereport');
1524 foreach ($coursereports as $report=>$dir) {
1525 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1526 if (file_exists($libfile)) {
1527 require_once($libfile);
1528 $reportfunction = $report.'_report_extend_navigation';
1529 if (function_exists($report.'_report_extend_navigation')) {
1530 $reportfunction($reportnav, $course, $this->page->context);
1531 }
6644741d 1532 }
6644741d 1533 }
1534 }
3406acde 1535 return true;
6644741d 1536 }
da3ab9c4 1537
3406acde
SH
1538 /**
1539 * Clears the navigation cache
1540 */
1541 public function clear_cache() {
1542 $this->cache->clear();
da3ab9c4 1543 }
88f77c3c
SH
1544
1545 public function set_expansion_limit($type) {
1546 $nodes = $this->find_all_of_type($type);
1547 foreach ($nodes as &$node) {
1548 foreach ($node->children as &$child) {
1549 $child->display = false;
1550 }
1551 }
1552 return true;
1553 }
7d2a0492 1554}
1555
1556/**
1557 * The limited global navigation class used for the AJAX extension of the global
1558 * navigation class.
1559 *
1560 * The primary methods that are used in the global navigation class have been overriden
1561 * to ensure that only the relevant branch is generated at the root of the tree.
1562 * This can be done because AJAX is only used when the backwards structure for the
1563 * requested branch exists.
1564 * This has been done only because it shortens the amounts of information that is generated
1565 * which of course will speed up the response time.. because no one likes laggy AJAX.
1566 *
1567 * @package moodlecore
babb3911 1568 * @subpackage navigation
7d2a0492 1569 * @copyright 2009 Sam Hemelryk
1570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1571 */
507a7a9a 1572class global_navigation_for_ajax extends global_navigation {
3406acde
SH
1573
1574 /** @var array */
1575 protected $expandable = array();
1576
7d2a0492 1577 /**
3406acde 1578 * Constructs the navigation for use in AJAX request
3406acde
SH
1579 */
1580 public function __construct() {
1581 global $SITE;
1582 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1583 $this->children = new navigation_node_collection();
1584 $this->rootnodes = array();
1585 //$this->rootnodes['site'] = $this->add_course($SITE);
1586 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1587 }
1588 /**
1589 * Initialise the navigation given the type and id for the branch to expand.
7d2a0492 1590 *
3406acde
SH
1591 * @param int $branchtype One of navigation_node::TYPE_*
1592 * @param int $id
1593 * @return array The expandable nodes
7d2a0492 1594 */
507a7a9a 1595 public function initialise($branchtype, $id) {
3406acde 1596 global $DB, $PAGE;
507a7a9a 1597
7d2a0492 1598 if ($this->initialised || during_initial_install()) {
95b97515 1599 return $this->expandable;
7d2a0492 1600 }
507a7a9a
SH
1601
1602 // Branchtype will be one of navigation_node::TYPE_*
1603 switch ($branchtype) {
507a7a9a
SH
1604 case self::TYPE_COURSE :
1605 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
1606 require_course_login($course);
3406acde
SH
1607 $this->page = $PAGE;
1608 $coursenode = $this->add_course($course);
1609 $this->add_course_essentials($coursenode, $course);
1610 if ($this->format_display_course_content($course->format)) {
1611 $this->load_course_sections($course, $coursenode);
1612 }
7d2a0492 1613 break;
507a7a9a 1614 case self::TYPE_SECTION :
3406acde 1615 $sql = 'SELECT c.*, cs.section AS sectionnumber
507a7a9a
SH
1616 FROM {course} c
1617 LEFT JOIN {course_sections} cs ON cs.course = c.id
1618 WHERE cs.id = ?';
1619 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
1620 require_course_login($course);
3406acde
SH
1621 $this->page = $PAGE;
1622 $coursenode = $this->add_course($course);
1623 $this->add_course_essentials($coursenode, $course);
1624 $sections = $this->load_course_sections($course, $coursenode);
1625 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
7d2a0492 1626 break;
507a7a9a
SH
1627 case self::TYPE_ACTIVITY :
1628 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
1629 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1630 require_course_login($course, true, $cm);
3406acde
SH
1631 $this->page = $PAGE;
1632 $coursenode = $this->load_course($course);
1633 $sections = $this->load_course_sections($course, $coursenode);
1634 foreach ($sections as $section) {
1635 if ($section->id == $cm->section) {
1636 $cm->sectionnumber = $section->section;
1637 break;
1638 }
1639 }
1640 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1641 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
7d2a0492 1642 break;
507a7a9a 1643 default:
3406acde 1644 throw new Exception('Unknown type');
507a7a9a 1645 return $this->expandable;
7d2a0492 1646 }
507a7a9a 1647
507a7a9a 1648 $this->find_expandable($this->expandable);
507a7a9a 1649 return $this->expandable;
7d2a0492 1650 }
7d2a0492 1651}
1652
1653/**
1654 * Navbar class
1655 *
1656 * This class is used to manage the navbar, which is initialised from the navigation
1657 * object held by PAGE
1658 *
1659 * @package moodlecore
babb3911 1660 * @subpackage navigation
7d2a0492 1661 * @copyright 2009 Sam Hemelryk
1662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1663 */
1664class navbar extends navigation_node {
1665 /** @var bool */
1666 protected $initialised = false;
1667 /** @var mixed */
1668 protected $keys = array();
1669 /** @var null|string */
1670 protected $content = null;
3406acde 1671 /** @var moodle_page object */
7d2a0492 1672 protected $page;
1673 /** @var bool */
31759089 1674 protected $ignoreactive = false;
1675 /** @var bool */
7d2a0492 1676 protected $duringinstall = false;
7a7e209d
SH
1677 /** @var bool */
1678 protected $hasitems = false;
3406acde
SH
1679 /** @var array */
1680 protected $items;
1681 /** @var array */
1682 public $children = array();
7d2a0492 1683 /**
1684 * The almighty constructor
3406acde
SH
1685 *
1686 * @param moodle_page $page
7d2a0492 1687 */
3406acde 1688 public function __construct(moodle_page $page) {
507a7a9a 1689 global $CFG;
7d2a0492 1690 if (during_initial_install()) {
1691 $this->duringinstall = true;
1692 return false;
1693 }
1694 $this->page = $page;
1695 $this->text = get_string('home');
1696 $this->shorttext = get_string('home');
1697 $this->action = new moodle_url($CFG->wwwroot);
1698 $this->nodetype = self::NODETYPE_BRANCH;
1699 $this->type = self::TYPE_SYSTEM;
1700 }
1701
1702 /**
1703 * Quick check to see if the navbar will have items in.
1704 *
1705 * @return bool Returns true if the navbar will have items, false otherwise
1706 */
1707 public function has_items() {
1708 if ($this->duringinstall) {
1709 return false;
7a7e209d
SH
1710 } else if ($this->hasitems !== false) {
1711 return true;
7d2a0492 1712 }
3406acde 1713 $this->page->navigation->initialise($this->page);
bf6c37c7 1714
7a7e209d 1715 $activenodefound = ($this->page->navigation->contains_active_node() ||
3406acde 1716 $this->page->settingsnav->contains_active_node());
bf6c37c7 1717
3406acde 1718 $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
7a7e209d 1719 $this->hasitems = $outcome;
bf6c37c7 1720 return $outcome;
31759089 1721 }
1722
3406acde
SH
1723 /**
1724 * Turn on/off ignore active
1725 *
1726 * @param bool $setting
1727 */
31759089 1728 public function ignore_active($setting=true) {
1729 $this->ignoreactive = ($setting);
7d2a0492 1730 }
3406acde
SH
1731 public function get($key, $type = null) {
1732 foreach ($this->children as &$child) {
1733 if ($child->key === $key && ($type == null || $type == $child->type)) {
1734 return $child;
1735 }
1736 }
1737 return false;
1738 }
7d2a0492 1739 /**
3406acde
SH
1740 * Returns an array of navigation_node's that make up the navbar.
1741 *
1742 * @return array
7d2a0492 1743 */
3406acde
SH
1744 public function get_items() {
1745 $items = array();
7d2a0492 1746 // Make sure that navigation is initialised
7a7e209d 1747 if (!$this->has_items()) {
3406acde 1748 return $items;
7a7e209d 1749 }
3406acde
SH
1750 if ($this->items !== null) {
1751 return $this->items;
7d2a0492 1752 }
1753
3406acde
SH
1754 if (count($this->children) > 0) {
1755 // Add the custom children
1756 $items = array_reverse($this->children);
1757 }
117bd748 1758
3406acde
SH
1759 $navigationactivenode = $this->page->navigation->find_active_node();
1760 $settingsactivenode = $this->page->settingsnav->find_active_node();
0b29477b 1761
7d2a0492 1762 // Check if navigation contains the active node
0b29477b 1763 if (!$this->ignoreactive) {
3406acde
SH
1764
1765 if ($navigationactivenode && $settingsactivenode) {
0b29477b 1766 // Parse a combined navigation tree
3406acde
SH
1767 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1768 if (!$settingsactivenode->mainnavonly) {
1769 $items[] = $settingsactivenode;
1770 }
1771 $settingsactivenode = $settingsactivenode->parent;
1772 }
1773 // Removes the first node from the settings (root node) from the list
1774 array_pop($items);
1775 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1776 if (!$navigationactivenode->mainnavonly) {
1777 $items[] = $navigationactivenode;
1778 }
1779 $navigationactivenode = $navigationactivenode->parent;
0b29477b 1780 }
3406acde 1781 } else if ($navigationactivenode) {
0b29477b 1782 // Parse the navigation tree to get the active node
3406acde
SH
1783 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1784 if (!$navigationactivenode->mainnavonly) {
1785 $items[] = $navigationactivenode;
1786 }
1787 $navigationactivenode = $navigationactivenode->parent;
1788 }
1789 } else if ($settingsactivenode) {
0b29477b 1790 // Parse the settings navigation to get the active node
3406acde
SH
1791 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1792 if (!$settingsactivenode->mainnavonly) {
1793 $items[] = $settingsactivenode;
1794 }
1795 $settingsactivenode = $settingsactivenode->parent;
1796 }
0b29477b 1797 }
7d2a0492 1798 }
a3bbac8b 1799
3406acde
SH
1800 $items[] = new navigation_node(array(
1801 'text'=>$this->page->navigation->text,
1802 'shorttext'=>$this->page->navigation->shorttext,
1803 'key'=>$this->page->navigation->key,
1804 'action'=>$this->page->navigation->action
1805 ));
a3bbac8b 1806
3406acde
SH
1807 $this->items = array_reverse($items);
1808 return $this->items;
7d2a0492 1809 }
507a7a9a 1810
7d2a0492 1811 /**
3406acde 1812 * Add a new navigation_node to the navbar, overrides parent::add
7d2a0492 1813 *
1814 * This function overrides {@link navigation_node::add()} so that we can change
1815 * the way nodes get added to allow us to simply call add and have the node added to the
1816 * end of the navbar
1817 *
1818 * @param string $text
7d2a0492 1819 * @param string|moodle_url $action
d972bad1 1820 * @param int $type
1821 * @param string|int $key
1822 * @param string $shorttext
7d2a0492 1823 * @param string $icon
3406acde 1824 * @return navigation_node
7d2a0492 1825 */
f9fc1461 1826 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3406acde
SH
1827 if ($this->content !== null) {
1828 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
1829 }
1830
1831 // Properties array used when creating the new navigation node
1832 $itemarray = array(
1833 'text' => $text,
1834 'type' => $type
1835 );
1836 // Set the action if one was provided
1837 if ($action!==null) {
1838 $itemarray['action'] = $action;
1839 }
1840 // Set the shorttext if one was provided
1841 if ($shorttext!==null) {
1842 $itemarray['shorttext'] = $shorttext;
1843 }
1844 // Set the icon if one was provided
1845 if ($icon!==null) {
1846 $itemarray['icon'] = $icon;
7d2a0492 1847 }
3406acde
SH
1848 // Default the key to the number of children if not provided
1849 if ($key === null) {
1850 $key = count($this->children);
7d2a0492 1851 }
3406acde
SH
1852 // Set the key
1853 $itemarray['key'] = $key;
1854 // Set the parent to this node
1855 $itemarray['parent'] = $this;
1856 // Add the child using the navigation_node_collections add method
1857 $this->children[] = new navigation_node($itemarray);
1858 return $this;
7d2a0492 1859 }
1860}
1861
1862/**
1863 * Class used to manage the settings option for the current page
1864 *
1865 * This class is used to manage the settings options in a tree format (recursively)
1866 * and was created initially for use with the settings blocks.
1867 *
1868 * @package moodlecore
babb3911 1869 * @subpackage navigation
7d2a0492 1870 * @copyright 2009 Sam Hemelryk
1871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1872 */
1873class settings_navigation extends navigation_node {
1874 /** @var stdClass */
1875 protected $context;
3406acde 1876 /** @var navigation_cache */
7d2a0492 1877 protected $cache;
3406acde 1878 /** @var moodle_page */
7d2a0492 1879 protected $page;
3406acde 1880 /** @var string */
d9d2817a 1881 protected $adminsection;
7d2a0492 1882 /**
1883 * Sets up the object with basic settings and preparse it for use
3406acde
SH
1884 *
1885 * @param moodle_page $page
7d2a0492 1886 */
507a7a9a 1887 public function __construct(moodle_page &$page) {
7d2a0492 1888 if (during_initial_install()) {
1889 return false;
1890 }
7d2a0492 1891 $this->page = $page;
1892 // Initialise the main navigation. It is most important that this is done
1893 // before we try anything
1894 $this->page->navigation->initialise();
1895 // Initialise the navigation cache
f5b5a822 1896 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3406acde 1897 $this->children = new navigation_node_collection();
7d2a0492 1898 }
1899 /**
1900 * Initialise the settings navigation based on the current context
1901 *
1902 * This function initialises the settings navigation tree for a given context
1903 * by calling supporting functions to generate major parts of the tree.
3406acde 1904 *
7d2a0492 1905 */
1906 public function initialise() {
0b29477b 1907 global $DB;
4f0c2d00 1908
7d2a0492 1909 if (during_initial_install()) {
1910 return false;
1911 }
1912 $this->id = 'settingsnav';
1913 $this->context = $this->page->context;
0b29477b
SH
1914
1915 $context = $this->context;
1916 if ($context->contextlevel == CONTEXT_BLOCK) {
1917 $this->load_block_settings();
1918 $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));
1919 }
1920
1921 switch ($context->contextlevel) {
7d2a0492 1922 case CONTEXT_SYSTEM:
0b29477b
SH
1923 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
1924 $this->load_front_page_settings(($context->id == $this->context->id));
1925 }
7d2a0492 1926 break;
1927 case CONTEXT_COURSECAT:
0b29477b 1928 $this->load_category_settings();
7d2a0492 1929 break;
1930 case CONTEXT_COURSE:
0b29477b
SH
1931 if ($this->page->course->id != SITEID) {
1932 $this->load_course_settings(($context->id == $this->context->id));
7d2a0492 1933 } else {
0b29477b 1934 $this->load_front_page_settings(($context->id == $this->context->id));
7d2a0492 1935 }
1936 break;
1937 case CONTEXT_MODULE:
0b29477b
SH
1938 $this->load_module_settings();
1939 $this->load_course_settings();
7d2a0492 1940 break;
1941 case CONTEXT_USER:
0b29477b
SH
1942 if ($this->page->course->id != SITEID) {
1943 $this->load_course_settings();
7d2a0492 1944 }
7d2a0492 1945 break;
1946 }
1947
3406acde
SH
1948 $settings = $this->load_user_settings($this->page->course->id);
1949 $admin = $this->load_administration_settings();
0b29477b 1950
3406acde
SH
1951 if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
1952 $admin->force_open();
1953 } else if ($context->contextlevel == CONTEXT_USER && $settings) {
1954 $settings->force_open();
0b29477b
SH
1955 }
1956
7d2a0492 1957 // Check if the user is currently logged in as another user
1958 if (session_is_loggedinas()) {
1959 // Get the actual user, we need this so we can display an informative return link
1960 $realuser = session_get_realuser();
1961 // Add the informative return to original user link
a6855934 1962 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
f9fc1461 1963 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
7d2a0492 1964 }
1965
1966 // Make sure the first child doesnt have proceed with hr set to true
7d2a0492 1967
3406acde
SH
1968 foreach ($this->children as $key=>$node) {
1969 if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
1970 $node->remove();
1971 }
1972 }
7d2a0492 1973 }
1974 /**
1975 * Override the parent function so that we can add preceeding hr's and set a
1976 * root node class against all first level element
1977 *
1978 * It does this by first calling the parent's add method {@link navigation_node::add()}
117bd748 1979 * and then proceeds to use the key to set class and hr
7d2a0492 1980 *
1981 * @param string $text
91152a35 1982 * @param sting|moodle_url $url
7d2a0492 1983 * @param string $shorttext
1984 * @param string|int $key
1985 * @param int $type
7d2a0492 1986 * @param string $icon
3406acde 1987 * @return navigation_node
7d2a0492 1988 */
f9fc1461 1989 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3406acde
SH
1990 $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
1991 $node->add_class('root_node');
1992 return $node;
7d2a0492 1993 }
a6e34701 1994
1995 /**
1996 * This function allows the user to add something to the start of the settings
1997 * navigation, which means it will be at the top of the settings navigation block
1998 *
1999 * @param string $text
2000 * @param sting|moodle_url $url
2001 * @param string $shorttext
2002 * @param string|int $key
2003 * @param int $type
2004 * @param string $icon
3406acde 2005 * @return navigation_node
a6e34701 2006 */
f9fc1461 2007 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
a6e34701 2008 $children = $this->children;
3406acde
SH
2009 $this->children = new get_class($children);
2010 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2011 foreach ($children as $child) {
2012 $this->children->add($child);
a6e34701 2013 }
3406acde 2014 return $node;
a6e34701 2015 }
7d2a0492 2016 /**
2017 * Load the site administration tree
2018 *
2019 * This function loads the site administration tree by using the lib/adminlib library functions
2020 *
3406acde 2021 * @param navigation_node $referencebranch A reference to a branch in the settings
7d2a0492 2022 * navigation tree
3406acde 2023 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
7d2a0492 2024 * tree and start at the beginning
2025 * @return mixed A key to access the admin tree by
2026 */
0e3eee62 2027 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
507a7a9a 2028 global $CFG;
0e3eee62 2029
7d2a0492 2030 // Check if we are just starting to generate this navigation.
2031 if ($referencebranch === null) {
0e3eee62 2032
d9d2817a 2033 // Require the admin lib then get an admin structure
0e3eee62
SH
2034 if (!function_exists('admin_get_root')) {
2035 require_once($CFG->dirroot.'/lib/adminlib.php');
2036 }
2037 $adminroot = admin_get_root(false, false);
d9d2817a
SH
2038 // This is the active section identifier
2039 $this->adminsection = $this->page->url->param('section');
4f0c2d00 2040
d9d2817a
SH
2041 // Disable the navigation from automatically finding the active node
2042 navigation_node::$autofindactive = false;
3406acde 2043 $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
0e3eee62
SH
2044 foreach ($adminroot->children as $adminbranch) {
2045 $this->load_administration_settings($referencebranch, $adminbranch);
2046 }
d9d2817a 2047 navigation_node::$autofindactive = true;
0e3eee62 2048
d9d2817a 2049 // Use the admin structure to locate the active page
3406acde
SH
2050 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2051 $currentnode = $this;
2052 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2053 $currentnode = $currentnode->get($pathkey);
2054 }
2055 if ($currentnode) {
2056 $currentnode->make_active();
7d2a0492 2057 }
0e3eee62 2058 }
3406acde 2059 return $referencebranch;
8140c440 2060 } else if ($adminbranch->check_access()) {
7d2a0492 2061 // We have a reference branch that we can access and is not hidden `hurrah`
2062 // Now we need to display it and any children it may have
2063 $url = null;
2064 $icon = null;
2065 if ($adminbranch instanceof admin_settingpage) {
a6855934 2066 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
7d2a0492 2067 } else if ($adminbranch instanceof admin_externalpage) {
2068 $url = $adminbranch->url;
2069 }
2070
2071 // Add the branch
3406acde 2072 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
8140c440 2073
2074 if ($adminbranch->is_hidden()) {
d9d2817a
SH
2075 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2076 $reference->add_class('hidden');
2077 } else {
2078 $reference->display = false;
2079 }
8140c440 2080 }
2081
7d2a0492 2082 // Check if we are generating the admin notifications and whether notificiations exist
2083 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2084 $reference->add_class('criticalnotification');
2085 }
2086 // Check if this branch has children
2087 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2088 foreach ($adminbranch->children as $branch) {
2089 // Generate the child branches as well now using this branch as the reference
459e384e 2090 $this->load_administration_settings($reference, $branch);
7d2a0492 2091 }
2092 } else {
f9fc1461 2093 $reference->icon = new pix_icon('i/settings', '');
7d2a0492 2094 }
2095 }
2096 }
2097
3406acde
SH
2098 /**
2099 * Gets a navigation node given an array of keys that represent the path to
2100 * the desired node.
2101 *
2102 * @param array $path
2103 * @return navigation_node|false
2104 */
2105 protected function get_by_path(array $path) {
2106 $node = $this->get(array_shift($path));
2107 foreach ($path as $key) {
2108 $node->get($key);
2109 }
2110 return $node;
2111 }
2112
7d2a0492 2113 /**
2114 * Generate the list of modules for the given course.
2115 *
2116 * The array of resources and activities that can be added to a course is then
2117 * stored in the cache so that we can access it for anywhere.
2118 * It saves us generating it all the time
2119 *
2120 * <code php>
2121 * // To get resources:
2122 * $this->cache->{'course'.$courseid.'resources'}
2123 * // To get activities:
2124 * $this->cache->{'course'.$courseid.'activities'}
2125 * </code>
2126 *
2127 * @param stdClass $course The course to get modules for
2128 */
2129 protected function get_course_modules($course) {
2130 global $CFG;
2131 $mods = $modnames = $modnamesplural = $modnamesused = array();
2132 // This function is included when we include course/lib.php at the top
2133 // of this file
2134 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2135 $resources = array();
2136 $activities = array();
2137 foreach($modnames as $modname=>$modnamestr) {
2138 if (!course_allowed_module($course, $modname)) {
2139 continue;
2140 }
2141
2142 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2143 if (!file_exists($libfile)) {
2144 continue;
2145 }
2146 include_once($libfile);
2147 $gettypesfunc = $modname.'_get_types';
2148 if (function_exists($gettypesfunc)) {
2149 $types = $gettypesfunc();
2150 foreach($types as $type) {
2151 if (!isset($type->modclass) || !isset($type->typestr)) {
2152 debugging('Incorrect activity type in '.$modname);
2153 continue;
2154 }
2155 if ($type->modclass == MOD_CLASS_RESOURCE) {
2156 $resources[html_entity_decode($type->type)] = $type->typestr;
2157 } else {
2158 $activities[html_entity_decode($type->type)] = $type->typestr;
2159 }
2160 }
2161 } else {
2162 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2163 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2164 $resources[$modname] = $modnamestr;
2165 } else {
2166 // all other archetypes are considered activity
2167 $activities[$modname] = $modnamestr;
2168 }
2169 }
2170 }
2171 $this->cache->{'course'.$course->id.'resources'} = $resources;
2172 $this->cache->{'course'.$course->id.'activities'} = $activities;
2173 }
2174
2175 /**
2176 * This function loads the course settings that are available for the user
2177 *
0b29477b 2178 * @param bool $forceopen If set to true the course node will be forced open
3406acde 2179 * @return navigation_node|false
7d2a0492 2180 */
0b29477b 2181 protected function load_course_settings($forceopen = false) {
4f0c2d00 2182 global $CFG, $USER, $SESSION, $OUTPUT;
7d2a0492 2183
2184 $course = $this->page->course;
4f0c2d00 2185 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
7d2a0492 2186 if (!$this->cache->cached('canviewcourse'.$course->id)) {
4f0c2d00 2187 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
7d2a0492 2188 }
2189 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2190 return false;
2191 }
2192
3406acde
SH
2193 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2194 if ($forceopen) {
2195 $coursenode->force_open();
2196 }
117bd748 2197
4f0c2d00 2198 if (has_capability('moodle/course:update', $coursecontext)) {
7d2a0492 2199 // Add the turn on/off settings
a6855934 2200 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
7d2a0492 2201 if ($this->page->user_is_editing()) {
2202 $url->param('edit', 'off');
2203 $editstring = get_string('turneditingoff');
2204 } else {
2205 $url->param('edit', 'on');
2206 $editstring = get_string('turneditingon');
2207 }
f9fc1461 2208 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
7d2a0492 2209
7d2a0492 2210 if ($this->page->user_is_editing()) {
2211 // Add `add` resources|activities branches
2212 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2213 if (file_exists($structurefile)) {
2214 require_once($structurefile);
2215 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2216 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2217 } else {
2218 $formatstring = get_string('topic');
2219 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2220 }
2221 if (!$this->cache->cached('coursesections'.$course->id)) {
2222 $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
2223 }
2224 $sections = $this->cache->{'coursesections'.$course->id};
117bd748 2225
3406acde
SH
2226 $addresource = $this->add(get_string('addresource'));
2227 $addactivity = $this->add(get_string('addactivity'));
7d2a0492 2228 if ($formatidentifier!==0) {
3406acde
SH
2229 $addresource->force_open();
2230 $addactivity->force_open();
7d2a0492 2231 }
2232
2233 if (!$this->cache->cached('course'.$course->id.'resources')) {
459e384e 2234 $this->get_course_modules($course);
7d2a0492 2235 }
2236 $resources = $this->cache->{'course'.$course->id.'resources'};
2237 $activities = $this->cache->{'course'.$course->id.'activities'};
117bd748 2238
9cf45d02
SH
2239 $textlib = textlib_get_instance();
2240
7d2a0492 2241 foreach ($sections as $section) {
2242 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2243 continue;
2244 }
a6855934 2245 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
7d2a0492 2246 if ($section->section == 0) {
d972bad1 2247 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2248 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
7d2a0492 2249 } else {
d972bad1 2250 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2251 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
7d2a0492 2252 }
2253 foreach ($resources as $value=>$resource) {
a6855934 2254 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2255 $pos = strpos($value, '&type=');
2256 if ($pos!==false) {
9cf45d02
SH
2257 $url->param('add', $textlib->substr($value, 0,$pos));
2258 $url->param('type', $textlib->substr($value, $pos+6));
7d2a0492 2259 } else {
2260 $url->param('add', $value);
2261 }
3406acde 2262 $sectionresources->add($resource, $url, self::TYPE_SETTING);
7d2a0492 2263 }
2264 $subbranch = false;
2265 foreach ($activities as $activityname=>$activity) {
2266 if ($activity==='--') {
2267 $subbranch = false;
2268 continue;
2269 }
2270 if (strpos($activity, '--')===0) {
3406acde 2271 $subbranch = $sectionresources->add(trim($activity, '-'));
7d2a0492 2272 continue;
2273 }
a6855934 2274 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2275 $pos = strpos($activityname, '&type=');
2276 if ($pos!==false) {
9cf45d02
SH
2277 $url->param('add', $textlib->substr($activityname, 0,$pos));
2278 $url->param('type', $textlib->substr($activityname, $pos+6));
7d2a0492 2279 } else {
2280 $url->param('add', $activityname);
2281 }
2282 if ($subbranch !== false) {
3406acde 2283 $subbranch->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2284 } else {
3406acde 2285 $sectionresources->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2286 }
2287 }
2288 }
2289 }
2290
2291 // Add the course settings link
a6855934 2292 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
f9fc1461 2293 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2be4d090
MD
2294
2295 // Add the course completion settings link
2296 if ($CFG->enablecompletion && $course->enablecompletion) {
2297 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2298 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2299 }
7d2a0492 2300 }
117bd748 2301
4f0c2d00 2302 if (has_capability('moodle/role:assign', $coursecontext)) {
0b29477b 2303 // Add assign or override roles if allowed
4f0c2d00 2304 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
f9fc1461 2305 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
0b29477b 2306 // Override roles
4f0c2d00
PS
2307 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2308 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2309 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2310 }
2311 // Check role permissions
4f0c2d00
PS
2312 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2313 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2314 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2315 }
2316 // Manage filters
4f0c2d00
PS
2317 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2318 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2319 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2320 }
7d2a0492 2321 }
2322
2323 // Add view grade report is permitted
2324 $reportavailable = false;
4f0c2d00 2325 if (has_capability('moodle/grade:viewall', $coursecontext)) {
7d2a0492 2326 $reportavailable = true;
2327 } else if (!empty($course->showgrades)) {
2328 $reports = get_plugin_list('gradereport');
2329 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2330 arsort($reports); // user is last, we want to test it first
2331 foreach ($reports as $plugin => $plugindir) {
4f0c2d00 2332 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
7d2a0492 2333 //stop when the first visible plugin is found
2334 $reportavailable = true;
2335 break;
2336 }
2337 }
2338 }
2339 }
2340 if ($reportavailable) {
a6855934 2341 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
f9fc1461 2342 $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
7d2a0492 2343 }
2344
2345 // Add outcome if permitted
4f0c2d00 2346 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
a6855934 2347 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
f9fc1461 2348 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/outcomes', ''));
7d2a0492 2349 }
2350
2351 // Add meta course links
2352 if ($course->metacourse) {
4f0c2d00 2353 if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
a6855934 2354 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
f9fc1461 2355 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
4f0c2d00 2356 } else if (has_capability('moodle/role:assign', $coursecontext)) {
3406acde
SH
2357 $roleassign = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2358 $roleassign->hidden = true;
7d2a0492 2359 }
2360 }
2361
2362 // Manage groups in this course
4f0c2d00 2363 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
a6855934 2364 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
f9fc1461 2365 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/group', ''));
7d2a0492 2366 }
2367
7d2a0492 2368 // Backup this course
4f0c2d00 2369 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
a6855934 2370 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
f9fc1461 2371 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
7d2a0492 2372 }
2373
2374 // Restore to this course
4f0c2d00 2375 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
a6855934 2376 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
f9fc1461 2377 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
7d2a0492 2378 }
2379
2380 // Import data from other courses
4f0c2d00 2381 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
a6855934 2382 $url = new moodle_url('/course/import.php', array('id'=>$course->id));
f9fc1461 2383 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
7d2a0492 2384 }
2385
07ab0c80 2386 // Publish course on a hub
2387 if (has_capability('moodle/course:publish', $coursecontext)) {
2388 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2389 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/publish', ''));
2390 }
2391
7d2a0492 2392 // Reset this course
4f0c2d00 2393 if (has_capability('moodle/course:reset', $coursecontext)) {
a6855934 2394 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
f9fc1461 2395 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
7d2a0492 2396 }
7d2a0492 2397
2398 // Manage questions
2399 $questioncaps = array('moodle/question:add',
2400 'moodle/question:editmine',
2401 'moodle/question:editall',
2402 'moodle/question:viewmine',
2403 'moodle/question:viewall',
2404 'moodle/question:movemine',
2405 'moodle/question:moveall');
2406 if (has_any_capability($questioncaps, $this->context)) {
2407 $questionlink = $CFG->wwwroot.'/question/edit.php';
2408 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2409 $questionlink = $CFG->wwwroot.'/question/category.php';
2410 }
2411 if (isset($questionlink)) {
2412 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
f9fc1461 2413 $coursenode->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
7d2a0492 2414 }
2415
2416 // Repository Instances
2417 require_once($CFG->dirroot.'/repository/lib.php');
2418 $editabletypes = repository::get_editable_types($this->context);
2419 if (has_capability('moodle/course:update', $this->context) && !empty($editabletypes)) {
a6855934 2420 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$this->context->id));
f9fc1461 2421 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
7d2a0492 2422 }
2423
2424 // Manage files
2425 if (has_capability('moodle/course:managefiles', $this->context)) {
a6855934 2426 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
f9fc1461 2427 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
7d2a0492 2428 }
2429
2430 // Authorize hooks
2431 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2432 require_once($CFG->dirroot.'/enrol/authorize/const.php');
a6855934 2433 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
f9fc1461 2434 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2435 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2436 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2437 if ($cnt) {
a6855934 2438 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
f9fc1461 2439 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2440 }
2441 }
2442 }
2443
2444 // Unenrol link
4f0c2d00
PS
2445 if (empty($course->metacourse) && ($course->id!==SITEID)) {
2446 if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2447 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
2448 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2449 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2450 }
2451
2452 } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2453 // inspector, manager, etc. - do not show anything
2454 } else {
2455 // access because otherwise they would not get into this course at all
2456 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2457 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
7d2a0492 2458 }
2459 }
2460
7d2a0492 2461 // Switch roles
2462 $roles = array();
2463 $assumedrole = $this->in_alternative_role();
2464 if ($assumedrole!==false) {
2465 $roles[0] = get_string('switchrolereturn');
2466 }
2467 if (has_capability('moodle/role:switchroles', $this->context)) {
2468 $availableroles = get_switchable_roles($this->context);
2469 if (is_array($availableroles)) {
2470 foreach ($availableroles as $key=>$role) {
2471 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2472 continue;
2473 }
2474 $roles[$key] = $role;
2475 }
2476 }
2477 }
2478 if (is_array($roles) && count($roles)>0) {
3406acde 2479 $switchroles = $this->add(get_string('switchroleto'));
7d2a0492 2480 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3406acde 2481 $switchroles->force_open();
7d2a0492 2482 }
2483 $returnurl = $this->page->url;
2484 $returnurl->param('sesskey', sesskey());
2485 $SESSION->returnurl = serialize($returnurl);
2486 foreach ($roles as $key=>$name) {
a6855934 2487 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
3406acde 2488 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
7d2a0492 2489 }
2490 }
2491 // Return we are done
3406acde 2492 return $coursenode;
7d2a0492 2493 }
2494
2495 /**
2496 * This function calls the module function to inject module settings into the
2497 * settings navigation tree.
2498 *
2499 * This only gets called if there is a corrosponding function in the modules
2500 * lib file.
2501 *
2502 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2503 *
3406acde 2504 * @return navigation_node|false
7d2a0492 2505 */
2506 protected function load_module_settings() {
507a7a9a 2507 global $CFG;
4dd5bce8 2508
2509 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
0b29477b 2510 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
507a7a9a 2511 $this->page->set_cm($cm, $this->page->course);
4dd5bce8 2512 }
2513
3406acde
SH
2514 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2515 $modulenode->force_open();
4f0c2d00 2516
0b29477b
SH
2517 // Settings for the module
2518 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2519 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2520 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2521 }
2522 // Assign local roles
2523 if (count(get_assignable_roles($this->page->cm->context))>0) {
2524 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2525 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2526 }
2527 // Override roles
2528 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2529 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2530 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2531 }
2532 // Check role permissions
2533 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2534 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2535 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2536 }
2537 // Manage filters
2538 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2539 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2540 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2541 }
4f0c2d00 2542
507a7a9a
SH
2543 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2544 $function = $this->page->activityname.'_extend_settings_navigation';
117bd748 2545
7d2a0492 2546 if (file_exists($file)) {
2547 require_once($file);
2548 }
2549 if (!function_exists($function)) {
3406acde 2550 return $modulenode;
7d2a0492 2551 }
0b29477b
SH
2552
2553 $function($this, $modulenode);
2554
2555 // Remove the module node if there are no children
2556 if (empty($modulenode->children)) {
3406acde 2557 $modulenode->remove();
0b29477b
SH
2558 }
2559
3406acde 2560 return $modulenode;
7d2a0492 2561 }
2562
2563 /**
2564 * Loads the user settings block of the settings nav
117bd748 2565 *
7d2a0492 2566 * This function is simply works out the userid and whether we need to load
117bd748 2567 * just the current users profile settings, or the current user and the user the
7d2a0492 2568 * current user is viewing.
117bd748 2569 *
7d2a0492 2570 * This function has some very ugly code to work out the user, if anyone has
2571 * any bright ideas please feel free to intervene.
2572 *
2573 * @param int $courseid The course id of the current course
3406acde 2574 * @return navigation_node|false
7d2a0492 2575 */
2576 protected function load_user_settings($courseid=SITEID) {
0b29477b 2577 global $USER, $FULLME, $CFG;
7d2a0492 2578
2579 if (isguestuser() || !isloggedin()) {
2580 return false;
2581 }
2582
2583 // This is terribly ugly code, but I couldn't see a better way around it
2584 // we need to pick up the user id, it can be the current user or someone else
2585 // and the key depends on the current location
2586 // Default to look at id
2587 $userkey='id';
0b29477b
SH
2588 if (strpos($FULLME,'/blog/') || strpos($FULLME, $CFG->admin.'/roles/')) {
2589 // And blog and roles just do thier own thing using `userid`
2590 $userkey = 'userid';
3406acde 2591 } else if ($this->context->contextlevel >= CONTEXT_COURSECAT && strpos($FULLME, '/message/')===false && strpos($FULLME, '/mod/forum/user')===false && strpos($FULLME, '/user/editadvanced')===false) {
7d2a0492 2592 // If we have a course context and we are not in message or forum
2593 // Message and forum both pick the user up from `id`
2594 $userkey = 'user';
7d2a0492 2595 }
2596
2597 $userid = optional_param($userkey, $USER->id, PARAM_INT);
2598 if ($userid!=$USER->id) {
3406acde 2599 $usernode = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
0b29477b 2600 $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2601 } else {
3406acde 2602 $usernode = $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2603 }
3406acde 2604 return $usernode;
7d2a0492 2605 }
2606
2607 /**
2608 * This function gets called by {@link load_user_settings()} and actually works out
2609 * what can be shown/done
2610 *
2611 * @param int $courseid The current course' id
2612 * @param int $userid The user id to load for
2613 * @param string $gstitle The string to pass to get_string for the branch title
3406acde 2614 * @return navigation_node|false
7d2a0492 2615 */
2616 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
507a7a9a 2617 global $DB, $CFG, $USER, $SITE;
7d2a0492 2618
507a7a9a
SH
2619 if ($courseid != SITEID) {
2620 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
2621 $course = $this->page->course;
2622 } else {
2623 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
2624 }
2625 } else {
2626 $course = $SITE;
7d2a0492 2627 }
2628
2629 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
507a7a9a 2630 $systemcontext = get_system_context();
7d2a0492 2631 $currentuser = ($USER->id == $userid);
4f0c2d00 2632
7d2a0492 2633 if ($currentuser) {
2634 $user = $USER;
2635 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2636 } else {
7a7e209d 2637 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
7d2a0492 2638 return false;
2639 }
2640 // Check that the user can view the profile
2641 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2642 if ($course->id==SITEID) {
4f0c2d00 2643 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
7d2a0492 2644 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
2645 return false;
2646 }
2647 } else {
4f0c2d00 2648 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
7d2a0492 2649 return false;
2650 }
2651 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
2652 // If groups are in use, make sure we can see that group
2653 return false;
2654 }
2655 }
2656 }
2657
2658 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
2659
2660 // Add a user setting branch
3406acde 2661 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname));
7d2a0492 2662 $usersetting->id = 'usersettings';
2663
7d2a0492 2664 // Check if the user has been deleted
2665 if ($user->deleted) {
2666 if (!has_capability('moodle/user:update', $coursecontext)) {
2667 // We can't edit the user so just show the user deleted message
d972bad1 2668 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
7d2a0492 2669 } else {
2670 // We can edit the user so show the user deleted message and link it to the profile
a6855934 2671 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 2672 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
7d2a0492 2673 }
2674 return true;
2675 }
2676
7d2a0492 2677 // Add the profile edit link
2678 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
7a7e209d 2679 if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
a6855934 2680 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
7a7e209d 2681 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 2682 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
a6855934 2683 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 2684 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 2685 }
2686 }
2687
2688 // Change password link
2689 if (!empty($user->auth)) {
2690 $userauth = get_auth_plugin($user->auth);
2691 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
2692 $passwordchangeurl = $userauth->change_password_url();
2693 if (!$passwordchangeurl) {
2694 if (empty($CFG->loginhttps)) {
2695 $wwwroot = $CFG->wwwroot;
2696 } else {
2697 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2698 }
a6855934 2699 $passwordchangeurl = new moodle_url('/login/change_password.php');
7d2a0492 2700 } else {
2701 $urlbits = explode($passwordchangeurl. '?', 1);
2702 $passwordchangeurl = new moodle_url($urlbits[0]);
2703 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
2704 foreach ($matches as $pair) {
2705 $fullmeurl->param($pair[1],$pair[2]);
2706 }
2707 }
2708 }
2709 $passwordchangeurl->param('id', $course->id);
d972bad1 2710 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
7d2a0492 2711 }
2712 }
2713
2714 // View the roles settings
2715 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3406acde 2716 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
7d2a0492 2717
a6855934 2718 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2719 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2720
2721 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
7d2a0492 2722
2723 if (!empty($assignableroles)) {
a6855934 2724 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2725 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2726 }
2727
0b29477b
SH
2728 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
2729 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2730 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2731 }
2732
a6855934 2733 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2734 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2735 }
2736
2737 // Portfolio
7a7e209d 2738 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
24ba58ee
PL
2739 require_once($CFG->libdir . '/portfoliolib.php');
2740 if (portfolio_instances(true, false)) {
3406acde
SH
2741 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
2742 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
2743 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
24ba58ee 2744 }
7d2a0492 2745 }
2746
94e90ab7 2747 // Security keys
de7a00a4 2748 if ($currentuser && !is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $systemcontext)) {
a6855934 2749 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
94e90ab7 2750 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5eacbd4b 2751 }
2752
7d2a0492 2753 // Repository
2754 if (!$currentuser) {
2755 require_once($CFG->dirroot . '/repository/lib.php');
2756 $editabletypes = repository::get_editable_types($usercontext);
2757 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
a6855934 2758 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
d972bad1 2759 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
7d2a0492 2760 }
2761 }
2762
2763 // Messaging
7a7e209d 2764 if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
a6855934 2765 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 2766 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
7d2a0492 2767 }
2768
3406acde 2769 return $usersetting;
7d2a0492 2770 }
2771
0b29477b
SH
2772 /**
2773 * Loads block specific settings in the navigation
4f0c2d00 2774 *
3406acde 2775 * @return navigation_node
0b29477b
SH
2776 */
2777 protected function load_block_settings() {
2778 global $CFG;
2779
3406acde
SH
2780 $blocknode = $this->add(print_context_name($this->context));
2781 $blocknode->force_open();
0b29477b
SH
2782
2783 // Assign local roles
2784 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2785 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2786
2787 // Override roles
2788 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2789 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2790 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2791 }
2792 // Check role permissions
2793 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2794 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2795 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2796 }
2797
3406acde 2798 return $blocknode;
0b29477b
SH
2799 }
2800
2801 /**
2802 * Loads category specific settings in the navigation
2803 *
3406acde 2804 * @return navigation_node
0b29477b
SH
2805 */
2806 protected function load_category_settings() {
2807 global $CFG;
2808
ba9dc077
SH
2809 $categorynode = $this->add(print_context_name($this->context));
2810 $categorynode->force_open();
0b29477b
SH
2811
2812 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
ba9dc077
SH
2813 $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid)));
2814 $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid)));
0b29477b
SH
2815 }
2816
2817 // Assign local roles
2818 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
ba9dc077 2819 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
0b29477b
SH
2820
2821 // Override roles
2822 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2823 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
ba9dc077 2824 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
0b29477b
SH
2825 }
2826 // Check role permissions
2827 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2828 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
ba9dc077
SH
2829 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2830 }
2831 // Manage filters
2832 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
2833 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
2834 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
0b29477b
SH
2835 }
2836
ba9dc077 2837 return $categorynode;
0b29477b
SH
2838 }
2839
7d2a0492 2840 /**
2841 * Determine whether the user is assuming another role
2842 *
2843 * This function checks to see if the user is assuming another role by means of
2844 * role switching. In doing this we compare each RSW key (context path) against
2845 * the current context path. This ensures that we can provide the switching
2846 * options against both the course and any page shown under the course.
2847 *
2848 * @return bool|int The role(int) if the user is in another role, false otherwise
2849 */
2850 protected function in_alternative_role() {
2851 global $USER;
2852 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
2853 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
2854 return $USER->access['rsw'][$this->page->context->path];
2855 }
2856 foreach ($USER->access['rsw'] as $key=>$role) {
2857 if (strpos($this->context->path,$key)===0) {
2858 return $role;
2859 }
2860 }
2861 }
2862 return false;
2863 }
2864
2865 /**
2e7f1f79 2866 * This function loads all of the front page settings into the settings navigation.
2867 * This function is called when the user is on the front page, or $COURSE==$SITE
3406acde 2868 * @return navigation_node
7d2a0492 2869 */
0b29477b
SH
2870 protected function load_front_page_settings($forceopen = false) {
2871 global $SITE, $CFG;
7d2a0492 2872
0b29477b 2873 $course = clone($SITE);
4f0c2d00 2874 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
7d2a0492 2875
3406acde
SH
2876 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
2877 if ($forceopen) {
2878 $frontpage->force_open();
2879 }
0b29477b 2880 $frontpage->id = 'frontpagesettings';
507a7a9a 2881
4f0c2d00 2882 if (has_capability('moodle/course:update', $coursecontext)) {
7d2a0492 2883
2884 // Add the turn on/off settings
a6855934 2885 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
7d2a0492 2886 if ($this->page->user_is_editing()) {
2887 $url->param('edit', 'off');
2888 $editstring = get_string('turneditingoff');
2889 } else {
2890 $url->param('edit', 'on');
2891 $editstring = get_string('turneditingon');
2892 }
507a7a9a 2893 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
7d2a0492 2894
2895 // Add the course settings link
a6855934 2896 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
507a7a9a 2897 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
7d2a0492 2898 }
2e7f1f79 2899
2900 //Participants
4f0c2d00
PS
2901 if (has_capability('moodle/site:viewparticipants', $coursecontext)) {
2902 $url = new moodle_url('/user/index.php', array('contextid'=>$coursecontext->id));
507a7a9a 2903 $frontpage->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/users', ''));
2e7f1f79 2904 }
7d2a0492 2905
0b29477b 2906 // Roles
4f0c2d00 2907 if (has_capability('moodle/role:assign', $coursecontext)) {
0b29477b 2908 // Add assign or override roles if allowed
4f0c2d00 2909 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2910 $frontpage->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2911 // Override roles
4f0c2d00
PS
2912 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2913 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2914 $frontpage->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2915 }
2916 // Check role permissions
4f0c2d00
PS
2917 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2918 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2919 $frontpage->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2920 }
2921 // Manage filters
4f0c2d00
PS
2922 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2923 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2924 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2925 }
2926 }
2927
2928 // Backup this course
4f0c2d00 2929 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
0b29477b
SH
2930 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2931 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2932 }
2933
2934 // Restore to this course
4f0c2d00 2935 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
0b29477b
SH
2936 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2937 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2938 }
2939
2940 // Manage questions
2941 $questioncaps = array('moodle/question:add',
2942 'moodle/question:editmine',
2943 'moodle/question:editall',
2944 'moodle/question:viewmine',
2945 'moodle/question:viewall',
2946 'moodle/question:movemine',
2947 'moodle/question:moveall');
2948 if (has_any_capability($questioncaps, $this->context)) {
2949 $questionlink = $CFG->wwwroot.'/question/edit.php';
2950 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2951 $questionlink = $CFG->wwwroot.'/question/category.php';
2952 }
2953 if (isset($questionlink)) {
2954 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
2955 $frontpage->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
2956 }
2957
2958 // Manage files
2959 if (has_capability('moodle/course:managefiles', $this->context)) {
2960 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
2961 $frontpage->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
2962 }
3406acde 2963 return $frontpage;
7d2a0492 2964 }
f5b5a822 2965
2966 /**
2967 * This function marks the cache as volatile so it is cleared during shutdown
2968 */
2969 public function clear_cache() {
2970 $this->cache->volatile();
2971 }
7d2a0492 2972}
2973
2974/**
2975 * Simple class used to output a navigation branch in XML
2976 *
2977 * @package moodlecore
babb3911 2978 * @subpackage navigation
7d2a0492 2979 * @copyright 2009 Sam Hemelryk
2980 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2981 */
507a7a9a 2982class navigation_json {
7d2a0492 2983 /** @var array */
2984 protected $nodetype = array('node','branch');
2985 /** @var array */
2986 protected $expandable = array();
2987 /**
2988 * Turns a branch and all of its children into XML
2989 *
2990 * @param navigation_node $branch
2991 * @return string XML string
2992 */
2993 public function convert($branch) {
2994 $xml = $this->convert_child($branch);
2995 return $xml;
2996 }
2997 /**
2998 * Set the expandable items in the array so that we have enough information
2999 * to attach AJAX events
3406acde 3000 * @param array $expandable
7d2a0492 3001 */
3002 public function set_expandable($expandable) {
3003 foreach ($expandable as $node) {
3004 $this->expandable[(string)$node['branchid']] = $node;
3005 }
3006 }
3007 /**
3008 * Recusively converts a child node and its children to XML for output
3009 *
3010 * @param navigation_node $child The child to convert
3011 * @param int $depth Pointlessly used to track the depth of the XML structure
3406acde 3012 * @return string JSON
7d2a0492 3013 */
3014 protected function convert_child($child, $depth=1) {
3015 global $OUTPUT;
3016
3017 if (!$child->display) {
3018 return '';
3019 }
3020 $attributes = array();
3021 $attributes['id'] = $child->id;
507a7a9a 3022 $attributes['name'] = $child->text;
7d2a0492 3023 $attributes['type'] = $child->type;
3024 $attributes['key'] = $child->key;
7d2a0492 3025 $attributes['class'] = $child->get_css_type();
7da3a799
SH
3026
3027 if ($child->icon instanceof pix_icon) {
3028 $attributes['icon'] = array(
3029 'component' => $child->icon->component,
3030 'pix' => $child->icon->pix,
3031 );
3032 foreach ($child->icon->attributes as $key=>$value) {
3033 if ($key == 'class') {
3034 $attributes['icon']['classes'] = explode(' ', $value);
3035 } else if (!array_key_exists($key, $attributes['icon'])) {
3036 $attributes['icon'][$key] = $value;
3037 }
3038
3039 }
3040 } else if (!empty($child->icon)) {
3041 $attributes['icon'] = (string)$child->icon;
3042 }
3043
7d2a0492 3044 if ($child->forcetitle || $child->title !== $child->text) {
3045 $attributes['title'] = htmlentities($child->title);
3046 }
3047 if (array_key_exists((string)$child->key, $this->expandable)) {
3048 $attributes['expandable'] = $child->key;
3049 $child->add_class($this->expandable[$child->key]['id']);
3050 }
6644741d 3051
7d2a0492 3052 if (count($child->classes)>0) {
3053 $attributes['class'] .= ' '.join(' ',$child->classes);
3054 }
3055 if (is_string($child->action)) {
3056 $attributes['link'] = $child->action;
3057 } else if ($child->action instanceof moodle_url) {
3058 $attributes['link'] = $child->action->out();
3059 }
3060 $attributes['hidden'] = ($child->hidden);
3406acde 3061 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
7d2a0492 3062
7d2a0492 3063 if (count($child->children)>0) {
507a7a9a 3064 $attributes['children'] = array();
7d2a0492 3065 foreach ($child->children as $subchild) {
507a7a9a 3066 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
7d2a0492 3067 }
7d2a0492 3068 }
507a7a9a
SH
3069
3070 if ($depth > 1) {
3071 return $attributes;
3072 } else {
3073 return json_encode($attributes);
3074 }
7d2a0492 3075 }
3076}
3077
3078/**
3079 * The cache class used by global navigation and settings navigation to cache bits
3080 * and bobs that are used during their generation.
3081 *
3082 * It is basically an easy access point to session with a bit of smarts to make
3083 * sure that the information that is cached is valid still.
3084 *
3085 * Example use:
3086 * <code php>
3087 * if (!$cache->viewdiscussion()) {
3088 * // Code to do stuff and produce cachable content
3089 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3090 * }
3091 * $content = $cache->viewdiscussion;
3092 * </code>
3093 *
3094 * @package moodlecore
babb3911 3095 * @subpackage navigation
7d2a0492 3096 * @copyright 2009 Sam Hemelryk
3097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3098 */
3099class navigation_cache {
3100 /** @var int */
3101 protected $creation;
3102 /** @var array */
3103 protected $session;
3104 /** @var string */
3105 protected $area;
3106 /** @var int */
3107 protected $timeout;
3108 /** @var stdClass */
3109 protected $currentcontext;
3110 /** @var int */
3111 const CACHETIME = 0;
3112 /** @var int */
3113 const CACHEUSERID = 1;
3114 /** @var int */
3115 const CACHEVALUE = 2;
f5b5a822 3116 /** @var null|array An array of navigation cache areas to expire on shutdown */
3117 public static $volatilecaches;
117bd748 3118
7d2a0492 3119 /**
3120 * Contructor for the cache. Requires two arguments
3121 *
3122 * @param string $area The string to use to segregate this particular cache
3123 * it can either be unique to start a fresh cache or if you want
3124 * to share a cache then make it the string used in the original
3125 * cache
3126 * @param int $timeout The number of seconds to time the information out after
3127 */
3128 public function __construct($area, $timeout=60) {
507a7a9a 3129 global $SESSION;
7d2a0492 3130 $this->creation = time();
3131 $this->area = $area;
3132
3133 if (!isset($SESSION->navcache)) {
3134 $SESSION->navcache = new stdClass;
3135 }
3136
3137 if (!isset($SESSION->navcache->{$area})) {
3138 $SESSION->navcache->{$area} = array();
3139 }
3140 $this->session = &$SESSION->navcache->{$area};
3141 $this->timeout = time()-$timeout;
3142 if (rand(0,10)===0) {
3143 $this->garbage_collection();
3144 }
3145 }
3146
3147 /**
3148 * Magic Method to retrieve something by simply calling using = cache->key
3149 *
3150 * @param mixed $key The identifier for the information you want out again
3151 * @return void|mixed Either void or what ever was put in
3152 */
3153 public function __get($key) {
3154 if (!$this->cached($key)) {
3155 return;
3156 }
3157 $information = $this->session[$key][self::CACHEVALUE];
3158 return unserialize($information);
3159 }
3160
3161 /**
3162 * Magic method that simply uses {@link set();} to store something in the cache
3163 *
3164 * @param string|int $key
3165 * @param mixed $information
3166 */
3167 public function __set($key, $information) {
3168 $this->set($key, $information);
3169 }
f5b5a822 3170
7d2a0492 3171 /**
3172 * Sets some information against the cache (session) for later retrieval
3173 *
3174 * @param string|int $key
3175 * @param mixed $information
3176 */
3177 public function set($key, $information) {
3178 global $USER;
3179 $information = serialize($information);
3180 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
3181 }
3182 /**
3183 * Check the existence of the identifier in the cache
3184 *
3185 * @param string|int $key
3186 * @return bool
3187 */
3188 public function cached($key) {
3189 global $USER;
3190 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
3191 return false;
3192 }
3193 return true;
3194 }
fdd35767 3195 /**
3196 * Compare something to it's equivilant in the cache
3197 *
3198 * @param string $key
3199 * @param m