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