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