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