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