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