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