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