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