navigation MDL-20735 Fixed issue with unset cm contexts for front page course
[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 *
22 * @since 2.0
23 * @package moodlecore
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29if (!function_exists('get_all_sections')) {
30 /** Include course lib for its functions */
31 require_once($CFG->dirroot.'/course/lib.php');
32}
33
f5b5a822 34/**
2561c4e9 35 * The name that will be used to separate the navigation cache within SESSION
f5b5a822 36 */
37define('NAVIGATION_CACHE_NAME', 'navigation');
38
7d2a0492 39/**
40 * This class is used to represent a node in a navigation tree
41 *
42 * This class is used to represent a node in a navigation tree within Moodle,
43 * the tree could be one of global navigation, settings navigation, or the navbar.
44 * Each node can be one of two types either a Leaf (default) or a branch.
45 * When a node is first created it is created as a leaf, when/if children are added
46 * the node then becomes a branch.
47 *
48 * @package moodlecore
babb3911 49 * @subpackage navigation
7d2a0492 50 * @copyright 2009 Sam Hemelryk
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 */
53class navigation_node {
54 /** Used to identify this node a leaf (default) */
55 const NODETYPE_LEAF = 0;
56 /** Used to identify this node a branch, happens with children */
57 const NODETYPE_BRANCH = 1;
58 /** Unknown node type */
59 const TYPE_UNKNOWN = null;
60 /** System node type */
61 const TYPE_SYSTEM = 0;
62 /** Category node type */
63 const TYPE_CATEGORY = 10;
64 /** Course node type */
65 const TYPE_COURSE = 20;
66 /** Course Structure node type */
67 const TYPE_SECTION = 30;
68 /** Activity node type, e.g. Forum, Quiz */
69 const TYPE_ACTIVITY = 40;
70 /** Resource node type, e.g. Link to a file, or label */
71 const TYPE_RESOURCE = 50;
72 /** A custom node type, default when adding without specifing type */
73 const TYPE_CUSTOM = 60;
74 /** Setting node type, used only within settings nav */
75 const TYPE_SETTING = 70;
b14ae498 76 /** Setting node type, used only within settings nav */
77 const TYPE_USER = 80;
7d2a0492 78
79 /** @var int Parameter to aid the coder in tracking [optional] */
80 public $id = null;
81 /** @var string|int The identifier for the node, used to retrieve the node */
82 public $key = null;
83 /** @var string The text to use for the node */
84 public $text = null;
85 /** @var string Short text to use if requested [optional] */
86 public $shorttext = null;
87 /** @var string The title attribute for an action if one is defined */
88 public $title = null;
89 /** @var string A string that can be used to build a help button */
90 public $helpbutton = null;
91 /** @var moodle_url|string|null An action for the node (link) */
92 public $action = null;
93 /** @var string The path to an icon to use for this node */
94 public $icon = null;
95 /** @var int See TYPE_* constants defined for this class */
96 public $type = self::TYPE_UNKNOWN;
97 /** @var int See NODETYPE_* constants defined for this class */
98 public $nodetype = self::NODETYPE_LEAF;
99 /** @var bool If set to true the node will be collapsed by default */
100 public $collapse = false;
101 /** @var bool If set to true the node will be expanded by default */
102 public $forceopen = false;
103 /** @var string An array of CSS classes for the node */
104 public $classes = array();
105 /** @var array An array of child nodes */
106 public $children = array();
107 /** @var bool If set to true the node will be recognised as active */
108 public $isactive = false;
109 /** @var string If set to true the node will be dimmed */
110 public $hidden = false;
111 /** @var bool If set to false the node will not be displayed */
112 public $display = true;
113 /** @var bool If set to true then an HR will be printed before the node */
114 public $preceedwithhr = false;
115 /** @var bool If set to true the the navigation bar should ignore this node */
116 public $mainnavonly = false;
117 /** @var bool If set to true a title will be added to the action no matter what */
118 public $forcetitle = false;
119 /** @var array */
b14ae498 120 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
7d2a0492 121 /** @var moodle_url */
122 protected static $fullmeurl = null;
123
124 /**
125 * Establish the node, with either text string or array or properites
126 *
127 * Called when first creating the node, requires one argument which can be either
128 * a string containing the text for the node or an array or properties one of
129 * which must be text.
130 *
131 * <code>
132 * $PAGE->navigation->newitem = 'This is a new nav item';
133 * // or
134 * $properties = array()
135 * $properties['text'] = 'This is a new nav item';
136 * $properties['short'] = 'This is a new nav item';
137 * $properties['action'] = moodle_url($CFG->wwwroot.'/course/category.php');
138 * $properties['icon'] = $OUTPUT->old_icon_url('i/course');
139 * $properties['type'] = navigation_node::TYPE_COURSE;
140 * $properties['key'] = 'newitem';
141 * $PAGE->navigation->newitem = $properties;
142 * </code>
143 *
144 * The following are properties that must/can be set in the properties array
145 * <ul>
146 * <li><b>text</b>: You must set text, if this is not set a coding exception is thrown.</li>
147 * <li><b>short</b> <i>optional</i>: A short description used for navbar optional.</li>
148 * <li><b>action</b> <i>optional</i>: This can be either a {@link moodle_url} for a link, or string that can be directly output in instead of the text.</li>
149 * <li><b>icon</b> <i>optional</i>: The path to an icon to display with the node.</li>
150 * <li><b>type</b> <i>optional</i>: This type of the node, defaults to TYPE_CUSTOM.</li>
151 * <li><b>key</b> <i>optional</i>: This can be set to allow you to easily retrieve a node you have created.</li>
152 * </ul>
153 *
154 * @param string|array $properties
155 */
156 public function __construct($properties) {
157 global $PAGE;
158 if (is_array($properties)) {
159 if (array_key_exists('text', $properties)) {
160 $this->text = $properties['text'];
161 }
162 if (array_key_exists('shorttext', $properties)) {
163 $this->shorttext = $properties['shorttext'];
164 }
165 if (array_key_exists('action', $properties)) {
166 $this->action = $properties['action'];
bf6c37c7 167 if (is_string($this->action)) {
168 $this->action = new moodle_url($this->action);
169 }
7d2a0492 170 $this->check_if_active();
171 }
172 if (array_key_exists('icon', $properties)) {
173 $this->icon = $properties['icon'];
174 }
175 if (array_key_exists('type', $properties)) {
176 $this->type = $properties['type'];
177 } else {
178 $this->type = self::TYPE_CUSTOM;
179 }
180 if (array_key_exists('key', $properties)) {
181 $this->key = $properties['key'];
182 }
183 } else if (is_string($properties)) {
184 $this->text = $properties;
185 }
186 if ($this->text === null) {
187 throw new coding_exception('You must set the text for the node when you create it.');
188 }
189 $this->title = $this->text;
190 if (strlen($this->text)>50) {
191 $this->text = substr($this->text, 0, 50).'...';
192 }
193 if (is_string($this->shorttext) && strlen($this->shorttext)>25) {
194 $this->shorttext = substr($this->shorttext, 0, 25).'...';
195 }
196 }
197
95b97515 198 /**
199 * This function overrides the active URL that is used to compare new nodes
200 * to find out if they are active.
117bd748 201 *
95b97515 202 * If null is passed then $fullmeurl will be regenerated when the next node
203 * is created/added
204 */
205 public static function override_active_url(moodle_url $url=null) {
206 self::$fullmeurl = $url;
207 }
208
7d2a0492 209 /**
210 * This function checks if the node is the active child by comparing its action
211 * to the current page URL obtained via $ME
212 *
0baa5d46 213 * This function compares the nodes url to the static var {@link navigation_node::fullmeurl}
214 * and if they match (based on $strenght) then the node is considered active.
215 *
216 * Note: This function is recursive, when you call it it will check itself and all
217 * children recursivily.
218 *
7d2a0492 219 * @staticvar moodle_url $fullmeurl
bf6c37c7 220 * @param int $strength When using the moodle_url compare function how strictly
221 * to check for a match. Defaults to URL_MATCH_EXACT
222 * Can be URL_MATCH_EXACT or URL_MATCH_BASE
7d2a0492 223 * @return bool True is active, false otherwise
224 */
bf6c37c7 225 public function check_if_active($strength=URL_MATCH_EXACT) {
226 global $FULLME, $PAGE;
7d2a0492 227 if (self::$fullmeurl == null) {
bf6c37c7 228 if ($PAGE->has_set_url()) {
229 $url = new moodle_url($PAGE->url);
230 } else {
231 $url = new moodle_url($FULLME);
7d2a0492 232 }
bf6c37c7 233 self::$fullmeurl = $url;
7d2a0492 234 }
bf6c37c7 235
236 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
7d2a0492 237 $this->make_active();
238 return true;
bf6c37c7 239 } else if (is_string($this->action) && $this->action==self::$fullmeurl->out()) {
7d2a0492 240 $this->make_active();
241 return true;
242 }
243 return false;
244 }
245 /**
246 * This function allows the user to add a child node to this node.
247 *
248 * @param string $text The text to display in the node
91152a35 249 * @param string $action Either a moodle_url or a bit of html to use instead of the text <i>optional</i>
7d2a0492 250 * @param int $type The type of node should be one of the const types of navigation_node <i>optional</i>
d972bad1 251 * @param string $shorttext The short text to use for this node
252 * @param string|int $key Sets the key that can be used to retrieve this node <i>optional</i>
7d2a0492 253 * @param string $icon The path to an icon to use for this node <i>optional</i>
254 * @return string The key that was used for this node
255 */
d972bad1 256 public function add($text, $action=null, $type=null, $shorttext=null, $key=null, $icon=null) {
7d2a0492 257 if ($this->nodetype !== self::NODETYPE_BRANCH) {
258 $this->nodetype = self::NODETYPE_BRANCH;
259 }
260 $itemarray = array('text'=>$text);
261 if ($type!==null) {
262 $itemarray['type'] = $type;
263 } else {
264 $type = self::TYPE_CUSTOM;
265 }
266 if ($action!==null) {
267 $itemarray['action'] = $action;
268 }
269
270 if ($shorttext!==null) {
271 $itemarray['shorttext'] = $shorttext;
272 }
273 if ($icon!==null) {
274 $itemarray['icon'] = $icon;
275 }
276 if ($key===null) {
277 $key = count($this->children);
278 }
d926f4b1 279
280 $key = $key.':'.$type;
281
7d2a0492 282 $itemarray['key'] = $key;
283 $this->children[$key] = new navigation_node($itemarray);
c73e37e0 284 if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
7d2a0492 285 $this->children[$key]->nodetype = self::NODETYPE_BRANCH;
286 }
287 if ($this->hidden) {
288 $this->children[$key]->hidden = true;
289 }
290 return $key;
291 }
292
293 /**
294 * Adds a new node to a particular point by recursing through an array of node keys
295 *
296 * @param array $patharray An array of keys to recurse to find the correct node
297 * @param string $text The text to display in the node
298 * @param string|int $key Sets the key that can be used to retrieve this node <i>optional</i>
299 * @param int $type The type of node should be one of the const types of navigation_node <i>optional</i>
300 * @param string $action Either a moodle_url or a bit of html to use instead of the text <i>optional</i>
301 * @param string $icon The path to an icon to use for this node <i>optional</i>
302 * @return mixed Either the key used for the node once added or false for failure
303 */
304 public function add_to_path($patharray, $key=null, $text=null, $shorttext=null, $type=null, $action=null, $icon=null) {
305 if (count($patharray)==0) {
d972bad1 306 $key = $this->add($text, $action, $type, $shorttext, $key, $icon);
7d2a0492 307 return $key;
308 } else {
309 $pathkey = array_shift($patharray);
310 $child = $this->get($pathkey);
311 if ($child!==false) {
312 return $child->add_to_path($patharray, $key, $text, $shorttext, $type, $action, $icon);
313 } else {
314 return false;
315 }
316 }
317 }
318
319 /**
320 * Add a css class to this particular node
117bd748 321 *
7d2a0492 322 * @param string $class The css class to add
323 * @return bool Returns true
324 */
325 public function add_class($class) {
326 if (!in_array($class, $this->classes)) {
327 $this->classes[] = $class;
328 }
329 return true;
330 }
331
332 /**
333 * Removes a given class from this node if it exists
334 *
335 * @param string $class
336 * @return bool
337 */
338 public function remove_class($class) {
339 if (in_array($class, $this->classes)) {
340 $key = array_search($class,$this->classes);
341 if ($key!==false) {
342 unset($this->classes[$key]);
343 return true;
344 }
345 }
346 return false;
347 }
348
349 /**
350 * Recurse down child nodes and collapse everything once a given
351 * depth of recursion has been reached.
352 *
353 * This function is used internally during the initialisation of the nav object
354 * after the tree has been generated to collapse it to a suitable depth.
355 *
356 * @param int $depth defualts to 2
357 * @return bool Returns true
358 */
359 protected function collapse_at_depth($depth=2) {
360 if ($depth>0 && $this->nodetype===self::NODETYPE_BRANCH) {
361 foreach (array_keys($this->children) as $key) {
362 $this->children[$key]->collapse_at_depth($depth-1);
363 }
364 return true;
365 } else {
366 $this->collapse_children();
367 return true;
368 }
369 }
370
371 /**
372 * Collapses all of the child nodes recursion optional
373 *
374 * @param bool $recurse If set to true child nodes are closed recursively
375 * @return bool Returns true
376 */
377 protected function collapse_children($recurse=true) {
378 if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0) {
379 foreach ($this->children as &$child) {
380 if (!$this->forceopen) {
381 $child->collapse = true;
382 }
383 if ($recurse && $child instanceof navigation_node) {
384 $child->collapse_children($recurse);
385 }
386 }
387 unset($child);
388 }
389 return true;
390 }
391
392 /**
393 * Produce the actual HTML content for the node including any action or icon
394 *
395 * @param bool $shorttext If true then short text is used rather than text if it has been set
396 * @return string The HTML content
397 */
398 public function content($shorttext=false) {
dfca6e99 399 global $OUTPUT, $CFG, $PAGE;
7d2a0492 400 if (!$this->display) {
401 return '';
402 }
403 if ($shorttext && $this->shorttext!==null) {
0a8e8b6f 404 $content = clean_text($this->shorttext);
7d2a0492 405 } else {
0a8e8b6f 406 $content = clean_text($this->text);
7d2a0492 407 }
0a8e8b6f 408 $title = '';
409 if ($this->forcetitle || ($this->shorttext!==null && $this->title !== $this->shorttext) || $this->title !== $this->text) {
410 $title = $this->title;
411 }
412
1c4eef57 413 if ($this->icon!==null) {
414 $icon = new html_image();
415 $icon->src = $this->icon;
1c4eef57 416 $content = $OUTPUT->image($icon).' '.$content;
417 } else if ($this->helpbutton!==null) {
418 $content = sprintf('%s<span class="clearhelpbutton">%s</span>',trim($this->helpbutton),$content);
419 }
420
b14ae498 421 if ($content != '' && ((is_object($this->action) && ($this->action instanceof moodle_url || $this->action instanceof html_link)) || is_string($this->action))) {
422 if (!($this->action instanceof html_link)) {
423 $link = new html_link();
424 $link->url = $this->action;
425 $link->text = clean_text($content);
426 } else {
427 $link = $this->action;
428 }
0a8e8b6f 429 if ($title !== '') {
430 $link->title = $title;
7d2a0492 431 }
432 if ($this->hidden) {
433 $link->add_class('dimmed');
434 }
bf6c37c7 435
a4bead67 436 if (!empty($CFG->framename) && ($PAGE->generaltype=='topframe' || $CFG->framename!='_top')) {
fa42a689 437 $breakoutaction = new breakout_of_frame_action();
438 $link->add_action($breakoutaction);
439 }
bf6c37c7 440
7d2a0492 441 $content = $OUTPUT->link($link);
442 } else {
1c4eef57 443 $span = new html_span();
444 $span->contents = $content;
0a8e8b6f 445 if ($title !== '') {
1c4eef57 446 $span->title = $title;
0a8e8b6f 447 }
7d2a0492 448 if ($this->hidden) {
1c4eef57 449 $span->add_class('dimmed_text');
7d2a0492 450 }
1c4eef57 451 $content = $OUTPUT->span($span);
7d2a0492 452 }
453 return $content;
454 }
117bd748 455
7d2a0492 456 /**
457 * Get the CSS type for this node
117bd748 458 *
7d2a0492 459 * @return string
460 */
461 public function get_css_type() {
462 if (array_key_exists($this->type, $this->namedtypes)) {
463 return 'type_'.$this->namedtypes[$this->type];
464 }
465 return 'type_unknown';
466 }
467
468 /**
469 * Find and return a child node if it exists (returns a reference to the child)
470 *
471 * This function is used to search for and return a reference to a child node when provided
472 * with the child nodes key and type.
473 * If the child is found a reference to it is returned otherwise the default is returned.
474 *
475 * @param string|int $key The key of the child node you are searching for.
476 * @param int $type The type of the node you are searching for. Defaults to TYPE_CATEGORY
477 * @param mixed $default The value to return if the child cannot be found
478 * @return mixed The child node or what ever default contains (usually false)
479 */
480 public function find_child($key, $type=self::TYPE_CATEGORY, $default = false) {
d926f4b1 481 list($key, $type) = $this->split_key_type($key, $type);
482 if (array_key_exists($key.":".$type, $this->children)) {
483 return $this->children[$key.":".$type];
7d2a0492 484 } else if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0 && $this->type<=$type) {
485 foreach ($this->children as &$child) {
486 $outcome = $child->find_child($key, $type);
487 if ($outcome !== false) {
488 return $outcome;
489 }
490 }
491 }
492 return $default;
493 }
494
495 /**
496 * Find the active child
497 *
498 * @param null|int $type
499 * @return navigation_node|bool
500 */
501 public function find_active_node($type=null) {
502 if ($this->contains_active_node()) {
503 if ($type!==null && $this->type===$type) {
504 return $this;
505 }
506 if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0) {
507 foreach ($this->children as $child) {
508 if ($child->isactive) {
509 return $child;
510 } else {
511 $outcome = $child->find_active_node($type);
512 if ($outcome!==false) {
513 return $outcome;
514 }
515 }
516 }
517 }
518 }
519 return false;
520 }
521
522 /**
523 * Returns the depth of a child
524 *
525 * @param string|int $key The key for the child we are looking for
526 * @param int $type The type of the child we are looking for
527 * @return int The depth of the child once found
528 */
529 public function find_child_depth($key, $type=self::TYPE_CATEGORY) {
530 $depth = 0;
d926f4b1 531 list($key, $type) = $this->split_key_type($key, $type);
532 if (array_key_exists($key.':'.$type, $this->children)) {
7d2a0492 533 $depth = 1;
534 } else if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0 && $this->type<=$type) {
535 foreach ($this->children as $child) {
536 $depth += $child->find_child_depth($key, $type);
537 }
538 }
539 return $depth;
540 }
541
da3ab9c4
SH
542 /**
543 * Finds all nodes that have the specified type
544 *
545 * @param int $type One of navigation_node::TYPE_*
546 * @return array An array of navigation_node references for nodes of type $type
547 */
548 public function get_children_by_type($type) {
549 $nodes = array();
550 if (count($this->children)>0) {
551 foreach ($this->children as &$child) {
552 if ($child->type === $type) {
553 $nodes[] = $child;
554 }
555 }
556 }
557 return $nodes;
558 }
559
6644741d 560 /**
561 * Finds all nodes (recursivily) that have the specified type, regardless of
562 * assumed order or position.
563 *
564 * @param int $type One of navigation_node::TYPE_*
565 * @return array An array of navigation_node references for nodes of type $type
566 */
567 public function find_children_by_type($type) {
568 $nodes = array();
569 if (count($this->children)>0) {
570 foreach ($this->children as &$child) {
571 if ($child->type === $type) {
572 $nodes[] = $child;
573 }
574 if (count($child->children)>0) {
575 $nodes = array_merge($nodes, $child->find_children_by_type($type));
576 }
577 }
578 }
579 return $nodes;
580 }
581
7d2a0492 582 /**
583 * Toogles display of nodes and child nodes based on type
584 *
585 * If the type of a node if more than the type specified it's display property is set to false
586 * and it is not shown
587 *
588 * @param int $type
589 * @param bool $display
590 */
591 public function toggle_type_display($type=self::TYPE_COURSE, $display=false) {
592 if ((int)$this->type > $type) {
593 $this->display = $display;
594 }
595 if (count($this->children)>0) {
596 foreach ($this->children as $child) {
597 $child->toggle_type_display($type, $display);
598 }
599 }
600 }
601
602 /**
603 * Find out if a child (or subchild) of this node contains an active node
604 *
605 * @return bool True if it does fales otherwise
606 */
607 public function contains_active_node() {
608 if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0) {
609 foreach ($this->children as $child) {
610 if ($child->isactive || $child->contains_active_node()) {
611 return true;
612 }
613 }
614 }
615 return false;
616 }
617
618 /**
619 * Find all nodes that are expandable for this node and its given children.
620 *
621 * This function recursively finds all nodes that are expandable by AJAX within
622 * [and including] this child.
623 *
624 * @param array $expandable An array to fill with the HTML id's of all branches
625 * that can be expanded by AJAX. This is a forced reference.
6644741d 626 * @param int $expansionlimit Optional/used internally can be one of navigation_node::TYPE_*
7d2a0492 627 */
6644741d 628 public function find_expandable(&$expandable, $expansionlimit = null) {
7d2a0492 629 static $branchcount;
630 if ($branchcount==null) {
631 $branchcount=1;
632 }
6644741d 633 if ($this->nodetype == self::NODETYPE_BRANCH && count($this->children)==0 && ($expansionlimit === null || $this->type < $expansionlimit)) {
7d2a0492 634 $this->id = 'expandable_branch_'.$branchcount;
6644741d 635 $this->add_class('canexpand');
7d2a0492 636 $branchcount++;
637 $expandable[] = array('id'=>$this->id,'branchid'=>$this->key,'type'=>$this->type);
6644741d 638 } else if ($this->nodetype==self::NODETYPE_BRANCH && ($expansionlimit === null || $this->type <= $expansionlimit)) {
7d2a0492 639 foreach ($this->children as $child) {
6644741d 640 $child->find_expandable($expandable, $expansionlimit);
7d2a0492 641 }
642 }
643 }
644
645 /**
646 * Used to return a child node with a given key
647 *
648 * This function searchs for a child node with the provided key and returns the
649 * child. If the child doesn't exist then this function returns false.
650 *
651 * @param int|string $key The key to search for
d926f4b1 652 * @param int $type Optional one of TYPE_* constants
7d2a0492 653 * @param navigation_node|bool The child if it exists or false
654 */
d926f4b1 655 public function get($key, $type=null) {
7d2a0492 656 if ($key===false) {
657 return false;
658 }
d926f4b1 659 list($key, $type) = $this->split_key_type($key);
7d2a0492 660 if ($this->nodetype === self::NODETYPE_BRANCH && count($this->children)>0) {
d926f4b1 661 if ($type!==null) {
662 if (array_key_exists($key.':'.$type, $this->children)) {
663 return $this->children[$key.':'.$type];
664 }
665 } else {
666 foreach (array_keys($this->children) as $childkey) {
667 if (strpos($childkey, $key.':')===0) {
668 return $this->children[$childkey];
669 }
670 }
7d2a0492 671 }
672 }
673 return false;
674 }
675
d926f4b1 676 /**
677 * This function is used to split a key into its key and value parts if the
678 * key is a combination of the two.
679 *
680 * Was introduced to help resolve MDL-20543
681 *
682 * @param string $key
683 * @param int|null $type
684 * @return array
685 */
686 protected function split_key_type($key, $type=null) {
687 /**
688 * If the key is a combination it will be of the form `key:type` where key
689 * could be anything and type will be an int value
690 */
691 if (preg_match('#^(.*)\:(\d{1,3})$#', $key, $match)) {
692 /**
693 * If type is null then we want to collect and return the type otherwise
694 * we will use the provided type. This ensures that if a type was specified
695 * it is not lost
696 */
697 if ($type===null) {
698 $type = $match[2];
699 }
700 $key = $match[1];
701 }
702 return array($key, $type);
703 }
704
7d2a0492 705 /**
706 * Fetch a node given a set of keys that describe its path
707 *
708 * @param array $keys An array of keys
709 * @return navigation_node|bool The node or false
710 */
711 public function get_by_path($keys) {
712 if (count($keys)==1) {
713 $key = array_shift($keys);
714 return $this->get($key);
715 } else {
716 $key = array_shift($keys);
717 $child = $this->get($key);
718 if ($child !== false) {
719 return $child->get_by_path($keys);
720 }
721 return false;
722 }
723 }
724
9da1ec27 725 /**
726 * Returns the child marked as active if there is one, false otherwise.
727 *
728 * @return navigation_node|bool The active node or false
729 */
730 public function get_active_node() {
731 foreach ($this->children as $child) {
732 if ($child->isactive) {
733 return $child;
734 }
735 }
736 return false;
737 }
738
7d2a0492 739 /**
740 * Mark this node as active
741 *
742 * This function marks the node as active my forcing the node to be open,
743 * setting isactive to true, and adding the class active_tree_node
744 */
745 public function make_active() {
746 $this->forceopen = true;
747 $this->isactive = true;
748 $this->add_class('active_tree_node');
749 }
750
751 /**
752 * This intense little function looks for branches that are forced open
753 * and checks to ensure that all parent nodes are also forced open.
754 */
755 public function respect_forced_open() {
756 foreach ($this->children as $child) {
757 $child->respect_forced_open();
758 if ($child->forceopen) {
759 $this->forceopen = true;
760 }
761 }
762 }
763
764 /**
765 * This function simply removes a given child node
766 *
767 * @param string|int $key The key that identifies a child node
768 * @return bool
769 */
3d97797b
SH
770 public function remove_child($key, $type=null) {
771 $child = $this->get($key, $type);
772
773 if ($child) {
774 unset($this->children[$child->key]);
7d2a0492 775 return true;
776 }
3d97797b 777
7d2a0492 778 return false;
779 }
780
781 /**
782 * Iterate all children and check if any of them are active
783 *
784 * This function iterates all children recursively until it sucecssfully marks
785 * a node as active, or gets to the end of the tree.
786 * This can be used on a cached branch to mark the active child.
787 *
bf6c37c7 788 * @param int $strength When using the moodle_url compare function how strictly
789 * to check for a match. Defaults to URL_MATCH_EXACTLY
7d2a0492 790 * @return bool True is a node was marked active false otherwise
791 */
bf6c37c7 792 public function reiterate_active_nodes($strength=URL_MATCH_EXACT) {
7d2a0492 793 if ($this->nodetype !== self::NODETYPE_BRANCH) {
794 return false;
795 }
796 foreach ($this->children as $child) {
bf6c37c7 797 $outcome = $child->check_if_active($strength);
7d2a0492 798 if (!$outcome && $child->nodetype === self::NODETYPE_BRANCH) {
bf6c37c7 799 $outcome = $child->reiterate_active_nodes($strength);
7d2a0492 800 }
801 if ($outcome) {
c705a24e 802 $this->forceopen = true;
7d2a0492 803 return true;
804 }
805 }
806 }
807
808 /**
809 * This function sets the title for the node and at the same time sets
810 * forcetitle to true to ensure that it is used if possible
811 *
812 * @param string $title
813 */
814 public function title($title) {
815 $this->title = $title;
816 $this->forcetitle = true;
817 }
818
819 /**
820 * Magic Method: When we unserialise an object make it `unactive`
821 *
822 * This is to ensure that when we take a branch out of the cache it is not marked
823 * active anymore, as we can't be sure it still is (infact it most likely isnt)
824 */
825 public function __wakeup(){
826 $this->forceopen = false;
827 $this->isactive = false;
828 $this->remove_class('active_tree_node');
829 }
830}
831
832/**
833 * The global navigation class used for... the global navigation
834 *
835 * This class is used by PAGE to store the global navigation for the site
836 * and is then used by the settings nav and navbar to save on processing and DB calls
837 *
838 * See
839 * <ul>
840 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
841 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
842 * </ul>
843 *
844 * @package moodlecore
babb3911 845 * @subpackage navigation
7d2a0492 846 * @copyright 2009 Sam Hemelryk
847 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
848 */
849class global_navigation extends navigation_node {
850 /** @var int */
851 protected $depthforward = 1;
852 /** @var cache */
853 protected $cache = null;
854 /** @var bool */
855 protected $initialised = false;
856
857 /** @var null|int */
858 public $expansionlimit = null;
859 /** @var stdClass */
860 public $context = null;
861 /** @var mixed */
862 public $expandable = null;
863 /** @var bool */
864 public $showemptybranches = true;
865 /** @var bool */
866 protected $isloggedin = false;
867
868 /**
869 * Sets up the object with basic settings and preparse it for use
870 */
871 public function __construct() {
872 global $CFG, $PAGE;
873 if (during_initial_install()) {
874 return false;
875 }
876 $this->key = 0;
877 $this->type = self::TYPE_SYSTEM;
878 $this->isloggedin = isloggedin();
879 $this->text = get_string('home');
880 $this->forceopen = true;
881 $this->action = new moodle_url($CFG->wwwroot);
f5b5a822 882 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
7d2a0492 883 $PAGE->requires->string_for_js('moveallsidetabstoblock','moodle');
884 $regenerate = optional_param('regenerate', null, PARAM_TEXT);
885 if ($regenerate==='navigation') {
886 $this->cache->clear();
887 }
888 }
889
890 /**
891 * Override: This function generated the content of the navigation
892 *
893 * If an expansion limit has been set then we hide everything to after that
894 * set limit type
895 *
896 * @return string
897 */
898 public function content() {
899 if ($this->expansionlimit!==null) {
900 $this->toggle_type_display($this->expansionlimit);
901 }
902 return parent::content();
903 }
117bd748 904
7d2a0492 905 /**
906 * Initialise the navigation object, calling it to auto generate
907 *
908 * This function starts the navigation object automatically retrieving what it
909 * needs from Moodle objects.
910 *
911 * It also passed Javascript args and function calls as required
912 *
913 * @return bool Returns true
914 */
915 public function initialise($jsargs = null) {
da3ab9c4 916 global $PAGE, $SITE, $CFG;
7d2a0492 917 if ($this->initialised || during_initial_install()) {
918 return true;
919 }
920 $start = microtime(false);
921 $this->depthforward = 1;
922 $this->context = &$PAGE->context;
923 $contextlevel = $this->context->contextlevel;
924 if ($contextlevel == CONTEXT_COURSE && $PAGE->course->id==$SITE->id) {
925 $contextlevel = 10;
926 }
927 $depth = 0;
83797643
SH
928
929 /**
930 * We always want to load the front page activities into the tree, these
931 * will appear at the bottom of the opening (site) node.
932 */
933 $sitekeys = array();
934 $this->load_course_activities($sitekeys, $SITE);
7d2a0492 935 switch ($contextlevel) {
f5b5a822 936 case CONTEXT_SYSTEM:
937 $this->cache->volatile();
7d2a0492 938 $depth = $this->load_for_category(false);
939 break;
117bd748 940 case CONTEXT_COURSECAT:
7d2a0492 941 $depth = $this->load_for_category();
942 break;
943 case CONTEXT_BLOCK:
117bd748 944 case CONTEXT_COURSE:
7d2a0492 945 $depth = $this->load_for_course();
946 break;
be6c8dfe 947 case CONTEXT_MODULE:
7d2a0492 948 $depth = $this->load_for_activity();
949 break;
117bd748 950 case CONTEXT_USER:
7d2a0492 951 $depth = $this->load_for_user();
952 break;
953 }
954 $this->collapse_at_depth($this->depthforward+$depth);
955 $this->respect_forced_open();
956 $expandable = array();
957 $this->find_expandable($expandable);
958 $this->expandable = $expandable;
959 $this->initialised = true;
960 return true;
961 }
962 /**
963 * This function loads the global navigation structure for a user.
964 *
965 * This gets called by {@link initialise()} when the context is CONTEXT_USER
966 */
967 protected function load_for_user() {
da3ab9c4 968 global $DB, $SITE, $PAGE, $CFG;
05c039e5 969 if (!empty($PAGE->course->id)) {
970 $courseid = $PAGE->course->id;
971 } else {
972 $courseid = optional_param('course', false, PARAM_INT);
973 }
7d2a0492 974 if ($courseid!==false && $courseid!=$SITE->id) {
975 $course = $DB->get_record('course', array('id'=>$courseid));
976 }
977 if (isset($course) && $course) {
da3ab9c4
SH
978 if (!empty($CFG->navshowallcourses)) {
979 $this->load_categories();
980 }
7d2a0492 981 $this->load_for_course();
982 } else {
983 $this->load_categories();
984 }
985 }
986
987 /**
988 * Called by the initalise methods if the context was system or category
989 *
990 * @param bool $lookforid If system context then we dont want ID because
991 * it could be userid, courseid, or anything else
992 * @return int The depth to the active(requested) node
993 */
994 protected function load_for_category($lookforid=true) {
995 global $PAGE, $CFG;
996 $id = optional_param('id', null);
997 if ($lookforid && $id!==null) {
da3ab9c4
SH
998 if (!empty($CFG->navshowallcourses)) {
999 $this->load_categories();
1000 }
7d2a0492 1001 $this->load_categories($id);
1002 $depth = $this->find_child_depth($id);
1003 } else {
1004 $depth = $this->load_categories();
1005 }
1006 return $depth;
1007 }
1008
1009 /**
1010 * Called by the initialise methods if the context was course
1011 *
1012 * @return int The depth to the active(requested) node
1013 */
1014 protected function load_for_course() {
d755d8c3 1015 global $PAGE, $CFG, $USER;
7d2a0492 1016 $keys = array();
da3ab9c4
SH
1017 if (!empty($CFG->navshowallcourses)) {
1018 $this->load_categories();
1019 }
7d2a0492 1020 $depth = $this->load_course_categories($keys);
1021 $depth += $this->load_course($keys);
1022 if (!$this->format_display_course_content($PAGE->course->format)) {
1023 $child = $this->get_by_path($keys);
1024 if ($child!==false) {
1025 $child->nodetype = self::NODETYPE_LEAF;
1026 }
1027 return $depth;
1028 }
d755d8c3 1029
1030 if (isloggedin() && has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $PAGE->course->id))) {
1031 $depth += $this->load_course_activities($keys);
1032 $depth += $this->load_course_sections($keys);
1033 }
7d2a0492 1034 return $depth;
1035 }
1036
1037 /**
1038 * Check whether the course format defines a display_course_content function
1039 * that can be used to toggle whether or not to display course content
1040 *
1041 * $default is set to true, which may seem counter productive, however it ensures
1042 * backwards compatibility for course types that havn't yet defined the callback
1043 *
1044 * @param string $format
1045 * @param bool $default
1046 * @return bool
1047 */
1048 protected function format_display_course_content($format, $default=true) {
1049 global $CFG;
117bd748
PS
1050 //
1051 //
7d2a0492 1052 $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1053 if (file_exists($formatlib)) {
1054 require_once($formatlib);
1055 $displayfunc = 'callback_'.$format.'_display_content';
1056 if (function_exists($displayfunc) && !$displayfunc()) {
1057 return $displayfunc();
1058 }
1059 }
1060 return $default;
1061 }
1062
1063 /**
1064 * Internal method to load course activities into the global navigation structure
1065 * Course activities are activities that are in section 0
1066 *
1067 * @param array $keys By reference
1068 */
1069 protected function load_course_activities(&$keys, $course=null) {
1070 global $PAGE, $OUTPUT, $CFG, $FULLME;
1071
1072 if ($course === null) {
1073 $course = $PAGE->course;
1074 }
1075
3b7a763c 1076 if (!$this->cache->compare('modinfo'.$course->id, $course->modinfo, false)) {
7d2a0492 1077 $this->cache->{'modinfo'.$course->id} = get_fast_modinfo($course);
1078 }
1079 $modinfo = $this->cache->{'modinfo'.$course->id};
1080
1081 $resources = array('resource', 'label');
1082 if (!$this->cache->cached('canviewhiddenactivities')) {
1083 $this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
1084 }
1085 $viewhiddenactivities = $this->cache->canviewhiddenactivities;
117bd748 1086
7d2a0492 1087 foreach ($modinfo->cms as $module) {
1088 if ($module->sectionnum!='0' || (!$viewhiddenactivities && !$module->visible)) {
1089 continue;
1090 }
1091 $icon = null;
1092 if (!in_array($module->modname, $resources)) {
1093 if ($module->icon=='') {
1094 $icon = $OUTPUT->mod_icon_url('icon', $module->modname);
1095 }
1096 $url = new moodle_url($CFG->wwwroot.'/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
1097 $type = navigation_node::TYPE_ACTIVITY;
1098 } else {
1099 $url = null;
1100 $type = navigation_node::TYPE_RESOURCE;
1101 if ($module->modname!='label') {
1102 $url = new moodle_url('/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
1103 }
1104 if ($module->icon!=='') {
1105 $icon = $OUTPUT->old_icon_url(preg_replace('#\.(png|gif)$#i','',$module->icon));
1106 }
1107 }
1108 $this->add_to_path($keys, $module->id, $module->name, $module->name, $type, $url, $icon);
1109 $child = $this->find_child($module->id, $type);
1110 if ($child != false) {
0a8e8b6f 1111 $child->title(get_string('modulename', $module->modname));
7d2a0492 1112 if ($type==navigation_node::TYPE_ACTIVITY && $this->module_extends_navigation($module->modname)) {
1113 $child->nodetype = self::NODETYPE_BRANCH;
1114 }
1115 if (!$module->visible) {
1116 $child->hidden = true;
1117 }
1118 }
1119 }
1120 }
1121 /**
1122 * Internal function to load the activities within sections
117bd748 1123 *
7d2a0492 1124 * @param array $keys By reference
1125 */
1126 protected function load_section_activities(&$keys, $singlesectionid=false, $course=null) {
1127 global $PAGE, $OUTPUT, $CFG, $FULLME;
1128
1129 if ($course === null) {
1130 $course = $PAGE->course;
1131 }
1132
3b7a763c 1133 if (!$this->cache->compare('modinfo'.$course->id, $course->modinfo, false)) {
7d2a0492 1134 $this->cache->{'modinfo'.$course->id} = get_fast_modinfo($course);
1135 }
1136 $modinfo = $this->cache->{'modinfo'.$course->id};
1137
1138 if (!$this->cache->cached('coursesections'.$course->id)) {
1139 $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
1140 }
1141 $sections = $this->cache->{'coursesections'.$course->id};
1142
1143 $resources = array('resource', 'label');
1144
1145 if (!$this->cache->cached('canviewhiddenactivities')) {
1146 $this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
1147 }
1148 $viewhiddenactivities = $this->cache->viewhiddenactivities;
1149 foreach ($modinfo->cms as $module) {
1150 if ($module->sectionnum=='0' || (!$viewhiddenactivities && !$module->visible) || ($singlesectionid!=false && $module->sectionnum!==$singlesectionid)) {
1151 continue;
1152 }
1153 $icon = null;
1154 if (!in_array($module->modname, $resources)) {
1155 if ($module->icon=='') {
1156 $icon = $OUTPUT->mod_icon_url('icon', $module->modname);
1157 }
1158 $url = new moodle_url($CFG->wwwroot.'/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
1159 $type = navigation_node::TYPE_ACTIVITY;
1160 } else {
1161 $url = null;
1162 $type = navigation_node::TYPE_RESOURCE;
1163 if ($module->modname!='label') {
1164 $url = new moodle_url($CFG->wwwroot.'/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
1165 }
1166 if ($module->icon!=='') {
1167 $icon = $OUTPUT->old_icon_url(preg_replace('#\.(png|gif)$#i','',$module->icon));
1168 }
1169 }
1170 $path = $keys;
1171 $path[] = $sections[$module->sectionnum]->id;
1172 $this->add_to_path($path, $module->id, $module->name, $module->name, $type, $url, $icon);
1173 $child = $this->find_child($module->id, $type);
1174 if ($child != false) {
0a8e8b6f 1175 $child->title(get_string('modulename', $module->modname));
7d2a0492 1176 if (!$module->visible) {
1177 $child->hidden = true;
1178 }
1179 if ($type==navigation_node::TYPE_ACTIVITY && $this->module_extends_navigation($module->modname)) {
1180 $child->nodetype = self::NODETYPE_BRANCH;
1181 }
1182 }
1183 }
1184 }
1185
1186 /**
1187 * Check if a given module has a method to extend the navigation
1188 *
1189 * @param string $modname
1190 * @return bool
1191 */
1192 protected function module_extends_navigation($modname) {
1193 global $CFG;
1194 if ($this->cache->cached($modname.'_extends_navigation')) {
1195 return $this->cache->{$modname.'_extends_navigation'};
1196 }
1197 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1198 $function = $modname.'_extend_navigation';
1199 if (function_exists($function)) {
1200 $this->cache->{$modname.'_extends_navigation'} = true;
1201 return true;
1202 } else if (file_exists($file)) {
1203 require_once($file);
1204 if (function_exists($function)) {
1205 $this->cache->{$modname.'_extends_navigation'} = true;
1206 return true;
1207 }
1208 }
1209 $this->cache->{$modname.'_extends_navigation'} = false;
1210 return false;
1211 }
1212 /**
1213 * Load the global navigation structure for an activity
1214 *
1215 * @return int
1216 */
1217 protected function load_for_activity() {
da3ab9c4 1218 global $PAGE, $DB, $CFG;
7d2a0492 1219 $keys = array();
1220
1221 $sectionnum = false;
1222 if (!empty($PAGE->cm->section)) {
1223 $section = $DB->get_record('course_sections', array('id'=>$PAGE->cm->section));
1224 if (!empty($section->section)) {
1225 $sectionnum = $section->section;
1226 }
1227 }
1228
da3ab9c4
SH
1229 if (!empty($CFG->navshowallcourses)) {
1230 $this->load_categories();
1231 }
1232
7d2a0492 1233 $depth = $this->load_course_categories($keys);
1234 $depth += $this->load_course($keys);
1235 $depth += $this->load_course_activities($keys);
1236 $depth += $this->load_course_sections($keys);
91152a35 1237 $depth += $this->load_section_activities($keys,$sectionnum);
7d2a0492 1238 $depth += $this->load_activity($keys);
1239 return $depth;
1240 }
1241
1242 /**
1243 * This function loads any navigation items that might exist for an activity
1244 * by looking for and calling a function within the modules lib.php
1245 *
1246 * @param int $instanceid
1247 * @return void
1248 */
1249 protected function load_activity($keys) {
1250 global $DB, $CFG, $PAGE;
1251
4dd5bce8 1252 if (!$PAGE->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
7eef78de
SH
1253 // This is risky but we have no other choice... we need that module and the module
1254 // itself hasn't set PAGE->cm (usually set by require_login)
1255 // Chances are this is a front page module.
1256 $cm = get_coursemodule_from_id(false, $this->context->instanceid);
4dd5bce8 1257 if ($cm) {
7eef78de 1258 $cm->context = $this->context;
4dd5bce8 1259 $PAGE->set_cm($cm, $PAGE->course);
1260 } else {
1261 debugging('The module has not been set against the page but we are attempting to generate module specific information for navigation', DEBUG_DEVELOPER);
1262 return;
1263 }
1264 }
1265
7d2a0492 1266 $module = $DB->get_record('modules', array('id'=>$PAGE->cm->module));
117bd748 1267
7d2a0492 1268 if (!$module) {
4dd5bce8 1269 debugging('Invalid Module ID picked up while attempting to load the activity for the navigation', DEBUG_DEVELOPER);
7d2a0492 1270 return;
1271 }
1272
be6c8dfe 1273 $node = $this->find_child($PAGE->cm->id, self::TYPE_ACTIVITY);
1274 if ($node) {
1275 $node->make_active();
7eef78de
SH
1276 if (!isset($PAGE->course->context)) {
1277 // If we get here chances we are on a front page module
1278 $this->context = $PAGE->context;
1279 } else {
1280 $this->context = $PAGE->course->context;
1281 }
be6c8dfe 1282 $file = $CFG->dirroot.'/mod/'.$module->name.'/lib.php';
1283 $function = $module->name.'_extend_navigation';
417a273d
SH
1284
1285 if (empty($PAGE->cm->context)) {
1286 $PAGE->cm->context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->instance);
1287 }
1288
be6c8dfe 1289 if (file_exists($file)) {
1290 require_once($file);
117bd748 1291 if (function_exists($function)) {
459e384e 1292 $function($node, $PAGE->course, $module, $PAGE->cm);
7d2a0492 1293 }
1294 }
1295 }
1296 }
1297
1298 /**
1299 * Recursively adds an array of category objexts to the path provided by $keys
1300 *
1301 * @param array $keys An array of keys representing the path to add to
1302 * @param array $categories An array of [nested] categories to add
1303 * @param int $depth The current depth, this ensures we don't generate more than
1304 * we need to
1305 */
1306 protected function add_categories(&$keys, $categories, $depth=0) {
1307 global $CFG;
1308 if (is_array($categories) && count($categories)>0) {
1309 foreach ($categories as $category) {
1310 $url = new moodle_url($CFG->wwwroot.'/course/category.php', array('id'=>$category->id, 'categoryedit'=>'on', 'sesskey'=>sesskey()));
1311 $categorykey = $this->add_to_path($keys, $category->id, $category->name, $category->name, self::TYPE_CATEGORY, $url);
1312 if ($depth < $this->depthforward) {
1313 $this->add_categories(array_merge($keys, array($categorykey)), $category->id, $depth+1);
1314 }
1315 }
1316 }
1317 }
1318
1319 /**
1320 * This function adds a category to the nav tree based on the categories path
117bd748 1321 *
7d2a0492 1322 * @param stdClass $category
1323 */
1324 protected function add_category_by_path($category) {
1325 global $CFG;
1326 $url = new moodle_url($CFG->wwwroot.'/course/category.php', array('id'=>$category->id, 'categoryedit'=>'on', 'sesskey'=>sesskey()));
1327 $keys = explode('/',trim($category->path,'/ '));
1328 $currentcategory = array_pop($keys);
1329 $categorykey = $this->add_to_path($keys, $category->id, $category->name, $category->name, self::TYPE_CATEGORY, $url);
1330 return $categorykey;
1331 }
1332
1333 /**
1334 * Adds an array of courses to thier correct categories if the categories exist
1335 *
1336 * @param array $courses An array of course objects
1337 * @param int $categoryid An override to add the courses to
1338 * @return bool
1339 */
1340 public function add_courses($courses, $categoryid=null) {
1341 global $CFG, $OUTPUT, $SITE;
1342 if (is_array($courses) && count($courses)>0) {
1343 // Work out if the user can view hidden courses, just incase
1344 if (!$this->cache->cached('canviewhiddencourses')) {
1345 $this->cache->canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $this->context);
1346 }
1347 $canviewhidden = $this->cache->canviewhiddencourses;
1348 $expandcourse = $this->can_display_type(self::TYPE_SECTION);
1349 foreach ($courses as $course) {
1350 // Check if the user can't view hidden courses and if the course is hidden, if so skip and continue
1351 if ($course->id!=$SITE->id && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1352 continue;
1353 }
1354 // Process this course into the nav structure
1355 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id));
1356 if ($categoryid===null) {
da3ab9c4
SH
1357 $category = $this->find_child($course->category, self::TYPE_CATEGORY);
1358 } else if ($categoryid === false) {
1359 $category = $this;
7d2a0492 1360 } else {
1361 $category = $this->find_child($categoryid);
1362 }
1363 if ($category!==false) {
d972bad1 1364 $coursekey = $category->add($course->fullname, $url, self::TYPE_COURSE, $course->shortname, $course->id, $OUTPUT->old_icon_url('i/course'));
7d2a0492 1365 if (!$course->visible) {
1366 $category->get($course->id)->hidden = true;
1367 }
1368 if ($expandcourse!==true) {
1369 $category->get($course->id)->nodetype = self::NODETYPE_LEAF;
1370 }
1371 }
1372 }
1373 }
1374 return true;
1375 }
1376
1377 /**
1378 * Loads the current course into the navigation structure
1379 *
1380 * Loads the current course held by $PAGE {@link moodle_page()} into the navigation
1381 * structure.
1382 * If the course structure has an appropriate display method then the course structure
1383 * will also be displayed.
1384 *
1385 * @param array $keys The path to add the course to
1386 * @return bool
1387 */
1388 protected function load_course(&$keys, $course=null) {
1389 global $PAGE, $CFG, $OUTPUT;
1390 if ($course===null) {
1391 $course = $PAGE->course;
1392 }
83797643
SH
1393 if (is_object($course) && $course->id !== SITEID) {
1394
7d2a0492 1395 if (!$this->cache->cached('canviewhiddencourses')) {
1396 $this->cache->canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $this->context);
1397 }
1398 $canviewhidden = $this->cache->canviewhiddencourses;
1399
1400 if (!$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1401 return;
1402 }
1403 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id));
1404 $keys[] = $this->add_to_path($keys, $course->id, $course->fullname, $course->shortname, self::TYPE_COURSE, $url, $OUTPUT->old_icon_url('i/course'));
1405 $currentcourse = $this->find_child($course->id, self::TYPE_COURSE);
1406 if ($currentcourse!==false){
1407 $currentcourse->make_active();
1408 if (!$course->visible) {
1409 $currentcourse->hidden = true;
1410 }
4881edc9 1411
1412 //Participants
1413 if (has_capability('moodle/course:viewparticipants', $this->context)) {
1414 $participantskey = $currentcourse->add(get_string('participants'));
1415 $participants = $currentcourse->get($participantskey);
1416 if ($participants) {
78566999 1417 $participants->mainnavonly = true;
1418 $url = new moodle_url($CFG->wwwroot.'/user/index.php?id='.$course->id);
4881edc9 1419 $participants->add(get_string('participantslist'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/users'));
1420
1421 require_once($CFG->dirroot.'/blog/lib.php');
1422
1423 $currentgroup = groups_get_course_group($course, true);
1424 if ($course->id == SITEID) {
1425 $filterselect = '';
1426 } else if ($course->id && !$currentgroup) {
1427 $filterselect = $course->id;
1428 } else {
1429 $filterselect = $currentgroup;
1430 }
1431 $filterselect = clean_param($filterselect, PARAM_INT);
1432
1433 if ($CFG->bloglevel >= 3) {
1c7b8b93
NC
1434 $blogsurls = new moodle_url($CFG->wwwroot.'/blog/index.php', array('courseid' => $filterselect));
1435 $participants->add(get_string('blogs','blog'), $blogsurls->out());
4881edc9 1436 }
117bd748 1437
4881edc9 1438 if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->context) || has_capability('moodle/notes:view', $this->context))) {
1439 $participants->add(get_string('notes','notes'), new moodle_url($CFG->wwwroot.'/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1440 }
1441 }
1442 }
1443
1444 // View course reports
1445 if (has_capability('moodle/site:viewreports', $this->context)) { // basic capability for listing of reports
dfab77a2 1446 $reportkey = $currentcourse->add(get_string('reports'), new moodle_url($CFG->wwwroot.'/course/report.php', array('id'=>$course->id)), self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/stats'));
4881edc9 1447 $reportnav = $currentcourse->get($reportkey);
1448 if ($reportnav) {
1449 $coursereports = get_plugin_list('coursereport');
1450 foreach ($coursereports as $report=>$dir) {
dfab77a2 1451 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1452 if (file_exists($libfile)) {
1453 require_once($libfile);
1454 $reportfunction = $report.'_report_extend_navigation';
1455 if (function_exists($report.'_report_extend_navigation')) {
1456 $reportfunction($reportnav, $course, $this->context);
1457 }
4881edc9 1458 }
1459 }
1460 }
1461 }
7d2a0492 1462 }
1463
1464 if (!$this->can_display_type(self::TYPE_SECTION)) {
1465 if ($currentcourse!==false) {
1466 $currentcourse->nodetype = self::NODETYPE_LEAF;
1467 }
1468 return true;
1469 }
1470 }
1471 }
1472 /**
1473 * Loads the sections for a course
1474 *
1475 * @param array $keys By reference
1476 * @param stdClass $course The course that we are loading sections for
1477 */
1478 protected function load_course_sections(&$keys, $course=null) {
1479 global $PAGE, $CFG;
1480 if ($course === null) {
1481 $course = $PAGE->course;
1482 }
1483 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1484 $structurefunc = 'callback_'.$course->format.'_load_content';
1485 if (function_exists($structurefunc)) {
1486 $structurefunc($this, $keys, $course);
1487 } else if (file_exists($structurefile)) {
1488 require_once $structurefile;
1489 if (function_exists($structurefunc)) {
1490 $structurefunc($this, $keys, $course);
1491 } else {
1492 $this->add_course_section_generic($keys, $course);
1493 }
1494 } else {
1495 $this->add_course_section_generic($keys, $course);
1496 }
1497 }
1498 /**
1499 * This function loads the sections for a course if no given course format
1500 * methods have been defined to do so. Thus generic
1501 *
1502 * @param array $keys By reference
1503 * @param stdClass $course The course object to load for
1504 * @param string $name String to use to describe the current section to the user
1505 * @param string $activeparam Request variable to look for to determine the current section
1506 * @return bool
1507 */
1508 public function add_course_section_generic(&$keys, $course=null, $name=null, $activeparam = null) {
1509 global $PAGE, $CFG, $OUTPUT;
1510
1511 if ($course === null) {
1512 $course = $PAGE->course;
1513 }
1514
1515 $coursesecstr = 'coursesections'.$course->id;
1516 if (!$this->cache->cached($coursesecstr)) {
1517 $sections = get_all_sections($course->id);
1518 $this->cache->$coursesecstr = $sections;
1519 } else {
1520 $sections = $this->cache->$coursesecstr;
1521 }
117bd748 1522
3b7a763c 1523 if (!$this->cache->compare('modinfo'.$course->id, $course->modinfo, false)) {
7d2a0492 1524 $this->cache->{'modinfo'.$course->id} = get_fast_modinfo($course);
1525 }
1526 $modinfo = $this->cache->{'modinfo'.$course->id};
1527
1528 $depthforward = 0;
1529 if (!is_array($modinfo->sections)) {
1530 return $keys;
1531 }
1532
1533 if ($name === null) {
1534 $name = get_string('topic');
1535 }
1536
1537 if ($activeparam === null) {
1538 $activeparam = 'topic';
1539 }
1540
1541 $coursenode = $this->find_child($course->id, navigation_node::TYPE_COURSE);
1542 if ($coursenode!==false) {
1543 $coursenode->action->param($activeparam,'0');
1544 }
1545
1546 if (!$this->cache->cached('canviewhiddenactivities')) {
1547 $this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
1548 }
1549 $viewhiddenactivities = $this->cache->canviewhiddenactivities;
1550
1551 if (!$this->cache->cached('canviewhiddensections')) {
1552 $this->cache->canviewhiddensections = has_capability('moodle/course:viewhiddensections', $this->context);
1553 }
1554 $viewhiddensections = $this->cache->canviewhiddensections;
1555
1556 $selectedstructure = optional_param($activeparam,false,PARAM_INT);
5afb01e8 1557
1558 // This is required to make sure that if people have reduced the number
1559 // of sections after adding activities to sections that no longer exist
1560 // we dont show them
1561 // MDL-20242
1562 $sections = array_slice($sections, 0, $course->numsections, true);
1563
7d2a0492 1564 foreach ($sections as $section) {
1565 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptybranches && !array_key_exists($section->section, $modinfo->sections))) {
1566 continue;
1567 }
1568 if ($section->section!=0) {
1569 $sectionkeys = $keys;
1570 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1571 $this->add_to_path($sectionkeys, $section->id, $name.' '.$section->section, null, navigation_node::TYPE_SECTION, $url);
1572 $sectionchild = $this->find_child($section->id, navigation_node::TYPE_SECTION);
1573 if ($sectionchild !== false) {
1574 $sectionchild->nodetype = self::NODETYPE_BRANCH;
1575 if ($sectionchild->isactive) {
1576 $this->load_section_activities($sectionkeys, $section->section);
1577 }
1578 if (!$section->visible) {
1579 $sectionchild->hidden = true;
1580 }
1581 }
1582 }
1583 }
1584 return true;
1585 }
1586
1587 /**
1588 * Check if we are permitted to display a given type
1589 *
1590 * @return bool True if we are, False otherwise
1591 */
1592 protected function can_display_type($type) {
1593 if (!is_null($this->expansionlimit) && $this->expansionlimit < $type) {
1594 return false;
1595 }
1596 return true;
1597 }
1598
1599 /**
1600 * Loads the categories for the current course into the navigation structure
1601 *
1602 * @param array $keys Forced reference to and array to use for the keys
1603 * @return int The number of categories
1604 */
1605 protected function load_course_categories(&$keys) {
1606 global $PAGE, $CFG, $DB;
1607 $categories = $PAGE->categories;
1608 if (is_array($categories) && count($categories)>0) {
1609 $categories = array_reverse($categories);
1610 foreach ($categories as $category) {
da3ab9c4
SH
1611 $key = $category->id.':'.self::TYPE_CATEGORY;
1612 if (!$this->get_by_path(array_merge($keys, array($key)))) {
1613 $url = new moodle_url($CFG->wwwroot.'/course/category.php', array('id'=>$category->id, 'categoryedit'=>'on', 'sesskey'=>sesskey()));
1614 $keys[] = $this->add_to_path($keys, $category->id, $category->name, $category->name, self::TYPE_CATEGORY, $url);
1615 } else {
1616 $keys[] = $key;
1617 }
7d2a0492 1618 }
1619 }
1620 return count($categories);
1621 }
1622
1623 /**
1624 * This is called by load_for_category to load categories into the navigation structure
1625 *
1626 * @param int $categoryid The specific category to load
1627 * @return int The depth of categories that were loaded
1628 */
1629 protected function load_categories($categoryid=0) {
1630 global $PAGE, $CFG, $DB, $USER;
1631
ceebb2ec 1632 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1633
7d2a0492 1634 // Cache capability moodle/site:config we use this in the next bit of code
1635 if (!$this->cache->cached('hassiteconfig')) {
ceebb2ec 1636 $this->cache->hassiteconfig = has_capability('moodle/site:config', $systemcontext);
7d2a0492 1637 }
1638
1639 // If the user is logged in (but not as a guest), doesnt have the site config capability,
1640 // and my courses havn't been disabled then we will show the user's courses in the
1641 // global navigation, otherwise we will show up to FRONTPAGECOURSELIMIT available courses
ceebb2ec 1642 if (isloggedin() && !$this->cache->hassiteconfig && !isguestuser() && empty($CFG->disablemycourses)) {
7d2a0492 1643 if (!$this->cache->cached('mycourses')) {
1644 $this->cache->mycourses = get_my_courses($USER->id);
1645 }
1646 $courses = $this->cache->mycourses;
1647 } else {
1648 // Check whether we have already cached the available courses
1649 if (!$this->cache->cached('availablecourses')) {
1650 // Non-cached - get accessinfo
1651 if (isset($USER->access)) {
1652 $accessinfo = $USER->access;
1653 } else {
1654 $accessinfo = get_user_access_sitewide($USER->id);
1655 }
1656 // Get the available courses using get_user_courses_bycap
1657 $this->cache->availablecourses = get_user_courses_bycap($USER->id, 'moodle/course:view',
1658 $accessinfo, true, 'c.sortorder ASC',
1659 array('fullname','visible', 'category'),
1660 FRONTPAGECOURSELIMIT);
1661 }
1662 // Cache the available courses for a refresh
1663 $courses = $this->cache->availablecourses;
1664 }
1665
1666 // Iterate through all courses, and explode thier course category paths so that
1667 // we can retrieve all of the individual category id's that are required
1668 // to display the list of courses in the tree
1669 $categoryids = array();
1670 foreach ($courses as $course) {
1671 // If a category id has been specified and the current course is not within
1672 // that category or one of its children then skip this course
6644741d 1673 if ($categoryid!==0 && !preg_match('#/('.$categoryid.')(/|$)#', $course->categorypath)) {
7d2a0492 1674 continue;
1675 }
1676 $categorypathids = explode('/',trim($course->categorypath,' /'));
1677 // If no category has been specified limit the depth we display immediatly to
1678 // that of the nav var depthforwards
da3ab9c4 1679 if ($categoryid===0 && count($categorypathids)>($this->depthforward+1) && empty($CFG->navshowallcourses)) {
7d2a0492 1680 $categorypathids = array_slice($categorypathids, 0, ($this->depthforward+1));
1681 }
1682 $categoryids = array_merge($categoryids, $categorypathids);
1683 }
1684 // Remove duplicate categories (and there will be a few)
1685 $categoryids = array_unique($categoryids);
1686
1687 // Check whether we have some category ids to display and make sure that either
1688 // no category has been specified ($categoryid===0) or that the category that
1689 // has been specified is in the list.
1690 if (count($categoryids)>0 && ($categoryid===0 || in_array($categoryid, $categoryids))) {
1691 $catcachestr = 'categories'.join($categoryids);
1692 if (!$this->cache->cached($catcachestr)) {
1693 $this->cache->{$catcachestr} = $DB->get_records_select('course_categories', 'id IN ('.join(',', $categoryids).')', array(), 'path ASC, sortorder ASC');
1694 }
1695 $categories = $this->cache->{$catcachestr};
1696 // Retrieve the nessecary categories and then proceed to add them to the tree
1697 foreach ($categories as $category) {
1698 $this->add_category_by_path($category);
1699 }
1700 // Add the courses that were retrieved earlier to the
1701 $this->add_courses($courses);
6644741d 1702 } else if ($categoryid === 0) {
7d2a0492 1703 $keys = array();
1704 if ($categoryid!=0) {
1705 if (!$this->cache->cached('category'.$categoryid)) {
1706 $this->cache->{'category'.$categoryid} = $DB->get_record('course_categories', array('id' => $categoryid), 'id,name,path');
1707 }
1708 $category = $this->cache->{'category'.$categoryid};
1709 if ($category!=false) {
1710 $keys = explode('/',trim($category->path,'/ '));
1711 $categories = $DB->get_records_select('course_categories', 'id IN ('.join(',', $keys).')', array(), 'path ASC, sortorder ASC');
1712 foreach ($categories as $category) {
1713 $this->add_category_by_path($category);
1714 }
1715 }
117bd748 1716 }
7d2a0492 1717 $categories = $DB->get_records('course_categories', array('parent' => $categoryid), 'sortorder ASC');
1718 $this->add_categories($keys, $categories);
117bd748 1719 #$courses = $DB->get_records('course', array('category' => $categoryid), 'sortorder ASC', 'id,fullname,shortname,visible,category');
7d2a0492 1720 $this->add_courses($courses, $categoryid);
1721 }
1722 return 0;
1723 }
f5b5a822 1724
1725 /**
1726 * This function marks the cache as volatile so it is cleared during shutdown
1727 */
1728 public function clear_cache() {
1729 $this->cache->volatile();
1730 }
6644741d 1731
1732 /**
1733 * Finds all expandable nodes whilst ensuring that expansion limit is respected
1734 *
1735 * @param array $expandable A reference to an array that will be populated as
1736 * we go.
1737 */
1738 public function find_expandable(&$expandable) {
1739 parent::find_expandable($expandable, $this->expansionlimit);
1740 }
1741
1742 /**
1743 * Loads categories that contain no courses into the structure.
1744 *
1745 * These categories would normally be skipped, as such this function is purely
1746 * for the benefit of code external to navigationlib
1747 */
1748 public function load_empty_categories() {
1749 $categories = array();
1750 $categorynames = array();
1751 $categoryparents = array();
1752 make_categories_list($categorynames, $categoryparents, '', 0, $category = NULL);
1753 foreach ($categorynames as $id=>$name) {
1754 if (!$this->find_child($id, self::TYPE_CATEGORY)) {
1755 $category = new stdClass;
1756 $category->id = $id;
1757 if (array_key_exists($id, $categoryparents)) {
1758 $category->path = '/'.join('/',array_merge($categoryparents[$id],array($id)));
1759 $name = explode('/', $name);
1760 $category->name = join('/', array_splice($name, count($categoryparents[$id])));
1761 } else {
1762 $category->path = '/'.$id;
1763 $category->name = $name;
1764 }
1765 $this->add_category_by_path($category);
1766 }
1767 }
1768 }
da3ab9c4
SH
1769
1770 public function collapse_course_categories() {
1771 $categories = $this->get_children_by_type(self::TYPE_CATEGORY);
1772 while (count($categories) > 0) {
1773 foreach ($categories as $category) {
1774 $this->children = array_merge($this->children, $category->children);
1775 $this->remove_child($category->key, self::TYPE_CATEGORY);
1776}
1777 $categories = $this->get_children_by_type(self::TYPE_CATEGORY);
1778 }
1779 }
7d2a0492 1780}
1781
1782/**
1783 * The limited global navigation class used for the AJAX extension of the global
1784 * navigation class.
1785 *
1786 * The primary methods that are used in the global navigation class have been overriden
1787 * to ensure that only the relevant branch is generated at the root of the tree.
1788 * This can be done because AJAX is only used when the backwards structure for the
1789 * requested branch exists.
1790 * This has been done only because it shortens the amounts of information that is generated
1791 * which of course will speed up the response time.. because no one likes laggy AJAX.
1792 *
1793 * @package moodlecore
babb3911 1794 * @subpackage navigation
7d2a0492 1795 * @copyright 2009 Sam Hemelryk
1796 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1797 */
1798class limited_global_navigation extends global_navigation {
1799 /**
1800 * Initialise the limited navigation object, calling it to auto generate
1801 *
1802 * This function can be used to initialise the global navigation object more
1803 * flexibly by providing a couple of overrides.
1804 * This is used when the global navigation is being generated without other fully
1805 * initialised Moodle objects
1806 *
1807 * @param int $type What to load for e.g. TYPE_SYSTEM
1808 * @param int $instanceid The instance id for what ever is being loaded
1809 * @return array An array of nodes that are expandable by AJAX
1810 */
1811 public function initialise($type, $instanceid) {
1812 if ($this->initialised || during_initial_install()) {
95b97515 1813 return $this->expandable;
7d2a0492 1814 }
1815 $depth = 0;
1816 switch ($type) {
117bd748 1817 case self::TYPE_CATEGORY:
7d2a0492 1818 $depth = $this->load_category($instanceid);
1819 break;
117bd748 1820 case self::TYPE_COURSE:
7d2a0492 1821 $depth = $this->load_course($instanceid);
1822 break;
117bd748 1823 case self::TYPE_SECTION:
7d2a0492 1824 $depth = $this->load_section($instanceid);
1825 break;
117bd748 1826 case self::TYPE_ACTIVITY:
7d2a0492 1827 $depth = $this->load_activity($instanceid);
1828 break;
1829 }
1830 $this->collapse_at_depth($this->depthforward+$depth);
1831 $this->respect_forced_open();
1832 $expandable = array();
1833 $this->find_expandable($expandable);
1834 $this->expandable = $expandable;
1835 $this->initialised = true;
1836 return $expandable;
1837 }
1838
1839 /**
1840 * Loads the content (sub categories and courses) for a given a category
1841 *
1842 * @param int $instanceid
1843 */
1844 protected function load_category($instanceid) {
6644741d 1845 if (!$this->cache->cached('coursecatcontext'.$instanceid)) {
1846 $this->cache->{'coursecatcontext'.$instanceid} = get_context_instance(CONTEXT_COURSECAT, $instanceid);
7d2a0492 1847 }
6644741d 1848 $this->context = $this->cache->{'coursecatcontext'.$instanceid};
7d2a0492 1849 $this->load_categories($instanceid);
1850 }
1851
1852 /**
1853 * Use the instance id to load a course
117bd748 1854 *
7d2a0492 1855 * {@link global_navigation::load_course()}
1856 * @param int $instanceid
1857 */
1858 protected function load_course($instanceid) {
1859 global $DB, $PAGE;
1860
1861 if (!$this->cache->cached('course'.$instanceid)) {
1862 $this->cache->{'course'.$instanceid} = $DB->get_record('course', array('id'=>$instanceid));
1863 }
1864 $course = $this->cache->{'course'.$instanceid};
1865
1866 if (!$course) {
1867 echo "Invalid Course ID";
1868 break;
1869 }
1870
1871 if (!$this->format_display_course_content($course->format)) {
1872 return true;
1873 }
1874
1875 if (!$this->cache->cached('coursecontext'.$course->id)) {
1876 $this->cache->{'coursecontext'.$course->id} = get_context_instance(CONTEXT_COURSE, $course->id);
1877 }
1878 $this->context = $this->cache->{'coursecontext'.$course->id};
1879
1880 $keys = array();
1881 parent::load_course($keys, $course);
d755d8c3 1882
1883 if (isloggedin() && has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $instanceid))) {
1884
1885 if (!$this->cache->cached('course'.$course->id.'section0')) {
1886 $this->cache->{'course'.$course->id.'section0'} = $DB->get_record('course_sections', array('course'=>$course->id, 'section'=>'0'));
1887 }
1888 $section = $this->cache->{'course'.$course->id.'section0'};
1889 $this->load_section_activities($course, $section);
1890 if ($this->depthforward>0) {
1891 $this->load_course_sections($keys, $course);
1892 }
7d2a0492 1893 }
1894 }
1895 /**
1896 * Use the instance id to load a specific course section
1897 *
1898 * @param int $instanceid
1899 */
1900 protected function load_section($instanceid=0) {
1901 global $DB, $PAGE, $CFG;
1902 $section = $DB->get_record('course_sections', array('id'=>$instanceid));
117bd748 1903
7d2a0492 1904 if (!$section) {
1905 echo "Invalid Course Section ID";
1906 }
1907
1908 if (!$this->cache->cached('course'.$section->course)) {
1909 $this->cache->{'course'.$section->course} = $DB->get_record('course', array('id'=>$section->course));
1910 }
1911 $course = $this->cache->{'course'.$section->course};
1912 if (!$course) {
1913 echo "Invalid Course ID";
1914 }
1915
1916 if (!$this->cache->cached('coursecontext'.$course->id)) {
1917 $this->cache->{'coursecontext'.$course->id} = get_context_instance(CONTEXT_COURSE, $course->id);
1918 }
1919 $this->context = $this->cache->{'coursecontext'.$course->id};
1920
1921 // Call the function to generate course section
1922 $keys = array();
1923 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/navigation_format.php';
1924 $structurefunc = 'callback_'.$course->format.'_load_limited_section';
1925 if (function_exists($structurefunc)) {
1926 $sectionnode = $structurefunc($this, $keys, $course, $section);
1927 } else if (file_exists($structurefile)) {
1928 include $structurefile;
1929 if (function_exists($structurefunc)) {
1930 $sectionnode = $structurefunc($this, $keys, $course, $section);
1931 } else {
1932 $sectionnode = $this->limited_load_section_generic($keys, $course, $section);
1933 }
1934 } else {
1935 $sectionnode = $this->limited_load_section_generic($keys, $course, $section);
1936 }
1937 if ($this->depthforward>0) {
1938 $this->load_section_activities($course, $section);
1939 }
1940 }
1941 /**
1942 * This function is called if there is no specific course format function set
1943 * up to load sections into the global navigation.
1944 *
1945 * Note that if you are writing a course format you can call this function from your
1946 * callback function if you don't want to load anything special but just specify the
1947 * GET argument that identifies the current section as well as the string that
1948 * can be used to describve the section. e.g. weeks or topic
1949 *
1950 * @param array $keys
1951 * @param stdClass $course
1952 * @param stdClass $section
1953 * @param string $name
1954 * @param string $activeparam
1955 * @return navigation_node|bool
1956 */
1957 public function limited_load_section_generic($keys, $course, $section, $name=null, $activeparam = null) {
1958 global $PAGE, $CFG;
1959 if ($name === null) {
1960 $name = get_string('topic');
1961 }
1962
1963 if ($activeparam === null) {
1964 $activeparam = 'topic';
1965 }
1966
1967 if (!$this->cache->cached('canviewhiddensections')) {
1968 $this->cache->canviewhiddensections = has_capability('moodle/course:viewhiddensections', $this->context);
1969 }
1970 $viewhiddensections = $this->cache->canviewhiddensections;
1971
1972 $selectedstructure = optional_param($activeparam,false,PARAM_INT);
1973 if (!$viewhiddensections && !$section->visible) {
1974 continue;
1975 }
1976 if ($section->section!=0) {
1977 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, $activeparam=>$section->id));
1978 $keys[] = $this->add_to_path($keys, $section->id, $name.' '.$section->section, null, navigation_node::TYPE_SECTION, $url);
1979 $sectionchild = $this->find_child($section->id, navigation_node::TYPE_SECTION);
1980 if ($sectionchild !== false) {
1981 $sectionchild->nodetype = self::NODETYPE_BRANCH;
1982 $sectionchild->make_active();
1983 if (!$section->visible) {
1984 $sectionchild->hidden = true;
1985 }
1986 return $sectionchild;
1987 }
1988 }
1989 return false;
1990 }
1991
1992 /**
1993 * This function is used to load a course sections activities
1994 *
1995 * @param stdClass $course
1996 * @param stdClass $section
1997 * @return void
1998 */
1999 protected function load_section_activities($course, $section) {
2000 global $OUTPUT, $CFG;
2001 if (!is_object($section)) {
2002 return;
2003 }
2004 if ($section->section=='0') {
2005 $keys = array($section->course);
2006 } else {
2007 $keys = array($section->id);
2008 }
2009
2010 $modinfo = get_fast_modinfo($course);
117bd748 2011
7d2a0492 2012 $resources = array('resource', 'label');
2013
2014 if (!$this->cache->cached('canviewhiddenactivities')) {
2015 $this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
2016 }
2017 $viewhiddenactivities = $this->cache->canviewhiddenactivities;
117bd748 2018
7d2a0492 2019 foreach ($modinfo->cms as $module) {
2020 if ((!$viewhiddenactivities && !$module->visible) || $module->sectionnum != $section->section) {
2021 continue;
2022 }
2023 $icon = null;
2024 if (!in_array($module->modname, $resources)) {
2025 if ($module->icon=='') {
2026 $icon = $OUTPUT->mod_icon_url('icon', $module->modname);
2027 }
2028 $url = new moodle_url($CFG->wwwroot.'/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
2029 $type = navigation_node::TYPE_ACTIVITY;
2030 } else {
2031 $url = null;
2032 $type = navigation_node::TYPE_RESOURCE;
2033 if ($module->modname!='label') {
2034 $url = new moodle_url($CFG->wwwroot.'/mod/'.$module->modname.'/view.php', array('id'=>$module->id));
2035 }
2036 if ($module->icon!=='') {
2037 $icon = $OUTPUT->old_icon_url(preg_replace('#\.(png|gif)$#i','',$module->icon));
2038 }
2039 }
2040 $this->add_to_path($keys, $module->id, $module->name, $module->name, $type, $url, $icon);
2041 $child = $this->find_child($module->id, $type);
2042 if ($child != false) {
0a8e8b6f 2043 $child->title(get_string('modulename', $module->modname));
7d2a0492 2044 if (!$module->visible) {
2045 $child->hidden = true;
2046 }
2047 if ($type==navigation_node::TYPE_ACTIVITY && $this->module_extends_navigation($module->modname)) {
2048 $child->nodetype = self::NODETYPE_BRANCH;
2049 }
2050 }
2051 }
2052 }
2053
2054 /**
2055 * This function loads any navigation items that might exist for an activity
2056 * by looking for and calling a function within the modules lib.php
2057 *
2058 * @param int $instanceid
2059 * @return void
2060 */
2061 protected function load_activity($instanceid) {
2062 global $DB, $CFG;
2063 $cm = $DB->get_record('course_modules', array('id'=>$instanceid));
2064 if (!$cm) {
2065 echo "Invalid Course Module ID";
2066 return;
2067 }
2068 $module = $DB->get_record('modules', array('id'=>$cm->module));
2069 if (!$module) {
2070 echo "Invalid Module ID";
2071 return;
2072 }
2073 $course = $DB->get_record('course', array('id'=>$cm->course));
2074 if (!$course) {
2075 echo "Invalid Course ID";
2076 return;
2077 }
2078 $this->context = get_context_instance(CONTEXT_COURSE, $course->id);
2079
d972bad1 2080 $key = $this->add($module->name, null, self::TYPE_ACTIVITY, null, $instanceid);
7d2a0492 2081
2082 $file = $CFG->dirroot.'/mod/'.$module->name.'/lib.php';
2083 $function = $module->name.'_extend_navigation';
2084
2085 if (file_exists($file)) {
2086 require_once($file);
2087 if (function_exists($function)) {
2088 $node = $this->get($key);
459e384e 2089 $function($node, $course, $module, $cm);
7d2a0492 2090 }
2091 }
2092 }
2093}
2094
2095/**
2096 * Navbar class
2097 *
2098 * This class is used to manage the navbar, which is initialised from the navigation
2099 * object held by PAGE
2100 *
2101 * @package moodlecore
babb3911 2102 * @subpackage navigation
7d2a0492 2103 * @copyright 2009 Sam Hemelryk
2104 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2105 */
2106class navbar extends navigation_node {
2107 /** @var bool */
2108 protected $initialised = false;
2109 /** @var mixed */
2110 protected $keys = array();
2111 /** @var null|string */
2112 protected $content = null;
2113 /** @var page object */
2114 protected $page;
2115 /** @var bool */
31759089 2116 protected $ignoreactive = false;
2117 /** @var bool */
7d2a0492 2118 protected $duringinstall = false;
2119
2120 /**
2121 * The almighty constructor
2122 */
2123 public function __construct(&$page) {
2124 global $SITE, $CFG;
2125 if (during_initial_install()) {
2126 $this->duringinstall = true;
2127 return false;
2128 }
2129 $this->page = $page;
2130 $this->text = get_string('home');
2131 $this->shorttext = get_string('home');
2132 $this->action = new moodle_url($CFG->wwwroot);
2133 $this->nodetype = self::NODETYPE_BRANCH;
2134 $this->type = self::TYPE_SYSTEM;
2135 }
2136
2137 /**
2138 * Quick check to see if the navbar will have items in.
2139 *
2140 * @return bool Returns true if the navbar will have items, false otherwise
2141 */
2142 public function has_items() {
2143 if ($this->duringinstall) {
2144 return false;
2145 }
2146 $this->page->navigation->initialise();
bf6c37c7 2147
2148 if (!$this->page->navigation->contains_active_node() && !$this->page->settingsnav->contains_active_node()) {
2149 if (!$this->page->navigation->reiterate_active_nodes(URL_MATCH_BASE)) {
2150 $this->page->settingsnav->reiterate_active_nodes(URL_MATCH_BASE);
2151 }
2152 }
2153
2154 $outcome = (count($this->page->navbar->children)>0 || (!$this->ignoreactive && (
31759089 2155 $this->page->navigation->contains_active_node() ||
2156 $this->page->settingsnav->contains_active_node())
2157 ));
bf6c37c7 2158 return $outcome;
31759089 2159 }
2160
2161 public function ignore_active($setting=true) {
2162 $this->ignoreactive = ($setting);
7d2a0492 2163 }
2164
2165 /**
2166 * Generate the XHTML content for the navbar and return it
2167 *
2168 * We are lucky in that we can rely on PAGE->navigation for the structure
2169 * we simply need to look for the `active` path through the tree. We make this
2170 * easier by calling {@link strip_down_to_final_active()}.
2171 *
2172 * This function should in the future be refactored to work with a copy of the
2173 * PAGE->navigation object and strip it down to just this the active nodes using
2174 * a function that could be written again navigation_node called something like
2175 * strip_inactive_nodes(). I wrote this originally but currently the navigation
2176 * object is managed via references.
2177 *
2178 * @return string XHTML navbar content
2179 */
2180 public function content() {
2181 if ($this->duringinstall) {
2182 return '';
2183 }
2184
2185 // Make sure that navigation is initialised
2186 $this->page->navigation->initialise();
2187
2188 if ($this->content !== null) {
2189 return $this->content;
2190 }
2191
2192 // For screen readers
2193 $output = get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
117bd748 2194
9da1ec27 2195 $customchildren = (count($this->children) > 0);
7d2a0492 2196 // Check if navigation contains the active node
bf6c37c7 2197 if (!$this->ignoreactive) {
2198 if ($this->page->navigation->contains_active_node()) {
2199 // Parse the navigation tree to get the active node
2200 $output .= $this->parse_branch_to_html($this->page->navigation->children, true, $customchildren);
2201 } else if ($this->page->settingsnav->contains_active_node()) {
2202 // Parse the settings navigation to get the active node
2203 $output .= $this->parse_branch_to_html($this->page->settingsnav->children, true, $customchildren);
2204 } else if ($this->page->navigation->reiterate_active_nodes(URL_MATCH_BASE)) {
2205 // Parse the navigation tree to get the active node
2206 $output .= $this->parse_branch_to_html($this->page->navigation->children, true, $customchildren);
2207 } else if ($this->page->settingsnav->reiterate_active_nodes(URL_MATCH_BASE)) {
2208 // Parse the settings navigation to get the active node
2209 $output .= $this->parse_branch_to_html($this->page->settingsnav->children, true, $customchildren);
2210 } else {
2211 $output .= $this->parse_branch_to_html($this, true, $customchildren);
2212 }
2213
72b3485e 2214 } else {
2215 $output .= $this->parse_branch_to_html($this, true, $customchildren);
7d2a0492 2216 }
7d2a0492 2217 // Check if there are any children added by code
9da1ec27 2218 if ($customchildren) {
7d2a0492 2219 // Add the custom children
a4397489 2220 $output .= $this->parse_branch_to_html($this->children, false, false);
7d2a0492 2221 }
2222 $output .= "</ul>\n";
2223 $this->content = $output;
2224 return $output;
2225 }
2226 /**
2227 * This function converts an array of nodes into XHTML for the navbar
2228 *
2229 * @param array $navarray
2230 * @param bool $firstnode
2231 * @return string HTML
2232 */
f5b5a822 2233 protected function parse_branch_to_html($navarray, $firstnode=true, $moreafterthis=false) {
da3ab9c4 2234 global $CFG;
7d2a0492 2235 $separator = get_separator();
2236 $output = '';
2237 if ($firstnode===true) {
2238 // If this is the first node add the class first and display the
2239 // navbar properties (normally sitename)
2240 $output .= '<li class="first">'.parent::content(true).'</li>';
2241 }
2242 $count = 0;
72b3485e 2243 if (!is_array($navarray)) return $output;
7d2a0492 2244 // Iterate the navarray and display each node
2245 while (count($navarray)>0) {
2246 // Sanity check make sure we don't display WAY too much information
2247 // on the navbar. If we get to 20 items just stop!
2248 $count++;
2249 if ($count>20) {
9da1ec27 2250 // Maximum number of nodes in the navigation branch
7d2a0492 2251 return $output;
2252 }
2253 $child = false;
da3ab9c4 2254 // Iterate the nodes in navarray and find the active node
7d2a0492 2255 foreach ($navarray as $tempchild) {
2256 if ($tempchild->isactive || $tempchild->contains_active_node()) {
2257 $child = $tempchild;
2258 // We've got the first child we can break out of this foreach
2259 break;
2260 }
2261 }
2262 // Check if we found the child
2263 if ($child===false || $child->mainnavonly) {
2264 // Set navarray to an empty array so that we complete the while
2265 $navarray = array();
2266 } else {
2267 // We found an/the active node, set navarray to it's children so that
2268 // we come back through this while with the children of the active node
2269 $navarray = $child->children;
9da1ec27 2270 // If there are not more arrays being processed after this AND this is the last element
2271 // then we want to set the action to null so that it is not used
2272 if (!$moreafterthis && (!$child->contains_active_node() || ($child->find_active_node()==false || $child->find_active_node()->mainnavonly))) {
2273 $oldaction = $child->action;
2274 $child->action = null;
2275 }
8958174c
SH
2276 if ($child->type !== navigation_node::TYPE_CATEGORY || !isset($CFG->navshowcategories) || !empty($CFG->navshowcategories)) {
2277 // Now display the node
2278 $output .= '<li>'.$separator.' '.$child->content(true).'</li>';
da3ab9c4 2279 }
9da1ec27 2280 if (isset($oldaction)) {
2281 $child->action = $oldaction;
2282 }
7d2a0492 2283 }
2284 }
2285 // XHTML
2286 return $output;
2287 }
2288 /**
2289 * Add a new node to the navbar, overrides parent::add
2290 *
2291 * This function overrides {@link navigation_node::add()} so that we can change
2292 * the way nodes get added to allow us to simply call add and have the node added to the
2293 * end of the navbar
2294 *
2295 * @param string $text
7d2a0492 2296 * @param string|moodle_url $action
d972bad1 2297 * @param int $type
2298 * @param string|int $key
2299 * @param string $shorttext
7d2a0492 2300 * @param string $icon
2301 * @return string|int Identifier for this particular node
2302 */
d972bad1 2303 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, $icon=null) {
7d2a0492 2304 // Check if there are any keys in the objects keys array
2305 if (count($this->keys)===0) {
2306 // If there are no keys then we can use the add method
d972bad1 2307 $key = parent::add($text, $action, $type, $shorttext, $key, $icon);
7d2a0492 2308 } else {
2309 $key = $this->add_to_path($this->keys, $key, $text, $shorttext, $type, $action, $icon);
2310 }
2311 $this->keys[] = $key;
2312 $child = $this->get_by_path($this->keys);
2313 if ($child!==false) {
a4397489 2314 // This ensure that the child will be shown
2315 $child->make_active();
7d2a0492 2316 }
2317 return $key;
2318 }
2319}
2320
2321/**
2322 * Class used to manage the settings option for the current page
2323 *
2324 * This class is used to manage the settings options in a tree format (recursively)
2325 * and was created initially for use with the settings blocks.
2326 *
2327 * @package moodlecore
babb3911 2328 * @subpackage navigation
7d2a0492 2329 * @copyright 2009 Sam Hemelryk
2330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2331 */
2332class settings_navigation extends navigation_node {
2333 /** @var stdClass */
2334 protected $context;
2335 /** @var cache */
2336 protected $cache;
2337 /** @var page object */
2338 protected $page;
2339 /**
2340 * Sets up the object with basic settings and preparse it for use
2341 */
2342 public function __construct(&$page) {
2343 if (during_initial_install()) {
2344 return false;
2345 }
2346 static $settingsnavcount;
2347 $this->page = $page;
2348 // Initialise the main navigation. It is most important that this is done
2349 // before we try anything
2350 $this->page->navigation->initialise();
2351 // Initialise the navigation cache
f5b5a822 2352 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
7d2a0492 2353 }
2354 /**
2355 * Initialise the settings navigation based on the current context
2356 *
2357 * This function initialises the settings navigation tree for a given context
2358 * by calling supporting functions to generate major parts of the tree.
2359 */
2360 public function initialise() {
2361 global $SITE, $OUTPUT, $CFG, $ME;
2362 if (during_initial_install()) {
2363 return false;
2364 }
2365 $this->id = 'settingsnav';
2366 $this->context = $this->page->context;
2367 switch ($this->context->contextlevel) {
2368 case CONTEXT_SYSTEM:
f5b5a822 2369 $this->cache->volatile();
7d2a0492 2370 $adminkey = $this->load_administration_settings();
2371 $settingskey = $this->load_user_settings(SITEID);
2372 break;
2373 case CONTEXT_COURSECAT:
2374 $adminkey = $this->load_administration_settings();
2375 $adminnode = $this->get($adminkey);
2376 if ($adminnode!==false) {
2377 $adminnode->forceopen = true;
2378 }
2379 $settingskey = $this->load_user_settings(SITEID);
2380 break;
2381 case CONTEXT_COURSE:
2382 if ($this->page->course->id!==SITEID) {
2383 $coursekey = $this->load_course_settings();
2384 $coursenode = $this->get($coursekey);
2385 if ($coursenode!==false) {
2386 $coursenode->forceopen = true;
2387 }
2388 $settingskey = $this->load_user_settings($this->page->course->id);
2389 $adminkey = $this->load_administration_settings();
2390 } else {
2391 $this->load_front_page_settings();
2392 $settingskey = $this->load_user_settings($SITE->id);
2393 $adminkey = $this->load_administration_settings();
2394 }
2395 break;
2396 case CONTEXT_MODULE:
2397 $modulekey = $this->load_module_settings();
2398 $modulenode = $this->get($modulekey);
2399 if ($modulenode!==false) {
2400 $modulenode->forceopen = true;
2401 }
2402 $coursekey = $this->load_course_settings();
2403 $settingskey = $this->load_user_settings($this->page->course->id);
2404 $adminkey = $this->load_administration_settings();
2405 break;
2406 case CONTEXT_USER:
2407 $settingskey = $this->load_user_settings($this->page->course->id);
2408 $settingsnode = $this->get($settingskey);
2409 if ($settingsnode!==false) {
2410 $settingsnode->forceopen = true;
2411 }
2412 if ($this->page->course->id!==SITEID) {
2413 $coursekey = $this->load_course_settings();
2414 }
2415 $adminkey = $this->load_administration_settings();
2416 break;
2417 default:
2418 debugging('An unknown context has passed into settings_navigation::initialise', DEBUG_DEVELOPER);
2419 break;
2420 }
2421
2422 // Check if the user is currently logged in as another user
2423 if (session_is_loggedinas()) {
2424 // Get the actual user, we need this so we can display an informative return link
2425 $realuser = session_get_realuser();
2426 // Add the informative return to original user link
2427 $url = new moodle_url($CFG->wwwroot.'/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
d972bad1 2428 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('t/left'));
7d2a0492 2429 }
2430
2431 // Make sure the first child doesnt have proceed with hr set to true
2432 reset($this->children);
2433 current($this->children)->preceedwithhr = false;
2434
2435 $this->remove_empty_root_branches();
2436 $this->respect_forced_open();
2437 }
2438 /**
2439 * Override the parent function so that we can add preceeding hr's and set a
2440 * root node class against all first level element
2441 *
2442 * It does this by first calling the parent's add method {@link navigation_node::add()}
117bd748 2443 * and then proceeds to use the key to set class and hr
7d2a0492 2444 *
2445 * @param string $text
91152a35 2446 * @param sting|moodle_url $url
7d2a0492 2447 * @param string $shorttext
2448 * @param string|int $key
2449 * @param int $type
7d2a0492 2450 * @param string $icon
2451 * @return sting|int A key that can be used to reference the newly added node
2452 */
d972bad1 2453 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, $icon=null) {
2454 $key = parent::add($text, $url, $type, $shorttext, $key, $icon);
7d2a0492 2455 $this->get($key)->add_class('root_node');
2456 $this->get($key)->preceedwithhr = true;
2457 return $key;
2458 }
a6e34701 2459
2460 /**
2461 * This function allows the user to add something to the start of the settings
2462 * navigation, which means it will be at the top of the settings navigation block
2463 *
2464 * @param string $text
2465 * @param sting|moodle_url $url
2466 * @param string $shorttext
2467 * @param string|int $key
2468 * @param int $type
2469 * @param string $icon
2470 * @return sting|int A key that can be used to reference the newly added node
2471 */
2472 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, $icon=null) {
2473 $key = $this->add($text, $url, $type, $shorttext, $key, $icon);
2474 $children = $this->children;
2475 $this->children = array();
2476 $this->children[$key] = array_pop($children);
2477 foreach ($children as $k=>$child) {
2478 $this->children[$k] = $child;
2479 $this->get($k)->add_class('root_node');
2480 $this->get($k)->preceedwithhr = true;
2481 }
2482 return $key;
2483 }
7d2a0492 2484 /**
2485 * Load the site administration tree
2486 *
2487 * This function loads the site administration tree by using the lib/adminlib library functions
2488 *
2489 * @param navigation_node $referencebranch A reference to a branch in the settings
2490 * navigation tree
2491 * @param null|object $adminbranch The branch to add, if null generate the admin
2492 * tree and start at the beginning
2493 * @return mixed A key to access the admin tree by
2494 */
2495 protected function load_administration_settings($referencebranch=null, $adminbranch=null) {
2496 global $CFG, $OUTPUT, $FULLME, $ME;
2497 // Check if we are just starting to generate this navigation.
2498 if ($referencebranch === null) {
2499 // Check if we have cached an appropriate generation of the admin branch
2500 if (!$this->cache->cached('adminbranch')) {
2501 // We dont have a cached admin branch for this page so regenerate
2502 if (!function_exists('admin_get_root')) {
2503 require_once($CFG->dirroot.'/lib/adminlib.php');
2504 }
f5b5a822 2505 $adminroot = admin_get_root(false, false);
bf6c37c7 2506 $branchkey = $this->add(get_string('administrationsite'),new moodle_url($CFG->wwwroot.'/admin/'), self::TYPE_SETTING);
7d2a0492 2507 $referencebranch = $this->get($branchkey);
2508 foreach ($adminroot->children as $adminbranch) {
459e384e 2509 $this->load_administration_settings($referencebranch, $adminbranch);
7d2a0492 2510 }
2511 $this->cache->adminbranch = $this->get($branchkey);
2512 } else {
2513 // We have a cached admin branch so we simply need to stick it back in the tree
2514 $adminbranch = $this->cache->adminbranch;
2515 $outcome = $adminbranch->reiterate_active_nodes();
2516 $branchkey = count($this->children);
2517 $adminbranch->key = $branchkey;
2518 $this->nodetype = self::NODETYPE_BRANCH;
2519 $this->children[$branchkey] = $adminbranch;
2520 }
2521 // Return the branch key
2522 return $branchkey;
8140c440 2523 } else if ($adminbranch->check_access()) {
7d2a0492 2524 // We have a reference branch that we can access and is not hidden `hurrah`
2525 // Now we need to display it and any children it may have
2526 $url = null;
2527 $icon = null;
2528 if ($adminbranch instanceof admin_settingpage) {
2529 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
2530 } else if ($adminbranch instanceof admin_externalpage) {
2531 $url = $adminbranch->url;
2532 }
2533
2534 // Add the branch
d972bad1 2535 $branchkey = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, null, $icon);
7d2a0492 2536 $reference = $referencebranch->get($branchkey);
8140c440 2537
2538 if ($adminbranch->is_hidden()) {
2539 $reference->display = false;
2540 }
2541
7d2a0492 2542 // Check if we are generating the admin notifications and whether notificiations exist
2543 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2544 $reference->add_class('criticalnotification');
2545 }
2546 // Check if this branch has children
2547 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2548 foreach ($adminbranch->children as $branch) {
2549 // Generate the child branches as well now using this branch as the reference
459e384e 2550 $this->load_administration_settings($reference, $branch);
7d2a0492 2551 }
2552 } else {
2553 $reference->icon = $OUTPUT->old_icon_url('i/settings');
2554 }
2555 }
2556 }
2557
2558 /**
2559 * Generate the list of modules for the given course.
2560 *
2561 * The array of resources and activities that can be added to a course is then
2562 * stored in the cache so that we can access it for anywhere.
2563 * It saves us generating it all the time
2564 *
2565 * <code php>
2566 * // To get resources:
2567 * $this->cache->{'course'.$courseid.'resources'}
2568 * // To get activities:
2569 * $this->cache->{'course'.$courseid.'activities'}
2570 * </code>
2571 *
2572 * @param stdClass $course The course to get modules for
2573 */
2574 protected function get_course_modules($course) {
2575 global $CFG;
2576 $mods = $modnames = $modnamesplural = $modnamesused = array();
2577 // This function is included when we include course/lib.php at the top
2578 // of this file
2579 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2580 $resources = array();
2581 $activities = array();
2582 foreach($modnames as $modname=>$modnamestr) {
2583 if (!course_allowed_module($course, $modname)) {
2584 continue;
2585 }
2586
2587 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2588 if (!file_exists($libfile)) {
2589 continue;
2590 }
2591 include_once($libfile);
2592 $gettypesfunc = $modname.'_get_types';
2593 if (function_exists($gettypesfunc)) {
2594 $types = $gettypesfunc();
2595 foreach($types as $type) {
2596 if (!isset($type->modclass) || !isset($type->typestr)) {
2597 debugging('Incorrect activity type in '.$modname);
2598 continue;
2599 }
2600 if ($type->modclass == MOD_CLASS_RESOURCE) {
2601 $resources[html_entity_decode($type->type)] = $type->typestr;
2602 } else {
2603 $activities[html_entity_decode($type->type)] = $type->typestr;
2604 }
2605 }
2606 } else {
2607 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2608 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2609 $resources[$modname] = $modnamestr;
2610 } else {
2611 // all other archetypes are considered activity
2612 $activities[$modname] = $modnamestr;
2613 }
2614 }
2615 }
2616 $this->cache->{'course'.$course->id.'resources'} = $resources;
2617 $this->cache->{'course'.$course->id.'activities'} = $activities;
2618 }
2619
2620 /**
2621 * This function loads the course settings that are available for the user
2622 *
2623 * @return bool|mixed Either false of a key to access the course tree by
2624 */
2625 protected function load_course_settings() {
2626 global $CFG, $OUTPUT, $USER, $SESSION;
2627
2628 $course = $this->page->course;
2629 if (empty($course->context)) {
2630 if (!$this->cache->cached('coursecontext'.$course->id)) {
2631 $this->cache->{'coursecontext'.$course->id} = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
2632 }
2633 $course->context = $this->cache->{'coursecontext'.$course->id};
2634 }
2635 if (!$this->cache->cached('canviewcourse'.$course->id)) {
2636 $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:view', $course->context);
2637 }
2638 if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2639 return false;
2640 }
2641
2642 $coursenode = $this->page->navigation->find_child($course->id, global_navigation::TYPE_COURSE);
117bd748 2643
4881edc9 2644 $coursenodekey = $this->add(get_string('courseadministration'), null, $coursenode->type, null, 'courseadmin');
7d2a0492 2645 $coursenode = $this->get($coursenodekey);
117bd748 2646
7d2a0492 2647 if (has_capability('moodle/course:update', $course->context)) {
2648 // Add the turn on/off settings
2649 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2650 if ($this->page->user_is_editing()) {
2651 $url->param('edit', 'off');
2652 $editstring = get_string('turneditingoff');
2653 } else {
2654 $url->param('edit', 'on');
2655 $editstring = get_string('turneditingon');
2656 }
d972bad1 2657 $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/edit'));
7d2a0492 2658
7d2a0492 2659 if ($this->page->user_is_editing()) {
2660 // Add `add` resources|activities branches
2661 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2662 if (file_exists($structurefile)) {
2663 require_once($structurefile);
2664 $formatstring = call_user_func('callback_'.$course->format.'_definition');
2665 $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2666 } else {
2667 $formatstring = get_string('topic');
2668 $formatidentifier = optional_param('topic', 0, PARAM_INT);
2669 }
2670 if (!$this->cache->cached('coursesections'.$course->id)) {
2671 $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
2672 }
2673 $sections = $this->cache->{'coursesections'.$course->id};
117bd748 2674
7d2a0492 2675 $addresource = $this->get($this->add(get_string('addresource')));
2676 $addactivity = $this->get($this->add(get_string('addactivity')));
2677 if ($formatidentifier!==0) {
2678 $addresource->forceopen = true;
2679 $addactivity->forceopen = true;
2680 }
2681
2682 if (!$this->cache->cached('course'.$course->id.'resources')) {
459e384e 2683 $this->get_course_modules($course);
7d2a0492 2684 }
2685 $resources = $this->cache->{'course'.$course->id.'resources'};
2686 $activities = $this->cache->{'course'.$course->id.'activities'};
117bd748 2687
7d2a0492 2688 foreach ($sections as $section) {
2689 if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2690 continue;
2691 }
2692 $sectionurl = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
2693 if ($section->section == 0) {
d972bad1 2694 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2695 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
7d2a0492 2696 } else {
d972bad1 2697 $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2698 $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
7d2a0492 2699 }
2700 foreach ($resources as $value=>$resource) {
2701 $url = new moodle_url($CFG->wwwroot.'/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2702 $pos = strpos($value, '&type=');
2703 if ($pos!==false) {
2704 $url->param('add', substr($value, 0,$pos));
2705 $url->param('type', substr($value, $pos+6));
2706 } else {
2707 $url->param('add', $value);
2708 }
d972bad1 2709 $addresource->get($sectionresources)->add($resource, $url, self::TYPE_SETTING);
7d2a0492 2710 }
2711 $subbranch = false;
2712 foreach ($activities as $activityname=>$activity) {
2713 if ($activity==='--') {
2714 $subbranch = false;
2715 continue;
2716 }
2717 if (strpos($activity, '--')===0) {
2718 $subbranch = $addactivity->get($sectionactivities)->add(trim($activity, '-'));
2719 continue;
2720 }
2721 $url = new moodle_url($CFG->wwwroot.'/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2722 $pos = strpos($activityname, '&type=');
2723 if ($pos!==false) {
2724 $url->param('add', substr($activityname, 0,$pos));
2725 $url->param('type', substr($activityname, $pos+6));
2726 } else {
2727 $url->param('add', $activityname);
2728 }
2729 if ($subbranch !== false) {
d972bad1 2730 $addactivity->get($sectionactivities)->get($subbranch)->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2731 } else {
d972bad1 2732 $addactivity->get($sectionactivities)->add($activity, $url, self::TYPE_SETTING);
7d2a0492 2733 }
2734 }
2735 }
2736 }
2737
2738 // Add the course settings link
2739 $url = new moodle_url($CFG->wwwroot.'/course/edit.php', array('id'=>$course->id));
d972bad1 2740 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/settings'));
7d2a0492 2741 }
117bd748 2742
7d2a0492 2743 // Add assign or override roles if allowed
2744 if (has_capability('moodle/role:assign', $course->context)) {
2745 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$course->context->id));
d972bad1 2746 $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/roles'));
7d2a0492 2747 } else if (get_overridable_roles($course->context, ROLENAME_ORIGINAL)) {
2748 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/override.php', array('contextid'=>$course->context->id));
d972bad1 2749 $coursenode->add(get_string('overridepermissions', 'role'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/roles'));
7d2a0492 2750 }
2751
2752 // Add view grade report is permitted
2753 $reportavailable = false;
2754 if (has_capability('moodle/grade:viewall', $course->context)) {
2755 $reportavailable = true;
2756 } else if (!empty($course->showgrades)) {
2757 $reports = get_plugin_list('gradereport');
2758 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2759 arsort($reports); // user is last, we want to test it first
2760 foreach ($reports as $plugin => $plugindir) {
2761 if (has_capability('gradereport/'.$plugin.':view', $course->context)) {
2762 //stop when the first visible plugin is found
2763 $reportavailable = true;
2764 break;
2765 }
2766 }
2767 }
2768 }
2769 if ($reportavailable) {
2770 $url = new moodle_url($CFG->wwwroot.'/grade/report/index.php', array('id'=>$course->id));
d972bad1 2771 $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/grades'));
7d2a0492 2772 }
2773
2774 // Add outcome if permitted
2775 if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $course->context)) {
2776 $url = new moodle_url($CFG->wwwroot.'/grade/edit/outcome/course.php', array('id'=>$course->id));
d972bad1 2777 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/outcomes'));
7d2a0492 2778 }
2779
2780 // Add meta course links
2781 if ($course->metacourse) {
2782 if (has_capability('moodle/course:managemetacourse', $course->context)) {
2783 $url = new moodle_url($CFG->wwwroot.'/course/importstudents.php', array('id'=>$course->id));
d972bad1 2784 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/course'));
7d2a0492 2785 } else if (has_capability('moodle/role:assign', $course->context)) {
d972bad1 2786 $key = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/course'));
7d2a0492 2787 $coursenode->get($key)->hidden = true;;
2788 }
2789 }
2790
2791 // Manage groups in this course
2792 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $course->context)) {
2793 $url = new moodle_url($CFG->wwwroot.'/group/index.php', array('id'=>$course->id));
d972bad1 2794 $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/group'));
7d2a0492 2795 }
2796
7d2a0492 2797 // Backup this course
2798 if (has_capability('moodle/site:backup', $course->context)) {
2799 $url = new moodle_url($CFG->wwwroot.'/backup/backup.php', array('id'=>$course->id));
d972bad1 2800 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/backup'));
7d2a0492 2801 }
2802
2803 // Restore to this course
2804 if (has_capability('moodle/site:restore', $course->context)) {
2805 $url = new moodle_url($CFG->wwwroot.'/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
d972bad1 2806 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/restore'));
7d2a0492 2807 }
2808
2809 // Import data from other courses
2810 if (has_capability('moodle/site:import', $course->context)) {
2811 $url = new moodle_url($CFG->wwwroot.'/course/import.php', array('id'=>$course->id));
d972bad1 2812 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/restore'));
7d2a0492 2813 }
2814
2815 // Reset this course
2816 if (has_capability('moodle/course:reset', $course->context)) {
2817 $url = new moodle_url($CFG->wwwroot.'/course/reset.php', array('id'=>$course->id));
d972bad1 2818 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/return'));
7d2a0492 2819 }
7d2a0492 2820
2821 // Manage questions
2822 $questioncaps = array('moodle/question:add',
2823 'moodle/question:editmine',
2824 'moodle/question:editall',
2825 'moodle/question:viewmine',
2826 'moodle/question:viewall',
2827 'moodle/question:movemine',
2828 'moodle/question:moveall');
2829 if (has_any_capability($questioncaps, $this->context)) {
2830 $questionlink = $CFG->wwwroot.'/question/edit.php';
2831 } else if (has_capability('moodle/question:managecategory', $this->context)) {
2832 $questionlink = $CFG->wwwroot.'/question/category.php';
2833 }
2834 if (isset($questionlink)) {
2835 $url = new moodle_url($questionlink, array('courseid'=>$course->id));
d972bad1 2836 $coursenode->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/questions'));
7d2a0492 2837 }
2838
2839 // Repository Instances
2840 require_once($CFG->dirroot.'/repository/lib.php');
2841 $editabletypes = repository::get_editable_types($this->context);
2842 if (has_capability('moodle/course:update', $this->context) && !empty($editabletypes)) {
2843 $url = new moodle_url($CFG->wwwroot.'/repository/manage_instances.php', array('contextid'=>$this->context->id));
d972bad1 2844 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/repository'));
7d2a0492 2845 }
2846
2847 // Manage files
2848 if (has_capability('moodle/course:managefiles', $this->context)) {
2849 $url = new moodle_url($CFG->wwwroot.'/files/index.php', array('id'=>$course->id));
d972bad1 2850 $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/files'));
7d2a0492 2851 }
2852
2853 // Authorize hooks
2854 if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2855 require_once($CFG->dirroot.'/enrol/authorize/const.php');
2856 $url = new moodle_url($CFG->wwwroot.'/enrol/authorize/index.php', array('course'=>$course->id));
d972bad1 2857 $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/payment'));
7d2a0492 2858 if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2859 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2860 if ($cnt) {
2861 $url = new moodle_url($CFG->wwwroot.'/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
d972bad1 2862 $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/payment'));
7d2a0492 2863 }
2864 }
2865 }
2866
2867 // Unenrol link
2868 if (empty($course->metacourse)) {
2869 if (has_capability('moodle/legacy:guest', $this->context, NULL, false)) { // Are a guest now
2870 $url = new moodle_url($CFG->wwwroot.'/course/enrol.php', array('id'=>$course->id));
d972bad1 2871 $coursenode->add(get_string('enrolme', '', format_string($course->shortname)), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/user'));
7d2a0492 2872 } else if (has_capability('moodle/role:unassignself', $this->context, NULL, false) && get_user_roles($this->context, 0, false)) { // Have some role
2873 $url = new moodle_url($CFG->wwwroot.'/course/unenrol.php', array('id'=>$course->id));
d972bad1 2874 $coursenode->add(get_string('unenrolme', '', format_string($course->shortname)), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/user'));
7d2a0492 2875 }
2876 }
2877
2878 // Link to the user own profile (except guests)
2879 if (!isguestuser() and isloggedin()) {
2880 $url = new moodle_url($CFG->wwwroot.'/user/view.php', array('id'=>$USER->id, 'course'=>$course->id));
d972bad1 2881 $coursenode->add(get_string('profile'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/user'));
7d2a0492 2882 }
2883
2884 // Switch roles
2885 $roles = array();
2886 $assumedrole = $this->in_alternative_role();
2887 if ($assumedrole!==false) {
2888 $roles[0] = get_string('switchrolereturn');
2889 }
2890 if (has_capability('moodle/role:switchroles', $this->context)) {
2891 $availableroles = get_switchable_roles($this->context);
2892 if (is_array($availableroles)) {
2893 foreach ($availableroles as $key=>$role) {
2894 if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2895 continue;
2896 }
2897 $roles[$key] = $role;
2898 }
2899 }
2900 }
2901 if (is_array($roles) && count($roles)>0) {
2902 $switchroleskey = $this->add(get_string('switchroleto'));
2903 if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2904 $this->get($switchroleskey)->forceopen = true;
2905 }
2906 $returnurl = $this->page->url;
2907 $returnurl->param('sesskey', sesskey());
2908 $SESSION->returnurl = serialize($returnurl);
2909 foreach ($roles as $key=>$name) {
2910 $url = new moodle_url($CFG->wwwroot.'/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
d972bad1 2911 $this->get($switchroleskey)->add($name, $url, self::TYPE_SETTING, null, $key, $OUTPUT->old_icon_url('i/roles'));
7d2a0492 2912 }
2913 }
2914 // Return we are done
2915 return $coursenodekey;
2916 }
2917
2918 /**
2919 * This function calls the module function to inject module settings into the
2920 * settings navigation tree.
2921 *
2922 * This only gets called if there is a corrosponding function in the modules
2923 * lib file.
2924 *
2925 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2926 *
2927 * @return void|mixed The key to access the module method by
2928 */
2929 protected function load_module_settings() {
2930 global $CFG, $DB;
4dd5bce8 2931
2932 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
2933 $cm = get_coursemodule_from_id('chat', $this->context->instanceid);
2934 $cm->context = $this->context;
2935 if ($cm) {
2936 $this->page->set_cm($cm, $this->page->course);
2937 } else {
2938 debugging('The module has not been set against the page but we are attempting to generate module specific information for navigation', DEBUG_DEVELOPER);
2939 return;
2940 }
2941 }
2942
2943 if (!$this->page->cm) {
2944 debugging('The module has not been set against the page but we are attempting to generate module specific information for navigation', DEBUG_DEVELOPER);
2945 return;
2946 }
2947
417a273d
SH
2948 if (empty($this->page->cm->context)) {
2949 if ($this->context->instanceid === $this->page->cm->id) {
2950 $this->page->cm->context = $this->context;
2951 } else {
2952 $this->page->cm->context = get_context_instance(CONTEXT_MODULE, $this->page->cm->instance);
2953 }
2954 }
2955
4dd5bce8 2956 $module = $DB->get_record('modules', array('id'=>$this->page->cm->module));
7d2a0492 2957 if (!$module) {
4dd5bce8 2958 debugging('Invalid Module ID picked up while attempting to load the activity for the navigation', DEBUG_DEVELOPER);
7d2a0492 2959 return;
2960 }
2961
2962 $file = $CFG->dirroot.'/mod/'.$module->name.'/lib.php';
2963 $function = $module->name.'_extend_settings_navigation';
117bd748 2964
7d2a0492 2965 if (file_exists($file)) {
2966 require_once($file);
2967 }
2968 if (!function_exists($function)) {
2969 return;
2970 }
459e384e 2971 return $function($this,$module);
7d2a0492 2972 }
2973
2974 /**
2975 * Loads the user settings block of the settings nav
117bd748 2976 *
7d2a0492 2977 * This function is simply works out the userid and whether we need to load
117bd748 2978 * just the current users profile settings, or the current user and the user the
7d2a0492 2979 * current user is viewing.
117bd748 2980 *
7d2a0492 2981 * This function has some very ugly code to work out the user, if anyone has
2982 * any bright ideas please feel free to intervene.
2983 *
2984 * @param int $courseid The course id of the current course
2985 */
2986 protected function load_user_settings($courseid=SITEID) {
2987 global $USER, $FULLME;
2988
2989 if (isguestuser() || !isloggedin()) {
2990 return false;
2991 }
2992
2993 // This is terribly ugly code, but I couldn't see a better way around it
2994 // we need to pick up the user id, it can be the current user or someone else
2995 // and the key depends on the current location
2996 // Default to look at id
2997 $userkey='id';
2998 if ($this->context->contextlevel >= CONTEXT_COURSECAT && strpos($FULLME, '/message/')===false && strpos($FULLME, '/mod/forum/user')===false) {
2999 // If we have a course context and we are not in message or forum
3000 // Message and forum both pick the user up from `id`
3001 $userkey = 'user';
3002 } else if (strpos($FULLME,'/blog/') || strpos($FULLME, '/roles/')) {
3003 // And blog and roles just do thier own thing using `userid`
3004 $userkey = 'userid';
3005 }
3006
3007 $userid = optional_param($userkey, $USER->id, PARAM_INT);
3008 if ($userid!=$USER->id) {
3009 $this->generate_user_settings($courseid,$userid,'userviewingsettings');
3010 $this->generate_user_settings($courseid,$USER->id);
3011 } else {
3012 $this->generate_user_settings($courseid,$USER->id);
3013 }
3014 }
3015
3016 /**
3017 * This function gets called by {@link load_user_settings()} and actually works out
3018 * what can be shown/done
3019 *
3020 * @param int $courseid The current course' id
3021 * @param int $userid The user id to load for
3022 * @param string $gstitle The string to pass to get_string for the branch title
3023 * @return string|int The key to reference this user's settings
3024 */
3025 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3026 global $DB, $CFG, $USER;
3027
3028 $course = $DB->get_record("course", array("id"=>$courseid));
3029 if (!$course) {
3030 return false;
3031 }
3032
3033 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3034 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3035 $currentuser = ($USER->id == $userid);
3036 if ($currentuser) {
3037 $user = $USER;
3038 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3039 } else {
3040 $user = $DB->get_record('user', array('id'=>$userid));
3041 if (!$user) {
3042 return false;
3043 }
3044 // Check that the user can view the profile
3045 $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3046 if ($course->id==SITEID) {
3047 if ($CFG->forceloginforprofiles && !isteacherinanycourse() && !isteacherinanycourse($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3048 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3049 return false;
3050 }
3051 } else {
3052 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:view', $coursecontext, $user->id, false)) {
3053 return false;
3054 }
3055 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3056 // If groups are in use, make sure we can see that group
3057 return false;
3058 }
3059 }
3060 }
3061
3062 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3063
3064 // Add a user setting branch
3065 $usersettingskey = $this->add(get_string($gstitle, 'moodle', $fullname));
3066 $usersetting = $this->get($usersettingskey);
3067 $usersetting->id = 'usersettings';
3068
3069 // URL to the users profile
3070 $profileurl = new moodle_url($CFG->wwwroot.'/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3071
3072 // Check if the user has been deleted
3073 if ($user->deleted) {
3074 if (!has_capability('moodle/user:update', $coursecontext)) {
3075 // We can't edit the user so just show the user deleted message
d972bad1 3076 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
7d2a0492 3077 } else {
3078 // We can edit the user so show the user deleted message and link it to the profile
d972bad1 3079 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
7d2a0492 3080 }
3081 return true;
3082 }
3083
3084 // Add a link to view the user profile
3085 if ($currentuser) {
31759089 3086 $usersetting->add(get_string('viewprofile'), $profileurl, self::TYPE_SETTING);
7d2a0492 3087 } else {
31759089 3088 $usersetting->add(get_string('viewprofile','',$fullname), $profileurl, self::TYPE_SETTING);
7d2a0492 3089 }
3090
3091 // Add the profile edit link
3092 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3093 $url = false;
3094 if (($currentuser && has_capability('moodle/user:update', $systemcontext)) || (has_capability('moodle/user:update', $systemcontext) && !is_primary_admin($user->id))) {
3095 $url = new moodle_url($CFG->wwwroot.'/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3096 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3097 $url = new moodle_url($CFG->wwwroot.'/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3098 }
3099 if ($url!==false) {
d972bad1 3100 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
7d2a0492 3101 }
3102 }
3103
3104 // Change password link
3105 if (!empty($user->auth)) {
3106 $userauth = get_auth_plugin($user->auth);
3107 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3108 $passwordchangeurl = $userauth->change_password_url();
3109 if (!$passwordchangeurl) {
3110 if (empty($CFG->loginhttps)) {
3111 $wwwroot = $CFG->wwwroot;
3112 } else {
3113 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
3114 }
3115 $passwordchangeurl = new moodle_url($CFG->wwwroot.'/login/change_password.php');
3116 } else {
3117 $urlbits = explode($passwordchangeurl. '?', 1);
3118 $passwordchangeurl = new moodle_url($urlbits[0]);
3119 if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
3120 foreach ($matches as $pair) {
3121 $fullmeurl->param($pair[1],$pair[2]);
3122 }
3123 }
3124 }
3125 $passwordchangeurl->param('id', $course->id);
d972bad1 3126 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
7d2a0492 3127 }
3128 }
3129
3130 // View the roles settings
3131 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
d972bad1 3132 $roleskey = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
7d2a0492 3133
3134 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
d972bad1 3135 $usersetting->get($roleskey)->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3136
3137 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3138 $overridableroles = get_overridable_roles($usercontext, ROLENAME_BOTH);
3139
3140 if (!empty($assignableroles)) {
3141 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
d972bad1 3142 $usersetting->get($roleskey)->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3143 }
3144
3145 if (!empty($overridableroles)) {
3146 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/override.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
d972bad1 3147 $usersetting->get($roleskey)->add(get_string('overridepermissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3148 }
3149
3150 $url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
d972bad1 3151 $usersetting->get($roleskey)->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
7d2a0492 3152 }
3153
3154 // Portfolio
3155 if (empty($userindexpage) && $currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext) && portfolio_instances(true, false)) {
d972bad1 3156 $portfoliokey = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
7d2a0492 3157 $url = new moodle_url($CFG->wwwroot .'/user/portfolio.php');
d972bad1 3158 $usersetting->get($portfoliokey)->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
7d2a0492 3159 $url = new moodle_url($CFG->wwwroot .'/user/portfoliologs.php');
d972bad1 3160 $usersetting->get($portfoliokey)->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
7d2a0492 3161 }
3162
3163 // Repository
3164 if (!$currentuser) {
3165 require_once($CFG->dirroot . '/repository/lib.php');
3166 $editabletypes = repository::get_editable_types($usercontext);
3167 if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
3168 $url = new moodle_url($CFG->wwwroot .'/repository/manage_instances.php', array('contextid'=>$usercontext->id));
d972bad1 3169 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
7d2a0492 3170 }
3171 }
3172
3173 // Messaging
3174 if (empty($userindexpage) && has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
3175 $url = new moodle_url($CFG->wwwroot.'/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
d972bad1 3176 $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
7d2a0492 3177 }
3178
3179 return $usersettingskey;
3180 }
3181
3182 /**
3183 * Determine whether the user is assuming another role
3184 *
3185 * This function checks to see if the user is assuming another role by means of
3186 * role switching. In doing this we compare each RSW key (context path) against
3187 * the current context path. This ensures that we can provide the switching
3188 * options against both the course and any page shown under the course.
3189 *
3190 * @return bool|int The role(int) if the user is in another role, false otherwise
3191 */
3192 protected function in_alternative_role() {
3193 global $USER;
3194 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
3195 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
3196 return $USER->access['rsw'][$this->page->context->path];
3197 }
3198 foreach ($USER->access['rsw'] as $key=>$role) {
3199 if (strpos($this->context->path,$key)===0) {
3200 return $role;
3201 }
3202 }
3203 }
3204 return false;
3205 }
3206
3207 /**
2e7f1f79 3208 * This function loads all of the front page settings into the settings navigation.
3209 * This function is called when the user is on the front page, or $COURSE==$SITE
7d2a0492 3210 */
3211 protected function load_front_page_settings() {
3212 global $CFG, $USER, $OUTPUT, $SITE;
3213
3214 $course = $SITE;
3215 if (empty($course->context)) {
3216 $course->context = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
3217 }
3218 if (has_capability('moodle/course:update', $course->context)) {
3219
152fdf93 3220 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
7d2a0492 3221 $this->get($frontpage)->id = 'frontpagesettings';
3222 $this->get($frontpage)->forceopen = true;
3223
3224 // Add the turn on/off settings
3225 $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
3226 if ($this->page->user_is_editing()) {
3227 $url->param('edit', 'off');
3228 $editstring = get_string('turneditingoff');
3229 } else {
3230 $url->param('edit', 'on');
3231 $editstring = get_string('turneditingon');
3232 }
d972bad1 3233 $this->get($frontpage)->add($editstring, $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/edit'));
7d2a0492 3234
3235 // Add the course settings link
3236 $url = new moodle_url($CFG->wwwroot.'/admin/settings.php', array('section'=>'frontpagesettings'));
d972bad1 3237 $this->get($frontpage)->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/settings'));
7d2a0492 3238 }
2e7f1f79 3239
3240 //Participants
3241 if (has_capability('moodle/site:viewparticipants', $course->context)) {
3242 $url = new moodle_url($CFG->wwwroot.'/user/index.php?contextid='.$course->context->id);
3243 $this->get($frontpage)->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/users'));
3244 }
7d2a0492 3245 }
3246
3247
3248 /**
3249 * This function removes all root branches that have no children
3250 */
3251 public function remove_empty_root_branches() {
3252 foreach ($this->children as $key=>$node) {
3253 if ($node->nodetype != self::NODETYPE_BRANCH || count($node->children)===0) {
3254 $this->remove_child($key);
3255 }
3256 }
3257 }
f5b5a822 3258
3259 /**
3260 * This function marks the cache as volatile so it is cleared during shutdown
3261 */
3262 public function clear_cache() {
3263 $this->cache->volatile();
3264 }
7d2a0492 3265}
3266
3267/**
3268 * Simple class used to output a navigation branch in XML
3269 *
3270 * @package moodlecore
babb3911 3271 * @subpackage navigation
7d2a0492 3272 * @copyright 2009 Sam Hemelryk
3273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3274 */
3275class navigation_xml {
3276 /** @var array */
3277 protected $nodetype = array('node','branch');
3278 /** @var array */
3279 protected $expandable = array();
6644741d 3280 /** @var int */
3281 protected $expansionceiling = array();
7d2a0492 3282 /**
3283 * Turns a branch and all of its children into XML
3284 *
3285 * @param navigation_node $branch
3286 * @return string XML string
3287 */
3288 public function convert($branch) {
3289 $xml = $this->convert_child($branch);
3290 return $xml;
3291 }
3292 /**
3293 * Set the expandable items in the array so that we have enough information
3294 * to attach AJAX events
3295 */
3296 public function set_expandable($expandable) {
3297 foreach ($expandable as $node) {
3298 $this->expandable[(string)$node['branchid']] = $node;
3299 }
3300 }
6644741d 3301 /**
3302 * Sets the upper limit for expandable nodes. Any nodes that are of the specified
3303 * type or larger will not be expandable
3304 *
3305 * @param int $expansionceiling One of navigation_node::TYPE_*
3306 */
3307 public function set_expansionceiling($expansionceiling) {
3308 $tihs->expansionceiling = $expansionceiling;
3309 }
7d2a0492 3310 /**
3311 * Recusively converts a child node and its children to XML for output
3312 *
3313 * @param navigation_node $child The child to convert
3314 * @param int $depth Pointlessly used to track the depth of the XML structure
3315 */
3316 protected function convert_child($child, $depth=1) {
3317 global $OUTPUT;
3318
3319 if (!$child->display) {
3320 return '';
3321 }
3322 $attributes = array();
3323 $attributes['id'] = $child->id;
3324 $attributes['type'] = $child->type;
3325 $attributes['key'] = $child->key;
3326 $attributes['icon'] = $child->icon;
3327 $attributes['class'] = $child->get_css_type();
3328 if ($child->forcetitle || $child->title !== $child->text) {
3329 $attributes['title'] = htmlentities($child->title);
3330 }
3331 if (array_key_exists((string)$child->key, $this->expandable)) {
3332 $attributes['expandable'] = $child->key;
3333 $child->add_class($this->expandable[$child->key]['id']);
6644741d 3334 } else if ($child->type >= $this->expansionceiling) {
3335 $attributes['expansionceiling'] = $child->key;
7d2a0492 3336 }
6644741d 3337
7d2a0492 3338 if (count($child->classes)>0) {
3339 $attributes['class'] .= ' '.join(' ',$child->classes);
3340 }
3341 if (is_string($child->action)) {
3342 $attributes['link'] = $child->action;
3343 } else if ($child->action instanceof moodle_url) {
3344 $attributes['link'] = $child->action->out();
3345 }
3346 $attributes['hidden'] = ($child->hidden);
3347 $attributes['haschildren'] = (count($child->children)>0 || $child->type == navigation_node::TYPE_CATEGORY);
3348
3349 $xml = '<'.$this->nodetype[$child->nodetype];
3350 if (count($attributes)>0) {
3351 foreach ($attributes as $key=>$value) {
3352 if (is_bool($value)) {
3353 if ($value) {
3354 $xml .= ' '.$key.'="true"';
3355 } else {
3356 $xml .= ' '.$key.'="false"';
3357 }
3358 } else if ($value !== null) {
3359 $xml .= ' '.$key.'="'.$value.'"';
3360 }
3361 }
3362 }
3363 $xml .= '>';
3364 $xml .= '<name>'.htmlentities($child->text).'</name>';
3365 if (count($child->children)>0) {
3366 $xml .= '<children>';
3367 foreach ($child->children as $subchild) {
3368 $xml .= $this->convert_child($subchild, $depth+1);
3369 }
3370 $xml .= '</children>';
3371 }
3372 $xml .= '</'.$this->nodetype[$child->nodetype].'>';
3373 return $xml;
3374 }
3375}
3376
3377/**
3378 * The cache class used by global navigation and settings navigation to cache bits
3379 * and bobs that are used during their generation.
3380 *
3381 * It is basically an easy access point to session with a bit of smarts to make
3382 * sure that the information that is cached is valid still.
3383 *
3384 * Example use:
3385 * <code php>
3386 * if (!$cache->viewdiscussion()) {
3387 * // Code to do stuff and produce cachable content
3388 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3389 * }
3390 * $content = $cache->viewdiscussion;
3391 * </code>
3392 *
3393 * @package moodlecore
babb3911 3394 * @subpackage navigation
7d2a0492 3395 * @copyright 2009 Sam Hemelryk
3396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3397 */
3398class navigation_cache {
3399 /** @var int */
3400 protected $creation;
3401 /** @var array */
3402 protected $session;
3403 /** @var string */
3404 protected $area;
3405 /** @var int */
3406 protected $timeout;
3407 /** @var stdClass */
3408 protected $currentcontext;
3409 /** @var int */
3410 const CACHETIME = 0;
3411 /** @var int */
3412 const CACHEUSERID = 1;
3413 /** @var int */
3414 const CACHEVALUE = 2;
f5b5a822 3415 /** @var null|array An array of navigation cache areas to expire on shutdown */
3416 public static $volatilecaches;
117bd748 3417
7d2a0492 3418 /**
3419 * Contructor for the cache. Requires two arguments
3420 *
3421 * @param string $area The string to use to segregate this particular cache
3422 * it can either be unique to start a fresh cache or if you want
3423 * to share a cache then make it the string used in the original
3424 * cache
3425 * @param int $timeout The number of seconds to time the information out after
3426 */
3427 public function __construct($area, $timeout=60) {
3428 global $SESSION, $PAGE;
3429 $this->creation = time();
3430 $this->area = $area;
3431
3432 if (!isset($SESSION->navcache)) {
3433 $SESSION->navcache = new stdClass;
3434 }
3435
3436 if (!isset($SESSION->navcache->{$area})) {
3437 $SESSION->navcache->{$area} = array();
3438 }
3439 $this->session = &$SESSION->navcache->{$area};
3440 $this->timeout = time()-$timeout;
3441 if (rand(0,10)===0) {
3442 $this->garbage_collection();
3443 }
3444 }
3445
3446 /**
3447 * Magic Method to retrieve something by simply calling using = cache->key
3448 *
3449 * @param mixed $key The identifier for the information you want out again
3450 * @return void|mixed Either void or what ever was put in
3451 */
3452 public function __get($key) {
3453 if (!$this->cached($key)) {
3454 return;
3455 }
3456 $information = $this->session[$key][self::CACHEVALUE];
3457 return unserialize($information);
3458 }
3459
3460 /**
3461 * Magic method that simply uses {@link set();} to store something in the cache
3462 *
3463 * @param string|int $key
3464 * @param mixed $information
3465 */
3466 public function __set($key, $information) {
3467 $this->set($key, $information);
3468 }
f5b5a822 3469
7d2a0492 3470 /**
3471 * Sets some information against the cache (session) for later retrieval
3472 *
3473 * @param string|int $key
3474 * @param mixed $information
3475 */
3476 public function set($key, $information) {
3477 global $USER;
3478 $information = serialize($information);
3479 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
3480 }
3481 /**
3482 * Check the existence of the identifier in the cache
3483 *
3484 * @param string|int $key
3485 * @return bool
3486 */
3487 public function cached($key) {
3488 global $USER;
3489 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
3490 return false;
3491 }
3492 return true;
3493 }
fdd35767 3494 /**
3495 * Compare something to it's equivilant in the cache
3496 *
3497 * @param string $key
3498 * @param mixed $value
3499 * @param bool $serialise Whether to serialise the value before comparison
3500 * this should only be set to false if the value is already
3501 * serialised
3502 * @return bool If the value is the same false if it is not set or doesn't match
3503 */
3504 public function compare($key, $value, $serialise=true) {
3505 if ($this->cached($key)) {
3506 if ($serialise) {
3507 $value = serialize($value);
3508 }
3509 if ($this->session[$key][self::CACHEVALUE] === $value) {
3510 return true;
3511 }
3512 }
3513 return false;
3514 }
7d2a0492 3515 /**
babb3911 3516 * Wipes the entire cache, good to force regeneration
7d2a0492 3517 */
3518 public function clear() {
3519 $this->session = array();
3520 }
3521 /**
3522 * Checks all cache entries and removes any that have expired, good ole cleanup
3523 */
3524 protected function garbage_collection() {
3525 foreach ($this->session as $key=>$cachedinfo) {
3526 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
3527 unset($this->session[$key]);
3528 }
3529 }
3530 }
f5b5a822 3531
3532 /**
3533 * Marks the cache as being volatile (likely to change)
3534 *
3535 * Any caches marked as volatile will be destroyed at the on shutdown by
3536 * {@link navigation_node::destroy_volatile_caches()} which is registered
3537 * as a shutdown function if any caches are marked as volatile.
3538 *
3539 * @param bool $setting True to destroy the cache false not too
3540 */
3541 public function volatile($setting = true) {
3542 if (self::$volatilecaches===null) {
3543 self::$volatilecaches = array();
3544 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
3545 }
3546
3547 if ($setting) {
3548 self::$volatilecaches[$this->area] = $this->area;
3549 } else if (array_key_exists($this->area, self::$volatilecaches)) {