navigation MDL-22322 Icons not used for navigation branches and fixed indenting of...
[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() {
489 if ($this->forcetitle || ($this->shorttext!==null && $this->title !== $this->shorttext) || $this->title !== $this->text) {
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 }
0e3eee62 2096 }
3406acde 2097 return $referencebranch;
8140c440 2098 } else if ($adminbranch->check_access()) {
7d2a0492 2099 // We have a reference branch that we can access and is not hidden `hurrah`
2100 // Now we need to display it and any children it may have
2101 $url = null;
2102 $icon = null;
2103 if ($adminbranch instanceof admin_settingpage) {
a6855934 2104 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
7d2a0492 2105 } else if ($adminbranch instanceof admin_externalpage) {
2106 $url = $adminbranch->url;
2107 }
2108
2109 // Add the branch
3406acde 2110 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
8140c440 2111
2112 if ($adminbranch->is_hidden()) {
d9d2817a
SH
2113 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2114 $reference->add_class('hidden');
2115 } else {
2116 $reference->display = false;
2117 }
8140c440 2118 }
2119
7d2a0492 2120 // Check if we are generating the admin notifications and whether notificiations exist
2121 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2122 $reference->add_class('criticalnotification');
2123 }
2124 // Check if this branch has children
2125 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2126 foreach ($adminbranch->children as $branch) {
2127 // Generate the child branches as well now using this branch as the reference
459e384e 2128 $this->load_administration_settings($reference, $branch);
7d2a0492 2129 }
2130 } else {
f9fc1461 2131 $reference->icon = new pix_icon('i/settings', '');
7d2a0492 2132 }
2133 }
2134 }
2135
3406acde
SH
2136 /**
2137 * Gets a navigation node given an array of keys that represent the path to
2138 * the desired node.
2139 *
2140 * @param array $path
2141 * @return navigation_node|false
2142 */
2143 protected function get_by_path(array $path) {
2144 $node = $this->get(array_shift($path));
2145 foreach ($path as $key) {
2146 $node->get($key);
2147 }
2148 return $node;
2149 }
2150
7d2a0492 2151 /**
2152 * Generate the list of modules for the given course.
2153 *
2154 * The array of resources and activities that can be added to a course is then
2155 * stored in the cache so that we can access it for anywhere.
2156 * It saves us generating it all the time
2157 *
2158 * <code php>
2159 * // To get resources:
2160 * $this->cache->{'course'.$courseid.'resources'}
2161 * // To get activities:
2162 * $this->cache->{'course'.$courseid.'activities'}
2163 * </code>
2164 *
2165 * @param stdClass $course The course to get modules for
2166 */
2167 protected function get_course_modules($course) {
2168 global $CFG;
2169 $mods = $modnames = $modnamesplural = $modnamesused = array();
2170 // This function is included when we include course/lib.php at the top
2171 // of this file
2172 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2173 $resources = array();
2174 $activities = array();
2175 foreach($modnames as $modname=>$modnamestr) {
2176 if (!course_allowed_module($course, $modname)) {
2177 continue;
2178 }
2179
2180 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2181 if (!file_exists($libfile)) {
2182 continue;
2183 }
2184 include_once($libfile);
2185 $gettypesfunc = $modname.'_get_types';
2186 if (function_exists($gettypesfunc)) {
2187 $types = $gettypesfunc();
2188 foreach($types as $type) {
2189 if (!isset($type->modclass) || !isset($type->typestr)) {
2190 debugging('Incorrect activity type in '.$modname);
2191 continue;
2192 }
2193 if ($type->modclass == MOD_CLASS_RESOURCE) {
2194 $resources[html_entity_decode($type->type)] = $type->typestr;
2195 } else {
2196 $activities[html_entity_decode($type->type)] = $type->typestr;
2197 }
2198 }
2199 } else {
2200 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2201 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2202 $resources[$modname] = $modnamestr;
2203 } else {
2204 // all other archetypes are considered activity
2205 $activities[$modname] = $modnamestr;
2206 }
2207 }
2208 }
2209 $this->cache->{'course'.$course->id.'resources'} = $resources;
2210 $this->cache->{'course'.$course->id.'activities'} = $activities;
2211 }
2212
2213 /**
2214 * This function loads the course settings that are available for the user
2215 *
0b29477b 2216 * @param bool $forceopen If set to true the course node will be forced open
3406acde 2217 * @return navigation_node|false
7d2a0492 2218 */
0b29477b 2219 protected function load_course_settings($forceopen = false) {
4f0c2d00 2220 global $CFG, $USER, $SESSION, $OUTPUT;
7d2a0492 2221
2222 $course = $this->page->course;
4f0c2d00 2223 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
7d2a0492 2224 if (!$this->cache->cached('canviewcourse'.$course->id)) {
4f0c2d00 2225 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
7d2a0492 2226 }
2227 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2228 return false;
2229 }
2230
3406acde
SH
2231 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2232 if ($forceopen) {
2233 $coursenode->force_open();
2234 }
117bd748 2235
4f0c2d00 2236 if (has_capability('moodle/course:update', $coursecontext)) {
7d2a0492 2237 // Add the turn on/off settings
a6855934 2238 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
7d2a0492 2239 if ($this->page->user_is_editing()) {
2240 $url->param('edit', 'off');
2241 $editstring = get_string('turneditingoff');
2242 } else {
2243 $url->param('edit', 'on');
2244 $editstring = get_string('turneditingon');
2245 }
f9fc1461 2246 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
7d2a0492 2247
7d2a0492 2248 if ($this->page->user_is_editing()) {
2249 // Add `add` resources|activities branches
2250 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2251 if (file_exists($structurefile)) {
2252 require_once($structurefile);
2253 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2254 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2255 } else {
2256 $formatstring = get_string('topic');
2257 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2258 }
2259 if (!$this->cache->cached('coursesections'.$course->id)) {
2260 $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
2261 }
2262 $sections = $this->cache->{'coursesections'.$course->id};
117bd748 2263
3406acde
SH
2264 $addresource = $this->add(get_string('addresource'));
2265 $addactivity = $this->add(get_string('addactivity'));
7d2a0492 2266 if ($formatidentifier!==0) {
3406acde
SH
2267 $addresource->force_open();
2268 $addactivity->force_open();
7d2a0492 2269 }
2270
2271 if (!$this->cache->cached('course'.$course->id.'resources')) {
459e384e 2272 $this->get_course_modules($course);
7d2a0492 2273 }
2274 $resources = $this->cache->{'course'.$course->id.'resources'};
2275 $activities = $this->cache->{'course'.$course->id.'activities'};
117bd748 2276
9cf45d02
SH
2277 $textlib = textlib_get_instance();
2278
7d2a0492 2279 foreach ($sections as $section) {
2280 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2281 continue;
2282 }
a6855934 2283 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
7d2a0492 2284 if ($section->section == 0) {
d972bad1 2285 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2286 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
7d2a0492 2287 } else {
d972bad1 2288 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2289 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
7d2a0492 2290 }
2291 foreach ($resources as $value=>$resource) {
a6855934 2292 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2293 $pos = strpos($value, '&type=');
2294 if ($pos!==false) {
9cf45d02
SH
2295 $url->param('add', $textlib->substr($value, 0,$pos));
2296 $url->param('type', $textlib->substr($value, $pos+6));
7d2a0492 2297 } else {
2298 $url->param('add', $value);
2299 }
3406acde 2300 $sectionresources->add($resource, $url, self::TYPE_SETTING);
7d2a0492 2301 }
2302 $subbranch = false;
2303 foreach ($activities as $activityname=>$activity) {
2304 if ($activity==='--') {
2305 $subbranch = false;
2306 continue;
2307 }
2308 if (strpos($activity, '--')===0) {
3406acde 2309 $subbranch = $sectionresources->add(trim($activity, '-'));
7d2a0492 2310 continue;
2311 }
a6855934 2312 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
7d2a0492 2313 $pos = strpos($activityname, '&type=');
2314 if ($pos!==false) {
9cf45d02
SH
2315 $url->param('add', $textlib->substr($activityname, 0,$pos));
2316 $url->param('type', $textlib->substr($activityname, $pos+6));
7d2a0492 2317 } else {
2318 $url->param('add', $activityname);
2319 }
2320 if ($subbranch !== false) {
3406acde 2321 $subbranch->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2322 } else {
3406acde 2323 $sectionresources->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2324 }
2325 }
2326 }
2327 }
2328
2329 // Add the course settings link
a6855934 2330 $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
f9fc1461 2331 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2be4d090
MD
2332
2333 // Add the course completion settings link
2334 if ($CFG->enablecompletion && $course->enablecompletion) {
2335 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
2336 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2337 }
7d2a0492 2338 }
117bd748 2339
4f0c2d00 2340 if (has_capability('moodle/role:assign', $coursecontext)) {
0b29477b 2341 // Add assign or override roles if allowed
4f0c2d00 2342 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
f9fc1461 2343 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
0b29477b 2344 // Override roles
4f0c2d00
PS
2345 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2346 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2347 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2348 }
2349 // Check role permissions
4f0c2d00
PS
2350 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2351 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2352 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2353 }
2354 // Manage filters
4f0c2d00
PS
2355 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2356 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2357 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2358 }
7d2a0492 2359 }
2360
2361 // Add view grade report is permitted
2362 $reportavailable = false;
4f0c2d00 2363 if (has_capability('moodle/grade:viewall', $coursecontext)) {
7d2a0492 2364 $reportavailable = true;
2365 } else if (!empty($course->showgrades)) {
2366 $reports = get_plugin_list('gradereport');
2367 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2368 arsort($reports); // user is last, we want to test it first
2369 foreach ($reports as $plugin => $plugindir) {
4f0c2d00 2370 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
7d2a0492 2371 //stop when the first visible plugin is found
2372 $reportavailable = true;
2373 break;
2374 }
2375 }
2376 }
2377 }
2378 if ($reportavailable) {
a6855934 2379 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
b499db57 2380 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
7d2a0492 2381 }
2382
2383 // Add outcome if permitted
4f0c2d00 2384 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
a6855934 2385 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
f9fc1461 2386 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/outcomes', ''));
7d2a0492 2387 }
2388
2389 // Add meta course links
2390 if ($course->metacourse) {
4f0c2d00 2391 if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
a6855934 2392 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
f9fc1461 2393 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
4f0c2d00 2394 } else if (has_capability('moodle/role:assign', $coursecontext)) {
3406acde
SH
2395 $roleassign = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2396 $roleassign->hidden = true;
7d2a0492 2397 }
2398 }
2399
2400 // Manage groups in this course
4f0c2d00 2401 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
a6855934 2402 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
f9fc1461 2403 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/group', ''));
7d2a0492 2404 }
2405
7d2a0492 2406 // Backup this course
4f0c2d00 2407 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
a6855934 2408 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
f9fc1461 2409 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
7d2a0492 2410 }
2411
2412 // Restore to this course
4f0c2d00 2413 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
a6855934 2414 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
530fa981 2415 $url = null; // Disabled until restore is implemented. MDL-21432
f9fc1461 2416 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
7d2a0492 2417 }
2418
2419 // Import data from other courses
4f0c2d00 2420 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
a6855934 2421 $url = new moodle_url('/course/import.php', array('id'=>$course->id));
530fa981 2422 $url = null; // Disabled until restore is implemented. MDL-21432
f9fc1461 2423 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
7d2a0492 2424 }
2425
07ab0c80 2426 // Publish course on a hub
2427 if (has_capability('moodle/course:publish', $coursecontext)) {
2428 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
2429 $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/publish', ''));
2430 }
2431
7d2a0492 2432 // Reset this course
4f0c2d00 2433 if (has_capability('moodle/course:reset', $coursecontext)) {
a6855934 2434 $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
f9fc1461 2435 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
7d2a0492 2436 }
7d2a0492 2437
2438 // Manage questions
2439 $questioncaps = array('moodle/question:add',
2440 'moodle/question:editmine',
2441 'moodle/question:editall',
2442 'moodle/question:viewmine',
2443 'moodle/question:viewall',
2444 'moodle/question:movemine',
2445 'moodle/question:moveall');
2446 if (has_any_capability($questioncaps, $this->context)) {
2447 $questionlink = $CFG->wwwroot.'/question/edit.php';
2448 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2449 $questionlink = $CFG->wwwroot.'/question/category.php';
2450 }
2451 if (isset($questionlink)) {
2452 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
f9fc1461 2453 $coursenode->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
7d2a0492 2454 }
2455
2456 // Repository Instances
2457 require_once($CFG->dirroot.'/repository/lib.php');
2458 $editabletypes = repository::get_editable_types($this->context);
2459 if (has_capability('moodle/course:update', $this->context) && !empty($editabletypes)) {
a6855934 2460 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$this->context->id));
f9fc1461 2461 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
7d2a0492 2462 }
2463
2464 // Manage files
2465 if (has_capability('moodle/course:managefiles', $this->context)) {
a6855934 2466 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
f9fc1461 2467 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
7d2a0492 2468 }
2469
2470 // Authorize hooks
2471 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2472 require_once($CFG->dirroot.'/enrol/authorize/const.php');
a6855934 2473 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
f9fc1461 2474 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2475 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2476 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2477 if ($cnt) {
a6855934 2478 $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
f9fc1461 2479 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
7d2a0492 2480 }
2481 }
2482 }
2483
2484 // Unenrol link
4f0c2d00
PS
2485 if (empty($course->metacourse) && ($course->id!==SITEID)) {
2486 if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2487 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
2488 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2489 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2490 }
2491
2492 } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2493 // inspector, manager, etc. - do not show anything
2494 } else {
2495 // access because otherwise they would not get into this course at all
2496 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2497 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
7d2a0492 2498 }
2499 }
2500
7d2a0492 2501 // Switch roles
2502 $roles = array();
2503 $assumedrole = $this->in_alternative_role();
2504 if ($assumedrole!==false) {
2505 $roles[0] = get_string('switchrolereturn');
2506 }
2507 if (has_capability('moodle/role:switchroles', $this->context)) {
2508 $availableroles = get_switchable_roles($this->context);
2509 if (is_array($availableroles)) {
2510 foreach ($availableroles as $key=>$role) {
2511 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2512 continue;
2513 }
2514 $roles[$key] = $role;
2515 }
2516 }
2517 }
2518 if (is_array($roles) && count($roles)>0) {
3406acde 2519 $switchroles = $this->add(get_string('switchroleto'));
7d2a0492 2520 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3406acde 2521 $switchroles->force_open();
7d2a0492 2522 }
2523 $returnurl = $this->page->url;
2524 $returnurl->param('sesskey', sesskey());
2525 $SESSION->returnurl = serialize($returnurl);
2526 foreach ($roles as $key=>$name) {
a6855934 2527 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
3406acde 2528 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
7d2a0492 2529 }
2530 }
2531 // Return we are done
3406acde 2532 return $coursenode;
7d2a0492 2533 }
2534
2535 /**
2536 * This function calls the module function to inject module settings into the
2537 * settings navigation tree.
2538 *
2539 * This only gets called if there is a corrosponding function in the modules
2540 * lib file.
2541 *
2542 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2543 *
3406acde 2544 * @return navigation_node|false
7d2a0492 2545 */
2546 protected function load_module_settings() {
507a7a9a 2547 global $CFG;
4dd5bce8 2548
2549 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
0b29477b 2550 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
507a7a9a 2551 $this->page->set_cm($cm, $this->page->course);
4dd5bce8 2552 }
2553
3406acde
SH
2554 $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2555 $modulenode->force_open();
4f0c2d00 2556
0b29477b
SH
2557 // Settings for the module
2558 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2559 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2560 $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2561 }
2562 // Assign local roles
2563 if (count(get_assignable_roles($this->page->cm->context))>0) {
2564 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2565 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2566 }
2567 // Override roles
2568 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2569 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2570 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2571 }
2572 // Check role permissions
2573 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2574 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2575 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2576 }
2577 // Manage filters
2578 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2579 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2580 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2581 }
4f0c2d00 2582
59c7680f
SH
2583 // Add a backup link
2584 $featuresfunc = $this->page->activityname.'_supports';
2585 if ($featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
2586 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
2587 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING);
2588 }
2589
507a7a9a
SH
2590 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2591 $function = $this->page->activityname.'_extend_settings_navigation';
117bd748 2592
7d2a0492 2593 if (file_exists($file)) {
2594 require_once($file);
2595 }
2596 if (!function_exists($function)) {
3406acde 2597 return $modulenode;
7d2a0492 2598 }
0b29477b
SH
2599
2600 $function($this, $modulenode);
2601
2602 // Remove the module node if there are no children
2603 if (empty($modulenode->children)) {
3406acde 2604 $modulenode->remove();
0b29477b
SH
2605 }
2606
3406acde 2607 return $modulenode;
7d2a0492 2608 }
2609
2610 /**
2611 * Loads the user settings block of the settings nav
117bd748 2612 *
7d2a0492 2613 * This function is simply works out the userid and whether we need to load
117bd748 2614 * just the current users profile settings, or the current user and the user the
7d2a0492 2615 * current user is viewing.
117bd748 2616 *
7d2a0492 2617 * This function has some very ugly code to work out the user, if anyone has
2618 * any bright ideas please feel free to intervene.
2619 *
2620 * @param int $courseid The course id of the current course
3406acde 2621 * @return navigation_node|false
7d2a0492 2622 */
2623 protected function load_user_settings($courseid=SITEID) {
0b29477b 2624 global $USER, $FULLME, $CFG;
7d2a0492 2625
2626 if (isguestuser() || !isloggedin()) {
2627 return false;
2628 }
2629
2630 // This is terribly ugly code, but I couldn't see a better way around it
2631 // we need to pick up the user id, it can be the current user or someone else
2632 // and the key depends on the current location
2633 // Default to look at id
2634 $userkey='id';
0b29477b
SH
2635 if (strpos($FULLME,'/blog/') || strpos($FULLME, $CFG->admin.'/roles/')) {
2636 // And blog and roles just do thier own thing using `userid`
2637 $userkey = 'userid';
3406acde 2638 } else if ($this->context->contextlevel >= CONTEXT_COURSECAT && strpos($FULLME, '/message/')===false && strpos($FULLME, '/mod/forum/user')===false && strpos($FULLME, '/user/editadvanced')===false) {
7d2a0492 2639 // If we have a course context and we are not in message or forum
2640 // Message and forum both pick the user up from `id`
2641 $userkey = 'user';
7d2a0492 2642 }
2643
2644 $userid = optional_param($userkey, $USER->id, PARAM_INT);
2645 if ($userid!=$USER->id) {
3406acde 2646 $usernode = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
0b29477b 2647 $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2648 } else {
3406acde 2649 $usernode = $this->generate_user_settings($courseid, $USER->id);
7d2a0492 2650 }
3406acde 2651 return $usernode;
7d2a0492 2652 }
2653
2654 /**
2655 * This function gets called by {@link load_user_settings()} and actually works out
2656 * what can be shown/done
2657 *
2658 * @param int $courseid The current course' id
2659 * @param int $userid The user id to load for
2660 * @param string $gstitle The string to pass to get_string for the branch title
3406acde 2661 * @return navigation_node|false
7d2a0492 2662 */
2663 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
507a7a9a 2664 global $DB, $CFG, $USER, $SITE;
7d2a0492 2665
507a7a9a
SH
2666 if ($courseid != SITEID) {
2667 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
2668 $course = $this->page->course;
2669 } else {
2670 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
2671 }
2672 } else {
2673 $course = $SITE;
7d2a0492 2674 }
2675
2676 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
507a7a9a 2677 $systemcontext = get_system_context();
7d2a0492 2678 $currentuser = ($USER->id == $userid);
4f0c2d00 2679
7d2a0492 2680 if ($currentuser) {
2681 $user = $USER;
2682 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2683 } else {
7a7e209d 2684 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
7d2a0492 2685 return false;
2686 }
2687 // Check that the user can view the profile
2688 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
2689 if ($course->id==SITEID) {
4f0c2d00 2690 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
7d2a0492 2691 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
2692 return false;
2693 }
2694 } else {
4f0c2d00 2695 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
7d2a0492 2696 return false;
2697 }
2698 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
2699 // If groups are in use, make sure we can see that group
2700 return false;
2701 }
2702 }
2703 }
2704
2705 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
2706
2707 // Add a user setting branch
3406acde 2708 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname));
7d2a0492 2709 $usersetting->id = 'usersettings';
2710
7d2a0492 2711 // Check if the user has been deleted
2712 if ($user->deleted) {
2713 if (!has_capability('moodle/user:update', $coursecontext)) {
2714 // We can't edit the user so just show the user deleted message
d972bad1 2715 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
7d2a0492 2716 } else {
2717 // We can edit the user so show the user deleted message and link it to the profile
03d9401e
MD
2718 if ($course->id == SITEID) {
2719 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
2720 } else {
2721 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
2722 }
d972bad1 2723 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
7d2a0492 2724 }
2725 return true;
2726 }
2727
7d2a0492 2728 // Add the profile edit link
2729 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
7a7e209d 2730 if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
a6855934 2731 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
7a7e209d 2732 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 2733 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
a6855934 2734 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 2735 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 2736 }
2737 }
2738
2739 // Change password link
2740 if (!empty($user->auth)) {
2741 $userauth = get_auth_plugin($user->auth);
2742 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
2743 $passwordchangeurl = $userauth->change_password_url();
2744 if (!$passwordchangeurl) {
2745 if (empty($CFG->loginhttps)) {
2746 $wwwroot = $CFG->wwwroot;
2747 } else {
2748 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2749 }
a6855934 2750 $passwordchangeurl = new moodle_url('/login/change_password.php');
7d2a0492 2751 } else {
2752 $urlbits = explode($passwordchangeurl. '?', 1);
2753 $passwordchangeurl = new moodle_url($urlbits[0]);
2754 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
2755 foreach ($matches as $pair) {
2756 $fullmeurl->param($pair[1],$pair[2]);
2757 }
2758 }
2759 }
2760 $passwordchangeurl->param('id', $course->id);
d972bad1 2761 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
7d2a0492 2762 }
2763 }
2764
2765 // View the roles settings
2766 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3406acde 2767 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
7d2a0492 2768
a6855934 2769 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2770 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2771
2772 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
7d2a0492 2773
2774 if (!empty($assignableroles)) {
a6855934 2775 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2776 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2777 }
2778
0b29477b
SH
2779 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
2780 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2781 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2782 }
2783
a6855934 2784 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3406acde 2785 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 2786 }
2787
2788 // Portfolio
7a7e209d 2789 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
24ba58ee
PL
2790 require_once($CFG->libdir . '/portfoliolib.php');
2791 if (portfolio_instances(true, false)) {
3406acde
SH
2792 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
2793 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
2794 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
24ba58ee 2795 }
7d2a0492 2796 }
2797
94e90ab7 2798 // Security keys
de7a00a4 2799 if ($currentuser && !is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $systemcontext)) {
a6855934 2800 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
94e90ab7 2801 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
5eacbd4b 2802 }
2803
7d2a0492 2804 // Repository
2805 if (!$currentuser) {
2806 require_once($CFG->dirroot . '/repository/lib.php');
2807 $editabletypes = repository::get_editable_types($usercontext);
2808 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
a6855934 2809 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
d972bad1 2810 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
7d2a0492 2811 }
2812 }
2813
2814 // Messaging
03d9401e 2815 // TODO this is adding itself to the messaging settings for other people based on one's own setting
7a7e209d 2816 if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
a6855934 2817 $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 2818 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
7d2a0492 2819 }
2820
03d9401e
MD
2821 // Login as ...
2822 if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
2823 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
2824 $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
2825 }
2826
3406acde 2827 return $usersetting;
7d2a0492 2828 }
2829
0b29477b
SH
2830 /**
2831 * Loads block specific settings in the navigation
4f0c2d00 2832 *
3406acde 2833 * @return navigation_node
0b29477b
SH
2834 */
2835 protected function load_block_settings() {
2836 global $CFG;
2837
3406acde
SH
2838 $blocknode = $this->add(print_context_name($this->context));
2839 $blocknode->force_open();
0b29477b
SH
2840
2841 // Assign local roles
2842 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2843 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2844
2845 // Override roles
2846 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2847 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2848 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2849 }
2850 // Check role permissions
2851 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2852 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2853 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2854 }
2855
3406acde 2856 return $blocknode;
0b29477b
SH
2857 }
2858
2859 /**
2860 * Loads category specific settings in the navigation
2861 *
3406acde 2862 * @return navigation_node
0b29477b
SH
2863 */
2864 protected function load_category_settings() {
2865 global $CFG;
2866
ba9dc077
SH
2867 $categorynode = $this->add(print_context_name($this->context));
2868 $categorynode->force_open();
0b29477b
SH
2869
2870 if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
ba9dc077
SH
2871 $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid)));
2872 $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid)));
0b29477b
SH
2873 }
2874
2875 // Assign local roles
2876 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
ba9dc077 2877 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
0b29477b
SH
2878
2879 // Override roles
2880 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2881 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
ba9dc077 2882 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
0b29477b
SH
2883 }
2884 // Check role permissions
2885 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2886 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
ba9dc077
SH
2887 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2888 }
2889 // Manage filters
2890 if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
2891 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
2892 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
0b29477b
SH
2893 }
2894
ba9dc077 2895 return $categorynode;
0b29477b
SH
2896 }
2897
7d2a0492 2898 /**
2899 * Determine whether the user is assuming another role
2900 *
2901 * This function checks to see if the user is assuming another role by means of
2902 * role switching. In doing this we compare each RSW key (context path) against
2903 * the current context path. This ensures that we can provide the switching
2904 * options against both the course and any page shown under the course.
2905 *
2906 * @return bool|int The role(int) if the user is in another role, false otherwise
2907 */
2908 protected function in_alternative_role() {
2909 global $USER;
2910 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
2911 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
2912 return $USER->access['rsw'][$this->page->context->path];
2913 }
2914 foreach ($USER->access['rsw'] as $key=>$role) {
2915 if (strpos($this->context->path,$key)===0) {
2916 return $role;
2917 }
2918 }
2919 }
2920 return false;
2921 }
2922
2923 /**
2e7f1f79 2924 * This function loads all of the front page settings into the settings navigation.
2925 * This function is called when the user is on the front page, or $COURSE==$SITE
3406acde 2926 * @return navigation_node
7d2a0492 2927 */
0b29477b
SH
2928 protected function load_front_page_settings($forceopen = false) {
2929 global $SITE, $CFG;
7d2a0492 2930
0b29477b 2931 $course = clone($SITE);
4f0c2d00 2932 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
7d2a0492 2933
3406acde
SH
2934 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
2935 if ($forceopen) {
2936 $frontpage->force_open();
2937 }
0b29477b 2938 $frontpage->id = 'frontpagesettings';
507a7a9a 2939
4f0c2d00 2940 if (has_capability('moodle/course:update', $coursecontext)) {
7d2a0492 2941
2942 // Add the turn on/off settings
a6855934 2943 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
7d2a0492 2944 if ($this->page->user_is_editing()) {
2945 $url->param('edit', 'off');
2946 $editstring = get_string('turneditingoff');
2947 } else {
2948 $url->param('edit', 'on');
2949 $editstring = get_string('turneditingon');
2950 }
507a7a9a 2951 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
7d2a0492 2952
2953 // Add the course settings link
a6855934 2954 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
507a7a9a 2955 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
7d2a0492 2956 }
2e7f1f79 2957
2958 //Participants
4f0c2d00
PS
2959 if (has_capability('moodle/site:viewparticipants', $coursecontext)) {
2960 $url = new moodle_url('/user/index.php', array('contextid'=>$coursecontext->id));
507a7a9a 2961 $frontpage->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/users', ''));
2e7f1f79 2962 }
7d2a0492 2963
0b29477b 2964 // Roles
4f0c2d00 2965 if (has_capability('moodle/role:assign', $coursecontext)) {
0b29477b 2966 // Add assign or override roles if allowed
4f0c2d00 2967 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2968 $frontpage->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2969 // Override roles
4f0c2d00
PS
2970 if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2971 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2972 $frontpage->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2973 }
2974 // Check role permissions
4f0c2d00
PS
2975 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2976 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2977 $frontpage->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2978 }
2979 // Manage filters
4f0c2d00
PS
2980 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2981 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
0b29477b
SH
2982 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2983 }
2984 }
2985
2986 // Backup this course
4f0c2d00 2987 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
0b29477b
SH
2988 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2989 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2990 }
2991
2992 // Restore to this course
4f0c2d00 2993 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
0b29477b 2994 $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
b0f35692 2995 $url = null; // Disabled until restore is implemented. MDL-21432
0b29477b
SH
2996 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2997 }
2998
2999 // Manage questions
3000 $questioncaps = array('moodle/question:add',
3001 'moodle/question:editmine',
3002 'moodle/question:editall',
3003 'moodle/question:viewmine',
3004 'moodle/question:viewall',
3005 'moodle/question:movemine',
3006 'moodle/question:moveall');
3007 if (has_any_capability($questioncaps, $this->context)) {
3008 $questionlink = $CFG->wwwroot.'/question/edit.php';
3009 } else if (has_capability('moodle/question:managecategory', $this->context)) {
3010 $questionlink = $CFG->wwwroot.'/question/category.php';
3011 }
3012 if (isset($questionlink)) {
3013 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
3014 $frontpage->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
3015 }
3016
3017 // Manage files
3018 if (has_capability('moodle/course:managefiles', $this->context)) {
3019 $url = new moodle_url('/files/index.php', array('id'=>$course->id));
3020 $frontpage->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
3021 }
3406acde 3022 return $frontpage;
7d2a0492 3023 }
f5b5a822 3024
3025 /**
3026 * This function marks the cache as volatile so it is cleared during shutdown
3027 */
3028 public function clear_cache() {
3029 $this->cache->volatile();
3030 }
7d2a0492 3031}
3032
3033/**
3034 * Simple class used to output a navigation branch in XML
3035 *
3036 * @package moodlecore
babb3911 3037 * @subpackage navigation
7d2a0492 3038 * @copyright 2009 Sam Hemelryk
3039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3040 */
507a7a9a 3041class navigation_json {
7d2a0492 3042 /** @var array */
3043 protected $nodetype = array('node','branch');
3044 /** @var array */
3045 protected $expandable = array();
3046 /**
3047 * Turns a branch and all of its children into XML
3048 *
3049 * @param navigation_node $branch
3050 * @return string XML string
3051 */
3052 public function convert($branch) {
3053 $xml = $this->convert_child($branch);
3054 return $xml;
3055 }
3056 /**
3057 * Set the expandable items in the array so that we have enough information
3058 * to attach AJAX events
3406acde 3059 * @param array $expandable
7d2a0492 3060 */
3061 public function set_expandable($expandable) {
3062 foreach ($expandable as $node) {
3063 $this->expandable[(string)$node['branchid']] = $node;
3064 }
3065 }
3066 /**
3067 * Recusively converts a child node and its children to XML for output
3068 *
3069 * @param navigation_node $child The child to convert
3070 * @param int $depth Pointlessly used to track the depth of the XML structure
3406acde 3071 * @return string JSON
7d2a0492 3072 */
3073 protected function convert_child($child, $depth=1) {
3074 global $OUTPUT;
3075
3076 if (!$child->display) {
3077 return '';
3078 }
3079 $attributes = array();
3080 $attributes['id'] = $child->id;
507a7a9a 3081 $attributes['name'] = $child->text;
7d2a0492 3082 $attributes['type'] = $child->type;
3083 $attributes['key'] = $child->key;
7d2a0492 3084 $attributes['class'] = $child->get_css_type();
7da3a799
SH
3085
3086 if ($child->icon instanceof pix_icon) {
3087 $attributes['icon'] = array(
3088 'component' => $child->icon->component,
3089 'pix' => $child->icon->pix,
3090 );
3091 foreach ($child->icon->attributes as $key=>$value) {
3092 if ($key == 'class') {
3093 $attributes['icon']['classes'] = explode(' ', $value);
3094 } else if (!array_key_exists($key, $attributes['icon'])) {
3095 $attributes['icon'][$key] = $value;
3096 }
3097
3098 }
3099 } else if (!empty($child->icon)) {
3100 $attributes['icon'] = (string)$child->icon;
3101 }
3102
7d2a0492 3103 if ($child->forcetitle || $child->title !== $child->text) {
3104 $attributes['title'] = htmlentities($child->title);
3105 }
3106 if (array_key_exists((string)$child->key, $this->expandable)) {
3107 $attributes['expandable'] = $child->key;
3108 $child->add_class($this->expandable[$child->key]['id']);
3109 }
6644741d 3110
7d2a0492 3111 if (count($child->classes)>0) {
3112 $attributes['class'] .= ' '.join(' ',$child->classes);
3113 }
3114 if (is_string($child->action)) {
3115 $attributes['link'] = $child->action;
3116 } else if ($child->action instanceof moodle_url) {
3117 $attributes['link'] = $child->action->out();
3118 }
3119 $attributes['hidden'] = ($child->hidden);
3406acde 3120 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
7d2a0492 3121
7d2a0492 3122 if (count($child->children)>0) {
507a7a9a 3123 $attributes['children'] = array();
7d2a0492 3124 foreach ($child->children as $subchild) {
507a7a9a 3125 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
7d2a0492 3126 }
7d2a0492 3127 }
507a7a9a
SH
3128
3129 if ($depth > 1) {
3130 return $attributes;
3131 } else {
3132 return json_encode($attributes);
3133 }
7d2a0492 3134 }
3135}
3136
3137/**
3138 * The cache class used by global navigation and settings navigation to cache bits
3139 * and bobs that are used during their generation.
3140 *
3141 * It is basically an easy access point to session with a bit of smarts to make
3142 * sure that the information that is cached is valid still.
3143 *
3144 * Example use:
3145 * <code php>
3146 * if (!$cache->viewdiscussion()) {
3147 * // Code to do stuff and produce cachable content
3148 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3149 * }
3150 * $content = $cache->viewdiscussion;
3151 * </code>
3152 *
3153 * @package moodlecore
babb3911 3154 * @subpackage navigation
7d2a0492 3155 * @copyright 2009 Sam Hemelryk
3156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3157 */
3158class navigation_cache {
3159 /** @var int */
3160 protected $creation;
3161 /** @var array */
3162 protected $session;
3163 /** @var string */
3164 protected $area;
3165 /** @var int */
3166 protected $timeout;
3167 /** @var stdClass */
3168 protected $currentcontext;
3169 /** @var int */
3170 const CACHETIME = 0;
3171 /** @var int */
3172 const CACHEUSERID = 1;
3173 /** @var int */
3174 const CACHEVALUE = 2;
f5b5a822 3175 /** @var null|array An array of navigation cache areas to expire on shutdown */
3176 public static $volatilecaches;
117bd748 3177
7d2a0492 3178 /**
3179 * Contructor for the cache. Requires two arguments
3180 *
3181 * @param string $area The string to use to segregate this particular cache
3182 * it can either be unique to start a fresh cache or if you want
3183 * to share a cache then make it the string used in the original
3184 * cache
3185 * @param int $timeout The number of seconds to time the information out after
3186 */
3187 public function __construct($area, $timeout=60) {
507a7a9a 3188 global $SESSION;