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