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