6d67cced8190c1be8cde27b6c358bf78efd218e0
[moodle.git] / lib / navigationlib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * This file contains classes used to manage the navigation structures in Moodle
20  * and was introduced as part of the changes occuring in Moodle 2.0
21  *
22  * @since      2.0
23  * @package    core
24  * @subpackage navigation
25  * @copyright  2009 Sam Hemelryk
26  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27  */
29 defined('MOODLE_INTERNAL') || die();
31 /**
32  * The name that will be used to separate the navigation cache within SESSION
33  */
34 define('NAVIGATION_CACHE_NAME', 'navigation');
36 /**
37  * This class is used to represent a node in a navigation tree
38  *
39  * This class is used to represent a node in a navigation tree within Moodle,
40  * the tree could be one of global navigation, settings navigation, or the navbar.
41  * Each node can be one of two types either a Leaf (default) or a branch.
42  * When a node is first created it is created as a leaf, when/if children are added
43  * the node then becomes a branch.
44  *
45  * @package moodlecore
46  * @subpackage navigation
47  * @copyright 2009 Sam Hemelryk
48  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49  */
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 */
76     const TYPE_USER =       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] */
81     public $id = null;
82     /** @var string|int The identifier for the node, used to retrieve the node */
83     public $key = null;
84     /** @var string The text to use for the node */
85     public $text = null;
86     /** @var string Short text to use if requested [optional] */
87     public $shorttext = null;
88     /** @var string The title attribute for an action if one is defined */
89     public $title = null;
90     /** @var string A string that can be used to build a help button */
91     public $helpbutton = null;
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 */
95     public $icon = null;
96     /** @var int See TYPE_* constants defined for this class */
97     public $type = self::TYPE_UNKNOWN;
98     /** @var int See NODETYPE_* constants defined for this class */
99     public $nodetype = self::NODETYPE_LEAF;
100     /** @var bool If set to true the node will be collapsed by default */
101     public $collapse = false;
102     /** @var bool If set to true the node will be expanded by default */
103     public $forceopen = false;
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, you should never set this directly you should always call set_parent */
121     public $parent = null;
122     /** @var bool Override to not display the icon even if one is provided **/
123     public $hideicon = false;
124     /** @var array */
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;
131     /**
132      * Constructs a new navigation_node
133      *
134      * @param array|string $properties Either an array of properties or a string to use
135      *                     as the text for the node
136      */
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'];
149             }
150             if (array_key_exists('shorttext', $properties)) {
151                 $this->shorttext = $properties['shorttext'];
152             }
153             if (!array_key_exists('icon', $properties)) {
154                 $properties['icon'] = new pix_icon('i/navigationitem', 'moodle');
155             }
156             $this->icon = $properties['icon'];
157             if ($this->icon instanceof pix_icon) {
158                 if (empty($this->icon->attributes['class'])) {
159                     $this->icon->attributes['class'] = 'navicon';
160                 } else {
161                     $this->icon->attributes['class'] .= ' navicon';
162                 }
163             }
164             if (array_key_exists('type', $properties)) {
165                 $this->type = $properties['type'];
166             } else {
167                 $this->type = self::TYPE_CUSTOM;
168             }
169             if (array_key_exists('key', $properties)) {
170                 $this->key = $properties['key'];
171             }
172             // This needs to happen last because of the check_if_active call that occurs
173             if (array_key_exists('action', $properties)) {
174                 $this->action = $properties['action'];
175                 if (is_string($this->action)) {
176                     $this->action = new moodle_url($this->action);
177                 }
178                 if (self::$autofindactive) {
179                     $this->check_if_active();
180                 }
181             }
182             if (array_key_exists('parent', $properties)) {
183                 $this->set_parent($properties['parent']);
184             }
185         } else if (is_string($properties)) {
186             $this->text = $properties;
187         }
188         if ($this->text === null) {
189             throw new coding_exception('You must set the text for the node when you create it.');
190         }
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();
195     }
197     /**
198      * Checks if this node is the active node.
199      *
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.
202      *
203      * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
204      * @return bool
205      */
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));
212             } else {
213                 self::override_active_url(new moodle_url($FULLME));
214             }
215         }
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();
220             return true;
221         }
222         return false;
223     }
225     /**
226      * This sets the URL that the URL of new nodes get compared to when locating
227      * the active node.
228      *
229      * The active node is the node that matches the URL set here. By default this
230      * is either $PAGE->url or if that hasn't been set $FULLME.
231      *
232      * @param moodle_url $url The url to use for the fullmeurl.
233      */
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);
237     }
239     /**
240      * Creates a navigation node, ready to add it as a child using add_node
241      * function. (The created node needs to be added before you can use it.)
242      * @param string $text
243      * @param moodle_url|action_link $action
244      * @param int $type
245      * @param string $shorttext
246      * @param string|int $key
247      * @param pix_icon $icon
248      * @return navigation_node
249      */
250     public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
251             $shorttext=null, $key=null, pix_icon $icon=null) {
252         // Properties array used when creating the new navigation node
253         $itemarray = array(
254             'text' => $text,
255             'type' => $type
256         );
257         // Set the action if one was provided
258         if ($action!==null) {
259             $itemarray['action'] = $action;
260         }
261         // Set the shorttext if one was provided
262         if ($shorttext!==null) {
263             $itemarray['shorttext'] = $shorttext;
264         }
265         // Set the icon if one was provided
266         if ($icon!==null) {
267             $itemarray['icon'] = $icon;
268         }
269         // Set the key
270         $itemarray['key'] = $key;
271         // Construct and return
272         return new navigation_node($itemarray);
273     }
275     /**
276      * Adds a navigation node as a child of this node.
277      *
278      * @param string $text
279      * @param moodle_url|action_link $action
280      * @param int $type
281      * @param string $shorttext
282      * @param string|int $key
283      * @param pix_icon $icon
284      * @return navigation_node
285      */
286     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
287         // Create child node
288         $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
290         // Add the child to end and return
291         return $this->add_node($childnode);
292     }
294     /**
295      * Adds a navigation node as a child of this one, given a $node object
296      * created using the create function.
297      * @param navigation_node $childnode Node to add
298      * @param int|string $key The key of a node to add this before. If not
299      *   specified, adds at end of list
300      * @return navigation_node The added node
301      */
302     public function add_node(navigation_node $childnode, $beforekey=null) {
303         // First convert the nodetype for this node to a branch as it will now have children
304         if ($this->nodetype !== self::NODETYPE_BRANCH) {
305             $this->nodetype = self::NODETYPE_BRANCH;
306         }
307         // Set the parent to this node
308         $childnode->set_parent($this);
310         // Default the key to the number of children if not provided
311         if ($childnode->key === null) {
312             $childnode->key = $this->children->count();
313         }
315         // Add the child using the navigation_node_collections add method
316         $node = $this->children->add($childnode, $beforekey);
318         // If added node is a category node or the user is logged in and it's a course
319         // then mark added node as a branch (makes it expandable by AJAX)
320         $type = $childnode->type;
321         if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
322             $node->nodetype = self::NODETYPE_BRANCH;
323         }
324         // If this node is hidden mark it's children as hidden also
325         if ($this->hidden) {
326             $node->hidden = true;
327         }
328         // Return added node (reference returned by $this->children->add()
329         return $node;
330     }
332     /**
333      * Return a list of all the keys of all the child nodes.
334      * @return array the keys.
335      */
336     public function get_children_key_list() {
337         return $this->children->get_key_list();
338     }
340     /**
341      * Searches for a node of the given type with the given key.
342      *
343      * This searches this node plus all of its children, and their children....
344      * If you know the node you are looking for is a child of this node then please
345      * use the get method instead.
346      *
347      * @param int|string $key The key of the node we are looking for
348      * @param int $type One of navigation_node::TYPE_*
349      * @return navigation_node|false
350      */
351     public function find($key, $type) {
352         return $this->children->find($key, $type);
353     }
355     /**
356      * Get ths child of this node that has the given key + (optional) type.
357      *
358      * If you are looking for a node and want to search all children + thier children
359      * then please use the find method instead.
360      *
361      * @param int|string $key The key of the node we are looking for
362      * @param int $type One of navigation_node::TYPE_*
363      * @return navigation_node|false
364      */
365     public function get($key, $type=null) {
366         return $this->children->get($key, $type);
367     }
369     /**
370      * Removes this node.
371      *
372      * @return bool
373      */
374     public function remove() {
375         return $this->parent->children->remove($this->key, $this->type);
376     }
378     /**
379      * Checks if this node has or could have any children
380      *
381      * @return bool Returns true if it has children or could have (by AJAX expansion)
382      */
383     public function has_children() {
384         return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
385     }
387     /**
388      * Marks this node as active and forces it open.
389      *
390      * Important: If you are here because you need to mark a node active to get
391      * the navigation to do what you want have you looked at {@see navigation_node::override_active_url()}?
392      * You can use it to specify a different URL to match the active navigation node on
393      * rather than having to locate and manually mark a node active.
394      */
395     public function make_active() {
396         $this->isactive = true;
397         $this->add_class('active_tree_node');
398         $this->force_open();
399         if ($this->parent !== null) {
400             $this->parent->make_inactive();
401         }
402     }
404     /**
405      * Marks a node as inactive and recusised back to the base of the tree
406      * doing the same to all parents.
407      */
408     public function make_inactive() {
409         $this->isactive = false;
410         $this->remove_class('active_tree_node');
411         if ($this->parent !== null) {
412             $this->parent->make_inactive();
413         }
414     }
416     /**
417      * Forces this node to be open and at the same time forces open all
418      * parents until the root node.
419      *
420      * Recursive.
421      */
422     public function force_open() {
423         $this->forceopen = true;
424         if ($this->parent !== null) {
425             $this->parent->force_open();
426         }
427     }
429     /**
430      * Adds a CSS class to this node.
431      *
432      * @param string $class
433      * @return bool
434      */
435     public function add_class($class) {
436         if (!in_array($class, $this->classes)) {
437             $this->classes[] = $class;
438         }
439         return true;
440     }
442     /**
443      * Removes a CSS class from this node.
444      *
445      * @param string $class
446      * @return bool True if the class was successfully removed.
447      */
448     public function remove_class($class) {
449         if (in_array($class, $this->classes)) {
450             $key = array_search($class,$this->classes);
451             if ($key!==false) {
452                 unset($this->classes[$key]);
453                 return true;
454             }
455         }
456         return false;
457     }
459     /**
460      * Sets the title for this node and forces Moodle to utilise it.
461      * @param string $title
462      */
463     public function title($title) {
464         $this->title = $title;
465         $this->forcetitle = true;
466     }
468     /**
469      * Resets the page specific information on this node if it is being unserialised.
470      */
471     public function __wakeup(){
472         $this->forceopen = false;
473         $this->isactive = false;
474         $this->remove_class('active_tree_node');
475     }
477     /**
478      * Checks if this node or any of its children contain the active node.
479      *
480      * Recursive.
481      *
482      * @return bool
483      */
484     public function contains_active_node() {
485         if ($this->isactive) {
486             return true;
487         } else {
488             foreach ($this->children as $child) {
489                 if ($child->isactive || $child->contains_active_node()) {
490                     return true;
491                 }
492             }
493         }
494         return false;
495     }
497     /**
498      * Finds the active node.
499      *
500      * Searches this nodes children plus all of the children for the active node
501      * and returns it if found.
502      *
503      * Recursive.
504      *
505      * @return navigation_node|false
506      */
507     public function find_active_node() {
508         if ($this->isactive) {
509             return $this;
510         } else {
511             foreach ($this->children as &$child) {
512                 $outcome = $child->find_active_node();
513                 if ($outcome !== false) {
514                     return $outcome;
515                 }
516             }
517         }
518         return false;
519     }
521     /**
522      * Searches all children for the best matching active node
523      * @return navigation_node|false
524      */
525     public function search_for_active_node() {
526         if ($this->check_if_active(URL_MATCH_BASE)) {
527             return $this;
528         } else {
529             foreach ($this->children as &$child) {
530                 $outcome = $child->search_for_active_node();
531                 if ($outcome !== false) {
532                     return $outcome;
533                 }
534             }
535         }
536         return false;
537     }
539     /**
540      * Gets the content for this node.
541      *
542      * @param bool $shorttext If true shorttext is used rather than the normal text
543      * @return string
544      */
545     public function get_content($shorttext=false) {
546         if ($shorttext && $this->shorttext!==null) {
547             return format_string($this->shorttext);
548         } else {
549             return format_string($this->text);
550         }
551     }
553     /**
554      * Gets the title to use for this node.
555      *
556      * @return string
557      */
558     public function get_title() {
559         if ($this->forcetitle || $this->action != null){
560             return $this->title;
561         } else {
562             return '';
563         }
564     }
566     /**
567      * Gets the CSS class to add to this node to describe its type
568      *
569      * @return string
570      */
571     public function get_css_type() {
572         if (array_key_exists($this->type, $this->namedtypes)) {
573             return 'type_'.$this->namedtypes[$this->type];
574         }
575         return 'type_unknown';
576     }
578     /**
579      * Finds all nodes that are expandable by AJAX
580      *
581      * @param array $expandable An array by reference to populate with expandable nodes.
582      */
583     public function find_expandable(array &$expandable) {
584         foreach ($this->children as &$child) {
585             if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count() == 0 && $child->display) {
586                 $child->id = 'expandable_branch_'.(count($expandable)+1);
587                 $this->add_class('canexpand');
588                 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
589             }
590             $child->find_expandable($expandable);
591         }
592     }
594     /**
595      * Finds all nodes of a given type (recursive)
596      *
597      * @param int $type On of navigation_node::TYPE_*
598      * @return array
599      */
600     public function find_all_of_type($type) {
601         $nodes = $this->children->type($type);
602         foreach ($this->children as &$node) {
603             $childnodes = $node->find_all_of_type($type);
604             $nodes = array_merge($nodes, $childnodes);
605         }
606         return $nodes;
607     }
609     /**
610      * Removes this node if it is empty
611      */
612     public function trim_if_empty() {
613         if ($this->children->count() == 0) {
614             $this->remove();
615         }
616     }
618     /**
619      * Creates a tab representation of this nodes children that can be used
620      * with print_tabs to produce the tabs on a page.
621      *
622      * call_user_func_array('print_tabs', $node->get_tabs_array());
623      *
624      * @param array $inactive
625      * @param bool $return
626      * @return array Array (tabs, selected, inactive, activated, return)
627      */
628     public function get_tabs_array(array $inactive=array(), $return=false) {
629         $tabs = array();
630         $rows = array();
631         $selected = null;
632         $activated = array();
633         foreach ($this->children as $node) {
634             $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
635             if ($node->contains_active_node()) {
636                 if ($node->children->count() > 0) {
637                     $activated[] = $node->key;
638                     foreach ($node->children as $child) {
639                         if ($child->contains_active_node()) {
640                             $selected = $child->key;
641                         }
642                         $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
643                     }
644                 } else {
645                     $selected = $node->key;
646                 }
647             }
648         }
649         return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
650     }
652     /**
653      * Sets the parent for this node and if this node is active ensures that the tree is properly
654      * adjusted as well.
655      *
656      * @param navigation_node $parent
657      */
658     public function set_parent(navigation_node $parent) {
659         // Set the parent (thats the easy part)
660         $this->parent = $parent;
661         // Check if this node is active (this is checked during construction)
662         if ($this->isactive) {
663             // Force all of the parent nodes open so you can see this node
664             $this->parent->force_open();
665             // Make all parents inactive so that its clear where we are.
666             $this->parent->make_inactive();
667         }
668     }
671 /**
672  * Navigation node collection
673  *
674  * This class is responsible for managing a collection of navigation nodes.
675  * It is required because a node's unique identifier is a combination of both its
676  * key and its type.
677  *
678  * Originally an array was used with a string key that was a combination of the two
679  * however it was decided that a better solution would be to use a class that
680  * implements the standard IteratorAggregate interface.
681  *
682  * @package moodlecore
683  * @subpackage navigation
684  * @copyright 2010 Sam Hemelryk
685  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
686  */
687 class navigation_node_collection implements IteratorAggregate {
688     /**
689      * A multidimensional array to where the first key is the type and the second
690      * key is the nodes key.
691      * @var array
692      */
693     protected $collection = array();
694     /**
695      * An array that contains references to nodes in the same order they were added.
696      * This is maintained as a progressive array.
697      * @var array
698      */
699     protected $orderedcollection = array();
700     /**
701      * A reference to the last node that was added to the collection
702      * @var navigation_node
703      */
704     protected $last = null;
705     /**
706      * The total number of items added to this array.
707      * @var int
708      */
709     protected $count = 0;
711     /**
712      * Adds a navigation node to the collection
713      *
714      * @param navigation_node $node Node to add
715      * @param string $beforekey If specified, adds before a node with this key,
716      *   otherwise adds at end
717      * @return navigation_node Added node
718      */
719     public function add(navigation_node $node, $beforekey=null) {
720         global $CFG;
721         $key = $node->key;
722         $type = $node->type;
724         // First check we have a 2nd dimension for this type
725         if (!array_key_exists($type, $this->orderedcollection)) {
726             $this->orderedcollection[$type] = array();
727         }
728         // Check for a collision and report if debugging is turned on
729         if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
730             debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
731         }
733         // Find the key to add before
734         $newindex = $this->count;
735         $last = true;
736         if ($beforekey !== null) {
737             foreach ($this->collection as $index => $othernode) {
738                 if ($othernode->key === $beforekey) {
739                     $newindex = $index;
740                     $last = false;
741                     break;
742                 }
743             }
744             if ($newindex === $this->count) {
745                 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
746                         ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
747             }
748         }
750         // Add the node to the appropriate place in the by-type structure (which
751         // is not ordered, despite the variable name)
752         $this->orderedcollection[$type][$key] = $node;
753         if (!$last) {
754             // Update existing references in the ordered collection (which is the
755             // one that isn't called 'ordered') to shuffle them along if required
756             for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
757                 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
758             }
759         }
760         // Add a reference to the node to the progressive collection.
761         $this->collection[$newindex] = &$this->orderedcollection[$type][$key];
762         // Update the last property to a reference to this new node.
763         $this->last = &$this->orderedcollection[$type][$key];
765         // Reorder the array by index if needed
766         if (!$last) {
767             ksort($this->collection);
768         }
769         $this->count++;
770         // Return the reference to the now added node
771         return $node;
772     }
774     /**
775      * Return a list of all the keys of all the nodes.
776      * @return array the keys.
777      */
778     public function get_key_list() {
779         $keys = array();
780         foreach ($this->collection as $node) {
781             $keys[] = $node->key;
782         }
783         return $keys;
784     }
786     /**
787      * Fetches a node from this collection.
788      *
789      * @param string|int $key The key of the node we want to find.
790      * @param int $type One of navigation_node::TYPE_*.
791      * @return navigation_node|null
792      */
793     public function get($key, $type=null) {
794         if ($type !== null) {
795             // If the type is known then we can simply check and fetch
796             if (!empty($this->orderedcollection[$type][$key])) {
797                 return $this->orderedcollection[$type][$key];
798             }
799         } else {
800             // Because we don't know the type we look in the progressive array
801             foreach ($this->collection as $node) {
802                 if ($node->key === $key) {
803                     return $node;
804                 }
805             }
806         }
807         return false;
808     }
810     /**
811      * Searches for a node with matching key and type.
812      *
813      * This function searches both the nodes in this collection and all of
814      * the nodes in each collection belonging to the nodes in this collection.
815      *
816      * Recursive.
817      *
818      * @param string|int $key  The key of the node we want to find.
819      * @param int $type  One of navigation_node::TYPE_*.
820      * @return navigation_node|null
821      */
822     public function find($key, $type=null) {
823         if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
824             return $this->orderedcollection[$type][$key];
825         } else {
826             $nodes = $this->getIterator();
827             // Search immediate children first
828             foreach ($nodes as &$node) {
829                 if ($node->key === $key && ($type === null || $type === $node->type)) {
830                     return $node;
831                 }
832             }
833             // Now search each childs children
834             foreach ($nodes as &$node) {
835                 $result = $node->children->find($key, $type);
836                 if ($result !== false) {
837                     return $result;
838                 }
839             }
840         }
841         return false;
842     }
844     /**
845      * Fetches the last node that was added to this collection
846      *
847      * @return navigation_node
848      */
849     public function last() {
850         return $this->last;
851     }
853     /**
854      * Fetches all nodes of a given type from this collection
855      */
856     public function type($type) {
857         if (!array_key_exists($type, $this->orderedcollection)) {
858             $this->orderedcollection[$type] = array();
859         }
860         return $this->orderedcollection[$type];
861     }
862     /**
863      * Removes the node with the given key and type from the collection
864      *
865      * @param string|int $key
866      * @param int $type
867      * @return bool
868      */
869     public function remove($key, $type=null) {
870         $child = $this->get($key, $type);
871         if ($child !== false) {
872             foreach ($this->collection as $colkey => $node) {
873                 if ($node->key == $key && $node->type == $type) {
874                     unset($this->collection[$colkey]);
875                     break;
876                 }
877             }
878             unset($this->orderedcollection[$child->type][$child->key]);
879             $this->count--;
880             return true;
881         }
882         return false;
883     }
885     /**
886      * Gets the number of nodes in this collection
887      *
888      * This option uses an internal count rather than counting the actual options to avoid
889      * a performance hit through the count function.
890      *
891      * @return int
892      */
893     public function count() {
894         return $this->count;
895     }
896     /**
897      * Gets an array iterator for the collection.
898      *
899      * This is required by the IteratorAggregator interface and is used by routines
900      * such as the foreach loop.
901      *
902      * @return ArrayIterator
903      */
904     public function getIterator() {
905         return new ArrayIterator($this->collection);
906     }
909 /**
910  * The global navigation class used for... the global navigation
911  *
912  * This class is used by PAGE to store the global navigation for the site
913  * and is then used by the settings nav and navbar to save on processing and DB calls
914  *
915  * See
916  * <ul>
917  * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
918  * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
919  * </ul>
920  *
921  * @package moodlecore
922  * @subpackage navigation
923  * @copyright 2009 Sam Hemelryk
924  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
925  */
926 class global_navigation extends navigation_node {
927     /**
928      * The Moodle page this navigation object belongs to.
929      * @var moodle_page
930      */
931     protected $page;
932     /** @var bool */
933     protected $initialised = false;
934     /** @var array */
935     protected $mycourses = array();
936     /** @var array */
937     protected $rootnodes = array();
938     /** @var bool */
939     protected $showemptysections = false;
940     /** @var bool */
941     protected $showcategories = null;
942     /** @var array */
943     protected $extendforuser = array();
944     /** @var navigation_cache */
945     protected $cache;
946     /** @var array */
947     protected $addedcourses = array();
948     /** @var array */
949     protected $addedcategories = array();
950     /** @var int */
951     protected $expansionlimit = 0;
952     /** @var int */
953     protected $useridtouseforparentchecks = 0;
955     /**
956      * Constructs a new global navigation
957      *
958      * @param moodle_page $page The page this navigation object belongs to
959      */
960     public function __construct(moodle_page $page) {
961         global $CFG, $SITE, $USER;
963         if (during_initial_install()) {
964             return;
965         }
967         if (get_home_page() == HOMEPAGE_SITE) {
968             // We are using the site home for the root element
969             $properties = array(
970                 'key' => 'home',
971                 'type' => navigation_node::TYPE_SYSTEM,
972                 'text' => get_string('home'),
973                 'action' => new moodle_url('/')
974             );
975         } else {
976             // We are using the users my moodle for the root element
977             $properties = array(
978                 'key' => 'myhome',
979                 'type' => navigation_node::TYPE_SYSTEM,
980                 'text' => get_string('myhome'),
981                 'action' => new moodle_url('/my/')
982             );
983         }
985         // Use the parents consturctor.... good good reuse
986         parent::__construct($properties);
988         // Initalise and set defaults
989         $this->page = $page;
990         $this->forceopen = true;
991         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
992     }
994     /**
995      * Mutator to set userid to allow parent to see child's profile
996      * page navigation. See MDL-25805 for initial issue. Linked to it
997      * is an issue explaining why this is a REALLY UGLY HACK thats not
998      * for you to use!
999      *
1000      * @param int $userid userid of profile page that parent wants to navigate around.
1001      */
1002     public function set_userid_for_parent_checks($userid) {
1003         $this->useridtouseforparentchecks = $userid;
1004     }
1007     /**
1008      * Initialises the navigation object.
1009      *
1010      * This causes the navigation object to look at the current state of the page
1011      * that it is associated with and then load the appropriate content.
1012      *
1013      * This should only occur the first time that the navigation structure is utilised
1014      * which will normally be either when the navbar is called to be displayed or
1015      * when a block makes use of it.
1016      *
1017      * @return bool
1018      */
1019     public function initialise() {
1020         global $CFG, $SITE, $USER, $DB;
1021         // Check if it has alread been initialised
1022         if ($this->initialised || during_initial_install()) {
1023             return true;
1024         }
1025         $this->initialised = true;
1027         // Set up the five base root nodes. These are nodes where we will put our
1028         // content and are as follows:
1029         // site:        Navigation for the front page.
1030         // myprofile:     User profile information goes here.
1031         // mycourses:   The users courses get added here.
1032         // courses:     Additional courses are added here.
1033         // users:       Other users information loaded here.
1034         $this->rootnodes = array();
1035         if (get_home_page() == HOMEPAGE_SITE) {
1036             // The home element should be my moodle because the root element is the site
1037             if (isloggedin() && !isguestuser()) {  // Makes no sense if you aren't logged in
1038                 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1039             }
1040         } else {
1041             // The home element should be the site because the root node is my moodle
1042             $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1043             if ($CFG->defaulthomepage == HOMEPAGE_MY) {
1044                 // We need to stop automatic redirection
1045                 $this->rootnodes['home']->action->param('redirect', '0');
1046             }
1047         }
1048         $this->rootnodes['site']      = $this->add_course($SITE);
1049         $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1050         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1051         $this->rootnodes['courses']   = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1052         $this->rootnodes['users']     = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1054         // Fetch all of the users courses.
1055         $limit = 20;
1056         if (!empty($CFG->navcourselimit)) {
1057             $limit = $CFG->navcourselimit;
1058         }
1060         $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit);
1061         $showallcourses = (count($mycourses) == 0 || !empty($CFG->navshowallcourses));
1062         $showcategories = ($showallcourses && $this->show_categories());
1063         $issite = ($this->page->course->id == SITEID);
1064         $ismycourse = (array_key_exists($this->page->course->id, $mycourses));
1066         // Check if any courses were returned.
1067         if (count($mycourses) > 0) {
1068             // Add all of the users courses to the navigation
1069             foreach ($mycourses as $course) {
1070                 $course->coursenode = $this->add_course($course, false, true);
1071             }
1072         }
1074         if ($showallcourses) {
1075             // Load all courses
1076             $this->load_all_courses();
1077         }
1079         // We always load the frontpage course to ensure it is available without
1080         // JavaScript enabled.
1081         $frontpagecourse = $this->load_course($SITE);
1082         $this->add_front_page_course_essentials($frontpagecourse, $SITE);
1083         $this->load_course_sections($SITE, $frontpagecourse);
1085         $canviewcourseprofile = true;
1087         if (!$issite) {
1088             // Next load context specific content into the navigation
1089             switch ($this->page->context->contextlevel) {
1090                 case CONTEXT_SYSTEM :
1091                     // This has already been loaded we just need to map the variable
1092                     $coursenode = $frontpagecourse;
1093                     $this->load_all_categories(null, $showcategories);
1094                     break;
1095                 case CONTEXT_COURSECAT :
1096                     // This has already been loaded we just need to map the variable
1097                     $coursenode = $frontpagecourse;
1098                     $this->load_all_categories($this->page->context->instanceid, $showcategories);
1099                     break;
1100                 case CONTEXT_BLOCK :
1101                 case CONTEXT_COURSE :
1102                     // Load the course associated with the page into the navigation
1103                     $course = $this->page->course;
1104                     if ($showcategories && !$ismycourse) {
1105                         $this->load_all_categories($course->category, $showcategories);
1106                     }
1107                     $coursenode = $this->load_course($course);
1109                     // If the course wasn't added then don't try going any further.
1110                     if (!$coursenode) {
1111                         $canviewcourseprofile = false;
1112                         break;
1113                     }
1115                     // If the user is not enrolled then we only want to show the
1116                     // course node and not populate it.
1118                     // Not enrolled, can't view, and hasn't switched roles
1119                     if (!can_access_course($course)) {
1120                         // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1121                         // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1122                         $isparent = false;
1123                         if ($this->useridtouseforparentchecks) {
1124                             if ($this->useridtouseforparentchecks != $USER->id) {
1125                                 $usercontext   = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST);
1126                                 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))
1127                                         and has_capability('moodle/user:viewdetails', $usercontext)) {
1128                                     $isparent = true;
1129                                 }
1130                             }
1131                         }
1133                         if (!$isparent) {
1134                             $coursenode->make_active();
1135                             $canviewcourseprofile = false;
1136                             break;
1137                         }
1138                     }
1139                     // Add the essentials such as reports etc...
1140                     $this->add_course_essentials($coursenode, $course);
1141                     if ($this->format_display_course_content($course->format)) {
1142                         // Load the course sections
1143                         $sections = $this->load_course_sections($course, $coursenode);
1144                     }
1145                     if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1146                         $coursenode->make_active();
1147                     }
1148                     break;
1149                 case CONTEXT_MODULE :
1150                     $course = $this->page->course;
1151                     $cm = $this->page->cm;
1153                     if ($showcategories && !$ismycourse) {
1154                         $this->load_all_categories($course->category, $showcategories);
1155                     }
1157                     // Load the course associated with the page into the navigation
1158                     $coursenode = $this->load_course($course);
1160                     // If the course wasn't added then don't try going any further.
1161                     if (!$coursenode) {
1162                         $canviewcourseprofile = false;
1163                         break;
1164                     }
1166                     // If the user is not enrolled then we only want to show the
1167                     // course node and not populate it.
1168                     if (!can_access_course($course)) {
1169                         $coursenode->make_active();
1170                         $canviewcourseprofile = false;
1171                         break;
1172                     }
1174                     $this->add_course_essentials($coursenode, $course);
1175                     // Load the course sections into the page
1176                     $sections = $this->load_course_sections($course, $coursenode);
1177                     if ($course->id != SITEID) {
1178                         // Find the section for the $CM associated with the page and collect
1179                         // its section number.
1180                         if (isset($cm->sectionnum)) {
1181                             $cm->sectionnumber = $cm->sectionnum;
1182                         } else {
1183                             foreach ($sections as $section) {
1184                                 if ($section->id == $cm->section) {
1185                                     $cm->sectionnumber = $section->section;
1186                                     break;
1187                                 }
1188                             }
1189                         }
1191                         // Load all of the section activities for the section the cm belongs to.
1192                         if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) {
1193                             list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course);
1194                             $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray);
1195                         } else {
1196                             $activities = array();
1197                             if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) {
1198                                 // "stealth" activity from unavailable section
1199                                 $activities[$cm->id] = $activity;
1200                             }
1201                         }
1202                     } else {
1203                         $activities = array();
1204                         $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
1205                     }
1206                     if (!empty($activities[$cm->id])) {
1207                         // Finally load the cm specific navigaton information
1208                         $this->load_activity($cm, $course, $activities[$cm->id]);
1209                         // Check if we have an active ndoe
1210                         if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) {
1211                             // And make the activity node active.
1212                             $activities[$cm->id]->make_active();
1213                         }
1214                     } else {
1215                         //TODO: something is wrong, what to do? (Skodak)
1216                     }
1217                     break;
1218                 case CONTEXT_USER :
1219                     $course = $this->page->course;
1220                     if ($showcategories && !$ismycourse) {
1221                         $this->load_all_categories($course->category, $showcategories);
1222                     }
1223                     // Load the course associated with the user into the navigation
1224                     $coursenode = $this->load_course($course);
1226                     // If the course wasn't added then don't try going any further.
1227                     if (!$coursenode) {
1228                         $canviewcourseprofile = false;
1229                         break;
1230                     }
1232                     // If the user is not enrolled then we only want to show the
1233                     // course node and not populate it.
1234                     if (!can_access_course($course)) {
1235                         $coursenode->make_active();
1236                         $canviewcourseprofile = false;
1237                         break;
1238                     }
1239                     $this->add_course_essentials($coursenode, $course);
1240                     $sections = $this->load_course_sections($course, $coursenode);
1241                     break;
1242             }
1243         }
1245         $limit = 20;
1246         if (!empty($CFG->navcourselimit)) {
1247             $limit = $CFG->navcourselimit;
1248         }
1249         if ($showcategories) {
1250             $categories = $this->find_all_of_type(self::TYPE_CATEGORY);
1251             foreach ($categories as &$category) {
1252                 if ($category->children->count() >= $limit) {
1253                     $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1254                     $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1255                 }
1256             }
1257         } else if ($this->rootnodes['courses']->children->count() >= $limit) {
1258             $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING);
1259         }
1261         // Load for the current user
1262         $this->load_for_user();
1263         if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) {
1264             $this->load_for_user(null, true);
1265         }
1266         // Load each extending user into the navigation.
1267         foreach ($this->extendforuser as $user) {
1268             if ($user->id != $USER->id) {
1269                 $this->load_for_user($user);
1270             }
1271         }
1273         // Give the local plugins a chance to include some navigation if they want.
1274         foreach (get_list_of_plugins('local') as $plugin) {
1275             if (!file_exists($CFG->dirroot.'/local/'.$plugin.'/lib.php')) {
1276                 continue;
1277             }
1278             require_once($CFG->dirroot.'/local/'.$plugin.'/lib.php');
1279             $function = $plugin.'_extends_navigation';
1280             if (function_exists($function)) {
1281                 $function($this);
1282             }
1283         }
1285         // Remove any empty root nodes
1286         foreach ($this->rootnodes as $node) {
1287             // Dont remove the home node
1288             if ($node->key !== 'home' && !$node->has_children()) {
1289                 $node->remove();
1290             }
1291         }
1293         if (!$this->contains_active_node()) {
1294             $this->search_for_active_node();
1295         }
1297         // If the user is not logged in modify the navigation structure as detailed
1298         // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1299         if (!isloggedin()) {
1300             $activities = clone($this->rootnodes['site']->children);
1301             $this->rootnodes['site']->remove();
1302             $children = clone($this->children);
1303             $this->children = new navigation_node_collection();
1304             foreach ($activities as $child) {
1305                 $this->children->add($child);
1306             }
1307             foreach ($children as $child) {
1308                 $this->children->add($child);
1309             }
1310         }
1311         return true;
1312     }
1314     /**
1315      * Returns true is courses should be shown within categories on the navigation.
1316      *
1317      * @return bool
1318      */
1319     protected function show_categories() {
1320         global $CFG, $DB;
1321         if ($this->showcategories === null) {
1322             $this->showcategories = !empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1;
1323         }
1324         return $this->showcategories;
1325     }
1327     /**
1328      * Checks the course format to see whether it wants the navigation to load
1329      * additional information for the course.
1330      *
1331      * This function utilises a callback that can exist within the course format lib.php file
1332      * The callback should be a function called:
1333      * callback_{formatname}_display_content()
1334      * It doesn't get any arguments and should return true if additional content is
1335      * desired. If the callback doesn't exist we assume additional content is wanted.
1336      *
1337      * @param string $format The course format
1338      * @return bool
1339      */
1340     protected function format_display_course_content($format) {
1341         global $CFG;
1342         $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
1343         if (file_exists($formatlib)) {
1344             require_once($formatlib);
1345             $displayfunc = 'callback_'.$format.'_display_content';
1346             if (function_exists($displayfunc) && !$displayfunc()) {
1347                 return $displayfunc();
1348             }
1349         }
1350         return true;
1351     }
1353     /**
1354      * Loads of the the courses in Moodle into the navigation.
1355      *
1356      * @global moodle_database $DB
1357      * @param string|array $categoryids Either a string or array of category ids to load courses for
1358      * @return array An array of navigation_node
1359      */
1360     protected function load_all_courses($categoryids=null) {
1361         global $CFG, $DB, $USER;
1363         if ($categoryids !== null) {
1364             if (is_array($categoryids)) {
1365                 list ($categoryselect, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'catid');
1366             } else {
1367                 $categoryselect = '= :categoryid';
1368                 $params = array('categoryid', $categoryids);
1369             }
1370             $params['siteid'] = SITEID;
1371             $categoryselect = ' AND c.category '.$categoryselect;
1372         } else {
1373             $params = array('siteid' => SITEID);
1374             $categoryselect = '';
1375         }
1377         list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1378         list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses) + array(SITEID), SQL_PARAMS_NAMED, 'lcourse', false);
1379         $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category, cat.path AS categorypath $ccselect
1380                   FROM {course} c
1381                        $ccjoin
1382              LEFT JOIN {course_categories} cat ON cat.id=c.category
1383                  WHERE c.id {$courseids} {$categoryselect}
1384               ORDER BY c.sortorder ASC";
1385         $limit = 20;
1386         if (!empty($CFG->navcourselimit)) {
1387             $limit = $CFG->navcourselimit;
1388         }
1389         $courses = $DB->get_records_sql($sql, $params + $courseparams, 0, $limit);
1391         $coursenodes = array();
1392         foreach ($courses as $course) {
1393             context_instance_preload($course);
1394             $coursenodes[$course->id] = $this->add_course($course);
1395         }
1396         return $coursenodes;
1397     }
1399     /**
1400      * Loads all categories (top level or if an id is specified for that category)
1401      *
1402      * @param int $categoryid The category id to load or null/0 to load all base level categories
1403      * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1404      *        as the requested category and any parent categories.
1405      * @return void
1406      */
1407     protected function load_all_categories($categoryid = null, $showbasecategories = false) {
1408         global $DB;
1410         // Check if this category has already been loaded
1411         if ($categoryid !== null && array_key_exists($categoryid, $this->addedcategories) && $this->addedcategories[$categoryid]->children->count() > 0) {
1412             return $this->addedcategories[$categoryid];
1413         }
1415         $coursestoload = array();
1416         if (empty($categoryid)) { // can be 0
1417             // We are going to load all of the first level categories (categories without parents)
1418             $categories = $DB->get_records('course_categories', array('parent'=>'0'), 'sortorder ASC, id ASC');
1419         } else if (array_key_exists($categoryid, $this->addedcategories)) {
1420             // The category itself has been loaded already so we just need to ensure its subcategories
1421             // have been loaded
1422             list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1423             if ($showbasecategories) {
1424                 // We need to include categories with parent = 0 as well
1425                 $sql = "SELECT *
1426                           FROM {course_categories} cc
1427                          WHERE (parent = :categoryid OR parent = 0) AND
1428                                parent {$sql}
1429                       ORDER BY depth DESC, sortorder ASC, id ASC";
1430             } else {
1431                 $sql = "SELECT *
1432                           FROM {course_categories} cc
1433                          WHERE parent = :categoryid AND
1434                                parent {$sql}
1435                       ORDER BY depth DESC, sortorder ASC, id ASC";
1436             }
1437             $params['categoryid'] = $categoryid;
1438             $categories = $DB->get_records_sql($sql, $params);
1439             if (count($categories) == 0) {
1440                 // There are no further categories that require loading.
1441                 return;
1442             }
1443         } else {
1444             // This category hasn't been loaded yet so we need to fetch it, work out its category path
1445             // and load this category plus all its parents and subcategories
1446             $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1447             $coursestoload = explode('/', trim($category->path, '/'));
1448             list($select, $params) = $DB->get_in_or_equal($coursestoload);
1449             $select = 'id '.$select.' OR parent '.$select;
1450             if ($showbasecategories) {
1451                 $select .= ' OR parent = 0';
1452             }
1453             $params = array_merge($params, $params);
1454             $categories = $DB->get_records_select('course_categories', $select, $params, 'sortorder');
1455         }
1457         // Now we have an array of categories we need to add them to the navigation.
1458         while (!empty($categories)) {
1459             $category = reset($categories);
1460             if (array_key_exists($category->id, $this->addedcategories)) {
1461                 // Do nothing
1462             } else if ($category->parent == '0') {
1463                 $this->add_category($category, $this->rootnodes['courses']);
1464             } else if (array_key_exists($category->parent, $this->addedcategories)) {
1465                 $this->add_category($category, $this->addedcategories[$category->parent]);
1466             } else {
1467                 // This category isn't in the navigation and niether is it's parent (yet).
1468                 // We need to go through the category path and add all of its components in order.
1469                 $path = explode('/', trim($category->path, '/'));
1470                 foreach ($path as $catid) {
1471                     if (!array_key_exists($catid, $this->addedcategories)) {
1472                         // This category isn't in the navigation yet so add it.
1473                         $subcategory = $categories[$catid];
1474                         if ($subcategory->parent == '0') {
1475                             // Yay we have a root category - this likely means we will now be able
1476                             // to add categories without problems.
1477                             $this->add_category($subcategory, $this->rootnodes['courses']);
1478                         } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1479                             // The parent is in the category (as we'd expect) so add it now.
1480                             $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1481                             // Remove the category from the categories array.
1482                             unset($categories[$catid]);
1483                         } else {
1484                             // We should never ever arrive here - if we have then there is a bigger
1485                             // problem at hand.
1486                             throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1487                         }
1488                     }
1489                 }
1490             }
1491             // Remove the category from the categories array now that we know it has been added.
1492             unset($categories[$category->id]);
1493         }
1494         // Check if there are any categories to load.
1495         if (count($coursestoload) > 0) {
1496             $this->load_all_courses($coursestoload);
1497         }
1498     }
1500     /**
1501      * Adds a structured category to the navigation in the correct order/place
1502      *
1503      * @param stdClass $category
1504      * @param navigation_node $parent
1505      */
1506     protected function add_category(stdClass $category, navigation_node $parent) {
1507         if (array_key_exists($category->id, $this->addedcategories)) {
1508             return;
1509         }
1510         $url = new moodle_url('/course/category.php', array('id' => $category->id));
1511         $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
1512         $categoryname = format_string($category->name, true, array('context' => $context));
1513         $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id);
1514         if (empty($category->visible)) {
1515             if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1516                 $categorynode->hidden = true;
1517             } else {
1518                 $categorynode->display = false;
1519             }
1520         }
1521         $this->addedcategories[$category->id] = &$categorynode;
1522     }
1524     /**
1525      * Loads the given course into the navigation
1526      *
1527      * @param stdClass $course
1528      * @return navigation_node
1529      */
1530     protected function load_course(stdClass $course) {
1531         if ($course->id == SITEID) {
1532             return $this->rootnodes['site'];
1533         } else if (array_key_exists($course->id, $this->addedcourses)) {
1534             return $this->addedcourses[$course->id];
1535         } else {
1536             return $this->add_course($course);
1537         }
1538     }
1540     /**
1541      * Loads all of the courses section into the navigation.
1542      *
1543      * This function utilisies a callback that can be implemented within the course
1544      * formats lib.php file to customise the navigation that is generated at this
1545      * point for the course.
1546      *
1547      * By default (if not defined) the method {@see load_generic_course_sections} is
1548      * called instead.
1549      *
1550      * @param stdClass $course Database record for the course
1551      * @param navigation_node $coursenode The course node within the navigation
1552      * @return array Array of navigation nodes for the section with key = section id
1553      */
1554     protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1555         global $CFG;
1556         $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1557         $structurefunc = 'callback_'.$course->format.'_load_content';
1558         if (function_exists($structurefunc)) {
1559             return $structurefunc($this, $course, $coursenode);
1560         } else if (file_exists($structurefile)) {
1561             require_once $structurefile;
1562             if (function_exists($structurefunc)) {
1563                 return $structurefunc($this, $course, $coursenode);
1564             } else {
1565                 return $this->load_generic_course_sections($course, $coursenode);
1566             }
1567         } else {
1568             return $this->load_generic_course_sections($course, $coursenode);
1569         }
1570     }
1572     /**
1573      * Generates an array of sections and an array of activities for the given course.
1574      *
1575      * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1576      *
1577      * @param stdClass $course
1578      * @return array Array($sections, $activities)
1579      */
1580     protected function generate_sections_and_activities(stdClass $course) {
1581         global $CFG;
1582         require_once($CFG->dirroot.'/course/lib.php');
1584         if (!$this->cache->cached('course_sections_'.$course->id) || !$this->cache->cached('course_activites_'.$course->id)) {
1585             $modinfo = get_fast_modinfo($course);
1586             $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1588             $activities = array();
1590             foreach ($sections as $key => $section) {
1591                 $sections[$key]->hasactivites = false;
1592                 if (!array_key_exists($section->section, $modinfo->sections)) {
1593                     continue;
1594                 }
1595                 foreach ($modinfo->sections[$section->section] as $cmid) {
1596                     $cm = $modinfo->cms[$cmid];
1597                     if (!$cm->uservisible) {
1598                         continue;
1599                     }
1600                     $activity = new stdClass;
1601                     $activity->section = $section->section;
1602                     $activity->name = $cm->name;
1603                     $activity->icon = $cm->icon;
1604                     $activity->iconcomponent = $cm->iconcomponent;
1605                     $activity->id = $cm->id;
1606                     $activity->hidden = (!$cm->visible);
1607                     $activity->modname = $cm->modname;
1608                     $activity->nodetype = navigation_node::NODETYPE_LEAF;
1609                     $activity->onclick = $cm->get_on_click();
1610                     $url = $cm->get_url();
1611                     if (!$url) {
1612                         $activity->url = null;
1613                         $activity->display = false;
1614                     } else {
1615                         $activity->url = $cm->get_url()->out();
1616                         $activity->display = true;
1617                         if (self::module_extends_navigation($cm->modname)) {
1618                             $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1619                         }
1620                     }
1621                     $activities[$cmid] = $activity;
1622                     $sections[$key]->hasactivites = true;
1623                 }
1624             }
1625             $this->cache->set('course_sections_'.$course->id, $sections);
1626             $this->cache->set('course_activites_'.$course->id, $activities);
1627         } else {
1628             $sections = $this->cache->{'course_sections_'.$course->id};
1629             $activities = $this->cache->{'course_activites_'.$course->id};
1630         }
1631         return array($sections, $activities);
1632     }
1634     /**
1635      * Generically loads the course sections into the course's navigation.
1636      *
1637      * @param stdClass $course
1638      * @param navigation_node $coursenode
1639      * @param string $courseformat The course format
1640      * @return array An array of course section nodes
1641      */
1642     public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat='unknown') {
1643         global $CFG, $DB, $USER;
1644         require_once($CFG->dirroot.'/course/lib.php');
1646         list($sections, $activities) = $this->generate_sections_and_activities($course);
1648         $namingfunction = 'callback_'.$courseformat.'_get_section_name';
1649         $namingfunctionexists = (function_exists($namingfunction));
1651         $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1653         $urlfunction = 'callback_'.$courseformat.'_get_section_url';
1654         if (empty($CFG->navlinkcoursesections) || !function_exists($urlfunction)) {
1655             $urlfunction = null;
1656         }
1658         $keyfunction = 'callback_'.$courseformat.'_request_key';
1659         $key = course_get_display($course->id);
1660         if (defined('AJAX_SCRIPT') && AJAX_SCRIPT == '0' && function_exists($keyfunction) && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1661             $key = optional_param($keyfunction(), $key, PARAM_INT);
1662         }
1664         $navigationsections = array();
1665         foreach ($sections as $sectionid => $section) {
1666             $section = clone($section);
1667             if ($course->id == SITEID) {
1668                 $this->load_section_activities($coursenode, $section->section, $activities);
1669             } else {
1670                 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !$section->hasactivites)) {
1671                     continue;
1672                 }
1673                 if ($namingfunctionexists) {
1674                     $sectionname = $namingfunction($course, $section, $sections);
1675                 } else {
1676                     $sectionname = get_string('section').' '.$section->section;
1677                 }
1679                 $url = null;
1680                 if (!empty($urlfunction)) {
1681                     $url = $urlfunction($course->id, $section->section);
1682                 }
1683                 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1684                 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1685                 $sectionnode->hidden = (!$section->visible);
1686                 if ($key != '0' && $section->section != '0' && $section->section == $key && $this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites) {
1687                     $sectionnode->make_active();
1688                     $this->load_section_activities($sectionnode, $section->section, $activities);
1689                 }
1690                 $section->sectionnode = $sectionnode;
1691                 $navigationsections[$sectionid] = $section;
1692             }
1693         }
1694         return $navigationsections;
1695     }
1696     /**
1697      * Loads all of the activities for a section into the navigation structure.
1698      *
1699      * @todo 2.2 - $activities should always be an array and we should no longer check for it being a
1700      *             course_modinfo object
1701      *
1702      * @param navigation_node $sectionnode
1703      * @param int $sectionnumber
1704      * @param course_modinfo $modinfo Object returned from {@see get_fast_modinfo()}
1705      * @return array Array of activity nodes
1706      */
1707     protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $activities) {
1708         // A static counter for JS function naming
1709         static $legacyonclickcounter = 0;
1711         if ($activities instanceof course_modinfo) {
1712             debugging('global_navigation::load_section_activities argument 3 should now recieve an array of activites. See that method for an example.', DEBUG_DEVELOPER);
1713             list($sections, $activities) = $this->generate_sections_and_activities($activities->course);
1714         }
1716         $activitynodes = array();
1717         foreach ($activities as $activity) {
1718             if ($activity->section != $sectionnumber) {
1719                 continue;
1720             }
1721             if ($activity->icon) {
1722                 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1723             } else {
1724                 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1725             }
1727             // Prepare the default name and url for the node
1728             $activityname = format_string($activity->name, true, array('context' => get_context_instance(CONTEXT_MODULE, $activity->id)));
1729             $action = new moodle_url($activity->url);
1731             // Check if the onclick property is set (puke!)
1732             if (!empty($activity->onclick)) {
1733                 // Increment the counter so that we have a unique number.
1734                 $legacyonclickcounter++;
1735                 // Generate the function name we will use
1736                 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1737                 $propogrationhandler = '';
1738                 // Check if we need to cancel propogation. Remember inline onclick
1739                 // events would return false if they wanted to prevent propogation and the
1740                 // default action.
1741                 if (strpos($activity->onclick, 'return false')) {
1742                     $propogrationhandler = 'e.halt();';
1743                 }
1744                 // Decode the onclick - it has already been encoded for display (puke)
1745                 $onclick = htmlspecialchars_decode($activity->onclick);
1746                 // Build the JS function the click event will call
1747                 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1748                 $this->page->requires->js_init_code($jscode);
1749                 // Override the default url with the new action link
1750                 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1751             }
1753             $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1754             $activitynode->title(get_string('modulename', $activity->modname));
1755             $activitynode->hidden = $activity->hidden;
1756             $activitynode->display = $activity->display;
1757             $activitynode->nodetype = $activity->nodetype;
1758             $activitynodes[$activity->id] = $activitynode;
1759         }
1761         return $activitynodes;
1762     }
1763     /**
1764      * Loads a stealth module from unavailable section
1765      * @param navigation_node $coursenode
1766      * @param stdClass $modinfo
1767      * @return navigation_node or null if not accessible
1768      */
1769     protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1770         if (empty($modinfo->cms[$this->page->cm->id])) {
1771             return null;
1772         }
1773         $cm = $modinfo->cms[$this->page->cm->id];
1774         if (!$cm->uservisible) {
1775             return null;
1776         }
1777         if ($cm->icon) {
1778             $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1779         } else {
1780             $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1781         }
1782         $url = $cm->get_url();
1783         $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1784         $activitynode->title(get_string('modulename', $cm->modname));
1785         $activitynode->hidden = (!$cm->visible);
1786         if (!$url) {
1787             // Don't show activities that don't have links!
1788             $activitynode->display = false;
1789         } else if (self::module_extends_navigation($cm->modname)) {
1790             $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1791         }
1792         return $activitynode;
1793     }
1794     /**
1795      * Loads the navigation structure for the given activity into the activities node.
1796      *
1797      * This method utilises a callback within the modules lib.php file to load the
1798      * content specific to activity given.
1799      *
1800      * The callback is a method: {modulename}_extend_navigation()
1801      * Examples:
1802      *  * {@see forum_extend_navigation()}
1803      *  * {@see workshop_extend_navigation()}
1804      *
1805      * @param cm_info|stdClass $cm
1806      * @param stdClass $course
1807      * @param navigation_node $activity
1808      * @return bool
1809      */
1810     protected function load_activity($cm, stdClass $course, navigation_node $activity) {
1811         global $CFG, $DB;
1813         // make sure we have a $cm from get_fast_modinfo as this contains activity access details
1814         if (!($cm instanceof cm_info)) {
1815             $modinfo = get_fast_modinfo($course);
1816             $cm = $modinfo->get_cm($cm->id);
1817         }
1819         $activity->make_active();
1820         $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1821         $function = $cm->modname.'_extend_navigation';
1823         if (file_exists($file)) {
1824             require_once($file);
1825             if (function_exists($function)) {
1826                 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1827                 $function($activity, $course, $activtyrecord, $cm);
1828                 return true;
1829             }
1830         }
1831         $activity->nodetype = navigation_node::NODETYPE_LEAF;
1832         return false;
1833     }
1834     /**
1835      * Loads user specific information into the navigation in the appropriate place.
1836      *
1837      * If no user is provided the current user is assumed.
1838      *
1839      * @param stdClass $user
1840      * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
1841      * @return bool
1842      */
1843     protected function load_for_user($user=null, $forceforcontext=false) {
1844         global $DB, $CFG, $USER;
1846         if ($user === null) {
1847             // We can't require login here but if the user isn't logged in we don't
1848             // want to show anything
1849             if (!isloggedin() || isguestuser()) {
1850                 return false;
1851             }
1852             $user = $USER;
1853         } else if (!is_object($user)) {
1854             // If the user is not an object then get them from the database
1855             list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
1856             $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
1857             $user = $DB->get_record_sql($sql, array('userid' => (int)$user), MUST_EXIST);
1858             context_instance_preload($user);
1859         }
1861         $iscurrentuser = ($user->id == $USER->id);
1863         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1865         // Get the course set against the page, by default this will be the site
1866         $course = $this->page->course;
1867         $baseargs = array('id'=>$user->id);
1868         if ($course->id != SITEID && (!$iscurrentuser || $forceforcontext)) {
1869             $coursenode = $this->load_course($course);
1870             $baseargs['course'] = $course->id;
1871             $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1872             $issitecourse = false;
1873         } else {
1874             // Load all categories and get the context for the system
1875             $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1876             $issitecourse = true;
1877         }
1879         // Create a node to add user information under.
1880         if ($iscurrentuser && !$forceforcontext) {
1881             // If it's the current user the information will go under the profile root node
1882             $usernode = $this->rootnodes['myprofile'];
1883             $course = get_site();
1884             $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1885             $issitecourse = true;
1886         } else {
1887             if (!$issitecourse) {
1888                 // Not the current user so add it to the participants node for the current course
1889                 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1890                 $userviewurl = new moodle_url('/user/view.php', $baseargs);
1891             } else {
1892                 // This is the site so add a users node to the root branch
1893                 $usersnode = $this->rootnodes['users'];
1894                 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
1895                     $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1896                 }
1897                 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
1898             }
1899             if (!$usersnode) {
1900                 // We should NEVER get here, if the course hasn't been populated
1901                 // with a participants node then the navigaiton either wasn't generated
1902                 // for it (you are missing a require_login or set_context call) or
1903                 // you don't have access.... in the interests of no leaking informatin
1904                 // we simply quit...
1905                 return false;
1906             }
1907             // Add a branch for the current user
1908             $usernode = $usersnode->add(fullname($user, true), $userviewurl, self::TYPE_USER, null, $user->id);
1910             if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1911                 $usernode->make_active();
1912             }
1913         }
1915         // If the user is the current user or has permission to view the details of the requested
1916         // user than add a view profile link.
1917         if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1918             if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
1919                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
1920             } else {
1921                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1922             }
1923         }
1925         if (!empty($CFG->navadduserpostslinks)) {
1926             // Add nodes for forum posts and discussions if the user can view either or both
1927             // There are no capability checks here as the content of the page is based
1928             // purely on the forums the current user has access too.
1929             $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1930             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1931             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1932         }
1934         // Add blog nodes
1935         if (!empty($CFG->bloglevel)) {
1936             if (!$this->cache->cached('userblogoptions'.$user->id)) {
1937                 require_once($CFG->dirroot.'/blog/lib.php');
1938                 // Get all options for the user
1939                 $options = blog_get_options_for_user($user);
1940                 $this->cache->set('userblogoptions'.$user->id, $options);
1941             } else {
1942                 $options = $this->cache->{'userblogoptions'.$user->id};
1943             }
1945             if (count($options) > 0) {
1946                 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
1947                 foreach ($options as $type => $option) {
1948                     if ($type == "rss") {
1949                         $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
1950                     } else {
1951                         $blogs->add($option['string'], $option['link']);
1952                     }
1953                 }
1954             }
1955         }
1957         if (!empty($CFG->messaging)) {
1958             $messageargs = null;
1959             if ($USER->id!=$user->id) {
1960                 $messageargs = array('id'=>$user->id);
1961             }
1962             $url = new moodle_url('/message/index.php',$messageargs);
1963             $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
1964         }
1966         $context = get_context_instance(CONTEXT_USER, $USER->id);
1967         if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) {
1968             $url = new moodle_url('/user/files.php');
1969             $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
1970         }
1972         // Add a node to view the users notes if permitted
1973         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1974             $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1975             if ($coursecontext->instanceid) {
1976                 $url->param('course', $coursecontext->instanceid);
1977             }
1978             $usernode->add(get_string('notes', 'notes'), $url);
1979         }
1981         // Add reports node
1982         $reporttab = $usernode->add(get_string('activityreports'));
1983         $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
1984         foreach ($reports as $reportfunction) {
1985             $reportfunction($reporttab, $user, $course);
1986         }
1987         $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1988         if ($anyreport || ($course->showreports && $iscurrentuser && $forceforcontext)) {
1989             // Add grade hardcoded grade report if necessary
1990             $gradeaccess = false;
1991             if (has_capability('moodle/grade:viewall', $coursecontext)) {
1992                 //ok - can view all course grades
1993                 $gradeaccess = true;
1994             } else if ($course->showgrades) {
1995                 if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1996                     //ok - can view own grades
1997                     $gradeaccess = true;
1998                 } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1999                     // ok - can view grades of this user - parent most probably
2000                     $gradeaccess = true;
2001                 } else if ($anyreport) {
2002                     // ok - can view grades of this user - parent most probably
2003                     $gradeaccess = true;
2004                 }
2005             }
2006             if ($gradeaccess) {
2007                 $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id)));
2008             }
2009         }
2010         // Check the number of nodes in the report node... if there are none remove the node
2011         $reporttab->trim_if_empty();
2013         // If the user is the current user add the repositories for the current user
2014         $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2015         if ($iscurrentuser) {
2016             if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2017                 require_once($CFG->dirroot . '/repository/lib.php');
2018                 $editabletypes = repository::get_editable_types($usercontext);
2019                 $haseditabletypes = !empty($editabletypes);
2020                 unset($editabletypes);
2021                 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2022             } else {
2023                 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2024             }
2025             if ($haseditabletypes) {
2026                 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2027             }
2028         } else if ($course->id == SITEID && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2030             // Add view grade report is permitted
2031             $reports = get_plugin_list('gradereport');
2032             arsort($reports); // user is last, we want to test it first
2034             $userscourses = enrol_get_users_courses($user->id);
2035             $userscoursesnode = $usernode->add(get_string('courses'));
2037             foreach ($userscourses as $usercourse) {
2038                 $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id);
2039                 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2040                 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2042                 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2043                 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2044                     foreach ($reports as $plugin => $plugindir) {
2045                         if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2046                             //stop when the first visible plugin is found
2047                             $gradeavailable = true;
2048                             break;
2049                         }
2050                     }
2051                 }
2053                 if ($gradeavailable) {
2054                     $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2055                     $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2056                 }
2058                 // Add a node to view the users notes if permitted
2059                 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2060                     $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2061                     $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2062                 }
2064                 if (can_access_course($usercourse, $user->id)) {
2065                     $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', ''));
2066                 }
2068                 $reporttab = $usercoursenode->add(get_string('activityreports'));
2070                 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2071                 foreach ($reports as $reportfunction) {
2072                     $reportfunction($reporttab, $user, $usercourse);
2073                 }
2075                 $reporttab->trim_if_empty();
2076             }
2077         }
2078         return true;
2079     }
2081     /**
2082      * This method simply checks to see if a given module can extend the navigation.
2083      *
2084      * TODO: A shared caching solution should be used to save details on what extends navigation
2085      *
2086      * @param string $modname
2087      * @return bool
2088      */
2089     protected static function module_extends_navigation($modname) {
2090         global $CFG;
2091         static $extendingmodules = array();
2092         if (!array_key_exists($modname, $extendingmodules)) {
2093             $extendingmodules[$modname] = false;
2094             $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2095             if (file_exists($file)) {
2096                 $function = $modname.'_extend_navigation';
2097                 require_once($file);
2098                 $extendingmodules[$modname] = (function_exists($function));
2099             }
2100         }
2101         return $extendingmodules[$modname];
2102     }
2103     /**
2104      * Extends the navigation for the given user.
2105      *
2106      * @param stdClass $user A user from the database
2107      */
2108     public function extend_for_user($user) {
2109         $this->extendforuser[] = $user;
2110     }
2112     /**
2113      * Returns all of the users the navigation is being extended for
2114      *
2115      * @return array
2116      */
2117     public function get_extending_users() {
2118         return $this->extendforuser;
2119     }
2120     /**
2121      * Adds the given course to the navigation structure.
2122      *
2123      * @param stdClass $course
2124      * @return navigation_node
2125      */
2126     public function add_course(stdClass $course, $forcegeneric = false, $ismycourse = false) {
2127         global $CFG;
2129         // We found the course... we can return it now :)
2130         if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2131             return $this->addedcourses[$course->id];
2132         }
2134         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2136         if ($course->id != SITEID && !$course->visible) {
2137             if (is_role_switched($course->id)) {
2138                 // user has to be able to access course in order to switch, let's skip the visibility test here
2139             } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2140                 return false;
2141             }
2142         }
2144         $issite = ($course->id == SITEID);
2145         $ismycourse = ($ismycourse && !$forcegeneric);
2146         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2148         if ($issite) {
2149             $parent = $this;
2150             $url = null;
2151             if (empty($CFG->usesitenameforsitepages)) {
2152                 $shortname = get_string('sitepages');
2153             }
2154         } else if ($ismycourse) {
2155             $parent = $this->rootnodes['mycourses'];
2156             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2157         } else {
2158             $parent = $this->rootnodes['courses'];
2159             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2160         }
2162         if (!$ismycourse && !$issite && !empty($course->category)) {
2163             if ($this->show_categories()) {
2164                 // We need to load the category structure for this course
2165                 $this->load_all_categories($course->category);
2166             }
2167             if (array_key_exists($course->category, $this->addedcategories)) {
2168                 $parent = $this->addedcategories[$course->category];
2169                 // This could lead to the course being created so we should check whether it is the case again
2170                 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2171                     return $this->addedcourses[$course->id];
2172                 }
2173             }
2174         }
2176         $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id);
2177         $coursenode->nodetype = self::NODETYPE_BRANCH;
2178         $coursenode->hidden = (!$course->visible);
2179         $coursenode->title(format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
2180         if (!$forcegeneric) {
2181             $this->addedcourses[$course->id] = &$coursenode;
2182         }
2183         if ($ismycourse && !empty($CFG->navshowallcourses)) {
2184             // We need to add this course to the general courses node as well as the
2185             // my courses node, rerun the function with the kill param
2186             $genericcourse = $this->add_course($course, true);
2187             if ($genericcourse->isactive) {
2188                 $genericcourse->make_inactive();
2189                 $genericcourse->collapse = true;
2190                 if ($genericcourse->parent && $genericcourse->parent->type == self::TYPE_CATEGORY) {
2191                     $parent = $genericcourse->parent;
2192                     while ($parent && $parent->type == self::TYPE_CATEGORY) {
2193                         $parent->collapse = true;
2194                         $parent = $parent->parent;
2195                     }
2196                 }
2197             }
2198         }
2200         return $coursenode;
2201     }
2202     /**
2203      * Adds essential course nodes to the navigation for the given course.
2204      *
2205      * This method adds nodes such as reports, blogs and participants
2206      *
2207      * @param navigation_node $coursenode
2208      * @param stdClass $course
2209      * @return bool
2210      */
2211     public function add_course_essentials($coursenode, stdClass $course) {
2212         global $CFG;
2214         if ($course->id == SITEID) {
2215             return $this->add_front_page_course_essentials($coursenode, $course);
2216         }
2218         if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2219             return true;
2220         }
2222         //Participants
2223         if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2224             $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2225             $currentgroup = groups_get_course_group($course, true);
2226             if ($course->id == SITEID) {
2227                 $filterselect = '';
2228             } else if ($course->id && !$currentgroup) {
2229                 $filterselect = $course->id;
2230             } else {
2231                 $filterselect = $currentgroup;
2232             }
2233             $filterselect = clean_param($filterselect, PARAM_INT);
2234             if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2235                and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2236                 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2237                 $participants->add(get_string('blogs','blog'), $blogsurls->out());
2238             }
2239             if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2240                 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2241             }
2242         } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2243             $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2244         }
2246         // View course reports
2247         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2248             $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2249             $coursereports = get_plugin_list('coursereport'); // deprecated
2250             foreach ($coursereports as $report=>$dir) {
2251                 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2252                 if (file_exists($libfile)) {
2253                     require_once($libfile);
2254                     $reportfunction = $report.'_report_extend_navigation';
2255                     if (function_exists($report.'_report_extend_navigation')) {
2256                         $reportfunction($reportnav, $course, $this->page->context);
2257                     }
2258                 }
2259             }
2261             $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2262             foreach ($reports as $reportfunction) {
2263                 $reportfunction($reportnav, $course, $this->page->context);
2264             }
2265         }
2266         return true;
2267     }
2268     /**
2269      * This generates the the structure of the course that won't be generated when
2270      * the modules and sections are added.
2271      *
2272      * Things such as the reports branch, the participants branch, blogs... get
2273      * added to the course node by this method.
2274      *
2275      * @param navigation_node $coursenode
2276      * @param stdClass $course
2277      * @return bool True for successfull generation
2278      */
2279     public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2280         global $CFG;
2282         if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2283             return true;
2284         }
2286         // Hidden node that we use to determine if the front page navigation is loaded.
2287         // This required as there are not other guaranteed nodes that may be loaded.
2288         $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2290         //Participants
2291         if (has_capability('moodle/course:viewparticipants',  get_system_context())) {
2292             $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2293         }
2295         $filterselect = 0;
2297         // Blogs
2298         if (!empty($CFG->bloglevel)
2299           and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2300           and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
2301             $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2302             $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
2303         }
2305         // Notes
2306         if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2307             $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2308         }
2310         // Tags
2311         if (!empty($CFG->usetags) && isloggedin()) {
2312             $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2313         }
2315         if (isloggedin()) {
2316             // Calendar
2317             $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2318             $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2319         }
2321         // View course reports
2322         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2323             $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2324             $coursereports = get_plugin_list('coursereport'); // deprecated
2325             foreach ($coursereports as $report=>$dir) {
2326                 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2327                 if (file_exists($libfile)) {
2328                     require_once($libfile);
2329                     $reportfunction = $report.'_report_extend_navigation';
2330                     if (function_exists($report.'_report_extend_navigation')) {
2331                         $reportfunction($reportnav, $course, $this->page->context);
2332                     }
2333                 }
2334             }
2336             $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2337             foreach ($reports as $reportfunction) {
2338                 $reportfunction($reportnav, $course, $this->page->context);
2339             }
2340         }
2341         return true;
2342     }
2344     /**
2345      * Clears the navigation cache
2346      */
2347     public function clear_cache() {
2348         $this->cache->clear();
2349     }
2351     /**
2352      * Sets an expansion limit for the navigation
2353      *
2354      * The expansion limit is used to prevent the display of content that has a type
2355      * greater than the provided $type.
2356      *
2357      * Can be used to ensure things such as activities or activity content don't get
2358      * shown on the navigation.
2359      * They are still generated in order to ensure the navbar still makes sense.
2360      *
2361      * @param int $type One of navigation_node::TYPE_*
2362      * @return <type>
2363      */
2364     public function set_expansion_limit($type) {
2365         $nodes = $this->find_all_of_type($type);
2366         foreach ($nodes as &$node) {
2367             // We need to generate the full site node
2368             if ($type == self::TYPE_COURSE && $node->key == SITEID) {
2369                 continue;
2370             }
2371             foreach ($node->children as &$child) {
2372                 // We still want to show course reports and participants containers
2373                 // or there will be navigation missing.
2374                 if ($type == self::TYPE_COURSE && $child->type === self::TYPE_CONTAINER) {
2375                     continue;
2376                 }
2377                 $child->display = false;
2378             }
2379         }
2380         return true;
2381     }
2382     /**
2383      * Attempts to get the navigation with the given key from this nodes children.
2384      *
2385      * This function only looks at this nodes children, it does NOT look recursivily.
2386      * If the node can't be found then false is returned.
2387      *
2388      * If you need to search recursivily then use the {@see find()} method.
2389      *
2390      * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2391      * may be of more use to you.
2392      *
2393      * @param string|int $key The key of the node you wish to receive.
2394      * @param int $type One of navigation_node::TYPE_*
2395      * @return navigation_node|false
2396      */
2397     public function get($key, $type = null) {
2398         if (!$this->initialised) {
2399             $this->initialise();
2400         }
2401         return parent::get($key, $type);
2402     }
2404     /**
2405      * Searches this nodes children and thier children to find a navigation node
2406      * with the matching key and type.
2407      *
2408      * This method is recursive and searches children so until either a node is
2409      * found of there are no more nodes to search.
2410      *
2411      * If you know that the node being searched for is a child of this node
2412      * then use the {@see get()} method instead.
2413      *
2414      * Note: If you are trying to set the active node {@see navigation_node::override_active_url()}
2415      * may be of more use to you.
2416      *
2417      * @param string|int $key The key of the node you wish to receive.
2418      * @param int $type One of navigation_node::TYPE_*
2419      * @return navigation_node|false
2420      */
2421     public function find($key, $type) {
2422         if (!$this->initialised) {
2423             $this->initialise();
2424         }
2425         return parent::find($key, $type);
2426     }
2429 /**
2430  * The limited global navigation class used for the AJAX extension of the global
2431  * navigation class.
2432  *
2433  * The primary methods that are used in the global navigation class have been overriden
2434  * to ensure that only the relevant branch is generated at the root of the tree.
2435  * This can be done because AJAX is only used when the backwards structure for the
2436  * requested branch exists.
2437  * This has been done only because it shortens the amounts of information that is generated
2438  * which of course will speed up the response time.. because no one likes laggy AJAX.
2439  *
2440  * @package moodlecore
2441  * @subpackage navigation
2442  * @copyright 2009 Sam Hemelryk
2443  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2444  */
2445 class global_navigation_for_ajax extends global_navigation {
2447     protected $branchtype;
2448     protected $instanceid;
2450     /** @var array */
2451     protected $expandable = array();
2453     /**
2454      * Constructs the navigation for use in AJAX request
2455      */
2456     public function __construct($page, $branchtype, $id) {
2457         $this->page = $page;
2458         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2459         $this->children = new navigation_node_collection();
2460         $this->branchtype = $branchtype;
2461         $this->instanceid = $id;
2462         $this->initialise();
2463     }
2464     /**
2465      * Initialise the navigation given the type and id for the branch to expand.
2466      *
2467      * @return array The expandable nodes
2468      */
2469     public function initialise() {
2470         global $CFG, $DB, $SITE;
2472         if ($this->initialised || during_initial_install()) {
2473             return $this->expandable;
2474         }
2475         $this->initialised = true;
2477         $this->rootnodes = array();
2478         $this->rootnodes['site']    = $this->add_course($SITE);
2479         $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2481         // Branchtype will be one of navigation_node::TYPE_*
2482         switch ($this->branchtype) {
2483             case self::TYPE_CATEGORY :
2484                 $this->load_all_categories($this->instanceid);
2485                 $limit = 20;
2486                 if (!empty($CFG->navcourselimit)) {
2487                     $limit = (int)$CFG->navcourselimit;
2488                 }
2489                 $courses = $DB->get_records('course', array('category' => $this->instanceid), 'sortorder','*', 0, $limit);
2490                 foreach ($courses as $course) {
2491                     $this->add_course($course);
2492                 }
2493                 break;
2494             case self::TYPE_COURSE :
2495                 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2496                 require_course_login($course);
2497                 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2498                 $coursenode = $this->add_course($course);
2499                 $this->add_course_essentials($coursenode, $course);
2500                 if ($this->format_display_course_content($course->format)) {
2501                     $this->load_course_sections($course, $coursenode);
2502                 }
2503                 break;
2504             case self::TYPE_SECTION :
2505                 $sql = 'SELECT c.*, cs.section AS sectionnumber
2506                         FROM {course} c
2507                         LEFT JOIN {course_sections} cs ON cs.course = c.id
2508                         WHERE cs.id = ?';
2509                 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2510                 require_course_login($course);
2511                 $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
2512                 $coursenode = $this->add_course($course);
2513                 $this->add_course_essentials($coursenode, $course);
2514                 $sections = $this->load_course_sections($course, $coursenode);
2515                 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2516                 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
2517                 break;
2518             case self::TYPE_ACTIVITY :
2519                 $sql = "SELECT c.*
2520                           FROM {course} c
2521                           JOIN {course_modules} cm ON cm.course = c.id
2522                          WHERE cm.id = :cmid";
2523                 $params = array('cmid' => $this->instanceid);
2524                 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2525                 $modinfo = get_fast_modinfo($course);
2526                 $cm = $modinfo->get_cm($this->instanceid);
2527                 require_course_login($course, true, $cm);
2528                 $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
2529                 $coursenode = $this->load_course($course);
2530                 if ($course->id == SITEID) {
2531                     $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2532                 } else {
2533                     $sections   = $this->load_course_sections($course, $coursenode);
2534                     list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
2535                     $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
2536                     $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
2537                 }
2538                 break;
2539             default:
2540                 throw new Exception('Unknown type');
2541                 return $this->expandable;
2542         }
2544         if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != SITEID) {
2545             $this->load_for_user(null, true);
2546         }
2548         $this->find_expandable($this->expandable);
2549         return $this->expandable;
2550     }
2552     /**
2553      * Returns an array of expandable nodes
2554      * @return array
2555      */
2556     public function get_expandable() {
2557         return $this->expandable;
2558     }
2561 /**
2562  * Navbar class
2563  *
2564  * This class is used to manage the navbar, which is initialised from the navigation
2565  * object held by PAGE
2566  *
2567  * @package moodlecore
2568  * @subpackage navigation
2569  * @copyright 2009 Sam Hemelryk
2570  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2571  */
2572 class navbar extends navigation_node {
2573     /** @var bool */
2574     protected $initialised = false;
2575     /** @var mixed */
2576     protected $keys = array();
2577     /** @var null|string */
2578     protected $content = null;
2579     /** @var moodle_page object */
2580     protected $page;
2581     /** @var bool */
2582     protected $ignoreactive = false;
2583     /** @var bool */
2584     protected $duringinstall = false;
2585     /** @var bool */
2586     protected $hasitems = false;
2587     /** @var array */
2588     protected $items;
2589     /** @var array */
2590     public $children = array();
2591     /** @var bool */
2592     public $includesettingsbase = false;
2593     /**
2594      * The almighty constructor
2595      *
2596      * @param moodle_page $page
2597      */
2598     public function __construct(moodle_page $page) {
2599         global $CFG;
2600         if (during_initial_install()) {
2601             $this->duringinstall = true;
2602             return false;
2603         }
2604         $this->page = $page;
2605         $this->text = get_string('home');
2606         $this->shorttext = get_string('home');
2607         $this->action = new moodle_url($CFG->wwwroot);
2608         $this->nodetype = self::NODETYPE_BRANCH;
2609         $this->type = self::TYPE_SYSTEM;
2610     }
2612     /**
2613      * Quick check to see if the navbar will have items in.
2614      *
2615      * @return bool Returns true if the navbar will have items, false otherwise
2616      */
2617     public function has_items() {
2618         if ($this->duringinstall) {
2619             return false;
2620         } else if ($this->hasitems !== false) {
2621             return true;
2622         }
2623         $this->page->navigation->initialise($this->page);
2625         $activenodefound = ($this->page->navigation->contains_active_node() ||
2626                             $this->page->settingsnav->contains_active_node());
2628         $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2629         $this->hasitems = $outcome;
2630         return $outcome;
2631     }
2633     /**
2634      * Turn on/off ignore active
2635      *
2636      * @param bool $setting
2637      */
2638     public function ignore_active($setting=true) {
2639         $this->ignoreactive = ($setting);
2640     }
2641     public function get($key, $type = null) {
2642         foreach ($this->children as &$child) {
2643             if ($child->key === $key && ($type == null || $type == $child->type)) {
2644                 return $child;
2645             }
2646         }
2647         return false;
2648     }
2649     /**
2650      * Returns an array of navigation_node's that make up the navbar.
2651      *
2652      * @return array
2653      */
2654     public function get_items() {
2655         $items = array();
2656         // Make sure that navigation is initialised
2657         if (!$this->has_items()) {
2658             return $items;
2659         }
2660         if ($this->items !== null) {
2661             return $this->items;
2662         }
2664         if (count($this->children) > 0) {
2665             // Add the custom children
2666             $items = array_reverse($this->children);
2667         }
2669         $navigationactivenode = $this->page->navigation->find_active_node();
2670         $settingsactivenode = $this->page->settingsnav->find_active_node();
2672         // Check if navigation contains the active node
2673         if (!$this->ignoreactive) {
2675             if ($navigationactivenode && $settingsactivenode) {
2676                 // Parse a combined navigation tree
2677                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2678                     if (!$settingsactivenode->mainnavonly) {
2679                         $items[] = $settingsactivenode;
2680                     }
2681                     $settingsactivenode = $settingsactivenode->parent;
2682                 }
2683                 if (!$this->includesettingsbase) {
2684                     // Removes the first node from the settings (root node) from the list
2685                     array_pop($items);
2686                 }
2687                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2688                     if (!$navigationactivenode->mainnavonly) {
2689                         $items[] = $navigationactivenode;
2690                     }
2691                     $navigationactivenode = $navigationactivenode->parent;
2692                 }
2693             } else if ($navigationactivenode) {
2694                 // Parse the navigation tree to get the active node
2695                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
2696                     if (!$navigationactivenode->mainnavonly) {
2697                         $items[] = $navigationactivenode;
2698                     }
2699                     $navigationactivenode = $navigationactivenode->parent;
2700                 }
2701             } else if ($settingsactivenode) {
2702                 // Parse the settings navigation to get the active node
2703                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
2704                     if (!$settingsactivenode->mainnavonly) {
2705                         $items[] = $settingsactivenode;
2706                     }
2707                     $settingsactivenode = $settingsactivenode->parent;
2708                 }
2709             }
2710         }
2712         $items[] = new navigation_node(array(
2713             'text'=>$this->page->navigation->text,
2714             'shorttext'=>$this->page->navigation->shorttext,
2715             'key'=>$this->page->navigation->key,
2716             'action'=>$this->page->navigation->action
2717         ));
2719         $this->items = array_reverse($items);
2720         return $this->items;
2721     }
2723     /**
2724      * Add a new navigation_node to the navbar, overrides parent::add
2725      *
2726      * This function overrides {@link navigation_node::add()} so that we can change
2727      * the way nodes get added to allow us to simply call add and have the node added to the
2728      * end of the navbar
2729      *
2730      * @param string $text
2731      * @param string|moodle_url $action
2732      * @param int $type
2733      * @param string|int $key
2734      * @param string $shorttext
2735      * @param string $icon
2736      * @return navigation_node
2737      */
2738     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
2739         if ($this->content !== null) {
2740             debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
2741         }
2743         // Properties array used when creating the new navigation node
2744         $itemarray = array(
2745             'text' => $text,
2746             'type' => $type
2747         );
2748         // Set the action if one was provided
2749         if ($action!==null) {
2750             $itemarray['action'] = $action;
2751         }
2752         // Set the shorttext if one was provided
2753         if ($shorttext!==null) {
2754             $itemarray['shorttext'] = $shorttext;
2755         }
2756         // Set the icon if one was provided
2757         if ($icon!==null) {
2758             $itemarray['icon'] = $icon;
2759         }
2760         // Default the key to the number of children if not provided
2761         if ($key === null) {
2762             $key = count($this->children);
2763         }
2764         // Set the key
2765         $itemarray['key'] = $key;
2766         // Set the parent to this node
2767         $itemarray['parent'] = $this;
2768         // Add the child using the navigation_node_collections add method
2769         $this->children[] = new navigation_node($itemarray);
2770         return $this;
2771     }
2774 /**
2775  * Class used to manage the settings option for the current page
2776  *
2777  * This class is used to manage the settings options in a tree format (recursively)
2778  * and was created initially for use with the settings blocks.
2779  *
2780  * @package moodlecore
2781  * @subpackage navigation
2782  * @copyright 2009 Sam Hemelryk
2783  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2784  */
2785 class settings_navigation extends navigation_node {
2786     /** @var stdClass */
2787     protected $context;
2788     /** @var moodle_page */
2789     protected $page;
2790     /** @var string */
2791     protected $adminsection;
2792     /** @var bool */
2793     protected $initialised = false;
2794     /** @var array */
2795     protected $userstoextendfor = array();
2796     /** @var navigation_cache **/
2797     protected $cache;
2799     /**
2800      * Sets up the object with basic settings and preparse it for use
2801      *
2802      * @param moodle_page $page
2803      */
2804     public function __construct(moodle_page &$page) {
2805         if (during_initial_install()) {
2806             return false;
2807         }
2808         $this->page = $page;
2809         // Initialise the main navigation. It is most important that this is done
2810         // before we try anything
2811         $this->page->navigation->initialise();
2812         // Initialise the navigation cache
2813         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2814         $this->children = new navigation_node_collection();
2815     }
2816     /**
2817      * Initialise the settings navigation based on the current context
2818      *
2819      * This function initialises the settings navigation tree for a given context
2820      * by calling supporting functions to generate major parts of the tree.
2821      *
2822      */
2823     public function initialise() {
2824         global $DB, $SESSION;
2826         if (during_initial_install()) {
2827             return false;
2828         } else if ($this->initialised) {
2829             return true;
2830         }
2831         $this->id = 'settingsnav';
2832         $this->context = $this->page->context;
2834         $context = $this->context;
2835         if ($context->contextlevel == CONTEXT_BLOCK) {
2836             $this->load_block_settings();
2837             $context = $context->get_parent_context();
2838         }
2840         switch ($context->contextlevel) {
2841             case CONTEXT_SYSTEM:
2842                 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
2843                     $this->load_front_page_settings(($context->id == $this->context->id));
2844                 }
2845                 break;
2846             case CONTEXT_COURSECAT:
2847                 $this->load_category_settings();
2848                 break;
2849             case CONTEXT_COURSE:
2850                 if ($this->page->course->id != SITEID) {
2851                     $this->load_course_settings(($context->id == $this->context->id));
2852                 } else {
2853                     $this->load_front_page_settings(($context->id == $this->context->id));
2854                 }
2855                 break;
2856             case CONTEXT_MODULE:
2857                 $this->load_module_settings();
2858                 $this->load_course_settings();
2859                 break;
2860             case CONTEXT_USER:
2861                 if ($this->page->course->id != SITEID) {
2862                     $this->load_course_settings();
2863                 }
2864                 break;
2865         }
2867         $settings = $this->load_user_settings($this->page->course->id);
2869         if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
2870             $admin = $this->load_administration_settings();
2871             $SESSION->load_navigation_admin = ($admin->has_children());
2872         } else {
2873             $admin = false;
2874         }
2876         if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
2877             $admin->force_open();
2878         } else if ($context->contextlevel == CONTEXT_USER && $settings) {
2879             $settings->force_open();
2880         }
2882         // Check if the user is currently logged in as another user
2883         if (session_is_loggedinas()) {
2884             // Get the actual user, we need this so we can display an informative return link
2885             $realuser = session_get_realuser();
2886             // Add the informative return to original user link
2887             $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
2888             $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
2889         }
2891         foreach ($this->children as $key=>$node) {
2892             if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
2893                 $node->remove();
2894             }
2895         }
2896         $this->initialised = true;
2897     }
2898     /**
2899      * Override the parent function so that we can add preceeding hr's and set a
2900      * root node class against all first level element
2901      *
2902      * It does this by first calling the parent's add method {@link navigation_node::add()}
2903      * and then proceeds to use the key to set class and hr
2904      *
2905      * @param string $text
2906      * @param sting|moodle_url $url
2907      * @param string $shorttext
2908      * @param string|int $key
2909      * @param int $type
2910      * @param string $icon
2911      * @return navigation_node
2912      */
2913     public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2914         $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
2915         $node->add_class('root_node');
2916         return $node;
2917     }
2919     /**
2920      * This function allows the user to add something to the start of the settings
2921      * navigation, which means it will be at the top of the settings navigation block
2922      *
2923      * @param string $text
2924      * @param sting|moodle_url $url
2925      * @param string $shorttext
2926      * @param string|int $key
2927      * @param int $type
2928      * @param string $icon
2929      * @return navigation_node
2930      */
2931     public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
2932         $children = $this->children;
2933         $childrenclass = get_class($children);
2934         $this->children = new $childrenclass;
2935         $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
2936         foreach ($children as $child) {
2937             $this->children->add($child);
2938         }
2939         return $node;
2940     }
2941     /**
2942      * Load the site administration tree
2943      *
2944      * This function loads the site administration tree by using the lib/adminlib library functions
2945      *
2946      * @param navigation_node $referencebranch A reference to a branch in the settings
2947      *      navigation tree
2948      * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
2949      *      tree and start at the beginning
2950      * @return mixed A key to access the admin tree by
2951      */
2952     protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
2953         global $CFG;
2955         // Check if we are just starting to generate this navigation.
2956         if ($referencebranch === null) {
2958             // Require the admin lib then get an admin structure
2959             if (!function_exists('admin_get_root')) {
2960                 require_once($CFG->dirroot.'/lib/adminlib.php');
2961             }
2962             $adminroot = admin_get_root(false, false);
2963             // This is the active section identifier
2964             $this->adminsection = $this->page->url->param('section');
2966             // Disable the navigation from automatically finding the active node
2967             navigation_node::$autofindactive = false;
2968             $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
2969             foreach ($adminroot->children as $adminbranch) {
2970                 $this->load_administration_settings($referencebranch, $adminbranch);
2971             }
2972             navigation_node::$autofindactive = true;
2974             // Use the admin structure to locate the active page
2975             if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2976                 $currentnode = $this;
2977                 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2978                     $currentnode = $currentnode->get($pathkey);
2979                 }
2980                 if ($currentnode) {
2981                     $currentnode->make_active();
2982                 }
2983             } else {
2984                 $this->scan_for_active_node($referencebranch);
2985             }
2986             return $referencebranch;
2987         } else if ($adminbranch->check_access()) {
2988             // We have a reference branch that we can access and is not hidden `hurrah`
2989             // Now we need to display it and any children it may have
2990             $url = null;
2991             $icon = null;
2992             if ($adminbranch instanceof admin_settingpage) {
2993                 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2994             } else if ($adminbranch instanceof admin_externalpage) {
2995                 $url = $adminbranch->url;
2996             }
2998             // Add the branch
2999             $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
3001             if ($adminbranch->is_hidden()) {
3002                 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
3003                     $reference->add_class('hidden');
3004                 } else {
3005                     $reference->display = false;
3006                 }
3007             }
3009             // Check if we are generating the admin notifications and whether notificiations exist
3010             if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
3011                 $reference->add_class('criticalnotification');
3012             }
3013             // Check if this branch has children
3014             if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
3015                 foreach ($adminbranch->children as $branch) {
3016                     // Generate the child branches as well now using this branch as the reference
3017                     $this->load_administration_settings($reference, $branch);
3018                 }
3019             } else {
3020                 $reference->icon = new pix_icon('i/settings', '');
3021             }
3022         }
3023     }
3025     /**
3026      * This function recursivily scans nodes until it finds the active node or there
3027      * are no more nodes.
3028      * @param navigation_node $node
3029      */
3030     protected function scan_for_active_node(navigation_node $node) {
3031         if (!$node->check_if_active() && $node->children->count()>0) {
3032             foreach ($node->children as &$child) {
3033                 $this->scan_for_active_node($child);
3034             }
3035         }
3036     }
3038     /**
3039      * Gets a navigation node given an array of keys that represent the path to
3040      * the desired node.
3041      *
3042      * @param array $path
3043      * @return navigation_node|false
3044      */
3045     protected function get_by_path(array $path) {
3046         $node = $this->get(array_shift($path));
3047         foreach ($path as $key) {
3048             $node->get($key);
3049         }
3050         return $node;
3051     }
3053     /**
3054      * Generate the list of modules for the given course.
3055      *
3056      * @param stdClass $course The course to get modules for
3057      */
3058     protected function get_course_modules($course) {
3059         global $CFG;
3060         $mods = $modnames = $modnamesplural = $modnamesused = array();
3061         // This function is included when we include course/lib.php at the top
3062         // of this file
3063         get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
3064         $resources = array();
3065         $activities = array();
3066         foreach($modnames as $modname=>$modnamestr) {
3067             if (!course_allowed_module($course, $modname)) {
3068                 continue;
3069             }
3071             $libfile = "$CFG->dirroot/mod/$modname/lib.php";
3072             if (!file_exists($libfile)) {
3073                 continue;
3074             }
3075             include_once($libfile);
3076             $gettypesfunc =  $modname.'_get_types';
3077             if (function_exists($gettypesfunc)) {
3078                 $types = $gettypesfunc();
3079                 foreach($types as $type) {
3080                     if (!isset($type->modclass) || !isset($type->typestr)) {
3081                         debugging('Incorrect activity type in '.$modname);
3082                         continue;
3083                     }
3084                     if ($type->modclass == MOD_CLASS_RESOURCE) {
3085                         $resources[html_entity_decode($type->type)] = $type->typestr;
3086                     } else {
3087                         $activities[html_entity_decode($type->type)] = $type->typestr;
3088                     }
3089                 }
3090             } else {
3091                 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3092                 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
3093                     $resources[$modname] = $modnamestr;
3094                 } else {
3095                     // all other archetypes are considered activity
3096                     $activities[$modname] = $modnamestr;
3097                 }
3098             }
3099         }
3100         return array($resources, $activities);
3101     }
3103     /**
3104      * This function loads the course settings that are available for the user
3105      *
3106      * @param bool $forceopen If set to true the course node will be forced open
3107      * @return navigation_node|false
3108      */
3109     protected function load_course_settings($forceopen = false) {
3110         global $CFG;
3112         $course = $this->page->course;
3113         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
3115         // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
3117         $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
3118         if ($forceopen) {
3119             $coursenode->force_open();
3120         }
3122         if (has_capability('moodle/course:update', $coursecontext)) {
3123             // Add the turn on/off settings
3124             $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
3125             if ($this->page->user_is_editing()) {
3126                 $url->param('edit', 'off');
3127                 $editstring = get_string('turneditingoff');
3128             } else {
3129                 $url->param('edit', 'on');
3130                 $editstring = get_string('turneditingon');
3131             }
3132             $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3134             if ($this->page->user_is_editing()) {
3135                 // Removed as per MDL-22732
3136                 // $this->add_course_editing_links($course);
3137             }
3139             // Add the course settings link
3140             $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
3141             $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3143             // Add the course completion settings link
3144             if ($CFG->enablecompletion && $course->enablecompletion) {
3145                 $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
3146                 $coursenode->add(get_string('completion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
3147             }
3148         }
3150         // add enrol nodes
3151         enrol_add_course_navigation($coursenode, $course);
3153         // Manage filters
3154         if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
3155             $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
3156             $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
3157         }
3159         // Add view grade report is permitted
3160         $reportavailable = false;
3161         if (has_capability('moodle/grade:viewall', $coursecontext)) {
3162             $reportavailable = true;
3163         } else if (!empty($course->showgrades)) {
3164             $reports = get_plugin_list('gradereport');
3165             if (is_array($reports) && count($reports)>0) {     // Get all installed reports
3166                 arsort($reports); // user is last, we want to test it first
3167                 foreach ($reports as $plugin => $plugindir) {
3168                     if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
3169                         //stop when the first visible plugin is found
3170                         $reportavailable = true;
3171                         break;
3172                     }
3173                 }
3174             }
3175         }
3176         if ($reportavailable) {
3177             $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
3178             $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
3179         }
3181         //  Add outcome if permitted
3182         if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
3183             $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
3184             $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
3185         }
3187         // Backup this course
3188         if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
3189             $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
3190             $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
3191         }
3193         // Restore to this course
3194         if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
3195             $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
3196             $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
3197         }
3199         // Import data from other courses
3200         if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
3201             $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
3202             $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/restore', ''));
3203         }
3205         // Publish course on a hub
3206         if (has_capability('moodle/course:publish', $coursecontext)) {
3207             $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
3208             $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
3209         }
3211         // Reset this course
3212         if (has_capability('moodle/course:reset', $coursecontext)) {
3213             $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
3214             $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
3215         }
3217         // Questions
3218         require_once($CFG->dirroot.'/question/editlib.php');
3219         question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
3221         if (has_capability('moodle/course:update', $coursecontext)) {
3222             // Repository Instances
3223             if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
3224                 require_once($CFG->dirroot . '/repository/lib.php');
3225                 $editabletypes = repository::get_editable_types($coursecontext);
3226                 $haseditabletypes = !empty($editabletypes);
3227                 unset($editabletypes);
3228                 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
3229             } else {
3230                 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
3231             }
3232             if ($haseditabletypes) {
3233                 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
3234                 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
3235             }
3236         }
3238         // Manage files
3239         if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
3240             // hidden in new courses and courses where legacy files were turned off
3241             $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
3242             $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/files', ''));
3243         }
3245         // Switch roles
3246         $roles = array();
3247         $assumedrole = $this->in_alternative_role();
3248         if ($assumedrole !== false) {
3249             $roles[0] = get_string('switchrolereturn');
3250         }
3251         if (has_capability('moodle/role:switchroles', $coursecontext)) {
3252             $availableroles = get_switchable_roles($coursecontext);
3253             if (is_array($availableroles)) {
3254                 foreach ($availableroles as $key=>$role) {
3255                     if ($assumedrole == (int)$key) {
3256                         continue;
3257                     }
3258                     $roles[$key] = $role;
3259                 }
3260             }
3261         }
3262         if (is_array($roles) && count($roles)>0) {
3263             $switchroles = $this->add(get_string('switchroleto'));
3264             if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
3265                 $switchroles->force_open();
3266             }
3267             $returnurl = $this->page->url;
3268             $returnurl->param('sesskey', sesskey());
3269             foreach ($roles as $key => $name) {
3270                 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$returnurl->out(false)));
3271                 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
3272             }
3273         }
3274         // Return we are done
3275         return $coursenode;
3276     }
3278     /**
3279      * Adds branches and links to the settings navigation to add course activities
3280      * and resources.
3281      *
3282      * @param stdClass $course
3283      */
3284     protected function add_course_editing_links($course) {
3285         global $CFG;
3287         require_once($CFG->dirroot.'/course/lib.php');
3289         // Add `add` resources|activities branches
3290         $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3291         if (file_exists($structurefile)) {
3292             require_once($structurefile);
3293             $requestkey = call_user_func('callback_'.$course->format.'_request_key');
3294             $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3295         } else {
3296             $requestkey = get_string('section');
3297             $formatidentifier = optional_param($requestkey, 0, PARAM_INT);
3298         }
3300         $sections = get_all_sections($course->id);
3302         $addresource = $this->add(get_string('addresource'));
3303         $addactivity = $this->add(get_string('addactivity'));
3304         if ($formatidentifier!==0) {
3305             $addresource->force_open();
3306             $addactivity->force_open();
3307         }
3309         $this->get_course_modules($course);
3311         $textlib = textlib_get_instance();
3313         foreach ($sections as $section) {
3314             if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
3315                 continue;
3316             }
3317             $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $requestkey=>$section->section));
3318             if ($section->section == 0) {
3319                 $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3320                 $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
3321             } else {
3322                 $sectionname = get_section_name($course, $section);
3323                 $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING);
3324                 $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING);
3325             }
3326             foreach ($resources as $value=>$resource) {
3327                 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3328                 $pos = strpos($value, '&type=');
3329                 if ($pos!==false) {
3330                     $url->param('add', $textlib->substr($value, 0,$pos));
3331                     $url->param('type', $textlib->substr($value, $pos+6));
3332                 } else {
3333                     $url->param('add', $value);
3334                 }
3335                 $sectionresources->add($resource, $url, self::TYPE_SETTING);
3336             }
3337             $subbranch = false;
3338             foreach ($activities as $activityname=>$activity) {
3339                 if ($activity==='--') {
3340                     $subbranch = false;
3341                     continue;
3342                 }
3343                 if (strpos($activity, '--')===0) {
3344                     $subbranch = $sectionactivities->add(trim($activity, '-'));
3345                     continue;
3346                 }
3347                 $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
3348                 $pos = strpos($activityname, '&type=');
3349                 if ($pos!==false) {
3350                     $url->param('add', $textlib->substr($activityname, 0,$pos));
3351                     $url->param('type', $textlib->substr($activityname, $pos+6));
3352                 } else {
3353                     $url->param('add', $activityname);
3354                 }
3355                 if ($subbranch !== false) {
3356                     $subbranch->add($activity, $url, self::TYPE_SETTING);
3357                 } else {
3358                     $sectionactivities->add($activity, $url, self::TYPE_SETTING);
3359                 }
3360             }
3361         }
3362     }
3364     /**
3365      * This function calls the module function to inject module settings into the
3366      * settings navigation tree.
3367      *
3368      * This only gets called if there is a corrosponding function in the modules
3369      * lib file.
3370      *
3371      * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
3372      *
3373      * @return navigation_node|false
3374      */
3375     protected function load_module_settings() {
3376         global $CFG;
3378         if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
3379             $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
3380             $this->page->set_cm($cm, $this->page->course);
3381         }
3383         $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
3384         if (file_exists($file)) {
3385             require_once($file);
3386         }
3388         $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname));
3389         $modulenode->force_open();
3391         // Settings for the module
3392         if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
3393             $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
3394             $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
3395         }
3396         // Assign local roles
3397         if (count(get_assignable_roles($this->page->cm->context))>0) {
3398             $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
3399             $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
3400         }
3401         // Override roles
3402         if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
3403             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
3404             $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
3405         }
3406         // Check role permissions
3407         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
3408             $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
3409             $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
3410         }
3411         // Manage filters
3412         if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
3413             $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
3414             $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
3415         }
3416         // Add reports
3417         $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
3418         foreach ($reports as $reportfunction) {
3419             $reportfunction($modulenode, $this->page->cm);
3420         }
3421         // Add a backup link
3422         $featuresfunc = $this->page->activityname.'_supports';
3423         if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
3424             $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
3425             $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
3426         }
3428         // Restore this activity
3429         $featuresfunc = $this->page->activityname.'_supports';
3430         if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
3431             $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
3432             $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
3433         }
3435         // Allow the active advanced grading method plugin to append its settings
3436         $featuresfunc = $this->page->activityname.'_supports';
3437         if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
3438             require_once($CFG->dirroot.'/grade/grading/lib.php');
3439             $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
3440             $gradingman->extend_settings_navigation($this, $modulenode);
3441         }
3443         $function = $this->page->activityname.'_extend_settings_navigation';
3444         if (!function_exists($function)) {
3445             return $modulenode;
3446         }
3448         $function($this, $modulenode);
3450         // Remove the module node if there are no children
3451         if (empty($modulenode->children)) {
3452             $modulenode->remove();
3453         }
3455         return $modulenode;
3456     }
3458     /**
3459      * Loads the user settings block of the settings nav
3460      *
3461      * This function is simply works out the userid and whether we need to load
3462      * just the current users profile settings, or the current user and the user the
3463      * current user is viewing.
3464      *
3465      * This function has some very ugly code to work out the user, if anyone has
3466      * any bright ideas please feel free to intervene.
3467      *
3468      * @param int $courseid The course id of the current course
3469      * @return navigation_node|false
3470      */
3471     protected function load_user_settings($courseid=SITEID) {
3472         global $USER, $FULLME, $CFG;
3474         if (isguestuser() || !isloggedin()) {
3475             return false;
3476         }
3478         $navusers = $this->page->navigation->get_extending_users();
3480         if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
3481             $usernode = null;
3482             foreach ($this->userstoextendfor as $userid) {
3483                 if ($userid == $USER->id) {
3484                     continue;
3485                 }
3486                 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
3487                 if (is_null($usernode)) {
3488                     $usernode = $node;
3489                 }
3490             }
3491             foreach ($navusers as $user) {
3492                 if ($user->id == $USER->id) {
3493                     continue;
3494                 }
3495                 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
3496                 if (is_null($usernode)) {
3497                     $usernode = $node;
3498                 }
3499             }
3500             $this->generate_user_settings($courseid, $USER->id);
3501         } else {
3502             $usernode = $this->generate_user_settings($courseid, $USER->id);
3503         }
3504         return $usernode;
3505     }
3507     /**
3508      * Extends the settings navigation for the given user.
3509      *
3510      * Note: This method gets called automatically if you call
3511      * $PAGE->navigation->extend_for_user($userid)
3512      *
3513      * @param int $userid
3514      */
3515     public function extend_for_user($userid) {
3516         global $CFG;
3518         if (!in_array($userid, $this->userstoextendfor)) {
3519             $this->userstoextendfor[] = $userid;
3520             if ($this->initialised) {
3521                 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
3522                 $children = array();
3523                 foreach ($this->children as $child) {
3524                     $children[] = $child;
3525                 }
3526                 array_unshift($children, array_pop($children));
3527                 $this->children = new navigation_node_collection();
3528                 foreach ($children as $child) {
3529                     $this->children->add($child);
3530                 }
3531             }
3532         }
3533     }
3535     /**
3536      * This function gets called by {@link load_user_settings()} and actually works out
3537      * what can be shown/done
3538      *
3539      * @global moodle_database $DB
3540      * @param int $courseid The current course' id
3541      * @param int $userid The user id to load for
3542      * @param string $gstitle The string to pass to get_string for the branch title
3543      * @return navigation_node|false
3544      */
3545     protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
3546         global $DB, $CFG, $USER, $SITE;
3548         if ($courseid != SITEID) {
3549             if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
3550                 $course = $this->page->course;
3551             } else {
3552                 list($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3553                 $sql = "SELECT c.* $select FROM {course} c $join WHERE c.id = :courseid";
3554                 $course = $DB->get_record_sql($sql, array('courseid' => $courseid), MUST_EXIST);
3555                 context_instance_preload($course);
3556             }
3557         } else {
3558             $course = $SITE;
3559         }
3561         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);   // Course context
3562         $systemcontext   = get_system_context();
3563         $currentuser = ($USER->id == $userid);
3565         if ($currentuser) {
3566             $user = $USER;
3567             $usercontext = get_context_instance(CONTEXT_USER, $user->id);       // User context
3568         } else {
3570             list($select, $join) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
3571             $sql = "SELECT u.* $select FROM {user} u $join WHERE u.id = :userid";
3572             $user = $DB->get_record_sql($sql, array('userid' => $userid), IGNORE_MISSING);
3573             if (!$user) {
3574                 return false;
3575             }
3576             context_instance_preload($user);
3578             // Check that the user can view the profile
3579             $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
3580             $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
3582             if ($course->id == SITEID) {
3583                 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {  // Reduce possibility of "browsing" userbase at site level
3584                     // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
3585                     return false;
3586                 }
3587             } else {
3588                 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
3589                 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
3590                 if ((!$canviewusercourse && !$canviewuser) || !can_access_course($course, $user->id)) {
3591                     return false;
3592                 }
3593                 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
3594                     // If groups are in use, make sure we can see that group
3595                     return false;
3596                 }
3597             }
3598         }
3600         $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
3602         $key = $gstitle;
3603         if ($gstitle != 'usercurrentsettings') {
3604             $key .= $userid;
3605         }
3607         // Add a user setting branch
3608         $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
3609         $usersetting->id = 'usersettings';
3610         if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
3611             // Automatically start by making it active
3612             $usersetting->make_active();
3613         }
3615         // Check if the user has been deleted
3616         if ($user->deleted) {
3617             if (!has_capability('moodle/user:update', $coursecontext)) {
3618                 // We can't edit the user so just show the user deleted message
3619                 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
3620             } else {
3621                 // We can edit the user so show the user deleted message and link it to the profile
3622                 if ($course->id == SITEID) {
3623                     $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
3624                 } else {
3625                     $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
3626                 }
3627                 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
3628             }
3629             return true;
3630         }
3632         $userauthplugin = false;
3633         if (!empty($user->auth)) {
3634             $userauthplugin = get_auth_plugin($user->auth);
3635         }
3637         // Add the profile edit link
3638         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
3639             if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
3640                 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
3641                 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3642             } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
3643                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
3644                     $url = $userauthplugin->edit_profile_url();
3645                     if (empty($url)) {
3646                         $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3647                     }
3648                     $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
3649                 }
3650             }
3651         }
3653         // Change password link
3654         if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
3655             $passwordchangeurl = $userauthplugin->change_password_url();
3656             if (empty($passwordchangeurl)) {
3657                 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
3658             }
3659             $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
3660         }
3662         // View the roles settings
3663         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
3664             $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
3666             $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
3667             $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
3669             $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
3671             if (!empty($assignableroles)) {
3672                 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3673                 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
3674             }
3676             if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
3677                 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3678                 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3679             }
3681             $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
3682             $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3683         }
3685         // Portfolio
3686         if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
3687             require_once($CFG->libdir . '/portfoliolib.php');
3688             if (portfolio_instances(true, false)) {
3689                 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
3691                 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
3692                 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
3694                 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
3695                 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
3696             }
3697         }
3699         $enablemanagetokens = false;
3700         if (!empty($CFG->enablerssfeeds)) {
3701             $enablemanagetokens = true;
3702         } else if (!is_siteadmin($USER->id)
3703              && !empty($CFG->enablewebservices)
3704              && has_capability('moodle/webservice:createtoken', get_system_context()) ) {
3705             $enablemanagetokens = true;
3706         }
3707         // Security keys
3708         if ($currentuser && $enablemanagetokens) {
3709             $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
3710             $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
3711         }
3713         // Repository
3714         if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
3715             if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
3716                 require_once($CFG->dirroot . '/repository/lib.php');
3717                 $editabletypes = repository::get_editable_types($usercontext);
3718                 $haseditabletypes = !empty($editabletypes);
3719                 unset($editabletypes);
3720                 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
3721             } else {
3722                 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
3723             }
3724             if ($haseditabletypes) {
3725                 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
3726                 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
3727             }
3728         }
3730         // Messaging
3731         if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
3732             $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
3733             $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
3734         }
3736         // Blogs
3737         if ($currentuser && !empty($CFG->bloglevel)) {
3738             $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
3739             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
3740             if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
3741                 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
3742                 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
3743             }
3744         }
3746         // Login as ...
3747         if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
3748             $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
3749             $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
3750         }
3752         return $usersetting;
3753     }
3755     /**
3756      * Loads block specific settings in the navigation
3757      *
3758      * @return navigation_node
3759      */
3760     protected function load_block_settings() {
3761         global $CFG;
3763         $blocknode = $this->add(print_context_name($this->context));
3764         $blocknode->force_open();
3766         // Assign local roles
3767         $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3768         $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
3770         // Override roles
3771         if (has_capability('moodle/role:review', $this->context) or  count(get_overridable_roles($this->context))>0) {
3772             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
3773             $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
3774         }
3775         // Check role permissions
3776         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
3777             $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
3778             $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
3779         }
3781         return $blocknode;
3782     }
3784     /**
3785      * Loads category specific settings in the navigation
3786      *
3787      * @return navigation_node
3788      */
3789     protected function load_category_settings() {
3790         global $CFG;
3792         $categorynode = $this->add(print_context_name($this->context));
3793         $categorynode->force_open();
3795         if (has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $this->context)) {
3796             $url = new moodle_url('/course/category.php', array('id'=>$this->context->instanceid, 'sesskey'=>sesskey()));
3797             if ($this->page->user_is_editing()) {
3798                 $url->param('categoryedit', '0');
3799                 $editstring = get_string('turneditingoff');
3800             } else {
3801                 $url->param('categoryedit', '1');
3802                 $editstring = get_string('turneditingon');
3803             }
3804             $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
3805         }
3807         if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
3808             $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
3809             $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
3811             $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
3812             $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
3813         }
3815         // Assign local roles
3816         if (has_capability('moodle/role:assign', $this->context)) {
3817             $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
3818             $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
3819         }
3821         // Override roles
3822         if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
3823             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));