3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
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
24 * @subpackage navigation
25 * @copyright 2009 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * The name that will be used to separate the navigation cache within SESSION
34 define('NAVIGATION_CACHE_NAME', 'navigation');
37 * This class is used to represent a node in a navigation tree
39 * This class is used to represent a node in a navigation tree within Moodle,
40 * the tree could be one of global navigation, settings navigation, or the navbar.
41 * Each node can be one of two types either a Leaf (default) or a branch.
42 * When a node is first created it is created as a leaf, when/if children are added
43 * the node then becomes a branch.
46 * @subpackage navigation
47 * @copyright 2009 Sam Hemelryk
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class navigation_node
implements renderable
{
51 /** @var int Used to identify this node a leaf (default) 0 */
52 const NODETYPE_LEAF
= 0;
53 /** @var int Used to identify this node a branch, happens with children 1 */
54 const NODETYPE_BRANCH
= 1;
55 /** @var null Unknown node type null */
56 const TYPE_UNKNOWN
= null;
57 /** @var int System node type 0 */
58 const TYPE_ROOTNODE
= 0;
59 /** @var int System node type 1 */
60 const TYPE_SYSTEM
= 1;
61 /** @var int Category node type 10 */
62 const TYPE_CATEGORY
= 10;
63 /** @var int Course node type 20 */
64 const TYPE_COURSE
= 20;
65 /** @var int Course Structure node type 30 */
66 const TYPE_SECTION
= 30;
67 /** @var int Activity node type, e.g. Forum, Quiz 40 */
68 const TYPE_ACTIVITY
= 40;
69 /** @var int Resource node type, e.g. Link to a file, or label 50 */
70 const TYPE_RESOURCE
= 50;
71 /** @var int A custom node type, default when adding without specifing type 60 */
72 const TYPE_CUSTOM
= 60;
73 /** @var int Setting node type, used only within settings nav 70 */
74 const TYPE_SETTING
= 70;
75 /** @var int Setting node type, used only within settings nav 80 */
77 /** @var int Setting node type, used for containers of no importance 90 */
78 const TYPE_CONTAINER
= 90;
80 /** @var int Parameter to aid the coder in tracking [optional] */
82 /** @var string|int The identifier for the node, used to retrieve the node */
84 /** @var string The text to use for the node */
86 /** @var string Short text to use if requested [optional] */
87 public $shorttext = null;
88 /** @var string The title attribute for an action if one is defined */
90 /** @var string A string that can be used to build a help button */
91 public $helpbutton = null;
92 /** @var moodle_url|action_link|null An action for the node (link) */
93 public $action = null;
94 /** @var pix_icon The path to an icon to use for this node */
96 /** @var int See TYPE_* constants defined for this class */
97 public $type = self
::TYPE_UNKNOWN
;
98 /** @var int See NODETYPE_* constants defined for this class */
99 public $nodetype = self
::NODETYPE_LEAF
;
100 /** @var bool If set to true the node will be collapsed by default */
101 public $collapse = false;
102 /** @var bool If set to true the node will be expanded by default */
103 public $forceopen = false;
104 /** @var array An array of CSS classes for the node */
105 public $classes = array();
106 /** @var navigation_node_collection An array of child nodes */
107 public $children = array();
108 /** @var bool If set to true the node will be recognised as active */
109 public $isactive = false;
110 /** @var bool If set to true the node will be dimmed */
111 public $hidden = false;
112 /** @var bool If set to false the node will not be displayed */
113 public $display = true;
114 /** @var bool If set to true then an HR will be printed before the node */
115 public $preceedwithhr = false;
116 /** @var bool If set to true the the navigation bar should ignore this node */
117 public $mainnavonly = false;
118 /** @var bool If set to true a title will be added to the action no matter what */
119 public $forcetitle = false;
120 /** @var navigation_node A reference to the node parent */
121 public $parent = null;
122 /** @var bool Override to not display the icon even if one is provided **/
123 public $hideicon = false;
125 protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
126 /** @var moodle_url */
127 protected static $fullmeurl = null;
128 /** @var bool toogles auto matching of active node */
129 public static $autofindactive = true;
132 * Constructs a new navigation_node
134 * @param array|string $properties Either an array of properties or a string to use
135 * as the text for the node
137 public function __construct($properties) {
138 if (is_array($properties)) {
139 // Check the array for each property that we allow to set at construction.
140 // text - The main content for the node
141 // shorttext - A short text if required for the node
142 // icon - The icon to display for the node
143 // type - The type of the node
144 // key - The key to use to identify the node
145 // parent - A reference to the nodes parent
146 // action - The action to attribute to this node, usually a URL to link to
147 if (array_key_exists('text', $properties)) {
148 $this->text
= $properties['text'];
150 if (array_key_exists('shorttext', $properties)) {
151 $this->shorttext
= $properties['shorttext'];
153 if (!array_key_exists('icon', $properties)) {
154 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
156 $this->icon
= $properties['icon'];
157 if ($this->icon
instanceof pix_icon
) {
158 if (empty($this->icon
->attributes
['class'])) {
159 $this->icon
->attributes
['class'] = 'navicon';
161 $this->icon
->attributes
['class'] .= ' navicon';
164 if (array_key_exists('type', $properties)) {
165 $this->type
= $properties['type'];
167 $this->type
= self
::TYPE_CUSTOM
;
169 if (array_key_exists('key', $properties)) {
170 $this->key
= $properties['key'];
172 if (array_key_exists('parent', $properties)) {
173 $this->parent
= $properties['parent'];
175 // This needs to happen last because of the check_if_active call that occurs
176 if (array_key_exists('action', $properties)) {
177 $this->action
= $properties['action'];
178 if (is_string($this->action
)) {
179 $this->action
= new moodle_url($this->action
);
181 if (self
::$autofindactive) {
182 $this->check_if_active();
185 } else if (is_string($properties)) {
186 $this->text
= $properties;
188 if ($this->text
=== null) {
189 throw new coding_exception('You must set the text for the node when you create it.');
191 // Default the title to the text
192 $this->title
= $this->text
;
193 // Instantiate a new navigation node collection for this nodes children
194 $this->children
= new navigation_node_collection();
198 * Checks if this node is the active node.
200 * This is determined by comparing the action for the node against the
201 * defined URL for the page. A match will see this node marked as active.
203 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
206 public function check_if_active($strength=URL_MATCH_EXACT
) {
207 global $FULLME, $PAGE;
208 // Set fullmeurl if it hasn't already been set
209 if (self
::$fullmeurl == null) {
210 if ($PAGE->has_set_url()) {
211 self
::override_active_url(new moodle_url($PAGE->url
));
213 self
::override_active_url(new moodle_url($FULLME));
217 // Compare the action of this node against the fullmeurl
218 if ($this->action
instanceof moodle_url
&& $this->action
->compare(self
::$fullmeurl, $strength)) {
219 $this->make_active();
226 * This sets the URL that the URL of new nodes get compared to when locating
229 * The active node is the node that matches the URL set here. By default this
230 * is either $PAGE->url or if that hasn't been set $FULLME.
232 * @param moodle_url $url The url to use for the fullmeurl.
234 public static function override_active_url(moodle_url
$url) {
235 // Clone the URL, in case the calling script changes their URL later.
236 self
::$fullmeurl = new moodle_url($url);
240 * Adds a navigation node as a child of this node.
242 * @param string $text
243 * @param moodle_url|action_link $action
245 * @param string $shorttext
246 * @param string|int $key
247 * @param pix_icon $icon
248 * @return navigation_node
250 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
251 // First convert the nodetype for this node to a branch as it will now have children
252 if ($this->nodetype
!== self
::NODETYPE_BRANCH
) {
253 $this->nodetype
= self
::NODETYPE_BRANCH
;
255 // Properties array used when creating the new navigation node
260 // Set the action if one was provided
261 if ($action!==null) {
262 $itemarray['action'] = $action;
264 // Set the shorttext if one was provided
265 if ($shorttext!==null) {
266 $itemarray['shorttext'] = $shorttext;
268 // Set the icon if one was provided
270 $itemarray['icon'] = $icon;
272 // Default the key to the number of children if not provided
274 $key = $this->children
->count();
277 $itemarray['key'] = $key;
278 // Set the parent to this node
279 $itemarray['parent'] = $this;
280 // Add the child using the navigation_node_collections add method
281 $node = $this->children
->add(new navigation_node($itemarray));
282 // If the node is a category node or the user is logged in and its a course
283 // then mark this node as a branch (makes it expandable by AJAX)
284 if (($type==self
::TYPE_CATEGORY
) ||
(isloggedin() && $type==self
::TYPE_COURSE
)) {
285 $node->nodetype
= self
::NODETYPE_BRANCH
;
287 // If this node is hidden mark it's children as hidden also
289 $node->hidden
= true;
291 // Return the node (reference returned by $this->children->add()
296 * Searches for a node of the given type with the given key.
298 * This searches this node plus all of its children, and their children....
299 * If you know the node you are looking for is a child of this node then please
300 * use the get method instead.
302 * @param int|string $key The key of the node we are looking for
303 * @param int $type One of navigation_node::TYPE_*
304 * @return navigation_node|false
306 public function find($key, $type) {
307 return $this->children
->find($key, $type);
311 * Get ths child of this node that has the given key + (optional) type.
313 * If you are looking for a node and want to search all children + thier children
314 * then please use the find method instead.
316 * @param int|string $key The key of the node we are looking for
317 * @param int $type One of navigation_node::TYPE_*
318 * @return navigation_node|false
320 public function get($key, $type=null) {
321 return $this->children
->get($key, $type);
329 public function remove() {
330 return $this->parent
->children
->remove($this->key
, $this->type
);
334 * Checks if this node has or could have any children
336 * @return bool Returns true if it has children or could have (by AJAX expansion)
338 public function has_children() {
339 return ($this->nodetype
=== navigation_node
::NODETYPE_BRANCH ||
$this->children
->count()>0);
343 * Marks this node as active and forces it open.
345 * Important: If you are here because you need to mark a node active to get
346 * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
347 * You can use it to specify a different URL to match the active navigation node on
348 * rather than having to locate and manually mark a node active.
350 public function make_active() {
351 $this->isactive
= true;
352 $this->add_class('active_tree_node');
354 if ($this->parent
!== null) {
355 $this->parent
->make_inactive();
360 * Marks a node as inactive and recusised back to the base of the tree
361 * doing the same to all parents.
363 public function make_inactive() {
364 $this->isactive
= false;
365 $this->remove_class('active_tree_node');
366 if ($this->parent
!== null) {
367 $this->parent
->make_inactive();
372 * Forces this node to be open and at the same time forces open all
373 * parents until the root node.
377 public function force_open() {
378 $this->forceopen
= true;
379 if ($this->parent
!== null) {
380 $this->parent
->force_open();
385 * Adds a CSS class to this node.
387 * @param string $class
390 public function add_class($class) {
391 if (!in_array($class, $this->classes
)) {
392 $this->classes
[] = $class;
398 * Removes a CSS class from this node.
400 * @param string $class
401 * @return bool True if the class was successfully removed.
403 public function remove_class($class) {
404 if (in_array($class, $this->classes
)) {
405 $key = array_search($class,$this->classes
);
407 unset($this->classes
[$key]);
415 * Sets the title for this node and forces Moodle to utilise it.
416 * @param string $title
418 public function title($title) {
419 $this->title
= $title;
420 $this->forcetitle
= true;
424 * Resets the page specific information on this node if it is being unserialised.
426 public function __wakeup(){
427 $this->forceopen
= false;
428 $this->isactive
= false;
429 $this->remove_class('active_tree_node');
433 * Checks if this node or any of its children contain the active node.
439 public function contains_active_node() {
440 if ($this->isactive
) {
443 foreach ($this->children
as $child) {
444 if ($child->isactive ||
$child->contains_active_node()) {
453 * Finds the active node.
455 * Searches this nodes children plus all of the children for the active node
456 * and returns it if found.
460 * @return navigation_node|false
462 public function find_active_node() {
463 if ($this->isactive
) {
466 foreach ($this->children
as &$child) {
467 $outcome = $child->find_active_node();
468 if ($outcome !== false) {
477 * Searches all children for the best matching active node
478 * @return navigation_node|false
480 public function search_for_active_node() {
481 if ($this->check_if_active(URL_MATCH_BASE
)) {
484 foreach ($this->children
as &$child) {
485 $outcome = $child->search_for_active_node();
486 if ($outcome !== false) {
495 * Gets the content for this node.
497 * @param bool $shorttext If true shorttext is used rather than the normal text
500 public function get_content($shorttext=false) {
501 if ($shorttext && $this->shorttext
!==null) {
502 return format_string($this->shorttext
);
504 return format_string($this->text
);
509 * Gets the title to use for this node.
513 public function get_title() {
514 if ($this->forcetitle ||
$this->action
!= null){
522 * Gets the CSS class to add to this node to describe its type
526 public function get_css_type() {
527 if (array_key_exists($this->type
, $this->namedtypes
)) {
528 return 'type_'.$this->namedtypes
[$this->type
];
530 return 'type_unknown';
534 * Finds all nodes that are expandable by AJAX
536 * @param array $expandable An array by reference to populate with expandable nodes.
538 public function find_expandable(array &$expandable) {
539 $isloggedin = (isloggedin() && !isguestuser());
540 if (!$isloggedin && $this->type
> self
::TYPE_CATEGORY
) {
543 foreach ($this->children
as &$child) {
544 if (!$isloggedin && $child->type
> self
::TYPE_CATEGORY
) {
547 if ($child->nodetype
== self
::NODETYPE_BRANCH
&& $child->children
->count()==0 && $child->display
) {
548 $child->id
= 'expandable_branch_'.(count($expandable)+
1);
549 $this->add_class('canexpand');
550 $expandable[] = array('id'=>$child->id
,'branchid'=>$child->key
,'type'=>$child->type
);
552 $child->find_expandable($expandable);
557 * Finds all nodes of a given type (recursive)
559 * @param int $type On of navigation_node::TYPE_*
562 public function find_all_of_type($type) {
563 $nodes = $this->children
->type($type);
564 foreach ($this->children
as &$node) {
565 $childnodes = $node->find_all_of_type($type);
566 $nodes = array_merge($nodes, $childnodes);
572 * Removes this node if it is empty
574 public function trim_if_empty() {
575 if ($this->children
->count() == 0) {
581 * Creates a tab representation of this nodes children that can be used
582 * with print_tabs to produce the tabs on a page.
584 * call_user_func_array('print_tabs', $node->get_tabs_array());
586 * @param array $inactive
587 * @param bool $return
588 * @return array Array (tabs, selected, inactive, activated, return)
590 public function get_tabs_array(array $inactive=array(), $return=false) {
594 $activated = array();
595 foreach ($this->children
as $node) {
596 $tabs[] = new tabobject($node->key
, $node->action
, $node->get_content(), $node->get_title());
597 if ($node->contains_active_node()) {
598 if ($node->children
->count() > 0) {
599 $activated[] = $node->key
;
600 foreach ($node->children
as $child) {
601 if ($child->contains_active_node()) {
602 $selected = $child->key
;
604 $rows[] = new tabobject($child->key
, $child->action
, $child->get_content(), $child->get_title());
607 $selected = $node->key
;
611 return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
616 * Navigation node collection
618 * This class is responsible for managing a collection of navigation nodes.
619 * It is required because a node's unique identifier is a combination of both its
622 * Originally an array was used with a string key that was a combination of the two
623 * however it was decided that a better solution would be to use a class that
624 * implements the standard IteratorAggregate interface.
626 * @package moodlecore
627 * @subpackage navigation
628 * @copyright 2010 Sam Hemelryk
629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
631 class navigation_node_collection
implements IteratorAggregate
{
633 * A multidimensional array to where the first key is the type and the second
634 * key is the nodes key.
637 protected $collection = array();
639 * An array that contains references to nodes in the same order they were added.
640 * This is maintained as a progressive array.
643 protected $orderedcollection = array();
645 * A reference to the last node that was added to the collection
646 * @var navigation_node
648 protected $last = null;
650 * The total number of items added to this array.
653 protected $count = 0;
655 * Adds a navigation node to the collection
657 * @param navigation_node $node
658 * @return navigation_node
660 public function add(navigation_node
$node) {
664 // First check we have a 2nd dimension for this type
665 if (!array_key_exists($type, $this->orderedcollection
)) {
666 $this->orderedcollection
[$type] = array();
668 // Check for a collision and report if debugging is turned on
669 if ($CFG->debug
&& array_key_exists($key, $this->orderedcollection
[$type])) {
670 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER
);
672 // Add the node to the appropriate place in the ordered structure.
673 $this->orderedcollection
[$type][$key] = $node;
674 // Add a reference to the node to the progressive collection.
675 $this->collection
[$this->count
] = &$this->orderedcollection
[$type][$key];
676 // Update the last property to a reference to this new node.
677 $this->last
= &$this->orderedcollection
[$type][$key];
679 // Return the reference to the now added node
684 * Fetches a node from this collection.
686 * @param string|int $key The key of the node we want to find.
687 * @param int $type One of navigation_node::TYPE_*.
688 * @return navigation_node|null
690 public function get($key, $type=null) {
691 if ($type !== null) {
692 // If the type is known then we can simply check and fetch
693 if (!empty($this->orderedcollection
[$type][$key])) {
694 return $this->orderedcollection
[$type][$key];
697 // Because we don't know the type we look in the progressive array
698 foreach ($this->collection
as $node) {
699 if ($node->key
=== $key) {
707 * Searches for a node with matching key and type.
709 * This function searches both the nodes in this collection and all of
710 * the nodes in each collection belonging to the nodes in this collection.
714 * @param string|int $key The key of the node we want to find.
715 * @param int $type One of navigation_node::TYPE_*.
716 * @return navigation_node|null
718 public function find($key, $type=null) {
719 if ($type !== null && array_key_exists($type, $this->orderedcollection
) && array_key_exists($key, $this->orderedcollection
[$type])) {
720 return $this->orderedcollection
[$type][$key];
722 $nodes = $this->getIterator();
723 // Search immediate children first
724 foreach ($nodes as &$node) {
725 if ($node->key
=== $key && ($type === null ||
$type === $node->type
)) {
729 // Now search each childs children
730 foreach ($nodes as &$node) {
731 $result = $node->children
->find($key, $type);
732 if ($result !== false) {
741 * Fetches the last node that was added to this collection
743 * @return navigation_node
745 public function last() {
749 * Fetches all nodes of a given type from this collection
751 public function type($type) {
752 if (!array_key_exists($type, $this->orderedcollection
)) {
753 $this->orderedcollection
[$type] = array();
755 return $this->orderedcollection
[$type];
758 * Removes the node with the given key and type from the collection
760 * @param string|int $key
764 public function remove($key, $type=null) {
765 $child = $this->get($key, $type);
766 if ($child !== false) {
767 foreach ($this->collection
as $colkey => $node) {
768 if ($node->key
== $key && $node->type
== $type) {
769 unset($this->collection
[$colkey]);
773 unset($this->orderedcollection
[$child->type
][$child->key
]);
781 * Gets the number of nodes in this collection
784 public function count() {
785 return count($this->collection
);
788 * Gets an array iterator for the collection.
790 * This is required by the IteratorAggregator interface and is used by routines
791 * such as the foreach loop.
793 * @return ArrayIterator
795 public function getIterator() {
796 return new ArrayIterator($this->collection
);
801 * The global navigation class used for... the global navigation
803 * This class is used by PAGE to store the global navigation for the site
804 * and is then used by the settings nav and navbar to save on processing and DB calls
808 * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
809 * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
812 * @package moodlecore
813 * @subpackage navigation
814 * @copyright 2009 Sam Hemelryk
815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
817 class global_navigation
extends navigation_node
{
819 * The Moodle page this navigation object belongs to.
824 protected $initialised = false;
826 protected $mycourses = array();
828 protected $rootnodes = array();
830 protected $showemptysections = false;
832 protected $extendforuser = array();
833 /** @var navigation_cache */
836 protected $addedcourses = array();
838 protected $expansionlimit = 0;
841 * Constructs a new global navigation
843 * @param moodle_page $page The page this navigation object belongs to
845 public function __construct(moodle_page
$page) {
846 global $CFG, $SITE, $USER;
848 if (during_initial_install()) {
852 if (get_home_page() == HOMEPAGE_SITE
) {
853 // We are using the site home for the root element
856 'type' => navigation_node
::TYPE_SYSTEM
,
857 'text' => get_string('home'),
858 'action' => new moodle_url('/')
861 // We are using the users my moodle for the root element
864 'type' => navigation_node
::TYPE_SYSTEM
,
865 'text' => get_string('myhome'),
866 'action' => new moodle_url('/my/')
870 // Use the parents consturctor.... good good reuse
871 parent
::__construct($properties);
873 // Initalise and set defaults
875 $this->forceopen
= true;
876 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
878 // Check if we need to clear the cache
879 $regenerate = optional_param('regenerate', null, PARAM_TEXT
);
880 if ($regenerate === 'navigation') {
881 $this->cache
->clear();
886 * Initialises the navigation object.
888 * This causes the navigation object to look at the current state of the page
889 * that it is associated with and then load the appropriate content.
891 * This should only occur the first time that the navigation structure is utilised
892 * which will normally be either when the navbar is called to be displayed or
893 * when a block makes use of it.
897 public function initialise() {
898 global $CFG, $SITE, $USER, $DB;
899 // Check if it has alread been initialised
900 if ($this->initialised ||
during_initial_install()) {
903 $this->initialised
= true;
905 // Set up the five base root nodes. These are nodes where we will put our
906 // content and are as follows:
907 // site: Navigation for the front page.
908 // myprofile: User profile information goes here.
909 // mycourses: The users courses get added here.
910 // courses: Additional courses are added here.
911 // users: Other users information loaded here.
912 $this->rootnodes
= array();
913 if (get_home_page() == HOMEPAGE_SITE
) {
914 // The home element should be my moodle because the root element is the site
915 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in
916 $this->rootnodes
['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self
::TYPE_SETTING
, null, 'home');
919 // The home element should be the site because the root node is my moodle
920 $this->rootnodes
['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self
::TYPE_SETTING
, null, 'home');
921 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
922 // We need to stop automatic redirection
923 $this->rootnodes
['home']->action
->param('redirect', '0');
926 $this->rootnodes
['site'] = $this->add_course($SITE);
927 $this->rootnodes
['myprofile'] = $this->add(get_string('myprofile'), null, self
::TYPE_USER
, null, 'myprofile');
928 $this->rootnodes
['mycourses'] = $this->add(get_string('mycourses'), null, self
::TYPE_ROOTNODE
, null, 'mycourses');
929 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
930 $this->rootnodes
['users'] = $this->add(get_string('users'), null, self
::TYPE_ROOTNODE
, null, 'users');
932 // Fetch all of the users courses.
934 if (!empty($CFG->navcourselimit
)) {
935 $limit = $CFG->navcourselimit
;
938 if (!empty($CFG->navshowcategories
) && $DB->count_records('course_categories') == 1) {
939 // There is only one category so we don't want to show categories
940 $CFG->navshowcategories
= false;
943 $this->mycourses
= enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
944 $showallcourses = (count($this->mycourses
) == 0 ||
!empty($CFG->navshowallcourses
));
945 $showcategories = ($showallcourses && !empty($CFG->navshowcategories
));
947 // Check if any courses were returned.
948 if (count($this->mycourses
) > 0) {
949 // Add all of the users courses to the navigation
950 foreach ($this->mycourses
as &$course) {
951 $course->coursenode
= $this->add_course($course);
955 if ($showcategories) {
956 // Load all categories (ensures we get the base categories)
957 $this->load_all_categories();
958 } else if ($showallcourses) {
960 $this->load_all_courses();
963 // We always load the frontpage course to ensure it is available without
964 // JavaScript enabled.
965 $frontpagecourse = $this->load_course($SITE);
966 $this->add_front_page_course_essentials($frontpagecourse, $SITE);
968 $canviewcourseprofile = true;
970 // Next load context specific content into the navigation
971 switch ($this->page
->context
->contextlevel
) {
972 case CONTEXT_SYSTEM
:
973 case CONTEXT_COURSECAT
:
974 // This has already been loaded we just need to map the variable
975 $coursenode = $frontpagecourse;
978 case CONTEXT_COURSE
:
979 // Load the course associated with the page into the navigation
980 $course = $this->page
->course
;
981 $coursenode = $this->load_course($course);
982 // If the user is not enrolled then we only want to show the
983 // course node and not populate it.
984 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
985 // Not enrolled, can't view, and hasn't switched roles
986 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext) && !is_role_switched($course->id
)) {
987 $coursenode->make_active();
988 $canviewcourseprofile = false;
991 // Add the essentials such as reports etc...
992 $this->add_course_essentials($coursenode, $course);
993 if ($this->format_display_course_content($course->format
)) {
994 // Load the course sections
995 $sections = $this->load_course_sections($course, $coursenode);
997 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
998 $coursenode->make_active();
1001 case CONTEXT_MODULE
:
1002 $course = $this->page
->course
;
1003 $cm = $this->page
->cm
;
1004 // Load the course associated with the page into the navigation
1005 $coursenode = $this->load_course($course);
1007 // If the user is not enrolled then we only want to show the
1008 // course node and not populate it.
1009 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1010 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext)) {
1011 $coursenode->make_active();
1012 $canviewcourseprofile = false;
1016 $this->add_course_essentials($coursenode, $course);
1017 // Load the course sections into the page
1018 $sections = $this->load_course_sections($course, $coursenode);
1019 if ($course->id
!== SITEID
) {
1020 // Find the section for the $CM associated with the page and collect
1021 // its section number.
1022 foreach ($sections as $section) {
1023 if ($section->id
== $cm->section
) {
1024 $cm->sectionnumber
= $section->section
;
1029 // Load all of the section activities for the section the cm belongs to.
1030 $activities = $this->load_section_activities($sections[$cm->sectionnumber
]->sectionnode
, $cm->sectionnumber
, get_fast_modinfo($course));
1032 $activities = array();
1033 $activities[$cm->id
] = $coursenode->get($cm->id
, navigation_node
::TYPE_ACTIVITY
);
1035 // Finally load the cm specific navigaton information
1036 $this->load_activity($cm, $course, $activities[$cm->id
]);
1037 // Check if we have an active ndoe
1038 if (!$activities[$cm->id
]->contains_active_node() && !$activities[$cm->id
]->search_for_active_node()) {
1039 // And make the activity node active.
1040 $activities[$cm->id
]->make_active();
1044 $course = $this->page
->course
;
1045 if ($course->id
!= SITEID
) {
1046 // Load the course associated with the user into the navigation
1047 $coursenode = $this->load_course($course);
1048 // If the user is not enrolled then we only want to show the
1049 // course node and not populate it.
1050 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1051 if (!is_enrolled($coursecontext) && !has_capability('moodle/course:view', $coursecontext)) {
1052 $coursenode->make_active();
1053 $canviewcourseprofile = false;
1056 $this->add_course_essentials($coursenode, $course);
1057 $sections = $this->load_course_sections($course, $coursenode);
1063 if (!empty($CFG->navcourselimit
)) {
1064 $limit = $CFG->navcourselimit
;
1066 if ($showcategories) {
1067 $categories = $this->find_all_of_type(self
::TYPE_CATEGORY
);
1068 foreach ($categories as &$category) {
1069 if ($category->children
->count() >= $limit) {
1070 $url = new moodle_url('/course/category.php', array('id'=>$category->key
));
1071 $category->add(get_string('viewallcourses'), $url, self
::TYPE_SETTING
);
1074 } else if ($this->rootnodes
['courses']->children
->count() >= $limit) {
1075 $this->rootnodes
['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self
::TYPE_SETTING
);
1078 // Load for the current user
1079 $this->load_for_user();
1080 if ($this->page
->context
->contextlevel
>= CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
&& $canviewcourseprofile) {
1081 $this->load_for_user(null, true);
1083 // Load each extending user into the navigation.
1084 foreach ($this->extendforuser
as $user) {
1085 if ($user->id
!== $USER->id
) {
1086 $this->load_for_user($user);
1090 // Give the local plugins a chance to include some navigation if they want.
1091 foreach (get_list_of_plugins('local') as $plugin) {
1092 if (!file_exists($CFG->dirroot
.'/local/'.$plugin.'/lib.php')) {
1095 require_once($CFG->dirroot
.'/local/'.$plugin.'/lib.php');
1096 $function = $plugin.'_extends_navigation';
1097 if (function_exists($function)) {
1102 // Remove any empty root nodes
1103 foreach ($this->rootnodes
as $node) {
1104 // Dont remove the home node
1105 if ($node->key
!== 'home' && !$node->has_children()) {
1110 if (!$this->contains_active_node()) {
1111 $this->search_for_active_node();
1114 // If the user is not logged in modify the navigation structure as detailed
1115 // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
1116 if (!isloggedin()) {
1117 $activities = clone($this->rootnodes
['site']->children
);
1118 $this->rootnodes
['site']->remove();
1119 $children = clone($this->children
);
1120 $this->children
= new navigation_node_collection();
1121 foreach ($activities as $child) {
1122 $this->children
->add($child);
1124 foreach ($children as $child) {
1125 $this->children
->add($child);
1131 * Checks the course format to see whether it wants the navigation to load
1132 * additional information for the course.
1134 * This function utilises a callback that can exist within the course format lib.php file
1135 * The callback should be a function called:
1136 * callback_{formatname}_display_content()
1137 * It doesn't get any arguments and should return true if additional content is
1138 * desired. If the callback doesn't exist we assume additional content is wanted.
1140 * @param string $format The course format
1143 protected function format_display_course_content($format) {
1145 $formatlib = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
1146 if (file_exists($formatlib)) {
1147 require_once($formatlib);
1148 $displayfunc = 'callback_'.$format.'_display_content';
1149 if (function_exists($displayfunc) && !$displayfunc()) {
1150 return $displayfunc();
1157 * Loads of the the courses in Moodle into the navigation.
1159 * @param string|array $categoryids Either a string or array of category ids to load courses for
1160 * @return array An array of navigation_node
1162 protected function load_all_courses($categoryids=null) {
1163 global $CFG, $DB, $USER;
1165 if ($categoryids !== null) {
1166 if (is_array($categoryids)) {
1167 list ($select, $params) = $DB->get_in_or_equal($categoryids);
1170 $params = array($categoryids);
1172 array_unshift($params, SITEID
);
1173 $select = ' AND c.category '.$select;
1175 $params = array(SITEID
);
1179 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1180 $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
1183 LEFT JOIN {course_categories} cat ON cat.id=c.category
1184 WHERE c.id <> ?$select
1185 ORDER BY c.sortorder ASC";
1187 if (!empty($CFG->navcourselimit
)) {
1188 $limit = $CFG->navcourselimit
;
1190 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
1192 $coursenodes = array();
1193 foreach ($courses as $course) {
1194 context_instance_preload($course);
1195 $coursenodes[$course->id
] = $this->add_course($course);
1197 return $coursenodes;
1201 * Loads all categories (top level or if an id is specified for that category)
1203 * @param int $categoryid
1206 protected function load_all_categories($categoryid=null) {
1208 if ($categoryid == null) {
1209 $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder');
1211 $category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST
);
1212 $wantedids = explode('/', trim($category->path
, '/'));
1213 list($select, $params) = $DB->get_in_or_equal($wantedids);
1214 $select = 'id '.$select.' OR parent '.$select;
1215 $params = array_merge($params, $params);
1216 $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1218 $structured = array();
1219 $categoriestoload = array();
1220 foreach ($categories as $category) {
1221 if ($category->parent
== '0') {
1222 $structured[$category->id
] = array('category'=>$category, 'children'=>array());
1224 if ($category->parent
== $categoryid) {
1225 $categoriestoload[] = $category->id
;
1228 $id = $category->parent
;
1229 while ($id != '0') {
1231 if (!array_key_exists($id, $categories)) {
1232 $categories[$id] = $DB->get_record('course_categories', array('id'=>$id), '*', MUST_EXIST
);
1234 $id = $categories[$id]->parent
;
1236 $parents = array_reverse($parents);
1237 $parentref = &$structured[array_shift($parents)];
1238 foreach ($parents as $parent) {
1239 if (!array_key_exists($parent, $parentref['children'])) {
1240 $parentref['children'][$parent] = array('category'=>$categories[$parent], 'children'=>array());
1242 $parentref = &$parentref['children'][$parent];
1244 if (!array_key_exists($category->id
, $parentref['children'])) {
1245 $parentref['children'][$category->id
] = array('category'=>$category, 'children'=>array());
1250 foreach ($structured as $category) {
1251 $this->add_category($category, $this->rootnodes
['courses']);
1254 if ($categoryid !== null && count($wantedids)) {
1255 foreach ($wantedids as $catid) {
1256 $this->load_all_courses($catid);
1262 * Adds a structured category to the navigation in the correct order/place
1264 * @param object $cat
1265 * @param navigation_node $parent
1267 protected function add_category($cat, navigation_node
$parent) {
1268 $category = $parent->get($cat['category']->id
, navigation_node
::TYPE_CATEGORY
);
1270 $category = $cat['category'];
1271 $url = new moodle_url('/course/category.php', array('id'=>$category->id
));
1272 $category = $parent->add($category->name
, null, self
::TYPE_CATEGORY
, $category->name
, $category->id
);
1274 foreach ($cat['children'] as $child) {
1275 $this->add_category($child, $category);
1280 * Loads the given course into the navigation
1282 * @param stdClass $course
1283 * @return navigation_node
1285 protected function load_course(stdClass
$course) {
1286 if ($course->id
== SITEID
) {
1287 $coursenode = $this->rootnodes
['site'];
1288 } else if (array_key_exists($course->id
, $this->mycourses
)) {
1289 if (!isset($this->mycourses
[$course->id
]->coursenode
)) {
1290 $this->mycourses
[$course->id
]->coursenode
= $this->add_course($course);
1292 $coursenode = $this->mycourses
[$course->id
]->coursenode
;
1294 $coursenode = $this->add_course($course);
1300 * Loads all of the courses section into the navigation.
1302 * This function utilisies a callback that can be implemented within the course
1303 * formats lib.php file to customise the navigation that is generated at this
1304 * point for the course.
1306 * By default (if not defined) the method {@see load_generic_course_sections} is
1309 * @param stdClass $course Database record for the course
1310 * @param navigation_node $coursenode The course node within the navigation
1311 * @return array Array of navigation nodes for the section with key = section id
1313 protected function load_course_sections(stdClass
$course, navigation_node
$coursenode) {
1315 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
1316 $structurefunc = 'callback_'.$course->format
.'_load_content';
1317 if (function_exists($structurefunc)) {
1318 return $structurefunc($this, $course, $coursenode);
1319 } else if (file_exists($structurefile)) {
1320 require_once $structurefile;
1321 if (function_exists($structurefunc)) {
1322 return $structurefunc($this, $course, $coursenode);
1324 return $this->load_generic_course_sections($course, $coursenode);
1327 return $this->load_generic_course_sections($course, $coursenode);
1332 * Generically loads the course sections into the course's navigation.
1334 * @param stdClass $course
1335 * @param navigation_node $coursenode
1336 * @param string $name The string that identifies each section. e.g Topic, or Week
1337 * @param string $activeparam The url used to identify the active section
1338 * @return array An array of course section nodes
1340 public function load_generic_course_sections(stdClass
$course, navigation_node
$coursenode, $courseformat='unknown') {
1341 global $CFG, $DB, $USER;
1343 require_once($CFG->dirroot
.'/course/lib.php');
1345 if (!$this->cache
->cached('modinfo'.$course->id
)) {
1346 $this->cache
->set('modinfo'.$course->id
, get_fast_modinfo($course));
1348 $modinfo = $this->cache
->{'modinfo'.$course->id
};
1350 if (!$this->cache
->cached('coursesections'.$course->id
)) {
1351 $this->cache
->set('coursesections'.$course->id
, array_slice(get_all_sections($course->id
), 0, $course->numsections+
1, true));
1353 $sections = $this->cache
->{'coursesections'.$course->id
};
1355 $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page
->context
);
1357 if (isloggedin() && !isguestuser()) {
1358 $activesection = $DB->get_field("course_display", "display", array("userid"=>$USER->id
, "course"=>$course->id
));
1360 $activesection = null;
1363 $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1364 $namingfunctionexists = (function_exists($namingfunction));
1366 $activeparamfunction = 'callback_'.$courseformat.'_request_key';
1367 if (function_exists($activeparamfunction)) {
1368 $activeparam = $activeparamfunction();
1370 $activeparam = 'section';
1372 $navigationsections = array();
1373 foreach ($sections as $sectionid=>$section) {
1374 $section = clone($section);
1375 if ($course->id
== SITEID
) {
1376 $this->load_section_activities($coursenode, $section->section
, $modinfo);
1378 if ((!$viewhiddensections && !$section->visible
) ||
(!$this->showemptysections
&& !array_key_exists($section->section
, $modinfo->sections
))) {
1381 if ($namingfunctionexists) {
1382 $sectionname = $namingfunction($course, $section, $sections);
1384 $sectionname = get_string('section').' '.$section->section
;
1386 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, $activeparam=>$section->section
));
1387 $sectionnode = $coursenode->add($sectionname, $url, navigation_node
::TYPE_SECTION
, null, $section->id
);
1388 $sectionnode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1389 $sectionnode->hidden
= (!$section->visible
);
1390 if ($this->page
->context
->contextlevel
!= CONTEXT_MODULE
&& ($sectionnode->isactive ||
($activesection != null && $section->section
== $activesection))) {
1391 $sectionnode->force_open();
1392 $this->load_section_activities($sectionnode, $section->section
, $modinfo);
1394 $section->sectionnode
= $sectionnode;
1395 $navigationsections[$sectionid] = $section;
1398 return $navigationsections;
1401 * Loads all of the activities for a section into the navigation structure.
1403 * @param navigation_node $sectionnode
1404 * @param int $sectionnumber
1405 * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1406 * @return array Array of activity nodes
1408 protected function load_section_activities(navigation_node
$sectionnode, $sectionnumber, $modinfo) {
1409 if (!array_key_exists($sectionnumber, $modinfo->sections
)) {
1413 $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page
->context
);
1414 $activities = array();
1416 foreach ($modinfo->sections
[$sectionnumber] as $cmid) {
1417 $cm = $modinfo->cms
[$cmid];
1418 if (!$viewhiddenactivities && !$cm->visible
) {
1422 $icon = new pix_icon($cm->icon
, get_string('modulename', $cm->modname
), $cm->iconcomponent
);
1424 $icon = new pix_icon('icon', get_string('modulename', $cm->modname
), $cm->modname
);
1426 $url = new moodle_url('/mod/'.$cm->modname
.'/view.php', array('id'=>$cm->id
));
1427 $activitynode = $sectionnode->add($cm->name
, $url, navigation_node
::TYPE_ACTIVITY
, $cm->name
, $cm->id
, $icon);
1428 $activitynode->title(get_string('modulename', $cm->modname
));
1429 $activitynode->hidden
= (!$cm->visible
);
1430 if ($cm->modname
== 'label') {
1431 $activitynode->display
= false;
1432 } else if ($this->module_extends_navigation($cm->modname
)) {
1433 $activitynode->nodetype
= navigation_node
::NODETYPE_BRANCH
;
1435 $activities[$cmid] = $activitynode;
1441 * Loads the navigation structure for the given activity into the activities node.
1443 * This method utilises a callback within the modules lib.php file to load the
1444 * content specific to activity given.
1446 * The callback is a method: {modulename}_extend_navigation()
1448 * * {@see forum_extend_navigation()}
1449 * * {@see workshop_extend_navigation()}
1451 * @param stdClass $cm
1452 * @param stdClass $course
1453 * @param navigation_node $activity
1456 protected function load_activity(stdClass
$cm, stdClass
$course, navigation_node
$activity) {
1459 $activity->make_active();
1460 $file = $CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php';
1461 $function = $cm->modname
.'_extend_navigation';
1463 if (file_exists($file)) {
1464 require_once($file);
1465 if (function_exists($function)) {
1466 $activtyrecord = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
1467 $function($activity, $course, $activtyrecord, $cm);
1471 $activity->nodetype
= navigation_node
::NODETYPE_LEAF
;
1475 * Loads user specific information into the navigation in the appopriate place.
1477 * If no user is provided the current user is assumed.
1479 * @param stdClass $user
1482 protected function load_for_user($user=null, $forceforcontext=false) {
1483 global $DB, $CFG, $USER;
1485 if ($user === null) {
1486 // We can't require login here but if the user isn't logged in we don't
1487 // want to show anything
1488 if (!isloggedin() ||
isguestuser()) {
1492 } else if (!is_object($user)) {
1493 // If the user is not an object then get them from the database
1494 $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST
);
1497 $iscurrentuser = ($user->id
== $USER->id
);
1499 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
1501 // Get the course set against the page, by default this will be the site
1502 $course = $this->page
->course
;
1503 $baseargs = array('id'=>$user->id
);
1504 if ($course->id
!== SITEID
&& (!$iscurrentuser ||
$forceforcontext)) {
1505 if (array_key_exists($course->id
, $this->mycourses
)) {
1506 $coursenode = $this->mycourses
[$course->id
]->coursenode
;
1508 $coursenode = $this->rootnodes
['courses']->find($course->id
, navigation_node
::TYPE_COURSE
);
1510 $coursenode = $this->load_course($course);
1513 $baseargs['course'] = $course->id
;
1514 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1515 $issitecourse = false;
1517 // Load all categories and get the context for the system
1518 $coursecontext = get_context_instance(CONTEXT_SYSTEM
);
1519 $issitecourse = true;
1522 // Create a node to add user information under.
1523 if ($iscurrentuser && !$forceforcontext) {
1524 // If it's the current user the information will go under the profile root node
1525 $usernode = $this->rootnodes
['myprofile'];
1527 if (!$issitecourse) {
1528 // Not the current user so add it to the participants node for the current course
1529 $usersnode = $coursenode->get('participants', navigation_node
::TYPE_CONTAINER
);
1530 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1532 // This is the site so add a users node to the root branch
1533 $usersnode = $this->rootnodes
['users'];
1534 $usersnode->action
= new moodle_url('/user/index.php', array('id'=>$course->id
));
1535 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1538 // We should NEVER get here, if the course hasn't been populated
1539 // with a participants node then the navigaiton either wasn't generated
1540 // for it (you are missing a require_login or set_context call) or
1541 // you don't have access.... in the interests of no leaking informatin
1542 // we simply quit...
1545 // Add a branch for the current user
1546 $usernode = $usersnode->add(fullname($user, true), $userviewurl, self
::TYPE_USER
, null, $user->id
);
1548 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $user->id
== $this->page
->context
->instanceid
) {
1549 $usernode->make_active();
1553 // If the user is the current user or has permission to view the details of the requested
1554 // user than add a view profile link.
1555 if ($iscurrentuser ||
has_capability('moodle/user:viewdetails', $coursecontext) ||
has_capability('moodle/user:viewdetails', $usercontext)) {
1556 if ($issitecourse ||
($iscurrentuser && !$forceforcontext)) {
1557 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1559 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1563 // Add nodes for forum posts and discussions if the user can view either or both
1564 $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1565 $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
1566 if ($canviewposts ||
$canviewdiscussions) {
1567 $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1568 if ($canviewposts) {
1569 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1571 if ($canviewdiscussions) {
1572 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions', 'course'=>$course->id
))));
1577 if (!empty($CFG->bloglevel
)) {
1578 require_once($CFG->dirroot
.'/blog/lib.php');
1579 // Get all options for the user
1580 $options = blog_get_options_for_user($user);
1581 if (count($options) > 0) {
1582 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
);
1583 foreach ($options as $option) {
1584 $blogs->add($option['string'], $option['link']);
1589 if (!empty($CFG->messaging
)) {
1590 $messageargs = null;
1591 if ($USER->id
!=$user->id
) {
1592 $messageargs = array('id'=>$user->id
);
1594 $url = new moodle_url('/message/index.php',$messageargs);
1595 $usernode->add(get_string('messages', 'message'), $url, self
::TYPE_SETTING
, null, 'messages');
1598 // TODO: Private file capability check
1599 if ($iscurrentuser) {
1600 $url = new moodle_url('/user/files.php');
1601 $usernode->add(get_string('myfiles'), $url, self
::TYPE_SETTING
);
1604 // Add a node to view the users notes if permitted
1605 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1606 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
));
1607 if ($coursecontext->instanceid
) {
1608 $url->param('course', $coursecontext->instanceid
);
1610 $usernode->add(get_string('notes', 'notes'), $url);
1613 // Add a reports tab and then add reports the the user has permission to see.
1614 $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1616 $viewreports = ($anyreport ||
($course->showreports
&& $iscurrentuser && $forceforcontext));
1618 $reporttab = $usernode->add(get_string('activityreports'));
1619 $reportargs = array('user'=>$user->id
);
1620 if (!empty($course->id
)) {
1621 $reportargs['id'] = $course->id
;
1623 $reportargs['id'] = SITEID
;
1625 if ($viewreports ||
has_capability('coursereport/outline:view', $coursecontext)) {
1626 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1627 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1630 if ($viewreports ||
has_capability('coursereport/log:viewtoday', $coursecontext)) {
1631 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1634 if ($viewreports ||
has_capability('coursereport/log:view', $coursecontext)) {
1635 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1638 if (!empty($CFG->enablestats
)) {
1639 if ($viewreports ||
has_capability('coursereport/stats:view', $coursecontext)) {
1640 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1644 $gradeaccess = false;
1645 if (has_capability('moodle/grade:viewall', $coursecontext)) {
1646 //ok - can view all course grades
1647 $gradeaccess = true;
1648 } else if ($course->showgrades
) {
1649 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1650 //ok - can view own grades
1651 $gradeaccess = true;
1652 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1653 // ok - can view grades of this user - parent most probably
1654 $gradeaccess = true;
1655 } else if ($anyreport) {
1656 // ok - can view grades of this user - parent most probably
1657 $gradeaccess = true;
1661 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1664 // Check the number of nodes in the report node... if there are none remove
1666 if (count($reporttab->children
)===0) {
1667 $usernode->remove_child($reporttab);
1671 // If the user is the current user add the repositories for the current user
1672 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
1673 if ($iscurrentuser) {
1674 require_once($CFG->dirroot
. '/repository/lib.php');
1675 $editabletypes = repository
::get_editable_types($usercontext);
1676 if (!empty($editabletypes)) {
1677 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id
)));
1679 } else if ($course->id
== SITEID
&& has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) ||
has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
1681 // Add view grade report is permitted
1682 $reports = get_plugin_list('gradereport');
1683 arsort($reports); // user is last, we want to test it first
1685 $userscourses = enrol_get_users_courses($user->id
);
1686 $userscoursesnode = $usernode->add(get_string('courses'));
1688 foreach ($userscourses as $usercourse) {
1689 $usercoursecontext = get_context_instance(CONTEXT_COURSE
, $usercourse->id
);
1690 $usercoursenode = $userscoursesnode->add($usercourse->shortname
, new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$usercourse->id
)), self
::TYPE_CONTAINER
);
1692 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
1693 if (!$gradeavailable && !empty($usercourse->showgrades
) && is_array($reports) && !empty($reports)) {
1694 foreach ($reports as $plugin => $plugindir) {
1695 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
1696 //stop when the first visible plugin is found
1697 $gradeavailable = true;
1703 if ($gradeavailable) {
1704 $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id
));
1705 $usercoursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/grades', ''));
1708 // Add a node to view the users notes if permitted
1709 if (!empty($CFG->enablenotes
) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
1710 $url = new moodle_url('/notes/index.php',array('user'=>$user->id
, 'course'=>$usercourse->id
));
1711 $usercoursenode->add(get_string('notes', 'notes'), $url, self
::TYPE_SETTING
);
1714 if (has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE
, $usercourse->id
))) {
1715 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id'=>$usercourse->id
)), self
::TYPE_SETTING
, null, null, new pix_icon('i/course', ''));
1718 $outlinetreport = ($anyreport ||
has_capability('coursereport/outline:view', $usercoursecontext));
1719 $logtodayreport = ($anyreport ||
has_capability('coursereport/log:viewtoday', $usercoursecontext));
1720 $logreport = ($anyreport ||
has_capability('coursereport/log:view', $usercoursecontext));
1721 $statsreport = ($anyreport ||
has_capability('coursereport/stats:view', $usercoursecontext));
1722 if ($outlinetreport ||
$logtodayreport ||
$logreport ||
$statsreport) {
1723 $reporttab = $usercoursenode->add(get_string('activityreports'));
1724 $reportargs = array('user'=>$user->id
, 'id'=>$usercourse->id
);
1725 if ($outlinetreport) {
1726 $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1727 $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1730 if ($logtodayreport) {
1731 $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1735 $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1738 if (!empty($CFG->enablestats
) && $statsreport) {
1739 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1748 * This method simply checks to see if a given module can extend the navigation.
1750 * @param string $modname
1753 protected function module_extends_navigation($modname) {
1755 if ($this->cache
->cached($modname.'_extends_navigation')) {
1756 return $this->cache
->{$modname.'_extends_navigation'};
1758 $file = $CFG->dirroot
.'/mod/'.$modname.'/lib.php';
1759 $function = $modname.'_extend_navigation';
1760 if (function_exists($function)) {
1761 $this->cache
->{$modname.'_extends_navigation'} = true;
1763 } else if (file_exists($file)) {
1764 require_once($file);
1765 if (function_exists($function)) {
1766 $this->cache
->{$modname.'_extends_navigation'} = true;
1770 $this->cache
->{$modname.'_extends_navigation'} = false;
1774 * Extends the navigation for the given user.
1776 * @param stdClass $user A user from the database
1778 public function extend_for_user($user) {
1779 $this->extendforuser
[] = $user;
1783 * Returns all of the users the navigation is being extended for
1787 public function get_extending_users() {
1788 return $this->extendforuser
;
1791 * Adds the given course to the navigation structure.
1793 * @param stdClass $course
1794 * @return navigation_node
1796 public function add_course(stdClass
$course, $forcegeneric = false) {
1798 $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page
->context
);
1799 if ($course->id
!== SITEID
&& !$canviewhidden && !$course->visible
) {
1803 $issite = ($course->id
== SITEID
);
1804 $ismycourse = (array_key_exists($course->id
, $this->mycourses
) && !$forcegeneric);
1805 $displaycategories = (!$ismycourse && !$issite && !empty($CFG->navshowcategories
));
1806 $shortname = $course->shortname
;
1811 $shortname = get_string('sitepages');
1812 } else if ($ismycourse) {
1813 $parent = $this->rootnodes
['mycourses'];
1814 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
1816 $parent = $this->rootnodes
['courses'];
1817 $url = new moodle_url('/course/view.php', array('id'=>$course->id
));
1820 if ($displaycategories) {
1821 // We need to load the category structure for this course
1822 $categoryfound = false;
1823 if (!empty($course->categorypath
)) {
1824 $categories = explode('/', trim($course->categorypath
, '/'));
1825 $category = $parent;
1826 while ($category && $categoryid = array_shift($categories)) {
1827 $category = $category->get($categoryid, self
::TYPE_CATEGORY
);
1829 if ($category instanceof navigation_node
) {
1830 $parent = $category;
1831 $categoryfound = true;
1833 if (!$categoryfound && $forcegeneric) {
1834 $this->load_all_categories($course->category
);
1835 if ($category = $parent->find($course->category
, self
::TYPE_CATEGORY
)) {
1836 $parent = $category;
1837 $categoryfound = true;
1840 } else if (!empty($course->category
)) {
1841 $this->load_all_categories($course->category
);
1842 if ($category = $parent->find($course->category
, self
::TYPE_CATEGORY
)) {
1843 $parent = $category;
1844 $categoryfound = true;
1846 if (!$categoryfound && !$forcegeneric) {
1847 $this->load_all_categories($course->category
);
1848 if ($category = $parent->find($course->category
, self
::TYPE_CATEGORY
)) {
1849 $parent = $category;
1850 $categoryfound = true;
1856 // We found the course... we can return it now :)
1857 if ($coursenode = $parent->get($course->id
, self
::TYPE_COURSE
)) {
1861 $coursenode = $parent->add($shortname, $url, self
::TYPE_COURSE
, $shortname, $course->id
);
1862 $coursenode->nodetype
= self
::NODETYPE_BRANCH
;
1863 $coursenode->hidden
= (!$course->visible
);
1864 $coursenode->title($course->fullname
);
1865 $this->addedcourses
[$course->id
] = &$coursenode;
1866 if ($ismycourse && !empty($CFG->navshowallcourses
)) {
1867 // We need to add this course to the general courses node as well as the
1868 // my courses node, rerun the function with the kill param
1869 $genericcourse = $this->add_course($course, true);
1870 if ($genericcourse->isactive
) {
1871 $genericcourse->make_inactive();
1872 $genericcourse->collapse
= true;
1873 if ($genericcourse->parent
&& $genericcourse->parent
->type
== self
::TYPE_CATEGORY
) {
1874 $parent = $genericcourse->parent
;
1875 while ($parent && $parent->type
== self
::TYPE_CATEGORY
) {
1876 $parent->collapse
= true;
1877 $parent = $parent->parent
;
1885 * Adds essential course nodes to the navigation for the given course.
1887 * This method adds nodes such as reports, blogs and participants
1889 * @param navigation_node $coursenode
1890 * @param stdClass $course
1893 public function add_course_essentials(navigation_node
$coursenode, stdClass
$course) {
1896 if ($course->id
== SITEID
) {
1897 return $this->add_front_page_course_essentials($coursenode, $course);
1900 if ($coursenode == false ||
$coursenode->get('participants', navigation_node
::TYPE_CONTAINER
)) {
1905 if (has_capability('moodle/course:viewparticipants', $this->page
->context
)) {
1906 require_once($CFG->dirroot
.'/blog/lib.php');
1907 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
1908 $currentgroup = groups_get_course_group($course, true);
1909 if ($course->id
== SITEID
) {
1911 } else if ($course->id
&& !$currentgroup) {
1912 $filterselect = $course->id
;
1914 $filterselect = $currentgroup;
1916 $filterselect = clean_param($filterselect, PARAM_INT
);
1917 if ($CFG->bloglevel
>= 3) {
1918 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1919 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1921 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
1922 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1924 } else if (count($this->extendforuser
) > 0 ||
$this->page
->course
->id
== $course->id
) {
1925 $participants = $coursenode->add(get_string('participants'), null, self
::TYPE_CONTAINER
, get_string('participants'), 'participants');
1928 // View course reports
1929 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
1930 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id
)), self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
1931 $coursereports = get_plugin_list('coursereport');
1932 foreach ($coursereports as $report=>$dir) {
1933 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
1934 if (file_exists($libfile)) {
1935 require_once($libfile);
1936 $reportfunction = $report.'_report_extend_navigation';
1937 if (function_exists($report.'_report_extend_navigation')) {
1938 $reportfunction($reportnav, $course, $this->page
->context
);
1946 * This generates the the structure of the course that won't be generated when
1947 * the modules and sections are added.
1949 * Things such as the reports branch, the participants branch, blogs... get
1950 * added to the course node by this method.
1952 * @param navigation_node $coursenode
1953 * @param stdClass $course
1954 * @return bool True for successfull generation
1956 public function add_front_page_course_essentials(navigation_node
$coursenode, stdClass
$course) {
1959 if ($coursenode == false ||
$coursenode->get('participants', navigation_node
::TYPE_CUSTOM
)) {
1964 if (has_capability('moodle/course:viewparticipants', $this->page
->context
)) {
1965 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id
), self
::TYPE_CUSTOM
, get_string('participants'), 'participants');
1968 $currentgroup = groups_get_course_group($course, true);
1969 if ($course->id
== SITEID
) {
1971 } else if ($course->id
&& !$currentgroup) {
1972 $filterselect = $course->id
;
1974 $filterselect = $currentgroup;
1976 $filterselect = clean_param($filterselect, PARAM_INT
);
1979 if (has_capability('moodle/blog:view', $this->page
->context
)) {
1980 require_once($CFG->dirroot
.'/blog/lib.php');
1981 if (blog_is_enabled_for_user()) {
1982 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1983 $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1988 if (!empty($CFG->enablenotes
) && (has_capability('moodle/notes:manage', $this->page
->context
) ||
has_capability('moodle/notes:view', $this->page
->context
))) {
1989 $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1993 if (!empty($CFG->usetags
) && isloggedin()) {
1994 $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
1998 // View course reports
1999 if (has_capability('moodle/site:viewreports', $this->page
->context
)) { // basic capability for listing of reports
2000 $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id
)), self
::TYPE_CONTAINER
, null, null, new pix_icon('i/stats', ''));
2001 $coursereports = get_plugin_list('coursereport');
2002 foreach ($coursereports as $report=>$dir) {
2003 $libfile = $CFG->dirroot
.'/course/report/'.$report.'/lib.php';
2004 if (file_exists($libfile)) {
2005 require_once($libfile);
2006 $reportfunction = $report.'_report_extend_navigation';
2007 if (function_exists($report.'_report_extend_navigation')) {
2008 $reportfunction($reportnav, $course, $this->page
->context
);
2017 * Clears the navigation cache
2019 public function clear_cache() {
2020 $this->cache
->clear();
2024 * Sets an expansion limit for the navigation
2026 * The expansion limit is used to prevent the display of content that has a type
2027 * greater than the provided $type.
2029 * Can be used to ensure things such as activities or activity content don't get
2030 * shown on the navigation.
2031 * They are still generated in order to ensure the navbar still makes sense.
2033 * @param int $type One of navigation_node::TYPE_*
2036 public function set_expansion_limit($type) {
2037 $nodes = $this->find_all_of_type($type);
2038 foreach ($nodes as &$node) {
2039 // We need to generate the full site node
2040 if ($type == self
::TYPE_COURSE
&& $node->key
== SITEID
) {
2043 foreach ($node->children
as &$child) {
2044 // We still want to show course reports and participants containers
2045 // or there will be navigation missing.
2046 if ($type == self
::TYPE_COURSE
&& $child->type
=== self
::TYPE_CONTAINER
) {
2049 $child->display
= false;
2055 * Attempts to get the navigation with the given key from this nodes children.
2057 * This function only looks at this nodes children, it does NOT look recursivily.
2058 * If the node can't be found then false is returned.
2060 * If you need to search recursivily then use the {@see find()} method.
2062 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2063 * may be of more use to you.
2065 * @param string|int $key The key of the node you wish to receive.
2066 * @param int $type One of navigation_node::TYPE_*
2067 * @return navigation_node|false
2069 public function get($key, $type = null) {
2070 if (!$this->initialised
) {
2071 $this->initialise();
2073 return parent
::get($key, $type);
2077 * Searches this nodes children and thier children to find a navigation node
2078 * with the matching key and type.
2080 * This method is recursive and searches children so until either a node is
2081 * found of there are no more nodes to search.
2083 * If you know that the node being searched for is a child of this node
2084 * then use the {@see get()} method instead.
2086 * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2087 * may be of more use to you.
2089 * @param string|int $key The key of the node you wish to receive.
2090 * @param int $type One of navigation_node::TYPE_*
2091 * @return navigation_node|false
2093 public function find($key, $type) {
2094 if (!$this->initialised
) {
2095 $this->initialise();
2097 return parent
::find($key, $type);
2102 * The limited global navigation class used for the AJAX extension of the global
2105 * The primary methods that are used in the global navigation class have been overriden
2106 * to ensure that only the relevant branch is generated at the root of the tree.
2107 * This can be done because AJAX is only used when the backwards structure for the
2108 * requested branch exists.
2109 * This has been done only because it shortens the amounts of information that is generated
2110 * which of course will speed up the response time.. because no one likes laggy AJAX.
2112 * @package moodlecore
2113 * @subpackage navigation
2114 * @copyright 2009 Sam Hemelryk
2115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2117 class global_navigation_for_ajax
extends global_navigation
{
2119 protected $branchtype;
2120 protected $instanceid;
2123 protected $expandable = array();
2126 * Constructs the navigation for use in AJAX request
2128 public function __construct($page, $branchtype, $id) {
2129 $this->page
= $page;
2130 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2131 $this->children
= new navigation_node_collection();
2132 $this->branchtype
= $branchtype;
2133 $this->instanceid
= $id;
2134 $this->initialise();
2137 * Initialise the navigation given the type and id for the branch to expand.
2139 * @return array The expandable nodes
2141 public function initialise() {
2142 global $CFG, $DB, $SITE;
2144 if ($this->initialised ||
during_initial_install()) {
2145 return $this->expandable
;
2147 $this->initialised
= true;
2149 $this->rootnodes
= array();
2150 $this->rootnodes
['site'] = $this->add_course($SITE);
2151 $this->rootnodes
['courses'] = $this->add(get_string('courses'), null, self
::TYPE_ROOTNODE
, null, 'courses');
2153 // Branchtype will be one of navigation_node::TYPE_*
2154 switch ($this->branchtype
) {
2155 case self
::TYPE_CATEGORY
:
2156 $this->load_all_categories($this->instanceid
);
2158 if (!empty($CFG->navcourselimit
)) {
2159 $limit = (int)$CFG->navcourselimit
;
2161 $courses = $DB->get_records('course', array('category' => $this->instanceid
), 'sortorder','*', 0, $limit);
2162 foreach ($courses as $course) {
2163 $this->add_course($course);
2166 case self
::TYPE_COURSE
:
2167 $course = $DB->get_record('course', array('id' => $this->instanceid
), '*', MUST_EXIST
);
2168 require_course_login($course);
2169 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2170 $coursenode = $this->add_course($course);
2171 $this->add_course_essentials($coursenode, $course);
2172 if ($this->format_display_course_content($course->format
)) {
2173 $this->load_course_sections($course, $coursenode);
2176 case self
::TYPE_SECTION
:
2177 $sql = 'SELECT c.*, cs.section AS sectionnumber
2179 LEFT JOIN {course_sections} cs ON cs.course = c.id
2181 $course = $DB->get_record_sql($sql, array($this->instanceid
), MUST_EXIST
);
2182 require_course_login($course);
2183 $this->page
->set_context(get_context_instance(CONTEXT_COURSE
, $course->id
));
2184 $coursenode = $this->add_course($course);
2185 $this->add_course_essentials($coursenode, $course);
2186 $sections = $this->load_course_sections($course, $coursenode);
2187 $this->load_section_activities($sections[$course->sectionnumber
]->sectionnode
, $course->sectionnumber
, get_fast_modinfo($course));
2189 case self
::TYPE_ACTIVITY
:
2190 $cm = get_coursemodule_from_id(false, $this->instanceid
, 0, false, MUST_EXIST
);
2191 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
2192 require_course_login($course, true, $cm);
2193 $this->page
->set_context(get_context_instance(CONTEXT_MODULE
, $cm->id
));
2194 $coursenode = $this->load_course($course);
2195 $sections = $this->load_course_sections($course, $coursenode);
2196 foreach ($sections as $section) {
2197 if ($section->id
== $cm->section
) {
2198 $cm->sectionnumber
= $section->section
;
2202 if ($course->id
== SITEID
) {
2203 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id
, self
::TYPE_ACTIVITY
));
2205 $activities = $this->load_section_activities($sections[$cm->sectionnumber
]->sectionnode
, $cm->sectionnumber
, get_fast_modinfo($course));
2206 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id
]);
2210 throw new Exception('Unknown type');
2211 return $this->expandable
;
2214 if ($this->page
->context
->contextlevel
== CONTEXT_COURSE
&& $this->page
->context
->instanceid
!= SITEID
) {
2215 $this->load_for_user(null, true);
2218 $this->find_expandable($this->expandable
);
2219 return $this->expandable
;
2223 * Returns an array of expandable nodes
2226 public function get_expandable() {
2227 return $this->expandable
;
2234 * This class is used to manage the navbar, which is initialised from the navigation
2235 * object held by PAGE
2237 * @package moodlecore
2238 * @subpackage navigation
2239 * @copyright 2009 Sam Hemelryk
2240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2242 class navbar
extends navigation_node
{
2244 protected $initialised = false;
2246 protected $keys = array();
2247 /** @var null|string */
2248 protected $content = null;
2249 /** @var moodle_page object */
2252 protected $ignoreactive = false;
2254 protected $duringinstall = false;
2256 protected $hasitems = false;
2260 public $children = array();
2262 public $includesettingsbase = false;
2264 * The almighty constructor
2266 * @param moodle_page $page
2268 public function __construct(moodle_page
$page) {
2270 if (during_initial_install()) {
2271 $this->duringinstall
= true;
2274 $this->page
= $page;
2275 $this->text
= get_string('home');
2276 $this->shorttext
= get_string('home');
2277 $this->action
= new moodle_url($CFG->wwwroot
);
2278 $this->nodetype
= self
::NODETYPE_BRANCH
;
2279 $this->type
= self
::TYPE_SYSTEM
;
2283 * Quick check to see if the navbar will have items in.
2285 * @return bool Returns true if the navbar will have items, false otherwise
2287 public function has_items() {
2288 if ($this->duringinstall
) {
2290 } else if ($this->hasitems
!== false) {
2293 $this->page
->navigation
->initialise($this->page
);
2295 $activenodefound = ($this->page
->navigation
->contains_active_node() ||
2296 $this->page
->settingsnav
->contains_active_node());
2298 $outcome = (count($this->children
)>0 ||
(!$this->ignoreactive
&& $activenodefound));
2299 $this->hasitems
= $outcome;
2304 * Turn on/off ignore active
2306 * @param bool $setting
2308 public function ignore_active($setting=true) {
2309 $this->ignoreactive
= ($setting);
2311 public function get($key, $type = null) {
2312 foreach ($this->children
as &$child) {
2313 if ($child->key
=== $key && ($type == null ||
$type == $child->type
)) {
2320 * Returns an array of navigation_node's that make up the navbar.
2324 public function get_items() {
2326 // Make sure that navigation is initialised
2327 if (!$this->has_items()) {
2330 if ($this->items
!== null) {
2331 return $this->items
;
2334 if (count($this->children
) > 0) {
2335 // Add the custom children
2336 $items = array_reverse($this->children
);
2339 $navigationactivenode = $this->page
->navigation
->find_active_node();
2340 $settingsactivenode = $this->page
->settingsnav
->find_active_node();
2342 // Check if navigation contains the active node
2343 if (!$this->ignoreactive
) {
2345 if ($navigationactivenode && $settingsactivenode) {
2346 // Parse a combined navigation tree
2347 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
2348 if (!$settingsactivenode->mainnavonly
) {
2349 $items[] = $settingsactivenode;
2351 $settingsactivenode = $settingsactivenode->parent
;
2353 if (!$this->includesettingsbase
) {
2354 // Removes the first node from the settings (root node) from the list
2357 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
2358 if (!$navigationactivenode->mainnavonly
) {
2359 $items[] = $navigationactivenode;
2361 $navigationactivenode = $navigationactivenode->parent
;
2363 } else if ($navigationactivenode) {
2364 // Parse the navigation tree to get the active node
2365 while ($navigationactivenode && $navigationactivenode->parent
!== null) {
2366 if (!$navigationactivenode->mainnavonly
) {
2367 $items[] = $navigationactivenode;
2369 $navigationactivenode = $navigationactivenode->parent
;
2371 } else if ($settingsactivenode) {
2372 // Parse the settings navigation to get the active node
2373 while ($settingsactivenode && $settingsactivenode->parent
!== null) {
2374 if (!$settingsactivenode->mainnavonly
) {
2375 $items[] = $settingsactivenode;
2377 $settingsactivenode = $settingsactivenode->parent
;
2382 $items[] = new navigation_node(array(
2383 'text'=>$this->page
->navigation
->text
,
2384 'shorttext'=>$this->page
->navigation
->shorttext
,
2385 'key'=>$this->page
->navigation
->key
,
2386 'action'=>$this->page
->navigation
->action
2389 $this->items
= array_reverse($items);
2390 return $this->items
;
2394 * Add a new navigation_node to the navbar, overrides parent::add
2396 * This function overrides {@link navigation_node::add()} so that we can change
2397 * the way nodes get added to allow us to simply call add and have the node added to the
2400 * @param string $text
2401 * @param string|moodle_url $action
2403 * @param string|int $key
2404 * @param string $shorttext
2405 * @param string $icon
2406 * @return navigation_node
2408 public function add($text, $action=null, $type=self
::TYPE_CUSTOM
, $shorttext=null, $key=null, pix_icon
$icon=null) {
2409 if ($this->content
!== null) {
2410 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER
);
2413 // Properties array used when creating the new navigation node
2418 // Set the action if one was provided
2419 if ($action!==null) {
2420 $itemarray['action'] = $action;
2422 // Set the shorttext if one was provided
2423 if ($shorttext!==null) {
2424 $itemarray['shorttext'] = $shorttext;
2426 // Set the icon if one was provided
2428 $itemarray['icon'] = $icon;
2430 // Default the key to the number of children if not provided
2431 if ($key === null) {
2432 $key = count($this->children
);
2435 $itemarray['key'] = $key;
2436 // Set the parent to this node
2437 $itemarray['parent'] = $this;
2438 // Add the child using the navigation_node_collections add method
2439 $this->children
[] = new navigation_node($itemarray);
2445 * Class used to manage the settings option for the current page
2447 * This class is used to manage the settings options in a tree format (recursively)
2448 * and was created initially for use with the settings blocks.
2450 * @package moodlecore
2451 * @subpackage navigation
2452 * @copyright 2009 Sam Hemelryk
2453 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2455 class settings_navigation
extends navigation_node
{
2456 /** @var stdClass */
2458 /** @var navigation_cache */
2460 /** @var moodle_page */
2463 protected $adminsection;
2465 protected $initialised = false;
2467 protected $userstoextendfor = array();
2470 * Sets up the object with basic settings and preparse it for use
2472 * @param moodle_page $page
2474 public function __construct(moodle_page
&$page) {
2475 if (during_initial_install()) {
2478 $this->page
= $page;
2479 // Initialise the main navigation. It is most important that this is done
2480 // before we try anything
2481 $this->page
->navigation
->initialise();
2482 // Initialise the navigation cache
2483 $this->cache
= new navigation_cache(NAVIGATION_CACHE_NAME
);
2484 $this->children
= new navigation_node_collection();
2487 * Initialise the settings navigation based on the current context
2489 * This function initialises the settings navigation tree for a given context
2490 * by calling supporting functions to generate major parts of the tree.
2493 public function initialise() {
2496 if (during_initial_install()) {
2498 } else if ($this->initialised
) {
2501 $this->id
= 'settingsnav';
2502 $this->context
= $this->page
->context
;
2504 $context = $this->context
;
2505 if ($context->contextlevel
== CONTEXT_BLOCK
) {
2506 $this->load_block_settings();
2507 $context = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid
));
2510 switch ($context->contextlevel
) {
2511 case CONTEXT_SYSTEM
:
2512 if ($this->page
->url
->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2513 $this->load_front_page_settings(($context->id
== $this->context
->id
));
2516 case CONTEXT_COURSECAT
:
2517 $this->load_category_settings();
2519 case CONTEXT_COURSE
:
2520 if ($this->page
->course
->id
!= SITEID
) {
2521 $this->load_course_settings(($context->id
== $this->context
->id
));
2523 $this->load_front_page_settings(($context->id
== $this->context
->id
));
2526 case CONTEXT_MODULE
:
2527 $this->load_module_settings();
2528 $this->load_course_settings();
2531 if ($this->page
->course
->id
!= SITEID
) {
2532 $this->load_course_settings();
2537 $settings = $this->load_user_settings($this->page
->course
->id
);
2538 $admin = $this->load_administration_settings();
2540 if ($context->contextlevel
== CONTEXT_SYSTEM
&& $admin) {
2541 $admin->force_open();
2542 } else if ($context->contextlevel
== CONTEXT_USER
&& $settings) {
2543 $settings->force_open();
2546 // Check if the user is currently logged in as another user
2547 if (session_is_loggedinas()) {
2548 // Get the actual user, we need this so we can display an informative return link
2549 $realuser = session_get_realuser();
2550 // Add the informative return to original user link
2551 $url = new moodle_url('/course/loginas.php',array('id'=>$this->page
->course
->id
, 'return'=>1,'sesskey'=>sesskey()));
2552 $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self
::TYPE_SETTING
, null, null, new pix_icon('t/left', ''));
2555 // Make sure the first child doesnt have proceed with hr set to true
2557 foreach ($this->children
as $key=>$node) {
2558 if ($node->nodetype
!= self
::NODETYPE_BRANCH ||
$node->children
->count()===0) {
2562 $this->initialised
= true;
2565 * Override the parent function so that we can add preceeding hr's and set a
2566 * root node class against all first level element
2568 * It does this by first calling the parent's add method {@link navigation_node::add()}
2569 * and then proceeds to use the key to set class and hr
2571 * @param string $text
2572 * @param sting|moodle_url $url
2573 * @param string $shorttext
2574 * @param string|int $key
2576 * @param string $icon
2577 * @return navigation_node
2579 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
2580 $node = parent
::add($text, $url, $type, $shorttext, $key, $icon);
2581 $node->add_class('root_node');
2586 * This function allows the user to add something to the start of the settings
2587 * navigation, which means it will be at the top of the settings navigation block
2589 * @param string $text
2590 * @param sting|moodle_url $url
2591 * @param string $shorttext
2592 * @param string|int $key
2594 * @param string $icon
2595 * @return navigation_node
2597 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon
$icon=null) {
2598 $children = $this->children
;
2599 $childrenclass = get_class($children);
2600 $this->children
= new $childrenclass;
2601 $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2602 foreach ($children as $child) {
2603 $this->children
->add($child);
2608 * Load the site administration tree
2610 * This function loads the site administration tree by using the lib/adminlib library functions
2612 * @param navigation_node $referencebranch A reference to a branch in the settings
2614 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2615 * tree and start at the beginning
2616 * @return mixed A key to access the admin tree by
2618 protected function load_administration_settings(navigation_node
$referencebranch=null, part_of_admin_tree
$adminbranch=null) {
2621 // Check if we are just starting to generate this navigation.
2622 if ($referencebranch === null) {
2624 // Require the admin lib then get an admin structure
2625 if (!function_exists('admin_get_root')) {
2626 require_once($CFG->dirroot
.'/lib/adminlib.php');
2628 $adminroot = admin_get_root(false, false);
2629 // This is the active section identifier
2630 $this->adminsection
= $this->page
->url
->param('section');
2632 // Disable the navigation from automatically finding the active node
2633 navigation_node
::$autofindactive = false;
2634 $referencebranch = $this->add(get_string('administrationsite'), null, self
::TYPE_SETTING
, null, 'root');
2635 foreach ($adminroot->children
as $adminbranch) {
2636 $this->load_administration_settings($referencebranch, $adminbranch);
2638 navigation_node
::$autofindactive = true;
2640 // Use the admin structure to locate the active page
2641 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection
, true)) {
2642 $currentnode = $this;
2643 while (($pathkey = array_pop($current->path
))!==null && $currentnode) {
2644 $currentnode = $currentnode->get($pathkey);
2647 $currentnode->make_active();
2650 $this->scan_for_active_node($referencebranch);
2652 return $referencebranch;
2653 } else if ($adminbranch->check_access()) {
2654 // We have a reference branch that we can access and is not hidden `hurrah`
2655 // Now we need to display it and any children it may have
2658 if ($adminbranch instanceof admin_settingpage
) {
2659 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name
));
2660 } else if ($adminbranch instanceof admin_externalpage
) {
2661 $url = $adminbranch->url
;
2665 $reference = $referencebranch->add($adminbranch->visiblename
, $url, self
::TYPE_SETTING
, null, $adminbranch->name
, $icon);
2667 if ($adminbranch->is_hidden()) {
2668 if (($adminbranch instanceof admin_externalpage ||
$adminbranch instanceof admin_settingpage
) && $adminbranch->name
== $this->adminsection
) {
2669 $reference->add_class('hidden');
2671 $reference->display
= false;
2675 // Check if we are generating the admin notifications and whether notificiations exist
2676 if ($adminbranch->name
=== 'adminnotifications' && admin_critical_warnings_present()) {
2677 $reference->add_class('criticalnotification');
2679 // Check if this branch has children
2680 if ($reference && isset($adminbranch->children
) && is_array($adminbranch->children
) && count($adminbranch->children
)>0) {
2681 foreach ($adminbranch->children
as $branch) {
2682 // Generate the child branches as well now using this branch as the reference
2683 $this->load_administration_settings($reference, $branch);
2686 $reference->icon
= new pix_icon('i/settings', '');
2692 * This function recursivily scans nodes until it finds the active node or there
2693 * are no more nodes.
2694 * @param navigation_node $node
2696 protected function scan_for_active_node(navigation_node
$node) {
2697 if (!$node->check_if_active() && $node->children
->count()>0) {
2698 foreach ($node->children
as &$child) {
2699 $this->scan_for_active_node($child);
2705 * Gets a navigation node given an array of keys that represent the path to
2708 * @param array $path
2709 * @return navigation_node|false
2711 protected function get_by_path(array $path) {
2712 $node = $this->get(array_shift($path));
2713 foreach ($path as $key) {
2720 * Generate the list of modules for the given course.
2722 * The array of resources and activities that can be added to a course is then
2723 * stored in the cache so that we can access it for anywhere.
2724 * It saves us generating it all the time
2727 * // To get resources:
2728 * $this->cache->{'course'.$courseid.'resources'}
2729 * // To get activities:
2730 * $this->cache->{'course'.$courseid.'activities'}
2733 * @param stdClass $course The course to get modules for
2735 protected function get_course_modules($course) {
2737 $mods = $modnames = $modnamesplural = $modnamesused = array();
2738 // This function is included when we include course/lib.php at the top
2740 get_all_mods($course->id
, $mods, $modnames, $modnamesplural, $modnamesused);
2741 $resources = array();
2742 $activities = array();
2743 foreach($modnames as $modname=>$modnamestr) {
2744 if (!course_allowed_module($course, $modname)) {
2748 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2749 if (!file_exists($libfile)) {
2752 include_once($libfile);
2753 $gettypesfunc = $modname.'_get_types';
2754 if (function_exists($gettypesfunc)) {
2755 $types = $gettypesfunc();
2756 foreach($types as $type) {
2757 if (!isset($type->modclass
) ||
!isset($type->typestr
)) {
2758 debugging('Incorrect activity type in '.$modname);
2761 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
2762 $resources[html_entity_decode($type->type
)] = $type->typestr
;
2764 $activities[html_entity_decode($type->type
)] = $type->typestr
;
2768 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
2769 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
2770 $resources[$modname] = $modnamestr;
2772 // all other archetypes are considered activity
2773 $activities[$modname] = $modnamestr;
2777 $this->cache
->{'course'.$course->id
.'resources'} = $resources;
2778 $this->cache
->{'course'.$course->id
.'activities'} = $activities;
2782 * This function loads the course settings that are available for the user
2784 * @param bool $forceopen If set to true the course node will be forced open
2785 * @return navigation_node|false
2787 protected function load_course_settings($forceopen = false) {
2788 global $CFG, $USER, $SESSION, $OUTPUT;
2790 $course = $this->page
->course
;
2791 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2793 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
2795 $coursenode = $this->add(get_string('courseadministration'), null, self
::TYPE_COURSE
, null, 'courseadmin');
2797 $coursenode->force_open();
2800 if (has_capability('moodle/course:update', $coursecontext)) {
2801 // Add the turn on/off settings
2802 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
2803 if ($this->page
->user_is_editing()) {
2804 $url->param('edit', 'off');
2805 $editstring = get_string('turneditingoff');
2807 $url->param('edit', 'on');
2808 $editstring = get_string('turneditingon');
2810 $coursenode->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
2812 if ($this->page
->user_is_editing()) {
2813 // Removed as per MDL-22732
2814 // $this->add_course_editing_links($course);
2817 // Add the course settings link
2818 $url = new moodle_url('/course/edit.php', array('id'=>$course->id
));
2819 $coursenode->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
2821 // Add the course completion settings link
2822 if ($CFG->enablecompletion
&& $course->enablecompletion
) {
2823 $url = new moodle_url('/course/completion.php', array('id'=>$course->id
));
2824 $coursenode->add(get_string('completion', 'completion'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
2829 enrol_add_course_navigation($coursenode, $course);
2832 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2833 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
2834 $coursenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
2837 // Add view grade report is permitted
2838 $reportavailable = false;
2839 if (has_capability('moodle/grade:viewall', $coursecontext)) {
2840 $reportavailable = true;
2841 } else if (!empty($course->showgrades
)) {
2842 $reports = get_plugin_list('gradereport');
2843 if (is_array($reports) && count($reports)>0) { // Get all installed reports
2844 arsort($reports); // user is last, we want to test it first
2845 foreach ($reports as $plugin => $plugindir) {
2846 if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2847 //stop when the first visible plugin is found
2848 $reportavailable = true;
2854 if ($reportavailable) {
2855 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id
));
2856 $gradenode = $coursenode->add(get_string('grades'), $url, self
::TYPE_SETTING
, null, 'grades', new pix_icon('i/grades', ''));
2859 // Add outcome if permitted
2860 if (!empty($CFG->enableoutcomes
) && has_capability('moodle/course:update', $coursecontext)) {
2861 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id
));
2862 $coursenode->add(get_string('outcomes', 'grades'), $url, self
::TYPE_SETTING
, null, 'outcomes', new pix_icon('i/outcomes', ''));
2865 // Backup this course
2866 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2867 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
2868 $coursenode->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, 'backup', new pix_icon('i/backup', ''));
2871 // Restore to this course
2872 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2873 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
2874 $coursenode->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, 'restore', new pix_icon('i/restore', ''));
2877 // Import data from other courses
2878 if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2879 $url = new moodle_url('/backup/import.php', array('id'=>$course->id
));
2880 $coursenode->add(get_string('import'), $url, self
::TYPE_SETTING
, null, 'import', new pix_icon('i/restore', ''));
2883 // Publish course on a hub
2884 if (has_capability('moodle/course:publish', $coursecontext)) {
2885 $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id
));
2886 $coursenode->add(get_string('publish'), $url, self
::TYPE_SETTING
, null, 'publish', new pix_icon('i/publish', ''));
2889 // Reset this course
2890 if (has_capability('moodle/course:reset', $coursecontext)) {
2891 $url = new moodle_url('/course/reset.php', array('id'=>$course->id
));
2892 $coursenode->add(get_string('reset'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/return', ''));
2896 require_once($CFG->dirroot
.'/question/editlib.php');
2897 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
2899 // Repository Instances
2900 require_once($CFG->dirroot
.'/repository/lib.php');
2901 $editabletypes = repository
::get_editable_types($coursecontext);
2902 if (has_capability('moodle/course:update', $coursecontext) && !empty($editabletypes)) {
2903 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$coursecontext->id
));
2904 $coursenode->add(get_string('repositories'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/repository', ''));
2908 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
2909 // hidden in new courses and courses where legacy files were turned off
2910 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
));
2911 $coursenode->add(get_string('courselegacyfiles'), $url, self
::TYPE_SETTING
, null, 'coursefiles', new pix_icon('i/files', ''));
2916 $assumedrole = $this->in_alternative_role();
2917 if ($assumedrole!==false) {
2918 $roles[0] = get_string('switchrolereturn');
2920 if (has_capability('moodle/role:switchroles', $coursecontext)) {
2921 $availableroles = get_switchable_roles($coursecontext);
2922 if (is_array($availableroles)) {
2923 foreach ($availableroles as $key=>$role) {
2924 if ($key == $CFG->guestroleid ||
$assumedrole===(int)$key) {
2927 $roles[$key] = $role;
2931 if (is_array($roles) && count($roles)>0) {
2932 $switchroles = $this->add(get_string('switchroleto'));
2933 if ((count($roles)==1 && array_key_exists(0, $roles))||
$assumedrole!==false) {
2934 $switchroles->force_open();
2936 $returnurl = $this->page
->url
;
2937 $returnurl->param('sesskey', sesskey());
2938 $SESSION->returnurl
= serialize($returnurl);
2939 foreach ($roles as $key=>$name) {
2940 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id
,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2941 $switchroles->add($name, $url, self
::TYPE_SETTING
, null, $key, new pix_icon('i/roles', ''));
2944 // Return we are done
2949 * Adds branches and links to the settings navigation to add course activities
2952 * @param stdClass $course
2954 protected function add_course_editing_links($course) {
2957 require_once($CFG->dirroot
.'/course/lib.php');
2959 // Add `add` resources|activities branches
2960 $structurefile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
2961 if (file_exists($structurefile)) {
2962 require_once($structurefile);
2963 $formatstring = call_user_func('callback_'.$course->format
.'_definition');
2964 $formatidentifier = optional_param(call_user_func('callback_'.$course->format
.'_request_key'), 0, PARAM_INT
);
2966 $formatstring = get_string('topic');
2967 $formatidentifier = optional_param('topic', 0, PARAM_INT
);
2970 $sections = get_all_sections($course->id
);
2972 $addresource = $this->add(get_string('addresource'));
2973 $addactivity = $this->add(get_string('addactivity'));
2974 if ($formatidentifier!==0) {
2975 $addresource->force_open();
2976 $addactivity->force_open();
2979 if (!$this->cache
->cached('course'.$course->id
.'resources')) {
2980 $this->get_course_modules($course);
2982 $resources = $this->cache
->{'course'.$course->id
.'resources'};
2983 $activities = $this->cache
->{'course'.$course->id
.'activities'};
2985 $textlib = textlib_get_instance();
2987 foreach ($sections as $section) {
2988 if ($formatidentifier !== 0 && $section->section
!= $formatidentifier) {
2991 $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id
, $formatstring=>$section->section
));
2992 if ($section->section
== 0) {
2993 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
2994 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self
::TYPE_SETTING
);
2996 $sectionresources = $addresource->add($formatstring.' '.$section->section
, $sectionurl, self
::TYPE_SETTING
);
2997 $sectionactivities = $addactivity->add($formatstring.' '.$section->section
, $sectionurl, self
::TYPE_SETTING
);
2999 foreach ($resources as $value=>$resource) {
3000 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3001 $pos = strpos($value, '&type=');
3003 $url->param('add', $textlib->substr($value, 0,$pos));
3004 $url->param('type', $textlib->substr($value, $pos+
6));
3006 $url->param('add', $value);
3008 $sectionresources->add($resource, $url, self
::TYPE_SETTING
);
3011 foreach ($activities as $activityname=>$activity) {
3012 if ($activity==='--') {
3016 if (strpos($activity, '--')===0) {
3017 $subbranch = $sectionactivities->add(trim($activity, '-'));
3020 $url = new moodle_url('/course/mod.php', array('id'=>$course->id
, 'sesskey'=>sesskey(), 'section'=>$section->section
));
3021 $pos = strpos($activityname, '&type=');
3023 $url->param('add', $textlib->substr($activityname, 0,$pos));
3024 $url->param('type', $textlib->substr($activityname, $pos+
6));
3026 $url->param('add', $activityname);
3028 if ($subbranch !== false) {
3029 $subbranch->add($activity, $url, self
::TYPE_SETTING
);
3031 $sectionactivities->add($activity, $url, self
::TYPE_SETTING
);
3038 * This function calls the module function to inject module settings into the
3039 * settings navigation tree.
3041 * This only gets called if there is a corrosponding function in the modules
3044 * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3046 * @return navigation_node|false
3048 protected function load_module_settings() {
3051 if (!$this->page
->cm
&& $this->context
->contextlevel
== CONTEXT_MODULE
&& $this->context
->instanceid
) {
3052 $cm = get_coursemodule_from_id(false, $this->context
->instanceid
, 0, false, MUST_EXIST
);
3053 $this->page
->set_cm($cm, $this->page
->course
);
3056 $file = $CFG->dirroot
.'/mod/'.$this->page
->activityname
.'/lib.php';
3057 if (file_exists($file)) {
3058 require_once($file);
3061 $modulenode = $this->add(get_string('pluginadministration', $this->page
->activityname
));
3062 $modulenode->force_open();
3064 // Settings for the module
3065 if (has_capability('moodle/course:manageactivities', $this->page
->cm
->context
)) {
3066 $url = new moodle_url('/course/modedit.php', array('update' => $this->page
->cm
->id
, 'return' => true, 'sesskey' => sesskey()));
3067 $modulenode->add(get_string('editsettings'), $url, navigation_node
::TYPE_SETTING
);
3069 // Assign local roles
3070 if (count(get_assignable_roles($this->page
->cm
->context
))>0) {
3071 $url = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->page
->cm
->context
->id
));
3072 $modulenode->add(get_string('localroles', 'role'), $url, self
::TYPE_SETTING
);
3075 if (has_capability('moodle/role:review', $this->page
->cm
->context
) or count(get_overridable_roles($this->page
->cm
->context
))>0) {
3076 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->page
->cm
->context
->id
));
3077 $modulenode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3079 // Check role permissions
3080 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page
->cm
->context
)) {
3081 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->page
->cm
->context
->id
));
3082 $modulenode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3085 if (has_capability('moodle/filter:manage', $this->page
->cm
->context
) && count(filter_get_available_in_context($this->page
->cm
->context
))>0) {
3086 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page
->cm
->context
->id
));
3087 $modulenode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
);
3090 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $this->page
->cm
->course
))) {
3091 $url = new moodle_url('/course/report/log/index.php', array('chooselog'=>'1','id'=>$this->page
->cm
->course
,'modid'=>$this->page
->cm
->id
));
3092 $modulenode->add(get_string('logs'), $url, self
::TYPE_SETTING
);
3095 // Add a backup link
3096 $featuresfunc = $this->page
->activityname
.'_supports';
3097 if ($featuresfunc(FEATURE_BACKUP_MOODLE2
) && has_capability('moodle/backup:backupactivity', $this->page
->cm
->context
)) {
3098 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page
->cm
->course
, 'cm'=>$this->page
->cm
->id
));
3099 $modulenode->add(get_string('backup'), $url, self
::TYPE_SETTING
);
3102 $function = $this->page
->activityname
.'_extend_settings_navigation';
3103 if (!function_exists($function)) {
3107 $function($this, $modulenode);
3109 // Remove the module node if there are no children
3110 if (empty($modulenode->children
)) {
3111 $modulenode->remove();
3118 * Loads the user settings block of the settings nav
3120 * This function is simply works out the userid and whether we need to load
3121 * just the current users profile settings, or the current user and the user the
3122 * current user is viewing.
3124 * This function has some very ugly code to work out the user, if anyone has
3125 * any bright ideas please feel free to intervene.
3127 * @param int $courseid The course id of the current course
3128 * @return navigation_node|false
3130 protected function load_user_settings($courseid=SITEID
) {
3131 global $USER, $FULLME, $CFG;
3133 if (isguestuser() ||
!isloggedin()) {
3137 $navusers = $this->page
->navigation
->get_extending_users();
3139 if (count($this->userstoextendfor
) > 0 ||
count($navusers) > 0) {
3141 foreach ($this->userstoextendfor
as $userid) {
3142 if ($userid == $USER->id
) {
3145 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3146 if (is_null($usernode)) {
3150 foreach ($navusers as $user) {
3151 if ($user->id
== $USER->id
) {
3154 $node = $this->generate_user_settings($courseid, $user->id
, 'userviewingsettings');
3155 if (is_null($usernode)) {
3159 $this->generate_user_settings($courseid, $USER->id
);
3161 $usernode = $this->generate_user_settings($courseid, $USER->id
);
3167 * Extends the settings navigation for the given user.
3169 * Note: This method gets called automatically if you call
3170 * $PAGE->navigation->extend_for_user($userid)
3172 * @param int $userid
3174 public function extend_for_user($userid) {
3177 if (!in_array($userid, $this->userstoextendfor
)) {
3178 $this->userstoextendfor
[] = $userid;
3179 if ($this->initialised
) {
3180 $this->generate_user_settings($this->page
->course
->id
, $userid, 'userviewingsettings');
3181 $children = array();
3182 foreach ($this->children
as $child) {
3183 $children[] = $child;
3185 array_unshift($children, array_pop($children));
3186 $this->children
= new navigation_node_collection();
3187 foreach ($children as $child) {
3188 $this->children
->add($child);
3195 * This function gets called by {@link load_user_settings()} and actually works out
3196 * what can be shown/done
3198 * @param int $courseid The current course' id
3199 * @param int $userid The user id to load for
3200 * @param string $gstitle The string to pass to get_string for the branch title
3201 * @return navigation_node|false
3203 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3204 global $DB, $CFG, $USER, $SITE;
3206 if ($courseid != SITEID
) {
3207 if (!empty($this->page
->course
->id
) && $this->page
->course
->id
== $courseid) {
3208 $course = $this->page
->course
;
3210 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST
);
3216 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3217 $systemcontext = get_system_context();
3218 $currentuser = ($USER->id
== $userid);
3222 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3224 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
3227 // Check that the user can view the profile
3228 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
); // User context
3229 if ($course->id
==SITEID
) {
3230 if ($CFG->forceloginforprofiles
&& !has_coursecontact_role($user->id
) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
3231 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3235 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) ||
!is_enrolled($coursecontext, $user->id
)) {
3238 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&& !has_capability('moodle/site:accessallgroups', $coursecontext)) {
3239 // If groups are in use, make sure we can see that group
3245 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page
->context
));
3248 if ($gstitle != 'usercurrentsettings') {
3252 // Add a user setting branch
3253 $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self
::TYPE_CONTAINER
, null, $key);
3254 $usersetting->id
= 'usersettings';
3255 if ($this->page
->context
->contextlevel
== CONTEXT_USER
&& $this->page
->context
->instanceid
== $user->id
) {
3256 // Automatically start by making it active
3257 $usersetting->make_active();
3260 // Check if the user has been deleted
3261 if ($user->deleted
) {
3262 if (!has_capability('moodle/user:update', $coursecontext)) {
3263 // We can't edit the user so just show the user deleted message
3264 $usersetting->add(get_string('userdeleted'), null, self
::TYPE_SETTING
);
3266 // We can edit the user so show the user deleted message and link it to the profile
3267 if ($course->id
== SITEID
) {
3268 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id
));
3270 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id
, 'course'=>$course->id
));
3272 $usersetting->add(get_string('userdeleted'), $profileurl, self
::TYPE_SETTING
);
3277 // Add the profile edit link
3278 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3279 if (($currentuser ||
is_siteadmin($USER) ||
!is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3280 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id
, 'course'=>$course->id
));
3281 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
3282 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) ||
($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3283 if (!empty($user->auth
)) {
3284 $userauth = get_auth_plugin($user->auth
);
3285 if ($userauth->can_edit_profile()) {
3286 $url = $userauth->edit_profile_url();
3288 $url = new moodle_url('/user/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
3290 $usersetting->add(get_string('editmyprofile'), $url, self
::TYPE_SETTING
);
3296 // Change password link
3297 if (!empty($user->auth
)) {
3298 $userauth = get_auth_plugin($user->auth
);
3299 if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
3300 $passwordchangeurl = $userauth->change_password_url();
3301 if (empty($passwordchangeurl)) {
3302 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id
));
3304 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self
::TYPE_SETTING
);
3308 // View the roles settings
3309 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3310 $roles = $usersetting->add(get_string('roles'), null, self
::TYPE_SETTING
);
3312 $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id
, 'courseid'=>$course->id
));
3313 $roles->add(get_string('thisusersroles', 'role'), $url, self
::TYPE_SETTING
);
3315 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH
);
3317 if (!empty($assignableroles)) {
3318 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3319 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self
::TYPE_SETTING
);
3322 if (has_capability('moodle/role:review', $usercontext) ||
count(get_overridable_roles($usercontext, ROLENAME_BOTH
))>0) {
3323 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3324 $roles->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3327 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id
,'userid'=>$user->id
, 'courseid'=>$course->id
));
3328 $roles->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3332 if ($currentuser && !empty($CFG->enableportfolios
) && has_capability('moodle/portfolio:export', $systemcontext)) {
3333 require_once($CFG->libdir
. '/portfoliolib.php');
3334 if (portfolio_instances(true, false)) {
3335 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self
::TYPE_SETTING
);
3337 $config = optional_param('config', 0, PARAM_INT
);
3338 $hide = optional_param('hide', 0, PARAM_INT
);
3339 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id
));
3341 $url->param('hide', $hide);
3343 if ($config !== 0) {
3344 $url->param('config', $config);
3346 $portfolio->add(get_string('configure', 'portfolio'), $url, self
::TYPE_SETTING
);
3348 $page = optional_param('page', 0, PARAM_INT
);
3349 $perpage = optional_param('perpage', 10, PARAM_INT
);
3350 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id
));
3352 $url->param('page', $page);
3354 if ($perpage !== 0) {
3355 $url->param('perpage', $perpage);
3357 $portfolio->add(get_string('logs', 'portfolio'), $url, self
::TYPE_SETTING
);
3361 $enablemanagetokens = false;
3362 if (!empty($CFG->enablerssfeeds
)) {
3363 $enablemanagetokens = true;
3364 } else if (!is_siteadmin($USER->id
)
3365 && !empty($CFG->enablewebservices
)
3366 && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3367 $enablemanagetokens = true;
3370 if ($currentuser && $enablemanagetokens) {
3371 $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3372 $usersetting->add(get_string('securitykeys', 'webservice'), $url, self
::TYPE_SETTING
);
3376 if (!$currentuser) {
3377 require_once($CFG->dirroot
. '/repository/lib.php');
3378 $editabletypes = repository
::get_editable_types($usercontext);
3379 if ($usercontext->contextlevel
== CONTEXT_USER
&& !empty($editabletypes)) {
3380 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id
));
3381 $usersetting->add(get_string('repositories', 'repository'), $url, self
::TYPE_SETTING
);
3386 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) ||
(!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id
))) {
3387 $url = new moodle_url('/message/edit.php', array('id'=>$user->id
, 'course'=>$course->id
));
3388 // Hide the node if messaging disabled
3389 $usersetting->add(get_string('editmymessage', 'message'), $url, self
::TYPE_SETTING
)->display
= !empty($CFG->messaging
);
3393 if (!empty($CFG->bloglevel
)) {
3394 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node
::TYPE_CONTAINER
, null, 'blogs');
3395 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node
::TYPE_SETTING
);
3396 if (!empty($CFG->useexternalblogs
) && $CFG->maxexternalblogsperuser
> 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM
))) {
3397 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node
::TYPE_SETTING
);
3398 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node
::TYPE_SETTING
);
3403 if (!$user->deleted
and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id
)) {
3404 $url = new moodle_url('/course/loginas.php', array('id'=>$course->id
, 'user'=>$user->id
, 'sesskey'=>sesskey()));
3405 $usersetting->add(get_string('loginas'), $url, self
::TYPE_SETTING
);
3408 return $usersetting;
3412 * Loads block specific settings in the navigation
3414 * @return navigation_node
3416 protected function load_block_settings() {
3419 $blocknode = $this->add(print_context_name($this->context
));
3420 $blocknode->force_open();
3422 // Assign local roles
3423 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
3424 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
);
3427 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
3428 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
3429 $blocknode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3431 // Check role permissions
3432 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
3433 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
3434 $blocknode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3441 * Loads category specific settings in the navigation
3443 * @return navigation_node
3445 protected function load_category_settings() {
3448 $categorynode = $this->add(print_context_name($this->context
));
3449 $categorynode->force_open();
3451 if ($this->page
->user_is_editing() && has_capability('moodle/category:manage', $this->context
)) {
3452 $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context
->instanceid
)));
3453 $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context
->instanceid
)));
3456 // Assign local roles
3457 $assignurl = new moodle_url('/'.$CFG->admin
.'/roles/assign.php', array('contextid'=>$this->context
->id
));
3458 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self
::TYPE_SETTING
);
3461 if (has_capability('moodle/role:review', $this->context
) or count(get_overridable_roles($this->context
))>0) {
3462 $url = new moodle_url('/'.$CFG->admin
.'/roles/permissions.php', array('contextid'=>$this->context
->id
));
3463 $categorynode->add(get_string('permissions', 'role'), $url, self
::TYPE_SETTING
);
3465 // Check role permissions
3466 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context
)) {
3467 $url = new moodle_url('/'.$CFG->admin
.'/roles/check.php', array('contextid'=>$this->context
->id
));
3468 $categorynode->add(get_string('checkpermissions', 'role'), $url, self
::TYPE_SETTING
);
3472 if (has_capability('moodle/cohort:manage', $this->context
) or has_capability('moodle/cohort:view', $this->context
)) {
3473 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', array('contextid' => $this->context
->id
)));
3477 if (has_capability('moodle/filter:manage', $this->context
) && count(filter_get_available_in_context($this->context
))>0) {
3478 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context
->id
));
3479 $categorynode->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
);
3482 return $categorynode;
3486 * Determine whether the user is assuming another role
3488 * This function checks to see if the user is assuming another role by means of
3489 * role switching. In doing this we compare each RSW key (context path) against
3490 * the current context path. This ensures that we can provide the switching
3491 * options against both the course and any page shown under the course.
3493 * @return bool|int The role(int) if the user is in another role, false otherwise
3495 protected function in_alternative_role() {
3497 if (!empty($USER->access
['rsw']) && is_array($USER->access
['rsw'])) {
3498 if (!empty($this->page
->context
) && !empty($USER->access
['rsw'][$this->page
->context
->path
])) {
3499 return $USER->access
['rsw'][$this->page
->context
->path
];
3501 foreach ($USER->access
['rsw'] as $key=>$role) {
3502 if (strpos($this->context
->path
,$key)===0) {
3511 * This function loads all of the front page settings into the settings navigation.
3512 * This function is called when the user is on the front page, or $COURSE==$SITE
3513 * @return navigation_node
3515 protected function load_front_page_settings($forceopen = false) {
3518 $course = clone($SITE);
3519 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
); // Course context
3521 $frontpage = $this->add(get_string('frontpagesettings'), null, self
::TYPE_SETTING
, null, 'frontpage');
3523 $frontpage->force_open();
3525 $frontpage->id
= 'frontpagesettings';
3527 if (has_capability('moodle/course:update', $coursecontext)) {
3529 // Add the turn on/off settings
3530 $url = new moodle_url('/course/view.php', array('id'=>$course->id
, 'sesskey'=>sesskey()));
3531 if ($this->page
->user_is_editing()) {
3532 $url->param('edit', 'off');
3533 $editstring = get_string('turneditingoff');
3535 $url->param('edit', 'on');
3536 $editstring = get_string('turneditingon');
3538 $frontpage->add($editstring, $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/edit', ''));
3540 // Add the course settings link
3541 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
3542 $frontpage->add(get_string('editsettings'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/settings', ''));
3546 enrol_add_course_navigation($frontpage, $course);
3549 if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3550 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id
));
3551 $frontpage->add(get_string('filters', 'admin'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/filter', ''));
3554 // Backup this course
3555 if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3556 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id
));
3557 $frontpage->add(get_string('backup'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/backup', ''));
3560 // Restore to this course
3561 if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3562 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id
));
3563 $frontpage->add(get_string('restore'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/restore', ''));
3567 $questioncaps = array('moodle/question:add',
3568 'moodle/question:editmine',
3569 'moodle/question:editall',
3570 'moodle/question:viewmine',
3571 'moodle/question:viewall',
3572 'moodle/question:movemine',
3573 'moodle/question:moveall');
3574 if (has_any_capability($questioncaps, $this->context
)) {
3575 $questionlink = $CFG->wwwroot
.'/question/edit.php';
3576 } else if (has_capability('moodle/question:managecategory', $this->context
)) {
3577 $questionlink = $CFG->wwwroot
.'/question/category.php';
3579 if (isset($questionlink)) {
3580 $url = new moodle_url($questionlink, array('courseid'=>$course->id
));
3581 $frontpage->add(get_string('questions','quiz'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/questions', ''));
3585 if ($course->legacyfiles
== 2 and has_capability('moodle/course:managefiles', $this->context
)) {
3586 //hiden in new installs
3587 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id
, 'itemid'=>0, 'component' => 'course', 'filearea'=>'legacy'));
3588 $frontpage->add(get_string('sitelegacyfiles'), $url, self
::TYPE_SETTING
, null, null, new pix_icon('i/files', ''));
3594 * This function marks the cache as volatile so it is cleared during shutdown
3596 public function clear_cache() {
3597 $this->cache
->volatile();
3602 * Simple class used to output a navigation branch in XML
3604 * @package moodlecore
3605 * @subpackage navigation
3606 * @copyright 2009 Sam Hemelryk
3607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3609 class navigation_json
{
3611 protected $nodetype = array('node','branch');
3613 protected $expandable = array();
3615 * Turns a branch and all of its children into XML
3617 * @param navigation_node $branch
3618 * @return string XML string
3620 public function convert($branch) {
3621 $xml = $this->convert_child($branch);
3625 * Set the expandable items in the array so that we have enough information
3626 * to attach AJAX events
3627 * @param array $expandable
3629 public function set_expandable($expandable) {
3630 foreach ($expandable as $node) {
3631 $this->expandable
[$node['branchid'].':'.$node['type']] = $node;
3635 * Recusively converts a child node and its children to XML for output
3637 * @param navigation_node $child The child to convert
3638 * @param int $depth Pointlessly used to track the depth of the XML structure
3639 * @return string JSON
3641 protected function convert_child($child, $depth=1) {
3644 if (!$child->display
) {
3647 $attributes = array();
3648 $attributes['id'] = $child->id
;
3649 $attributes['name'] = $child->text
;
3650 $attributes['type'] = $child->type
;
3651 $attributes['key'] = $child->key
;
3652 $attributes['class'] = $child->get_css_type();
3654 if ($child->icon
instanceof pix_icon
) {
3655 $attributes['icon'] = array(
3656 'component' => $child->icon
->component
,
3657 'pix' => $child->icon
->pix
,
3659 foreach ($child->icon
->attributes
as $key=>$value) {
3660 if ($key == 'class') {
3661 $attributes['icon']['classes'] = explode(' ', $value);
3662 } else if (!array_key_exists($key, $attributes['icon'])) {
3663 $attributes['icon'][$key] = $value;
3667 } else if (!empty($child->icon
)) {
3668 $attributes['icon'] = (string)$child->icon
;
3671 if ($child->forcetitle ||
$child->title
!== $child->text
) {
3672 $attributes['title'] = htmlentities($child->title
);
3674 if (array_key_exists($child->key
.':'.$child->type
, $this->expandable
)) {
3675 $attributes['expandable'] = $child->key
;
3676 $child->add_class($this->expandable
[$child->key
.':'.$child->type
]['id']);
3679 if (count($child->classes
)>0) {
3680 $attributes['class'] .= ' '.join(' ',$child->classes
);
3682 if (is_string($child->action
)) {
3683 $attributes['link'] = $child->action
;
3684 } else if ($child->action
instanceof moodle_url
) {
3685 $attributes['link'] = $child->action
->out();
3687 $attributes['hidden'] = ($child->hidden
);
3688 $attributes['haschildren'] = ($child->children
->count()>0 ||
$child->type
== navigation_node
::TYPE_CATEGORY
);
3690 if (count($child->children
)>0) {
3691 $attributes['children'] = array();
3692 foreach ($child->children
as $subchild) {
3693 $attributes['children'][] = $this->convert_child($subchild, $depth+
1);
3700 return json_encode($attributes);
3706 * The cache class used by global navigation and settings navigation to cache bits
3707 * and bobs that are used during their generation.
3709 * It is basically an easy access point to session with a bit of smarts to make
3710 * sure that the information that is cached is valid still.
3714 * if (!$cache->viewdiscussion()) {
3715 * // Code to do stuff and produce cachable content
3716 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3718 * $content = $cache->viewdiscussion;
3721 * @package moodlecore
3722 * @subpackage navigation
3723 * @copyright 2009 Sam Hemelryk
3724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3726 class navigation_cache
{
3728 protected $creation;
3735 /** @var stdClass */
3736 protected $currentcontext;
3738 const CACHETIME
= 0;
3740 const CACHEUSERID
= 1;
3742 const CACHEVALUE
= 2;
3743 /** @var null|array An array of navigation cache areas to expire on shutdown */
3744 public static $volatilecaches;
3747 * Contructor for the cache. Requires two arguments
3749 * @param string $area The string to use to segregate this particular cache
3750 * it can either be unique to start a fresh cache or if you want
3751 * to share a cache then make it the string used in the original
3753 * @param int $timeout The number of seconds to time the information out after
3755 public function __construct($area, $timeout=60) {
3757 $this->creation
= time();
3758 $this->area
= $area;
3760 if (!isset($SESSION->navcache
)) {
3761 $SESSION->navcache
= new stdClass
;
3764 if (!isset($SESSION->navcache
->{$area})) {
3765 $SESSION->navcache
->{$area} = array();
3767 $this->session
= &$SESSION->navcache
->{$area};
3768 $this->timeout
= time()-$timeout;
3769 if (rand(0,10)===0) {
3770 $this->garbage_collection();
3775 * Magic Method to retrieve something by simply calling using = cache->key
3777 * @param mixed $key The identifier for the information you want out again
3778 * @return void|mixed Either void or what ever was put in
3780 public function __get($key) {
3781 if (!$this->cached($key)) {
3784 $information = $this->session
[$key][self
::CACHEVALUE
];
3785 return unserialize($information);
3789 * Magic method that simply uses {@link set();} to store something in the cache
3791 * @param string|int $key
3792 * @param mixed $information
3794 public function __set($key, $information) {
3795 $this->set($key, $information);
3799 * Sets some information against the cache (session) for later retrieval
3801 * @param string|int $key
3802 * @param mixed $information
3804 public function set($key, $information) {
3806 $information = serialize($information);
3807 $this->session
[$key]= array(self
::CACHETIME
=>time(), self
::CACHEUSERID
=>$USER->id
, self
::CACHEVALUE
=>$information);
3810 * Check the existence of the identifier in the cache
3812 * @param string|int $key
3815 public function cached($key) {
3817 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
) {
3823 * Compare something to it's equivilant in the cache
3825 * @param string $key
3826 * @param mixed $value
3827 * @param bool $serialise Whether to serialise the value before comparison
3828 * this should only be set to false if the value is already
3830 * @return bool If the value is the same false if it is not set or doesn't match
3832 public function compare($key, $value, $serialise=true) {
3833 if ($this->cached($key)) {
3835 $value = serialize($value);
3837 if ($this->session
[$key][self
::CACHEVALUE
] === $value) {
3844 * Wipes the entire cache, good to force regeneration
3846 public function clear() {
3847 $this->session
= array();
3850 * Checks all cache entries and removes any that have expired, good ole cleanup
3852 protected function garbage_collection() {
3853 foreach ($this->session
as $key=>$cachedinfo) {
3854 if (is_array($cachedinfo) && $cachedinfo[self
::CACHETIME
]<$this->timeout
) {
3855 unset($this->session
[$key]);
3861 * Marks the cache as being volatile (likely to change)
3863 * Any caches marked as volatile will be destroyed at the on shutdown by
3864 * {@link navigation_node::destroy_volatile_caches()} which is registered
3865 * as a shutdown function if any caches are marked as volatile.
3867 * @param bool $setting True to destroy the cache false not too
3869 public function volatile($setting = true) {
3870 if (self
::$volatilecaches===null) {
3871 self
::$volatilecaches = array();
3872 register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
3876 self
::$volatilecaches[$this->area
] = $this->area
;
3877 } else if (array_key_exists($this->area
, self
::$volatilecaches)) {
3878 unset(self
::$volatilecaches[$this->area
]);
3883 * Destroys all caches marked as volatile
3885 * This function is static and works in conjunction with the static volatilecaches
3886 * property of navigation cache.
3887 * Because this function is static it manually resets the cached areas back to an
3890 public static function destroy_volatile_caches() {
3892 if (is_array(self
::$volatilecaches) && count(self
::$volatilecaches)>0) {
3893 foreach (self
::$volatilecaches as $area) {
3894 $SESSION->navcache
->{$area} = array();