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