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