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