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