Merge branch 'wip-MDL-43218-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / navigationlib.php
CommitLineData
7d2a0492 1<?php
7d2a0492 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
98556b23 18 * This file contains classes used to manage the navigation structures within Moodle.
7d2a0492 19 *
78bfb562
PS
20 * @since 2.0
21 * @package core
78bfb562
PS
22 * @copyright 2009 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7d2a0492 24 */
25
78bfb562
PS
26defined('MOODLE_INTERNAL') || die();
27
f5b5a822 28/**
2561c4e9 29 * The name that will be used to separate the navigation cache within SESSION
f5b5a822 30 */
31define('NAVIGATION_CACHE_NAME', 'navigation');
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
SH
384 *
385 * If you are looking for a node and want to search all children + thier children
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 *
700 * @since 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();
31fde54f 982 /** @var array 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;
88f77c3c 1004
8e8de15f
SH
1005 /** Used when loading categories to load all top level categories [parent = 0] **/
1006 const LOAD_ROOT_CATEGORIES = 0;
1007 /** Used when loading categories to load all categories **/
1008 const LOAD_ALL_CATEGORIES = -1;
1009
7d2a0492 1010 /**
3406acde
SH
1011 * Constructs a new global navigation
1012 *
3406acde 1013 * @param moodle_page $page The page this navigation object belongs to
7d2a0492 1014 */
3406acde 1015 public function __construct(moodle_page $page) {
4766a50c 1016 global $CFG, $SITE, $USER;
3406acde 1017
7d2a0492 1018 if (during_initial_install()) {
3406acde 1019 return;
7d2a0492 1020 }
3406acde 1021
4766a50c
SH
1022 if (get_home_page() == HOMEPAGE_SITE) {
1023 // We are using the site home for the root element
1024 $properties = array(
1025 'key' => 'home',
1026 'type' => navigation_node::TYPE_SYSTEM,
1027 'text' => get_string('home'),
1028 'action' => new moodle_url('/')
1029 );
1030 } else {
1031 // We are using the users my moodle for the root element
1032 $properties = array(
1033 'key' => 'myhome',
1034 'type' => navigation_node::TYPE_SYSTEM,
1035 'text' => get_string('myhome'),
1036 'action' => new moodle_url('/my/')
1037 );
dd8e5011 1038 }
4766a50c 1039
31fde54f 1040 // Use the parents constructor.... good good reuse
3406acde
SH
1041 parent::__construct($properties);
1042
1043 // Initalise and set defaults
1044 $this->page = $page;
7d2a0492 1045 $this->forceopen = true;
f5b5a822 1046 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
7d2a0492 1047 }
1048
b9bcad24
AB
1049 /**
1050 * Mutator to set userid to allow parent to see child's profile
1051 * page navigation. See MDL-25805 for initial issue. Linked to it
1052 * is an issue explaining why this is a REALLY UGLY HACK thats not
1053 * for you to use!
1054 *
5607036a 1055 * @param int $userid userid of profile page that parent wants to navigate around.
b9bcad24 1056 */
870815fa
SH
1057 public function set_userid_for_parent_checks($userid) {
1058 $this->useridtouseforparentchecks = $userid;
b9bcad24
AB
1059 }
1060
1061
7d2a0492 1062 /**
3406acde 1063 * Initialises the navigation object.
7d2a0492 1064 *
3406acde
SH
1065 * This causes the navigation object to look at the current state of the page
1066 * that it is associated with and then load the appropriate content.
7d2a0492 1067 *
3406acde
SH
1068 * This should only occur the first time that the navigation structure is utilised
1069 * which will normally be either when the navbar is called to be displayed or
1070 * when a block makes use of it.
7d2a0492 1071 *
3406acde 1072 * @return bool
7d2a0492 1073 */
3406acde 1074 public function initialise() {
58b602da
SH
1075 global $CFG, $SITE, $USER;
1076 // Check if it has already been initialised
7d2a0492 1077 if ($this->initialised || during_initial_install()) {
1078 return true;
1079 }
e2b436d0 1080 $this->initialised = true;
3406acde
SH
1081
1082 // Set up the five base root nodes. These are nodes where we will put our
1083 // content and are as follows:
58b602da
SH
1084 // site: Navigation for the front page.
1085 // myprofile: User profile information goes here.
1086 // currentcourse: The course being currently viewed.
1087 // mycourses: The users courses get added here.
1088 // courses: Additional courses are added here.
1089 // users: Other users information loaded here.
3406acde 1090 $this->rootnodes = array();
4766a50c 1091 if (get_home_page() == HOMEPAGE_SITE) {
3f9ccf85 1092 // The home element should be my moodle because the root element is the site
b9d4c7d3 1093 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
e26507b3 1094 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
3f9ccf85 1095 }
4766a50c
SH
1096 } else {
1097 // The home element should be the site because the root node is my moodle
e26507b3 1098 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
ab6ec58a 1099 if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
4766a50c
SH
1100 // We need to stop automatic redirection
1101 $this->rootnodes['home']->action->param('redirect', '0');
1102 }
1103 }
58b602da 1104 $this->rootnodes['site'] = $this->add_course($SITE);
e26507b3 1105 $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
6caf3f5c 1106 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
4c9464ca 1107 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
58b602da
SH
1108 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1109 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
3406acde 1110
80c69522
SH
1111 // We always load the frontpage course to ensure it is available without
1112 // JavaScript enabled.
1113 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1114 $this->load_course_sections($SITE, $this->rootnodes['site']);
1115
58b602da
SH
1116 $course = $this->page->course;
1117
8e8de15f 1118 // $issite gets set to true if the current pages course is the sites frontpage course
98556b23 1119 $issite = ($this->page->course->id == $SITE->id);
58b602da
SH
1120 // Determine if the user is enrolled in any course.
1121 $enrolledinanycourse = enrol_user_sees_own_courses();
4766a50c 1122
58b602da
SH
1123 $this->rootnodes['currentcourse']->mainnavonly = true;
1124 if ($enrolledinanycourse) {
1125 $this->rootnodes['mycourses']->isexpandable = true;
1126 if ($CFG->navshowallcourses) {
1127 // When we show all courses we need to show both the my courses and the regular courses branch.
1128 $this->rootnodes['courses']->isexpandable = true;
8e8de15f 1129 }
58b602da
SH
1130 } else {
1131 $this->rootnodes['courses']->isexpandable = true;
3406acde
SH
1132 }
1133
f87ce4e9
SH
1134 if ($this->rootnodes['mycourses']->isactive) {
1135 $this->load_courses_enrolled();
1136 }
1137
cede87e0
SH
1138 $canviewcourseprofile = true;
1139
6a16e136
SH
1140 // Next load context specific content into the navigation
1141 switch ($this->page->context->contextlevel) {
1142 case CONTEXT_SYSTEM :
58b602da 1143 // Nothing left to do here I feel.
6a16e136
SH
1144 break;
1145 case CONTEXT_COURSECAT :
58b602da
SH
1146 // This is essential, we must load categories.
1147 $this->load_all_categories($this->page->context->instanceid, true);
6a16e136
SH
1148 break;
1149 case CONTEXT_BLOCK :
1150 case CONTEXT_COURSE :
1151 if ($issite) {
58b602da 1152 // Nothing left to do here.
56c062a4 1153 break;
6a16e136 1154 }
b9bcad24 1155
6caf3f5c 1156 // Load the course associated with the current page into the navigation.
6caf3f5c 1157 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
6a16e136
SH
1158 // If the course wasn't added then don't try going any further.
1159 if (!$coursenode) {
1160 $canviewcourseprofile = false;
1161 break;
1162 }
e26507b3 1163
6a16e136
SH
1164 // If the user is not enrolled then we only want to show the
1165 // course node and not populate it.
1166
1167 // Not enrolled, can't view, and hasn't switched roles
1168 if (!can_access_course($course)) {
58b602da 1169 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
6a16e136 1170 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
58b602da 1171 if (!$this->current_user_is_parent_role()) {
56c062a4 1172 $coursenode->make_active();
6a16e136
SH
1173 $canviewcourseprofile = false;
1174 break;
1175 }
1176 }
6caf3f5c 1177
6a16e136
SH
1178 // Add the essentials such as reports etc...
1179 $this->add_course_essentials($coursenode, $course);
ee7084e9
MG
1180 // Extend course navigation with it's sections/activities
1181 $this->load_course_sections($course, $coursenode);
6a16e136
SH
1182 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1183 $coursenode->make_active();
1184 }
6caf3f5c 1185
6a16e136
SH
1186 break;
1187 case CONTEXT_MODULE :
1188 if ($issite) {
1189 // If this is the site course then most information will have
1190 // already been loaded.
1191 // However we need to check if there is more content that can
1192 // yet be loaded for the specific module instance.
e010b850 1193 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
6a16e136
SH
1194 if ($activitynode) {
1195 $this->load_activity($this->page->cm, $this->page->course, $activitynode);
56c062a4 1196 }
2027c10e 1197 break;
6a16e136 1198 }
2027c10e 1199
6a16e136
SH
1200 $course = $this->page->course;
1201 $cm = $this->page->cm;
cede87e0 1202
6a16e136 1203 // Load the course associated with the page into the navigation
58b602da 1204 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
56c062a4 1205
6a16e136
SH
1206 // If the course wasn't added then don't try going any further.
1207 if (!$coursenode) {
1208 $canviewcourseprofile = false;
1209 break;
1210 }
1211
1212 // If the user is not enrolled then we only want to show the
1213 // course node and not populate it.
1214 if (!can_access_course($course)) {
1215 $coursenode->make_active();
1216 $canviewcourseprofile = false;
1217 break;
1218 }
56c062a4 1219
6a16e136 1220 $this->add_course_essentials($coursenode, $course);
56c062a4 1221
6a16e136 1222 // Load the course sections into the page
e010b850
MG
1223 $this->load_course_sections($course, $coursenode, null, $cm);
1224 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
069c29b9
DM
1225 if (!empty($activity)) {
1226 // Finally load the cm specific navigaton information
1227 $this->load_activity($cm, $course, $activity);
1228 // Check if we have an active ndoe
1229 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1230 // And make the activity node active.
1231 $activity->make_active();
1232 }
6a16e136
SH
1233 }
1234 break;
1235 case CONTEXT_USER :
1236 if ($issite) {
1237 // The users profile information etc is already loaded
1238 // for the front page.
96e78552 1239 break;
6a16e136
SH
1240 }
1241 $course = $this->page->course;
6a16e136 1242 // Load the course associated with the user into the navigation
58b602da 1243 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2027c10e 1244
6a16e136
SH
1245 // If the course wasn't added then don't try going any further.
1246 if (!$coursenode) {
1247 $canviewcourseprofile = false;
1248 break;
1249 }
2027c10e 1250
6a16e136
SH
1251 // If the user is not enrolled then we only want to show the
1252 // course node and not populate it.
1253 if (!can_access_course($course)) {
1254 $coursenode->make_active();
1255 $canviewcourseprofile = false;
56c062a4 1256 break;
e52a5d3a 1257 }
6a16e136 1258 $this->add_course_essentials($coursenode, $course);
ee7084e9 1259 $this->load_course_sections($course, $coursenode);
6a16e136 1260 break;
7d2a0492 1261 }
7a7e209d 1262
3406acde
SH
1263 // Load for the current user
1264 $this->load_for_user();
98556b23 1265 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
87c215de
SH
1266 $this->load_for_user(null, true);
1267 }
7a7e209d
SH
1268 // Load each extending user into the navigation.
1269 foreach ($this->extendforuser as $user) {
44303ca6 1270 if ($user->id != $USER->id) {
7a7e209d
SH
1271 $this->load_for_user($user);
1272 }
1273 }
7a7e209d 1274
a683da3c 1275 // Give the local plugins a chance to include some navigation if they want.
d0cac8b5 1276 foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
5c1f0d1f
SH
1277 $function = "local_{$plugin}_extends_navigation";
1278 $oldfunction = "{$plugin}_extends_navigation";
a683da3c 1279 if (function_exists($function)) {
5c1f0d1f 1280 // This is the preferred function name as there is less chance of conflicts
a683da3c 1281 $function($this);
5c1f0d1f 1282 } else if (function_exists($oldfunction)) {
58b602da 1283 // We continue to support the old function name to ensure backwards compatibility
22ba3f08 1284 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. Support for the old callback will be dropped after the release of 2.4", DEBUG_DEVELOPER);
5c1f0d1f 1285 $oldfunction($this);
a683da3c
SH
1286 }
1287 }
1288
3406acde
SH
1289 // Remove any empty root nodes
1290 foreach ($this->rootnodes as $node) {
4766a50c 1291 // Dont remove the home node
75eb202e
SH
1292 /** @var navigation_node $node */
1293 if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
3406acde
SH
1294 $node->remove();
1295 }
1296 }
1297
7c4efe3b
SH
1298 if (!$this->contains_active_node()) {
1299 $this->search_for_active_node();
1300 }
1301
3406acde 1302 // If the user is not logged in modify the navigation structure as detailed
728ebac7 1303 // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
3406acde
SH
1304 if (!isloggedin()) {
1305 $activities = clone($this->rootnodes['site']->children);
1306 $this->rootnodes['site']->remove();
1307 $children = clone($this->children);
1308 $this->children = new navigation_node_collection();
1309 foreach ($activities as $child) {
1310 $this->children->add($child);
1311 }
1312 foreach ($children as $child) {
1313 $this->children->add($child);
1314 }
3406acde 1315 }
7d2a0492 1316 return true;
1317 }
9bf5af21 1318
58b602da
SH
1319 /**
1320 * Returns true if the current user is a parent of the user being currently viewed.
1321 *
1322 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1323 * other user being viewed this function returns false.
1324 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1325 *
1326 * @since 2.4
1327 * @return bool
1328 */
1329 protected function current_user_is_parent_role() {
1330 global $USER, $DB;
1331 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1332 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1333 if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1334 return false;
1335 }
1336 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1337 return true;
1338 }
1339 }
1340 return false;
1341 }
1342
9bf5af21 1343 /**
31fde54f 1344 * Returns true if courses should be shown within categories on the navigation.
9bf5af21 1345 *
58b602da 1346 * @param bool $ismycourse Set to true if you are calculating this for a course.
9bf5af21
SH
1347 * @return bool
1348 */
58b602da 1349 protected function show_categories($ismycourse = false) {
9bf5af21 1350 global $CFG, $DB;
58b602da
SH
1351 if ($ismycourse) {
1352 return $this->show_my_categories();
1353 }
9bf5af21 1354 if ($this->showcategories === null) {
58b602da
SH
1355 $show = false;
1356 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1357 $show = true;
1358 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1359 $show = true;
1360 }
6a16e136 1361 $this->showcategories = $show;
9bf5af21
SH
1362 }
1363 return $this->showcategories;
1364 }
1365
58b602da
SH
1366 /**
1367 * Returns true if we should show categories in the My Courses branch.
1368 * @return bool
1369 */
1370 protected function show_my_categories() {
1371 global $CFG, $DB;
1372 if ($this->showmycategories === null) {
1373 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1374 }
1375 return $this->showmycategories;
1376 }
1377
3406acde 1378 /**
31fde54f 1379 * Loads the courses in Moodle into the navigation.
3406acde 1380 *
8e8de15f
SH
1381 * @global moodle_database $DB
1382 * @param string|array $categoryids An array containing categories to load courses
1383 * for, OR null to load courses for all categories.
1384 * @return array An array of navigation_nodes one for each course
3406acde 1385 */
8e8de15f 1386 protected function load_all_courses($categoryids = null) {
98556b23 1387 global $CFG, $DB, $SITE;
4766a50c 1388
8e8de15f 1389 // Work out the limit of courses.
4766a50c
SH
1390 $limit = 20;
1391 if (!empty($CFG->navcourselimit)) {
1392 $limit = $CFG->navcourselimit;
1393 }
4766a50c 1394
8e8de15f
SH
1395 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1396
1397 // If we are going to show all courses AND we are showing categories then
1398 // to save us repeated DB calls load all of the categories now
1399 if ($this->show_categories()) {
1400 $this->load_all_categories($toload);
1401 }
1402
1403 // Will be the return of our efforts
3406acde 1404 $coursenodes = array();
8e8de15f 1405
f7ee4baa
SH
1406 // Check if we need to show categories.
1407 if ($this->show_categories()) {
1408 // Hmmm we need to show categories... this is going to be painful.
1409 // We now need to fetch up to $limit courses for each category to
1410 // be displayed.
1411 if ($categoryids !== null) {
1412 if (!is_array($categoryids)) {
1413 $categoryids = array($categoryids);
8e8de15f 1414 }
f7ee4baa
SH
1415 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1416 $categorywhere = 'WHERE cc.id '.$categorywhere;
1417 } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1418 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1419 $categoryparams = array();
1420 } else {
1421 $categorywhere = '';
1422 $categoryparams = array();
1423 }
8e8de15f 1424
f7ee4baa
SH
1425 // First up we are going to get the categories that we are going to
1426 // need so that we can determine how best to load the courses from them.
1427 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1428 FROM {course_categories} cc
1429 LEFT JOIN {course} c ON c.category = cc.id
1430 {$categorywhere}
1431 GROUP BY cc.id";
1432 $categories = $DB->get_recordset_sql($sql, $categoryparams);
1433 $fullfetch = array();
1434 $partfetch = array();
1435 foreach ($categories as $category) {
1436 if (!$this->can_add_more_courses_to_category($category->id)) {
1437 continue;
1438 }
1439 if ($category->coursecount > $limit * 5) {
1440 $partfetch[] = $category->id;
1441 } else if ($category->coursecount > 0) {
1442 $fullfetch[] = $category->id;
1443 }
1444 }
1445 $categories->close();
1446
1447 if (count($fullfetch)) {
1448 // First up fetch all of the courses in categories where we know that we are going to
1449 // need the majority of courses.
f7ee4baa 1450 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
2e4c0c91
FM
1451 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1452 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1453 $categoryparams['contextlevel'] = CONTEXT_COURSE;
f7ee4baa
SH
1454 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1455 FROM {course} c
1456 $ccjoin
fca2d3d7 1457 WHERE c.category {$categoryids}
f7ee4baa 1458 ORDER BY c.sortorder ASC";
fca2d3d7 1459 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
f7ee4baa 1460 foreach ($coursesrs as $course) {
fca2d3d7
PS
1461 if ($course->id == $SITE->id) {
1462 // This should not be necessary, frontpage is not in any category.
1463 continue;
1464 }
1465 if (array_key_exists($course->id, $this->addedcourses)) {
1466 // It is probably better to not include the already loaded courses
1467 // directly in SQL because inequalities may confuse query optimisers
1468 // and may interfere with query caching.
1469 continue;
1470 }
f7ee4baa 1471 if (!$this->can_add_more_courses_to_category($course->category)) {
8e8de15f
SH
1472 continue;
1473 }
db314f34 1474 context_helper::preload_from_record($course);
b0c6dc1c 1475 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
f7ee4baa 1476 continue;
8e8de15f 1477 }
f7ee4baa 1478 $coursenodes[$course->id] = $this->add_course($course);
8e8de15f 1479 }
f7ee4baa
SH
1480 $coursesrs->close();
1481 }
8e8de15f 1482
f7ee4baa
SH
1483 if (count($partfetch)) {
1484 // Next we will work our way through the categories where we will likely only need a small
1485 // proportion of the courses.
1486 foreach ($partfetch as $categoryid) {
2e4c0c91
FM
1487 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1488 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
8e8de15f 1489 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
f7ee4baa
SH
1490 FROM {course} c
1491 $ccjoin
fca2d3d7 1492 WHERE c.category = :categoryid
f7ee4baa 1493 ORDER BY c.sortorder ASC";
2e4c0c91 1494 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
f7ee4baa 1495 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
8e8de15f 1496 foreach ($coursesrs as $course) {
fca2d3d7
PS
1497 if ($course->id == $SITE->id) {
1498 // This should not be necessary, frontpage is not in any category.
1499 continue;
1500 }
1501 if (array_key_exists($course->id, $this->addedcourses)) {
1502 // It is probably better to not include the already loaded courses
1503 // directly in SQL because inequalities may confuse query optimisers
1504 // and may interfere with query caching.
1505 // This also helps to respect expected $limit on repeated executions.
1506 continue;
1507 }
8e8de15f 1508 if (!$this->can_add_more_courses_to_category($course->category)) {
f7ee4baa 1509 break;
8e8de15f 1510 }
db314f34 1511 context_helper::preload_from_record($course);
b0c6dc1c 1512 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
8e8de15f
SH
1513 continue;
1514 }
1515 $coursenodes[$course->id] = $this->add_course($course);
1516 }
1517 $coursesrs->close();
1518 }
8e8de15f 1519 }
8e8de15f 1520 } else {
8e8de15f 1521 // Prepare the SQL to load the courses and their contexts
f7ee4baa 1522 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
2e4c0c91
FM
1523 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1524 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1525 $courseparams['contextlevel'] = CONTEXT_COURSE;
8e8de15f 1526 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
f7ee4baa
SH
1527 FROM {course} c
1528 $ccjoin
1529 WHERE c.id {$courseids}
1530 ORDER BY c.sortorder ASC";
8e8de15f
SH
1531 $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1532 foreach ($coursesrs as $course) {
fca2d3d7
PS
1533 if ($course->id == $SITE->id) {
1534 // frotpage is not wanted here
1535 continue;
1536 }
6caf3f5c
ARN
1537 if ($this->page->course && ($this->page->course->id == $course->id)) {
1538 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1539 continue;
1540 }
db314f34 1541 context_helper::preload_from_record($course);
b0c6dc1c 1542 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
f7ee4baa
SH
1543 continue;
1544 }
8e8de15f 1545 $coursenodes[$course->id] = $this->add_course($course);
f7ee4baa
SH
1546 if (count($coursenodes) >= $limit) {
1547 break;
1548 }
8e8de15f
SH
1549 }
1550 $coursesrs->close();
3406acde 1551 }
f7ee4baa 1552
3406acde
SH
1553 return $coursenodes;
1554 }
1555
8e8de15f
SH
1556 /**
1557 * Returns true if more courses can be added to the provided category.
1558 *
98556b23
SH
1559 * @param int|navigation_node|stdClass $category
1560 * @return bool
8e8de15f
SH
1561 */
1562 protected function can_add_more_courses_to_category($category) {
1563 global $CFG;
1564 $limit = 20;
1565 if (!empty($CFG->navcourselimit)) {
1566 $limit = (int)$CFG->navcourselimit;
1567 }
1568 if (is_numeric($category)) {
1569 if (!array_key_exists($category, $this->addedcategories)) {
1570 return true;
1571 }
1572 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1573 } else if ($category instanceof navigation_node) {
db47f68f 1574 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
8e8de15f
SH
1575 return false;
1576 }
1577 $coursecount = count($category->children->type(self::TYPE_COURSE));
1578 } else if (is_object($category) && property_exists($category,'id')) {
1579 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1580 }
d4bb6462 1581 return ($coursecount <= $limit);
8e8de15f
SH
1582 }
1583
4766a50c
SH
1584 /**
1585 * Loads all categories (top level or if an id is specified for that category)
1586 *
e26507b3
SH
1587 * @param int $categoryid The category id to load or null/0 to load all base level categories
1588 * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1589 * as the requested category and any parent categories.
31fde54f 1590 * @return navigation_node|void returns a navigation node if a category has been loaded.
4766a50c 1591 */
8e8de15f 1592 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
58b602da 1593 global $CFG, $DB;
e26507b3
SH
1594
1595 // Check if this category has already been loaded
8e8de15f
SH
1596 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1597 return true;
e26507b3
SH
1598 }
1599
176b75b5
SH
1600 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1601 $sqlselect = "SELECT cc.*, $catcontextsql
1602 FROM {course_categories} cc
1603 JOIN {context} ctx ON cc.id = ctx.instanceid";
1604 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
957983b7 1605 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
176b75b5
SH
1606 $params = array();
1607
8e8de15f
SH
1608 $categoriestoload = array();
1609 if ($categoryid == self::LOAD_ALL_CATEGORIES) {
176b75b5
SH
1610 // We are going to load all categories regardless... prepare to fire
1611 // on the database server!
8e8de15f 1612 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
e26507b3 1613 // We are going to load all of the first level categories (categories without parents)
176b75b5 1614 $sqlwhere .= " AND cc.parent = 0";
e26507b3
SH
1615 } else if (array_key_exists($categoryid, $this->addedcategories)) {
1616 // The category itself has been loaded already so we just need to ensure its subcategories
1617 // have been loaded
1618 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1619 if ($showbasecategories) {
1620 // We need to include categories with parent = 0 as well
d4bb6462 1621 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
e26507b3 1622 } else {
176b75b5 1623 // All we need is categories that match the parent
d4bb6462 1624 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
e26507b3
SH
1625 }
1626 $params['categoryid'] = $categoryid;
4766a50c 1627 } else {
e26507b3
SH
1628 // This category hasn't been loaded yet so we need to fetch it, work out its category path
1629 // and load this category plus all its parents and subcategories
3992a46e 1630 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
8e8de15f
SH
1631 $categoriestoload = explode('/', trim($category->path, '/'));
1632 list($select, $params) = $DB->get_in_or_equal($categoriestoload);
176b75b5 1633 // We are going to use select twice so double the params
4766a50c 1634 $params = array_merge($params, $params);
d4bb6462
SH
1635 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1636 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
176b75b5
SH
1637 }
1638
1639 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1640 $categories = array();
1641 foreach ($categoriesrs as $category) {
1642 // Preload the context.. we'll need it when adding the category in order
1643 // to format the category name.
1644 context_helper::preload_from_record($category);
1645 if (array_key_exists($category->id, $this->addedcategories)) {
1646 // Do nothing, its already been added.
1647 } else if ($category->parent == '0') {
1648 // This is a root category lets add it immediately
1649 $this->add_category($category, $this->rootnodes['courses']);
1650 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1651 // This categories parent has already been added we can add this immediately
1652 $this->add_category($category, $this->addedcategories[$category->parent]);
1653 } else {
1654 $categories[] = $category;
1655 }
4766a50c 1656 }
176b75b5 1657 $categoriesrs->close();
e26507b3
SH
1658
1659 // Now we have an array of categories we need to add them to the navigation.
1660 while (!empty($categories)) {
1661 $category = reset($categories);
1662 if (array_key_exists($category->id, $this->addedcategories)) {
1663 // Do nothing
1664 } else if ($category->parent == '0') {
1665 $this->add_category($category, $this->rootnodes['courses']);
1666 } else if (array_key_exists($category->parent, $this->addedcategories)) {
1667 $this->add_category($category, $this->addedcategories[$category->parent]);
4766a50c 1668 } else {
e26507b3
SH
1669 // This category isn't in the navigation and niether is it's parent (yet).
1670 // We need to go through the category path and add all of its components in order.
1671 $path = explode('/', trim($category->path, '/'));
1672 foreach ($path as $catid) {
1673 if (!array_key_exists($catid, $this->addedcategories)) {
1674 // This category isn't in the navigation yet so add it.
1675 $subcategory = $categories[$catid];
c4afcf84
SH
1676 if ($subcategory->parent == '0') {
1677 // Yay we have a root category - this likely means we will now be able
1678 // to add categories without problems.
1679 $this->add_category($subcategory, $this->rootnodes['courses']);
1680 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
e26507b3
SH
1681 // The parent is in the category (as we'd expect) so add it now.
1682 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1683 // Remove the category from the categories array.
1684 unset($categories[$catid]);
1685 } else {
1686 // We should never ever arrive here - if we have then there is a bigger
1687 // problem at hand.
5607036a 1688 throw new coding_exception('Category path order is incorrect and/or there are missing categories');
e26507b3 1689 }
4766a50c 1690 }
4766a50c
SH
1691 }
1692 }
e26507b3
SH
1693 // Remove the category from the categories array now that we know it has been added.
1694 unset($categories[$category->id]);
4766a50c 1695 }
8e8de15f
SH
1696 if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1697 $this->allcategoriesloaded = true;
1698 }
e26507b3 1699 // Check if there are any categories to load.
8e8de15f
SH
1700 if (count($categoriestoload) > 0) {
1701 $readytoloadcourses = array();
1702 foreach ($categoriestoload as $category) {
1703 if ($this->can_add_more_courses_to_category($category)) {
1704 $readytoloadcourses[] = $category;
1705 }
1706 }
1707 if (count($readytoloadcourses)) {
1708 $this->load_all_courses($readytoloadcourses);
1709 }
4766a50c 1710 }
58b602da
SH
1711
1712 // Look for all categories which have been loaded
1713 if (!empty($this->addedcategories)) {
1714 $categoryids = array();
1715 foreach ($this->addedcategories as $category) {
1716 if ($this->can_add_more_courses_to_category($category)) {
1717 $categoryids[] = $category->key;
1718 }
1719 }
bb900d13
PS
1720 if ($categoryids) {
1721 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1722 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1723 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1724 FROM {course_categories} cc
1725 JOIN {course} c ON c.category = cc.id
1726 WHERE cc.id {$categoriessql}
1727 GROUP BY cc.id
1728 HAVING COUNT(c.id) > :limit";
1729 $excessivecategories = $DB->get_records_sql($sql, $params);
1730 foreach ($categories as &$category) {
1731 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
30142c19 1732 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
bb900d13
PS
1733 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1734 }
58b602da
SH
1735 }
1736 }
1737 }
4766a50c
SH
1738 }
1739
1740 /**
1741 * Adds a structured category to the navigation in the correct order/place
1742 *
db47f68f
RT
1743 * @param stdClass $category category to be added in navigation.
1744 * @param navigation_node $parent parent navigation node
1745 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1746 * @return void.
4766a50c 1747 */
db47f68f 1748 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
e26507b3 1749 if (array_key_exists($category->id, $this->addedcategories)) {
563329e8 1750 return;
e26507b3 1751 }
30142c19 1752 $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
b0c6dc1c 1753 $context = context_coursecat::instance($category->id);
63390481 1754 $categoryname = format_string($category->name, true, array('context' => $context));
db47f68f 1755 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
e26507b3 1756 if (empty($category->visible)) {
0601e0ee 1757 if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
e26507b3
SH
1758 $categorynode->hidden = true;
1759 } else {
1760 $categorynode->display = false;
14337688 1761 }
4766a50c 1762 }
082513ba 1763 $this->addedcategories[$category->id] = $categorynode;
4766a50c
SH
1764 }
1765
3406acde
SH
1766 /**
1767 * Loads the given course into the navigation
7d2a0492 1768 *
3406acde
SH
1769 * @param stdClass $course
1770 * @return navigation_node
1771 */
1772 protected function load_course(stdClass $course) {
98556b23
SH
1773 global $SITE;
1774 if ($course->id == $SITE->id) {
80c69522 1775 // This is always loaded during initialisation
e26507b3
SH
1776 return $this->rootnodes['site'];
1777 } else if (array_key_exists($course->id, $this->addedcourses)) {
80c69522 1778 // The course has already been loaded so return a reference
e26507b3 1779 return $this->addedcourses[$course->id];
3406acde 1780 } else {
80c69522 1781 // Add the course
e26507b3 1782 return $this->add_course($course);
3406acde 1783 }
3406acde
SH
1784 }
1785
1786 /**
1787 * Loads all of the courses section into the navigation.
1788 *
e010b850
MG
1789 * This function calls method from current course format, see
1790 * {@link format_base::extend_course_navigation()}
1791 * If course module ($cm) is specified but course format failed to create the node,
1792 * the activity node is created anyway.
3406acde 1793 *
e010b850 1794 * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
3406acde 1795 *
3406acde
SH
1796 * @param stdClass $course Database record for the course
1797 * @param navigation_node $coursenode The course node within the navigation
e010b850
MG
1798 * @param null|int $sectionnum If specified load the contents of section with this relative number
1799 * @param null|cm_info $cm If specified make sure that activity node is created (either
1800 * in containg section or by calling load_stealth_activity() )
3406acde 1801 */
e010b850
MG
1802 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1803 global $CFG, $SITE;
ee7084e9 1804 require_once($CFG->dirroot.'/course/lib.php');
e010b850
MG
1805 if (isset($cm->sectionnum)) {
1806 $sectionnum = $cm->sectionnum;
1807 }
1808 if ($sectionnum !== null) {
1809 $this->includesectionnum = $sectionnum;
1810 }
1811 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1812 if (isset($cm->id)) {
1813 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1814 if (empty($activity)) {
1815 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1816 }
1817 }
1818 }
3406acde 1819
e26507b3
SH
1820 /**
1821 * Generates an array of sections and an array of activities for the given course.
1822 *
1823 * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1824 *
1825 * @param stdClass $course
1826 * @return array Array($sections, $activities)
1827 */
1828 protected function generate_sections_and_activities(stdClass $course) {
1829 global $CFG;
1830 require_once($CFG->dirroot.'/course/lib.php');
1831
c18facf2 1832 $modinfo = get_fast_modinfo($course);
b5cf83f0 1833 $sections = $modinfo->get_section_info_all();
850acb35
MG
1834
1835 // For course formats using 'numsections' trim the sections list
1836 $courseformatoptions = course_get_format($course)->get_format_options();
1837 if (isset($courseformatoptions['numsections'])) {
1838 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
b5cf83f0 1839 }
850acb35 1840
c18facf2 1841 $activities = array();
e26507b3 1842
c18facf2 1843 foreach ($sections as $key => $section) {
2d9c0d11 1844 // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
51591b2c
AO
1845 $sections[$key] = clone($section);
1846 unset($sections[$key]->summary);
c18facf2
SH
1847 $sections[$key]->hasactivites = false;
1848 if (!array_key_exists($section->section, $modinfo->sections)) {
1849 continue;
1850 }
1851 foreach ($modinfo->sections[$section->section] as $cmid) {
1852 $cm = $modinfo->cms[$cmid];
c18facf2
SH
1853 $activity = new stdClass;
1854 $activity->id = $cm->id;
1855 $activity->course = $course->id;
1856 $activity->section = $section->section;
1857 $activity->name = $cm->name;
1858 $activity->icon = $cm->icon;
1859 $activity->iconcomponent = $cm->iconcomponent;
1860 $activity->hidden = (!$cm->visible);
1861 $activity->modname = $cm->modname;
1862 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1863 $activity->onclick = $cm->get_on_click();
1864 $url = $cm->get_url();
1865 if (!$url) {
1866 $activity->url = null;
1867 $activity->display = false;
1868 } else {
1869 $activity->url = $cm->get_url()->out();
4fd2a16e 1870 $activity->display = $cm->uservisible ? true : false;
c18facf2
SH
1871 if (self::module_extends_navigation($cm->modname)) {
1872 $activity->nodetype = navigation_node::NODETYPE_BRANCH;
d67e4821 1873 }
e26507b3 1874 }
c18facf2
SH
1875 $activities[$cmid] = $activity;
1876 if ($activity->display) {
1877 $sections[$key]->hasactivites = true;
1878 }
e26507b3 1879 }
e26507b3 1880 }
c18facf2 1881
e26507b3
SH
1882 return array($sections, $activities);
1883 }
1884
3406acde
SH
1885 /**
1886 * Generically loads the course sections into the course's navigation.
1887 *
1888 * @param stdClass $course
1889 * @param navigation_node $coursenode
3406acde
SH
1890 * @return array An array of course section nodes
1891 */
ee7084e9 1892 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
98556b23 1893 global $CFG, $DB, $USER, $SITE;
df997f84 1894 require_once($CFG->dirroot.'/course/lib.php');
435a512e 1895
e26507b3 1896 list($sections, $activities) = $this->generate_sections_and_activities($course);
0f4ab67d 1897
7487c856 1898 $navigationsections = array();
e26507b3 1899 foreach ($sections as $sectionid => $section) {
7487c856 1900 $section = clone($section);
98556b23 1901 if ($course->id == $SITE->id) {
e26507b3 1902 $this->load_section_activities($coursenode, $section->section, $activities);
3406acde 1903 } else {
ce4dfd27 1904 if (!$section->uservisible || (!$this->showemptysections &&
d67e4821 1905 !$section->hasactivites && $this->includesectionnum !== $section->section)) {
3406acde
SH
1906 continue;
1907 }
ce4dfd27 1908
ee7084e9
MG
1909 $sectionname = get_section_name($course, $section);
1910 $url = course_get_url($course, $section->section, array('navigation' => true));
ad470097 1911
3406acde
SH
1912 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1913 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
ce4dfd27 1914 $sectionnode->hidden = (!$section->visible || !$section->available);
e010b850 1915 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
e26507b3 1916 $this->load_section_activities($sectionnode, $section->section, $activities);
3406acde
SH
1917 }
1918 $section->sectionnode = $sectionnode;
7487c856 1919 $navigationsections[$sectionid] = $section;
3406acde
SH
1920 }
1921 }
7487c856 1922 return $navigationsections;
3406acde 1923 }
e010b850 1924
3406acde
SH
1925 /**
1926 * Loads all of the activities for a section into the navigation structure.
1927 *
1928 * @param navigation_node $sectionnode
1929 * @param int $sectionnumber
93123b17 1930 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1580cfdb 1931 * @param stdClass $course The course object the section and activities relate to.
3406acde
SH
1932 * @return array Array of activity nodes
1933 */
1580cfdb 1934 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
98556b23 1935 global $CFG, $SITE;
dee1a0fd
SH
1936 // A static counter for JS function naming
1937 static $legacyonclickcounter = 0;
3406acde 1938
e26507b3 1939 $activitynodes = array();
4037098e
SH
1940 if (empty($activities)) {
1941 return $activitynodes;
1942 }
1943
1944 if (!is_object($course)) {
1945 $activity = reset($activities);
1946 $courseid = $activity->course;
1947 } else {
1948 $courseid = $course->id;
1949 }
98556b23 1950 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
4037098e 1951
e26507b3
SH
1952 foreach ($activities as $activity) {
1953 if ($activity->section != $sectionnumber) {
3406acde
SH
1954 continue;
1955 }
e26507b3
SH
1956 if ($activity->icon) {
1957 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
3406acde 1958 } else {
e26507b3 1959 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
3406acde 1960 }
dee1a0fd
SH
1961
1962 // Prepare the default name and url for the node
b0c6dc1c 1963 $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
dee1a0fd
SH
1964 $action = new moodle_url($activity->url);
1965
1966 // Check if the onclick property is set (puke!)
1967 if (!empty($activity->onclick)) {
1968 // Increment the counter so that we have a unique number.
1969 $legacyonclickcounter++;
1970 // Generate the function name we will use
1971 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1972 $propogrationhandler = '';
1973 // Check if we need to cancel propogation. Remember inline onclick
1974 // events would return false if they wanted to prevent propogation and the
1975 // default action.
1976 if (strpos($activity->onclick, 'return false')) {
1977 $propogrationhandler = 'e.halt();';
1978 }
1979 // Decode the onclick - it has already been encoded for display (puke)
e5ad278a 1980 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
dee1a0fd
SH
1981 // Build the JS function the click event will call
1982 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1983 $this->page->requires->js_init_code($jscode);
1984 // Override the default url with the new action link
1985 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1986 }
1987
1988 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
e26507b3
SH
1989 $activitynode->title(get_string('modulename', $activity->modname));
1990 $activitynode->hidden = $activity->hidden;
4037098e 1991 $activitynode->display = $showactivities && $activity->display;
e26507b3
SH
1992 $activitynode->nodetype = $activity->nodetype;
1993 $activitynodes[$activity->id] = $activitynode;
3406acde
SH
1994 }
1995
e26507b3 1996 return $activitynodes;
3406acde 1997 }
2a62743c
PS
1998 /**
1999 * Loads a stealth module from unavailable section
2000 * @param navigation_node $coursenode
2001 * @param stdClass $modinfo
2002 * @return navigation_node or null if not accessible
2003 */
2004 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
2005 if (empty($modinfo->cms[$this->page->cm->id])) {
2006 return null;
2007 }
2008 $cm = $modinfo->cms[$this->page->cm->id];
2a62743c
PS
2009 if ($cm->icon) {
2010 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
2011 } else {
2012 $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
2013 }
0d8b6a69 2014 $url = $cm->get_url();
2a62743c
PS
2015 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
2016 $activitynode->title(get_string('modulename', $cm->modname));
2017 $activitynode->hidden = (!$cm->visible);
4fd2a16e
MG
2018 if (!$cm->uservisible) {
2019 // Do not show any error here, let the page handle exception that activity is not visible for the current user.
2020 // Also there may be no exception at all in case when teacher is logged in as student.
2021 $activitynode->display = false;
2022 } else if (!$url) {
0d8b6a69 2023 // Don't show activities that don't have links!
2a62743c 2024 $activitynode->display = false;
e26507b3 2025 } else if (self::module_extends_navigation($cm->modname)) {
2a62743c
PS
2026 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2027 }
2028 return $activitynode;
2029 }
3406acde
SH
2030 /**
2031 * Loads the navigation structure for the given activity into the activities node.
2032 *
2033 * This method utilises a callback within the modules lib.php file to load the
2034 * content specific to activity given.
2035 *
2036 * The callback is a method: {modulename}_extend_navigation()
2037 * Examples:
93123b17
EL
2038 * * {@link forum_extend_navigation()}
2039 * * {@link workshop_extend_navigation()}
3406acde 2040 *
f0dcc212 2041 * @param cm_info|stdClass $cm
3406acde
SH
2042 * @param stdClass $course
2043 * @param navigation_node $activity
2044 * @return bool
2045 */
0d8b6a69 2046 protected function load_activity($cm, stdClass $course, navigation_node $activity) {
3406acde 2047 global $CFG, $DB;
44303ca6 2048
f0dcc212
SH
2049 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2050 if (!($cm instanceof cm_info)) {
2051 $modinfo = get_fast_modinfo($course);
2052 $cm = $modinfo->get_cm($cm->id);
2053 }
577c8964 2054 $activity->nodetype = navigation_node::NODETYPE_LEAF;
3406acde
SH
2055 $activity->make_active();
2056 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2057 $function = $cm->modname.'_extend_navigation';
2058
2059 if (file_exists($file)) {
2060 require_once($file);
2061 if (function_exists($function)) {
2062 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2063 $function($activity, $course, $activtyrecord, $cm);
3406acde
SH
2064 }
2065 }
577c8964
MG
2066
2067 // Allow the active advanced grading method plugin to append module navigation
2068 $featuresfunc = $cm->modname.'_supports';
2069 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2070 require_once($CFG->dirroot.'/grade/grading/lib.php');
2071 $gradingman = get_grading_manager($cm->context, $cm->modname);
2072 $gradingman->extend_navigation($this, $activity);
2073 }
2074
2075 return $activity->has_children();
3406acde
SH
2076 }
2077 /**
4d00fded 2078 * Loads user specific information into the navigation in the appropriate place.
3406acde
SH
2079 *
2080 * If no user is provided the current user is assumed.
2081 *
3406acde 2082 * @param stdClass $user
4d00fded 2083 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
3406acde 2084 * @return bool
7a7e209d 2085 */
87c215de 2086 protected function load_for_user($user=null, $forceforcontext=false) {
98556b23 2087 global $DB, $CFG, $USER, $SITE;
4f0c2d00 2088
7a7e209d
SH
2089 if ($user === null) {
2090 // We can't require login here but if the user isn't logged in we don't
2091 // want to show anything
b9d4c7d3 2092 if (!isloggedin() || isguestuser()) {
7a7e209d
SH
2093 return false;
2094 }
2095 $user = $USER;
7a7e209d
SH
2096 } else if (!is_object($user)) {
2097 // If the user is not an object then get them from the database
e141bc81
SH
2098 $select = context_helper::get_preload_record_columns_sql('ctx');
2099 $sql = "SELECT u.*, $select
2100 FROM {user} u
2101 JOIN {context} ctx ON u.id = ctx.instanceid
2102 WHERE u.id = :userid AND
2103 ctx.contextlevel = :contextlevel";
2104 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2105 context_helper::preload_from_record($user);
7a7e209d 2106 }
136ca7c8
SH
2107
2108 $iscurrentuser = ($user->id == $USER->id);
2109
b0c6dc1c 2110 $usercontext = context_user::instance($user->id);
7a7e209d
SH
2111
2112 // Get the course set against the page, by default this will be the site
3406acde
SH
2113 $course = $this->page->course;
2114 $baseargs = array('id'=>$user->id);
98556b23 2115 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
58b602da 2116 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
7a7e209d 2117 $baseargs['course'] = $course->id;
b0c6dc1c 2118 $coursecontext = context_course::instance($course->id);
7a7e209d 2119 $issitecourse = false;
7d2a0492 2120 } else {
7a7e209d 2121 // Load all categories and get the context for the system
b0c6dc1c 2122 $coursecontext = context_system::instance();
7a7e209d
SH
2123 $issitecourse = true;
2124 }
2125
2126 // Create a node to add user information under.
87c215de 2127 if ($iscurrentuser && !$forceforcontext) {
3406acde
SH
2128 // If it's the current user the information will go under the profile root node
2129 $usernode = $this->rootnodes['myprofile'];
e96bc3f9 2130 $course = get_site();
b0c6dc1c 2131 $coursecontext = context_course::instance($course->id);
e96bc3f9 2132 $issitecourse = true;
7a7e209d
SH
2133 } else {
2134 if (!$issitecourse) {
2135 // Not the current user so add it to the participants node for the current course
3406acde 2136 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
ad93ddd5 2137 $userviewurl = new moodle_url('/user/view.php', $baseargs);
7a7e209d
SH
2138 } else {
2139 // This is the site so add a users node to the root branch
3406acde 2140 $usersnode = $this->rootnodes['users'];
8b0614d9
DP
2141 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2142 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2143 }
ad93ddd5 2144 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
7a7e209d 2145 }
f5c1e621
SH
2146 if (!$usersnode) {
2147 // We should NEVER get here, if the course hasn't been populated
2148 // with a participants node then the navigaiton either wasn't generated
2149 // for it (you are missing a require_login or set_context call) or
2150 // you don't have access.... in the interests of no leaking informatin
2151 // we simply quit...
2152 return false;
2153 }
7a7e209d 2154 // Add a branch for the current user
76565fa1
AG
2155 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2156 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
3406acde 2157
5ac851fb
SH
2158 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2159 $usernode->make_active();
2160 }
7a7e209d
SH
2161 }
2162
2163 // If the user is the current user or has permission to view the details of the requested
2164 // user than add a view profile link.
507a7a9a 2165 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
87c215de 2166 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
03d9401e
MD
2167 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2168 } else {
2169 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2170 }
7a7e209d
SH
2171 }
2172
356a6de3
SH
2173 if (!empty($CFG->navadduserpostslinks)) {
2174 // Add nodes for forum posts and discussions if the user can view either or both
2175 // There are no capability checks here as the content of the page is based
2176 // purely on the forums the current user has access too.
2177 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2178 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2179 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2180 }
7a7e209d 2181
27bad0a6 2182 // Add blog nodes
850d2db8 2183 if (!empty($CFG->enableblogs)) {
e26507b3
SH
2184 if (!$this->cache->cached('userblogoptions'.$user->id)) {
2185 require_once($CFG->dirroot.'/blog/lib.php');
2186 // Get all options for the user
2187 $options = blog_get_options_for_user($user);
2188 $this->cache->set('userblogoptions'.$user->id, $options);
2189 } else {
2190 $options = $this->cache->{'userblogoptions'.$user->id};
2191 }
2192
27bad0a6
SH
2193 if (count($options) > 0) {
2194 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
c000545d
JF
2195 foreach ($options as $type => $option) {
2196 if ($type == "rss") {
2197 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2198 } else {
2199 $blogs->add($option['string'], $option['link']);
2200 }
27bad0a6
SH
2201 }
2202 }
2203 }
2204
5ac851fb 2205 if (!empty($CFG->messaging)) {
0e1bd87c 2206 $messageargs = array('user1' => $USER->id);
447df209 2207 if ($USER->id != $user->id) {
0e1bd87c
MG
2208 $messageargs['user2'] = $user->id;
2209 }
2210 if ($course->id != $SITE->id) {
2211 $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
5ac851fb
SH
2212 }
2213 $url = new moodle_url('/message/index.php',$messageargs);
2214 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
c81b9f69 2215 }
c81b9f69 2216
d422fb22 2217 if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
4c886459 2218 $url = new moodle_url('/user/files.php');
82af55d7 2219 $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
78765507
DC
2220 }
2221
2188a697 2222 if (!empty($CFG->enablebadges) && $iscurrentuser &&
27806552
YB
2223 has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2224 $url = new moodle_url('/badges/mybadges.php');
2225 $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2226 }
2227
7a7e209d 2228 // Add a node to view the users notes if permitted
507a7a9a 2229 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
3406acde
SH
2230 $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2231 if ($coursecontext->instanceid) {
2232 $url->param('course', $coursecontext->instanceid);
2233 }
2234 $usernode->add(get_string('notes', 'notes'), $url);
7a7e209d
SH
2235 }
2236
7a7e209d 2237 // If the user is the current user add the repositories for the current user
9acb8241 2238 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
7a7e209d 2239 if ($iscurrentuser) {
e26507b3
SH
2240 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2241 require_once($CFG->dirroot . '/repository/lib.php');
2242 $editabletypes = repository::get_editable_types($usercontext);
2243 $haseditabletypes = !empty($editabletypes);
2244 unset($editabletypes);
2245 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2246 } else {
2247 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2248 }
2249 if ($haseditabletypes) {
ad70376c 2250 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
7a7e209d 2251 }
98556b23 2252 } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
9acb8241
SH
2253
2254 // Add view grade report is permitted
bd3b3bba 2255 $reports = core_component::get_plugin_list('gradereport');
9acb8241
SH
2256 arsort($reports); // user is last, we want to test it first
2257
2258 $userscourses = enrol_get_users_courses($user->id);
2259 $userscoursesnode = $usernode->add(get_string('courses'));
69816a5c 2260
9acb8241 2261 foreach ($userscourses as $usercourse) {
b0c6dc1c 2262 $usercoursecontext = context_course::instance($usercourse->id);
8ebbb06a
SH
2263 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2264 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
9acb8241
SH
2265
2266 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2267 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2268 foreach ($reports as $plugin => $plugindir) {
2269 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2270 //stop when the first visible plugin is found
2271 $gradeavailable = true;
2272 break;
deaf04c7 2273 }
9acb8241
SH
2274 }
2275 }
2276
2277 if ($gradeavailable) {
2278 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2279 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2280 }
2281
2282 // Add a node to view the users notes if permitted
2283 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2284 $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2285 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2286 }
2287
1344b0ca 2288 if (can_access_course($usercourse, $user->id)) {
9acb8241
SH
2289 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2290 }
2291
4d00fded
PS
2292 $reporttab = $usercoursenode->add(get_string('activityreports'));
2293
2294 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2295 foreach ($reports as $reportfunction) {
2296 $reportfunction($reporttab, $user, $usercourse);
2297 }
2298
4d00fded 2299 $reporttab->trim_if_empty();
9acb8241 2300 }
7a7e209d
SH
2301 }
2302 return true;
2303 }
2304
2305 /**
3406acde 2306 * This method simply checks to see if a given module can extend the navigation.
7d2a0492 2307 *
31fde54f 2308 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
e26507b3 2309 *
7d2a0492 2310 * @param string $modname
2311 * @return bool
2312 */
e010b850 2313 public static function module_extends_navigation($modname) {
7d2a0492 2314 global $CFG;
e26507b3
SH
2315 static $extendingmodules = array();
2316 if (!array_key_exists($modname, $extendingmodules)) {
2317 $extendingmodules[$modname] = false;
2318 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2319 if (file_exists($file)) {
2320 $function = $modname.'_extend_navigation';
2321 require_once($file);
2322 $extendingmodules[$modname] = (function_exists($function));
7d2a0492 2323 }
2324 }
e26507b3 2325 return $extendingmodules[$modname];
7d2a0492 2326 }
2327 /**
3406acde 2328 * Extends the navigation for the given user.
435a512e 2329 *
3406acde 2330 * @param stdClass $user A user from the database
7d2a0492 2331 */
3406acde
SH
2332 public function extend_for_user($user) {
2333 $this->extendforuser[] = $user;
5d07e957
SH
2334 }
2335
2336 /**
2337 * Returns all of the users the navigation is being extended for
2338 *
31fde54f 2339 * @return array An array of extending users.
5d07e957
SH
2340 */
2341 public function get_extending_users() {
2342 return $this->extendforuser;
7d2a0492 2343 }
7d2a0492 2344 /**
3406acde 2345 * Adds the given course to the navigation structure.
7d2a0492 2346 *
3406acde 2347 * @param stdClass $course
8e8de15f
SH
2348 * @param bool $forcegeneric
2349 * @param bool $ismycourse
3406acde 2350 * @return navigation_node
7d2a0492 2351 */
6caf3f5c 2352 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
98556b23 2353 global $CFG, $SITE;
44303ca6 2354
e26507b3
SH
2355 // We found the course... we can return it now :)
2356 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2357 return $this->addedcourses[$course->id];
2358 }
2359
b0c6dc1c 2360 $coursecontext = context_course::instance($course->id);
8ebbb06a 2361
98556b23 2362 if ($course->id != $SITE->id && !$course->visible) {
e26507b3
SH
2363 if (is_role_switched($course->id)) {
2364 // user has to be able to access course in order to switch, let's skip the visibility test here
8ebbb06a 2365 } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
e26507b3 2366 return false;
44303ca6 2367 }
7d2a0492 2368 }
7d2a0492 2369
98556b23 2370 $issite = ($course->id == $SITE->id);
8ebbb06a 2371 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
d20337f1
SH
2372 $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2373 // This is the name that will be shown for the course.
2374 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
4766a50c
SH
2375
2376 if ($issite) {
3406acde 2377 $parent = $this;
4766a50c 2378 $url = null;
016ba638 2379 if (empty($CFG->usesitenameforsitepages)) {
d20337f1 2380 $coursename = get_string('sitepages');
016ba638 2381 }
6caf3f5c
ARN
2382 } else if ($coursetype == self::COURSE_CURRENT) {
2383 $parent = $this->rootnodes['currentcourse'];
2384 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2385 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
db47f68f 2386 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
b0712163
SH
2387 // Nothing to do here the above statement set $parent to the category within mycourses.
2388 } else {
2389 $parent = $this->rootnodes['mycourses'];
2390 }
3406acde 2391 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
7a7e209d 2392 } else {
3406acde 2393 $parent = $this->rootnodes['courses'];
a6855934 2394 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
58b602da
SH
2395 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2396 if (!$this->is_category_fully_loaded($course->category)) {
8e8de15f 2397 // We need to load the category structure for this course
80c69522 2398 $this->load_all_categories($course->category, false);
8e8de15f
SH
2399 }
2400 if (array_key_exists($course->category, $this->addedcategories)) {
2401 $parent = $this->addedcategories[$course->category];
2402 // This could lead to the course being created so we should check whether it is the case again
2403 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2404 return $this->addedcourses[$course->id];
2405 }
3992a46e 2406 }
4766a50c
SH
2407 }
2408 }
2409
d20337f1 2410 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
3406acde
SH
2411 $coursenode->nodetype = self::NODETYPE_BRANCH;
2412 $coursenode->hidden = (!$course->visible);
1d8a1a87
SH
2413 // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2414 // later.
2415 $coursenode->title(str_replace('&amp;', '&', $fullname));
e26507b3 2416 if (!$forcegeneric) {
082513ba 2417 $this->addedcourses[$course->id] = $coursenode;
e26507b3 2418 }
e26507b3 2419
3406acde 2420 return $coursenode;
7d2a0492 2421 }
8e8de15f
SH
2422
2423 /**
2424 * Returns true if the category has already been loaded as have any child categories
2425 *
2426 * @param int $categoryid
2427 * @return bool
2428 */
2429 protected function is_category_fully_loaded($categoryid) {
2430 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2431 }
2432
7d2a0492 2433 /**
3406acde 2434 * Adds essential course nodes to the navigation for the given course.
7d2a0492 2435 *
3406acde 2436 * This method adds nodes such as reports, blogs and participants
7d2a0492 2437 *
3406acde
SH
2438 * @param navigation_node $coursenode
2439 * @param stdClass $course
31fde54f 2440 * @return bool returns true on successful addition of a node.
7d2a0492 2441 */
2027c10e 2442 public function add_course_essentials($coursenode, stdClass $course) {
98556b23 2443 global $CFG, $SITE;
7d2a0492 2444
98556b23 2445 if ($course->id == $SITE->id) {
3406acde 2446 return $this->add_front_page_course_essentials($coursenode, $course);
7d2a0492 2447 }
7d2a0492 2448
2027c10e 2449 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
3406acde 2450 return true;
7d2a0492 2451 }
7d2a0492 2452
3406acde
SH
2453 //Participants
2454 if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
3406acde 2455 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
24f4bfcf
SC
2456 if (!empty($CFG->enableblogs)) {
2457 if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2458 and has_capability('moodle/blog:view', context_system::instance())) {
0967e635
MG
2459 $blogsurls = new moodle_url('/blog/index.php');
2460 if ($course->id == $SITE->id) {
2461 $blogsurls->param('courseid', 0);
2462 } else if ($currentgroup = groups_get_course_group($course, true)) {
2463 $blogsurls->param('groupid', $currentgroup);
2464 } else {
2465 $blogsurls->param('courseid', $course->id);
2466 }
24f4bfcf
SC
2467 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2468 }
3406acde
SH
2469 }
2470 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
41eae0d9 2471 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
3406acde 2472 }
533299cb 2473 } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
3406acde
SH
2474 $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2475 }
2476
27806552 2477 // Badges.
1dcb9ff1
YB
2478 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2479 has_capability('moodle/badges:viewbadges', $this->page->context)) {
2480 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
27806552
YB
2481
2482 $coursenode->add(get_string('coursebadges', 'badges'), null,
2483 navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2484 $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2485 navigation_node::TYPE_SETTING, null, 'badgesview',
2486 new pix_icon('i/badge', get_string('badgesview', 'badges')));
2487 }
2488
7d2a0492 2489 return true;
2490 }
deaf04c7 2491 /**
31fde54f 2492 * This generates the structure of the course that won't be generated when
deaf04c7
SH
2493 * the modules and sections are added.
2494 *
2495 * Things such as the reports branch, the participants branch, blogs... get
2496 * added to the course node by this method.
2497 *
2498 * @param navigation_node $coursenode
2499 * @param stdClass $course
2500 * @return bool True for successfull generation
2501 */
3406acde
SH
2502 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2503 global $CFG;
7d2a0492 2504
1fa692ed 2505 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
3406acde 2506 return true;
7a7e209d
SH
2507 }
2508
1fa692ed
SH
2509 // Hidden node that we use to determine if the front page navigation is loaded.
2510 // This required as there are not other guaranteed nodes that may be loaded.
2511 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2512
3406acde 2513 //Participants
0601e0ee 2514 if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
3406acde
SH
2515 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2516 }
435a512e 2517
83a5e4fc 2518 $filterselect = 0;
593270c6
MD
2519
2520 // Blogs
850d2db8 2521 if (!empty($CFG->enableblogs)
8f6c1f34 2522 and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
b0c6dc1c 2523 and has_capability('moodle/blog:view', context_system::instance())) {
8f6c1f34 2524 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
ec21eaba 2525 $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
7d2a0492 2526 }
593270c6 2527
27806552 2528 //Badges
1dcb9ff1 2529 if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
27806552
YB
2530 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2531 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2532 }
2533
593270c6 2534 // Notes
3406acde
SH
2535 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2536 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2537 }
593270c6
MD
2538
2539 // Tags
2540 if (!empty($CFG->usetags) && isloggedin()) {
3406acde 2541 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
7d2a0492 2542 }
6644741d 2543
e7f9b7ab
SH
2544 if (isloggedin()) {
2545 // Calendar
2546 $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2547 $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2548 }
6644741d 2549
3406acde 2550 return true;
6644741d 2551 }
da3ab9c4 2552
3406acde
SH
2553 /**
2554 * Clears the navigation cache
2555 */
2556 public function clear_cache() {
2557 $this->cache->clear();
da3ab9c4 2558 }
88f77c3c 2559
deaf04c7
SH
2560 /**
2561 * Sets an expansion limit for the navigation
2562 *
2563 * The expansion limit is used to prevent the display of content that has a type
2564 * greater than the provided $type.
2565 *
2566 * Can be used to ensure things such as activities or activity content don't get
2567 * shown on the navigation.
2568 * They are still generated in order to ensure the navbar still makes sense.
2569 *
2570 * @param int $type One of navigation_node::TYPE_*
31fde54f 2571 * @return bool true when complete.
deaf04c7 2572 */
88f77c3c 2573 public function set_expansion_limit($type) {
98556b23 2574 global $SITE;
88f77c3c 2575 $nodes = $this->find_all_of_type($type);
8718ffba
SH
2576
2577 // We only want to hide specific types of nodes.
2578 // Only nodes that represent "structure" in the navigation tree should be hidden.
2579 // If we hide all nodes then we risk hiding vital information.
2580 $typestohide = array(
2581 self::TYPE_CATEGORY,
2582 self::TYPE_COURSE,
2583 self::TYPE_SECTION,
2584 self::TYPE_ACTIVITY
2585 );
2586
ba7b1ca5 2587 foreach ($nodes as $node) {
1af67ecb 2588 // We need to generate the full site node
98556b23 2589 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
1af67ecb
SH
2590 continue;
2591 }
ba7b1ca5 2592 foreach ($node->children as $child) {
8718ffba 2593 $child->hide($typestohide);
88f77c3c
SH
2594 }
2595 }
2596 return true;
2597 }
deaf04c7
SH
2598 /**
2599 * Attempts to get the navigation with the given key from this nodes children.
2600 *
2601 * This function only looks at this nodes children, it does NOT look recursivily.
2602 * If the node can't be found then false is returned.
2603 *
93123b17 2604 * If you need to search recursivily then use the {@link global_navigation::find()} method.
deaf04c7 2605 *
93123b17 2606 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
deaf04c7
SH
2607 * may be of more use to you.
2608 *
2609 * @param string|int $key The key of the node you wish to receive.
2610 * @param int $type One of navigation_node::TYPE_*
2611 * @return navigation_node|false
2612 */
e2b436d0 2613 public function get($key, $type = null) {
246a9b05
SH
2614 if (!$this->initialised) {
2615 $this->initialise();
2616 }
54dc15ab 2617 return parent::get($key, $type);
e2b436d0
SH
2618 }
2619
deaf04c7 2620 /**
31fde54f 2621 * Searches this nodes children and their children to find a navigation node
deaf04c7
SH
2622 * with the matching key and type.
2623 *
2624 * This method is recursive and searches children so until either a node is
31fde54f 2625 * found or there are no more nodes to search.
deaf04c7
SH
2626 *
2627 * If you know that the node being searched for is a child of this node
93123b17 2628 * then use the {@link global_navigation::get()} method instead.
deaf04c7 2629 *
93123b17 2630 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
deaf04c7
SH
2631 * may be of more use to you.
2632 *
2633 * @param string|int $key The key of the node you wish to receive.
2634 * @param int $type One of navigation_node::TYPE_*
2635 * @return navigation_node|false
2636 */
e2b436d0 2637 public function find($key, $type) {
246a9b05
SH
2638 if (!$this->initialised) {
2639 $this->initialise();
2640 }
58b602da
SH
2641 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2642 return $this->rootnodes[$key];
2643 }
54dc15ab 2644 return parent::find($key, $type);
e2b436d0 2645 }
f87ce4e9
SH
2646
2647 /**
2648 * They've expanded the 'my courses' branch.
2649 */
2650 protected function load_courses_enrolled() {
2651 global $CFG, $DB;
2652 $sortorder = 'visible DESC';
a75dfd6f
EL
2653 // Prevent undefined $CFG->navsortmycoursessort errors.
2654 if (empty($CFG->navsortmycoursessort)) {
2655 $CFG->navsortmycoursessort = 'sortorder';
2656 }
f87ce4e9
SH
2657 // Append the chosen sortorder.
2658 $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2659 $courses = enrol_get_my_courses(null, $sortorder);
c629c91f 2660 if (count($courses) && $this->show_my_categories()) {
f87ce4e9
SH
2661 // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2662 // In order to make sure we load everything required we must first find the categories that are not
2663 // base categories and work out the bottom category in thier path.
2664 $categoryids = array();
2665 foreach ($courses as $course) {
2666 $categoryids[] = $course->category;
2667 }
2668 $categoryids = array_unique($categoryids);
2669 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2670 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2671 foreach ($categories as $category) {
2672 $bits = explode('/', trim($category->path,'/'));
2673 $categoryids[] = array_shift($bits);
2674 }
2675 $categoryids = array_unique($categoryids);
2676 $categories->close();
2677
2678 // Now we load the base categories.
2679 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2680 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2681 foreach ($categories as $category) {
257b59e7 2682 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
f87ce4e9
SH
2683 }
2684 $categories->close();
2685 } else {
2686 foreach ($courses as $course) {
2687 $this->add_course($course, false, self::COURSE_MY);
2688 }
2689 }
2690 }
7d2a0492 2691}
2692
2693/**
98556b23 2694 * The global navigation class used especially for AJAX requests.
7d2a0492 2695 *
2696 * The primary methods that are used in the global navigation class have been overriden
2697 * to ensure that only the relevant branch is generated at the root of the tree.
2698 * This can be done because AJAX is only used when the backwards structure for the
2699 * requested branch exists.
2700 * This has been done only because it shortens the amounts of information that is generated
2701 * which of course will speed up the response time.. because no one likes laggy AJAX.
2702 *
31fde54f
AG
2703 * @package core
2704 * @category navigation
7d2a0492 2705 * @copyright 2009 Sam Hemelryk
2706 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2707 */
507a7a9a 2708class global_navigation_for_ajax extends global_navigation {
3406acde 2709
31fde54f 2710 /** @var int used for determining what type of navigation_node::TYPE_* is being used */
39ae5e54 2711 protected $branchtype;
31fde54f
AG
2712
2713 /** @var int the instance id */
39ae5e54
SH
2714 protected $instanceid;
2715
31fde54f 2716 /** @var array Holds an array of expandable nodes */
3406acde
SH
2717 protected $expandable = array();
2718
7d2a0492 2719 /**
31fde54f
AG
2720 * Constructs the navigation for use in an AJAX request
2721 *
2722 * @param moodle_page $page moodle_page object
2723 * @param int $branchtype
2724 * @param int $id
3406acde 2725 */
246a9b05 2726 public function __construct($page, $branchtype, $id) {
4766a50c 2727 $this->page = $page;
3406acde
SH
2728 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2729 $this->children = new navigation_node_collection();
39ae5e54
SH
2730 $this->branchtype = $branchtype;
2731 $this->instanceid = $id;
2732 $this->initialise();
3406acde
SH
2733 }
2734 /**
2735 * Initialise the navigation given the type and id for the branch to expand.
7d2a0492 2736 *
31fde54f 2737 * @return array An array of the expandable nodes
7d2a0492 2738 */
39ae5e54 2739 public function initialise() {
58b602da 2740 global $DB, $SITE;
507a7a9a 2741
7d2a0492 2742 if ($this->initialised || during_initial_install()) {
95b97515 2743 return $this->expandable;
7d2a0492 2744 }
246a9b05
SH
2745 $this->initialised = true;
2746
2747 $this->rootnodes = array();
e26507b3 2748 $this->rootnodes['site'] = $this->add_course($SITE);
58b602da 2749 $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
246a9b05 2750 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
507a7a9a
SH
2751
2752 // Branchtype will be one of navigation_node::TYPE_*
39ae5e54 2753 switch ($this->branchtype) {
58b602da
SH
2754 case 0:
2755 if ($this->instanceid === 'mycourses') {
2756 $this->load_courses_enrolled();
2757 } else if ($this->instanceid === 'courses') {
2758 $this->load_courses_other();
2759 }
2760 break;
4766a50c 2761 case self::TYPE_CATEGORY :
d4bb6462 2762 $this->load_category($this->instanceid);
4766a50c 2763 break;
db47f68f
RT
2764 case self::TYPE_MY_CATEGORY :
2765 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2766 break;
507a7a9a 2767 case self::TYPE_COURSE :
74df2951 2768 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
04bcd1ce 2769 require_course_login($course, true, null, false, true);
b0c6dc1c 2770 $this->page->set_context(context_course::instance($course->id));
3406acde
SH
2771 $coursenode = $this->add_course($course);
2772 $this->add_course_essentials($coursenode, $course);
ee7084e9 2773 $this->load_course_sections($course, $coursenode);
7d2a0492 2774 break;
507a7a9a 2775 case self::TYPE_SECTION :
3406acde 2776 $sql = 'SELECT c.*, cs.section AS sectionnumber
507a7a9a
SH
2777 FROM {course} c
2778 LEFT JOIN {course_sections} cs ON cs.course = c.id
2779 WHERE cs.id = ?';
39ae5e54 2780 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
04bcd1ce 2781 require_course_login($course, true, null, false, true);
b0c6dc1c 2782 $this->page->set_context(context_course::instance($course->id));
3406acde
SH
2783 $coursenode = $this->add_course($course);
2784 $this->add_course_essentials($coursenode, $course);
e010b850 2785 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
7d2a0492 2786 break;
507a7a9a 2787 case self::TYPE_ACTIVITY :
c78262b5
SH
2788 $sql = "SELECT c.*
2789 FROM {course} c
2790 JOIN {course_modules} cm ON cm.course = c.id
2791 WHERE cm.id = :cmid";
2792 $params = array('cmid' => $this->instanceid);
2793 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
f0dcc212
SH
2794 $modinfo = get_fast_modinfo($course);
2795 $cm = $modinfo->get_cm($this->instanceid);
04bcd1ce 2796 require_course_login($course, true, $cm, false, true);
b0c6dc1c 2797 $this->page->set_context(context_module::instance($cm->id));
3406acde 2798 $coursenode = $this->load_course($course);
e010b850
MG
2799 if ($course->id != $SITE->id) {
2800 $this->load_course_sections($course, $coursenode, null, $cm);
1aa1e9b5 2801 }
e010b850 2802 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
7d2a0492 2803 break;
507a7a9a 2804 default:
3406acde 2805 throw new Exception('Unknown type');
507a7a9a 2806 return $this->expandable;
7d2a0492 2807 }
588a3953 2808
98556b23 2809 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
588a3953
SH
2810 $this->load_for_user(null, true);
2811 }
2812
507a7a9a 2813 $this->find_expandable($this->expandable);
507a7a9a 2814 return $this->expandable;
246a9b05
SH
2815 }
2816
58b602da
SH
2817 /**
2818 * They've expanded the general 'courses' branch.
2819 */
2820 protected function load_courses_other() {
2821 $this->load_all_courses();
2822 }
2823
d4bb6462
SH
2824 /**
2825 * Loads a single category into the AJAX navigation.
2826 *
2827 * This function is special in that it doesn't concern itself with the parent of
2828 * the requested category or its siblings.
2829 * This is because with the AJAX navigation we know exactly what is wanted and only need to
2830 * request that.
2831 *
2832 * @global moodle_database $DB
db47f68f
RT
2833 * @param int $categoryid id of category to load in navigation.
2834 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2835 * @return void.
d4bb6462 2836 */
db47f68f 2837 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
d4bb6462
SH
2838 global $CFG, $DB;
2839
2840 $limit = 20;
2841 if (!empty($CFG->navcourselimit)) {
2842 $limit = (int)$CFG->navcourselimit;
2843 }
2844
2845 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2846 $sql = "SELECT cc.*, $catcontextsql
2847 FROM {course_categories} cc
2848 JOIN {context} ctx ON cc.id = ctx.instanceid
2849 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2850 (cc.id = :categoryid1 OR cc.parent = :categoryid2)
957983b7 2851 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
d4bb6462
SH
2852 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2853 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
0627e1ce 2854 $categorylist = array();
d4bb6462
SH
2855 $subcategories = array();
2856 $basecategory = null;
2857 foreach ($categories as $category) {
0627e1ce 2858 $categorylist[] = $category->id;
d4bb6462
SH
2859 context_helper::preload_from_record($category);
2860 if ($category->id == $categoryid) {
db47f68f 2861 $this->add_category($category, $this, $nodetype);
d4bb6462
SH
2862 $basecategory = $this->addedcategories[$category->id];
2863 } else {
42b40f99 2864 $subcategories[$category->id] = $category;
d4bb6462
SH
2865 }
2866 }
2867 $categories->close();
2868
d4bb6462 2869
42b40f99
DV
2870 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2871 // else show all courses.
db47f68f
RT
2872 if ($nodetype === self::TYPE_MY_CATEGORY) {
2873 $courses = enrol_get_my_courses();
42b40f99
DV
2874 $categoryids = array();
2875
19263336 2876 // Only search for categories if basecategory was found.
42b40f99 2877 if (!is_null($basecategory)) {
19263336 2878 // Get course parent category ids.
42b40f99
DV
2879 foreach ($courses as $course) {
2880 $categoryids[] = $course->category;
2881 }
2882
19263336
EL
2883 // Get a unique list of category ids which a part of the path
2884 // to user's courses.
2885 $coursesubcategories = array();
2886 $addedsubcategories = array();
42b40f99
DV
2887
2888 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2889 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2890
2891 foreach ($categories as $category){
19263336 2892 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
42b40f99 2893 }
19263336 2894 $coursesubcategories = array_unique($coursesubcategories);
42b40f99 2895
19263336
EL
2896 // Only add a subcategory if it is part of the path to user's course and
2897 // wasn't already added.
2898 foreach ($subcategories as $subid => $subcategory) {
2899 if (in_array($subid, $coursesubcategories) &&
2900 !in_array($subid, $addedsubcategories)) {
42b40f99 2901 $this->add_category($subcategory, $basecategory, $nodetype);
19263336 2902 $addedsubcategories[] = $subid;
42b40f99
DV
2903 }
2904 }
2905 }
19263336 2906
db47f68f 2907 foreach ($courses as $course) {
0627e1ce
RT
2908 // Add course if it's in category.
2909 if (in_array($course->category, $categorylist)) {
2910 $this->add_course($course, true, self::COURSE_MY);
2911 }
db47f68f
RT
2912 }
2913 } else {
42b40f99
DV
2914 if (!is_null($basecategory)) {
2915 foreach ($subcategories as $key=>$category) {
2916 $this->add_category($category, $basecategory, $nodetype);
2917 }
2918 }
db47f68f
RT
2919 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2920 foreach ($courses as $course) {
2921 $this->add_course($course);
2922 }
2923 $courses->close();
d4bb6462 2924 }
d4bb6462
SH
2925 }
2926
deaf04c7
SH
2927 /**
2928 * Returns an array of expandable nodes
2929 * @return array
2930 */
246a9b05
SH
2931 public function get_expandable() {
2932 return $this->expandable;
7d2a0492 2933 }
7d2a0492 2934}
2935
2936/**
2937 * Navbar class
2938 *
2939 * This class is used to manage the navbar, which is initialised from the navigation
2940 * object held by PAGE
2941 *
31fde54f
AG
2942 * @package core
2943 * @category navigation
7d2a0492 2944 * @copyright 2009 Sam Hemelryk
2945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 */
2947class navbar extends navigation_node {
31fde54f 2948 /** @var bool A switch for whether the navbar is initialised or not */
7d2a0492 2949 protected $initialised = false;
31fde54f 2950 /** @var mixed keys used to reference the nodes on the navbar */
7d2a0492 2951 protected $keys = array();
31fde54f 2952 /** @var null|string content of the navbar */
7d2a0492 2953 protected $content = null;
31fde54f 2954 /** @var moodle_page object the moodle page that this navbar belongs to */
7d2a0492 2955 protected $page;
31fde54f 2956 /** @var bool A switch for whether to ignore the active navigation information */
31759089 2957 protected $ignoreactive = false;
31fde54f 2958 /** @var bool A switch to let us know if we are in the middle of an install */
7d2a0492 2959 protected $duringinstall = false;
31fde54f 2960 /** @var bool A switch for whether the navbar has items */
7a7e209d 2961 protected $hasitems = false;
31fde54f 2962 /** @var array An array of navigation nodes for the navbar */
3406acde 2963 protected $items;
31fde54f 2964 /** @var array An array of child node objects */
3406acde 2965 public $children = array();
31fde54f 2966 /** @var bool A switch for whether we want to include the root node in the navbar */
4d5059d4 2967 public $includesettingsbase = false;
c16b882b
SH
2968 /** @var navigation_node[] $prependchildren */
2969 protected $prependchildren = array();
7d2a0492 2970 /**
2971 * The almighty constructor
3406acde
SH
2972 *
2973 * @param moodle_page $page
7d2a0492 2974 */
3406acde 2975 public function __construct(moodle_page $page) {
507a7a9a 2976 global $CFG;
7d2a0492 2977 if (during_initial_install()) {
2978 $this->duringinstall = true;
2979 return false;
2980 }
2981 $this->page = $page;
2982 $this->text = get_string('home');
2983 $this->shorttext = get_string('home');
2984 $this->action = new moodle_url($CFG->wwwroot);
2985 $this->nodetype = self::NODETYPE_BRANCH;
2986 $this->type = self::TYPE_SYSTEM;
2987 }
2988
2989 /**
2990 * Quick check to see if the navbar will have items in.
2991 *
2992 * @return bool Returns true if the navbar will have items, false otherwise
2993 */
2994 public function has_items() {
2995 if ($this->duringinstall) {
2996 return false;
7a7e209d
SH
2997 } else if ($this->hasitems !== false) {
2998 return true;
7d2a0492 2999 }
3406acde 3000 $this->page->navigation->initialise($this->page);
bf6c37c7 3001
7a7e209d 3002 $activenodefound = ($this->page->navigation->contains_active_node() ||
3406acde 3003 $this->page->settingsnav->contains_active_node());
bf6c37c7 3004
c16b882b 3005 $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
7a7e209d 3006 $this->hasitems = $outcome;
bf6c37c7 3007 return $outcome;
31759089 3008 }
3009
3406acde
SH
3010 /**
3011 * Turn on/off ignore active
3012 *
3013 * @param bool $setting
3014 */
31759089 3015 public function ignore_active($setting=true) {
3016 $this->ignoreactive = ($setting);
7d2a0492 3017 }
31fde54f
AG
3018
3019 /**
3020 * Gets a navigation node
3021 *
3022 * @param string|int $key for referencing the navbar nodes
3023 * @param int $type navigation_node::TYPE_*
3024 * @return navigation_node|bool
3025 */
3406acde
SH
3026 public function get($key, $type = null) {
3027 foreach ($this->children as &$child) {
3028 if ($child->key === $key && ($type == null || $type == $child->type)) {
3029 return $child;
3030 }
3031 }
c16b882b
SH
3032 foreach ($this->prependchildren as &$child) {
3033 if ($child->key === $key && ($type == null || $type == $child->type)) {
3034 return $child;
3035 }
3036 }
3406acde
SH
3037 return false;
3038 }
7d2a0492 3039 /**
3406acde 3040 * Returns an array of navigation_node's that make up the navbar.
435a512e 3041 *
3406acde 3042 * @return array
7d2a0492 3043 */
3406acde 3044 public function get_items() {
abb29010 3045 global $CFG;
3406acde 3046 $items = array();
7d2a0492 3047 // Make sure that navigation is initialised
7a7e209d 3048 if (!$this->has_items()) {
3406acde 3049 return $items;
7a7e209d 3050 }
3406acde
SH
3051 if ($this->items !== null) {
3052 return $this->items;
7d2a0492 3053 }
3054