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