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