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