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