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