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