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