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