MDL-38442 navigation: set_expansion_limit now only hides structural nodes
[moodle.git] / lib / navigationlib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * This file contains classes used to manage the navigation structures within Moodle.
19  *
20  * @since      2.0
21  * @package    core
22  * @copyright  2009 Sam Hemelryk
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die();
28 /**
29  * The name that will be used to separate the navigation cache within SESSION
30  */
31 define('NAVIGATION_CACHE_NAME', 'navigation');
33 /**
34  * This class is used to represent a node in a navigation tree
35  *
36  * This class is used to represent a node in a navigation tree within Moodle,
37  * the tree could be one of global navigation, settings navigation, or the navbar.
38  * Each node can be one of two types either a Leaf (default) or a branch.
39  * When a node is first created it is created as a leaf, when/if children are added
40  * the node then becomes a branch.
41  *
42  * @package   core
43  * @category  navigation
44  * @copyright 2009 Sam Hemelryk
45  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  */
47 class navigation_node implements renderable {
48     /** @var int Used to identify this node a leaf (default) 0 */
49     const NODETYPE_LEAF =   0;
50     /** @var int Used to identify this node a branch, happens with children  1 */
51     const NODETYPE_BRANCH = 1;
52     /** @var null Unknown node type null */
53     const TYPE_UNKNOWN =    null;
54     /** @var int System node type 0 */
55     const TYPE_ROOTNODE =   0;
56     /** @var int System node type 1 */
57     const TYPE_SYSTEM =     1;
58     /** @var int Category node type 10 */
59     const TYPE_CATEGORY =   10;
60     /** var int Category displayed in MyHome navigation node */
61     const TYPE_MY_CATEGORY = 11;
62     /** @var int Course node type 20 */
63     const TYPE_COURSE =     20;
64     /** @var int Course Structure node type 30 */
65     const TYPE_SECTION =    30;
66     /** @var int Activity node type, e.g. Forum, Quiz 40 */
67     const TYPE_ACTIVITY =   40;
68     /** @var int Resource node type, e.g. Link to a file, or label 50 */
69     const TYPE_RESOURCE =   50;
70     /** @var int A custom node type, default when adding without specifing type 60 */
71     const TYPE_CUSTOM =     60;
72     /** @var int Setting node type, used only within settings nav 70 */
73     const TYPE_SETTING =    70;
74     /** @var int Setting node type, used only within settings nav 80 */
75     const TYPE_USER =       80;
76     /** @var int Setting node type, used for containers of no importance 90 */
77     const TYPE_CONTAINER =  90;
78     /** var int Course the current user is not enrolled in */
79     const COURSE_OTHER = 0;
80     /** var int Course the current user is enrolled in but not viewing */
81     const COURSE_MY = 1;
82     /** var int Course the current user is currently viewing */
83     const COURSE_CURRENT = 2;
85     /** @var int Parameter to aid the coder in tracking [optional] */
86     public $id = null;
87     /** @var string|int The identifier for the node, used to retrieve the node */
88     public $key = null;
89     /** @var string The text to use for the node */
90     public $text = null;
91     /** @var string Short text to use if requested [optional] */
92     public $shorttext = null;
93     /** @var string The title attribute for an action if one is defined */
94     public $title = null;
95     /** @var string A string that can be used to build a help button */
96     public $helpbutton = null;
97     /** @var moodle_url|action_link|null An action for the node (link) */
98     public $action = null;
99     /** @var pix_icon The path to an icon to use for this node */
100     public $icon = null;
101     /** @var int See TYPE_* constants defined for this class */
102     public $type = self::TYPE_UNKNOWN;
103     /** @var int See NODETYPE_* constants defined for this class */
104     public $nodetype = self::NODETYPE_LEAF;
105     /** @var bool If set to true the node will be collapsed by default */
106     public $collapse = false;
107     /** @var bool If set to true the node will be expanded by default */
108     public $forceopen = false;
109     /** @var array An array of CSS classes for the node */
110     public $classes = array();
111     /** @var navigation_node_collection An array of child nodes */
112     public $children = array();
113     /** @var bool If set to true the node will be recognised as active */
114     public $isactive = false;
115     /** @var bool If set to true the node will be dimmed */
116     public $hidden = false;
117     /** @var bool If set to false the node will not be displayed */
118     public $display = true;
119     /** @var bool If set to true then an HR will be printed before the node */
120     public $preceedwithhr = false;
121     /** @var bool If set to true the the navigation bar should ignore this node */
122     public $mainnavonly = false;
123     /** @var bool If set to true a title will be added to the action no matter what */
124     public $forcetitle = false;
125     /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
126     public $parent = null;
127     /** @var bool Override to not display the icon even if one is provided **/
128     public $hideicon = false;
129     /** @var bool Set to true if we KNOW that this node can be expanded.  */
130     public $isexpandable = false;
131     /** @var array */
132     protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
133     /** @var moodle_url */
134     protected static $fullmeurl = null;
135     /** @var bool toogles auto matching of active node */
136     public static $autofindactive = true;
137     /** @var mixed If set to an int, that section will be included even if it has no activities */
138     public $includesectionnum = false;
140     /**
141      * Constructs a new navigation_node
142      *
143      * @param array|string $properties Either an array of properties or a string to use
144      *                     as the text for the node
145      */
146     public function __construct($properties) {
147         if (is_array($properties)) {
148             // Check the array for each property that we allow to set at construction.
149             // text         - The main content for the node
150             // shorttext    - A short text if required for the node
151             // icon         - The icon to display for the node
152             // type         - The type of the node
153             // key          - The key to use to identify the node
154             // parent       - A reference to the nodes parent
155             // action       - The action to attribute to this node, usually a URL to link to
156             if (array_key_exists('text', $properties)) {
157                 $this->text = $properties['text'];
158             }
159             if (array_key_exists('shorttext', $properties)) {
160                 $this->shorttext = $properties['shorttext'];
161             }
162             if (!array_key_exists('icon', $properties)) {
163                 $properties['icon'] = new pix_icon('i/navigationitem', '');
164             }
165             $this->icon = $properties['icon'];
166             if ($this->icon instanceof pix_icon) {
167                 if (empty($this->icon->attributes['class'])) {
168                     $this->icon->attributes['class'] = 'navicon';
169                 } else {
170                     $this->icon->attributes['class'] .= ' navicon';
171                 }
172             }
173             if (array_key_exists('type', $properties)) {
174                 $this->type = $properties['type'];
175             } else {
176                 $this->type = self::TYPE_CUSTOM;
177             }
178             if (array_key_exists('key', $properties)) {
179                 $this->key = $properties['key'];
180             }
181             // This needs to happen last because of the check_if_active call that occurs
182             if (array_key_exists('action', $properties)) {
183                 $this->action = $properties['action'];
184                 if (is_string($this->action)) {
185                     $this->action = new moodle_url($this->action);
186                 }
187                 if (self::$autofindactive) {
188                     $this->check_if_active();
189                 }
190             }
191             if (array_key_exists('parent', $properties)) {
192                 $this->set_parent($properties['parent']);
193             }
194         } else if (is_string($properties)) {
195             $this->text = $properties;
196         }
197         if ($this->text === null) {
198             throw new coding_exception('You must set the text for the node when you create it.');
199         }
200         // Instantiate a new navigation node collection for this nodes children
201         $this->children = new navigation_node_collection();
202     }
204     /**
205      * Checks if this node is the active node.
206      *
207      * This is determined by comparing the action for the node against the
208      * defined URL for the page. A match will see this node marked as active.
209      *
210      * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
211      * @return bool
212      */
213     public function check_if_active($strength=URL_MATCH_EXACT) {
214         global $FULLME, $PAGE;
215         // Set fullmeurl if it hasn't already been set
216         if (self::$fullmeurl == null) {
217             if ($PAGE->has_set_url()) {
218                 self::override_active_url(new moodle_url($PAGE->url));
219             } else {
220                 self::override_active_url(new moodle_url($FULLME));
221             }
222         }
224         // Compare the action of this node against the fullmeurl
225         if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
226             $this->make_active();
227             return true;
228         }
229         return false;
230     }
232     /**
233      * This sets the URL that the URL of new nodes get compared to when locating
234      * the active node.
235      *
236      * The active node is the node that matches the URL set here. By default this
237      * is either $PAGE->url or if that hasn't been set $FULLME.
238      *
239      * @param moodle_url $url The url to use for the fullmeurl.
240      */
241     public static function override_active_url(moodle_url $url) {
242         // Clone the URL, in case the calling script changes their URL later.
243         self::$fullmeurl = new moodle_url($url);
244     }
246     /**
247      * Creates a navigation node, ready to add it as a child using add_node
248      * function. (The created node needs to be added before you can use it.)
249      * @param string $text
250      * @param moodle_url|action_link $action
251      * @param int $type
252      * @param string $shorttext
253      * @param string|int $key
254      * @param pix_icon $icon
255      * @return navigation_node
256      */
257     public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
258             $shorttext=null, $key=null, pix_icon $icon=null) {
259         // Properties array used when creating the new navigation node
260         $itemarray = array(
261             'text' => $text,
262             'type' => $type
263         );
264         // Set the action if one was provided
265         if ($action!==null) {
266             $itemarray['action'] = $action;
267         }
268         // Set the shorttext if one was provided
269         if ($shorttext!==null) {
270             $itemarray['shorttext'] = $shorttext;
271         }
272         // Set the icon if one was provided
273         if ($icon!==null) {
274             $itemarray['icon'] = $icon;
275         }
276         // Set the key
277         $itemarray['key'] = $key;
278         // Construct and return
279         return new navigation_node($itemarray);
280     }
282     /**
283      * Adds a navigation node as a child of this node.
284      *
285      * @param string $text
286      * @param moodle_url|action_link $action
287      * @param int $type
288      * @param string $shorttext
289      * @param string|int $key
290      * @param pix_icon $icon
291      * @return navigation_node
292      */
293     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
294         // Create child node
295         $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
297         // Add the child to end and return
298         return $this->add_node($childnode);
299     }
301     /**
302      * Adds a navigation node as a child of this one, given a $node object
303      * created using the create function.
304      * @param navigation_node $childnode Node to add
305      * @param string $beforekey
306      * @return navigation_node The added node
307      */
308     public function add_node(navigation_node $childnode, $beforekey=null) {
309         // First convert the nodetype for this node to a branch as it will now have children
310         if ($this->nodetype !== self::NODETYPE_BRANCH) {
311             $this->nodetype = self::NODETYPE_BRANCH;
312         }
313         // Set the parent to this node
314         $childnode->set_parent($this);
316         // Default the key to the number of children if not provided
317         if ($childnode->key === null) {
318             $childnode->key = $this->children->count();
319         }
321         // Add the child using the navigation_node_collections add method
322         $node = $this->children->add($childnode, $beforekey);
324         // If added node is a category node or the user is logged in and it's a course
325         // then mark added node as a branch (makes it expandable by AJAX)
326         $type = $childnode->type;
327         if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY)) {
328             $node->nodetype = self::NODETYPE_BRANCH;
329         }
330         // If this node is hidden mark it's children as hidden also
331         if ($this->hidden) {
332             $node->hidden = true;
333         }
334         // Return added node (reference returned by $this->children->add()
335         return $node;
336     }
338     /**
339      * Return a list of all the keys of all the child nodes.
340      * @return array the keys.
341      */
342     public function get_children_key_list() {
343         return $this->children->get_key_list();
344     }
346     /**
347      * Searches for a node of the given type with the given key.
348      *
349      * This searches this node plus all of its children, and their children....
350      * If you know the node you are looking for is a child of this node then please
351      * use the get method instead.
352      *
353      * @param int|string $key The key of the node we are looking for
354      * @param int $type One of navigation_node::TYPE_*
355      * @return navigation_node|false
356      */
357     public function find($key, $type) {
358         return $this->children->find($key, $type);
359     }
361     /**
362      * Get the child of this node that has the given key + (optional) type.
363      *
364      * If you are looking for a node and want to search all children + thier children
365      * then please use the find method instead.
366      *
367      * @param int|string $key The key of the node we are looking for
368      * @param int $type One of navigation_node::TYPE_*
369      * @return navigation_node|false
370      */
371     public function get($key, $type=null) {
372         return $this->children->get($key, $type);
373     }
375     /**
376      * Removes this node.
377      *
378      * @return bool
379      */
380     public function remove() {
381         return $this->parent->children->remove($this->key, $this->type);
382     }
384     /**
385      * Checks if this node has or could have any children
386      *
387      * @return bool Returns true if it has children or could have (by AJAX expansion)
388      */
389     public function has_children() {
390         return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
391     }
393     /**
394      * Marks this node as active and forces it open.
395      *
396      * Important: If you are here because you need to mark a node active to get
397      * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
398      * You can use it to specify a different URL to match the active navigation node on
399      * rather than having to locate and manually mark a node active.
400      */
401     public function make_active() {
402         $this->isactive = true;
403         $this->add_class('active_tree_node');
404         $this->force_open();
405         if ($this->parent !== null) {
406             $this->parent->make_inactive();
407         }
408     }
410     /**
411      * Marks a node as inactive and recusised back to the base of the tree
412      * doing the same to all parents.
413      */
414     public function make_inactive() {
415         $this->isactive = false;
416         $this->remove_class('active_tree_node');
417         if ($this->parent !== null) {
418             $this->parent->make_inactive();
419         }
420     }
422     /**
423      * Forces this node to be open and at the same time forces open all
424      * parents until the root node.
425      *
426      * Recursive.
427      */
428     public function force_open() {
429         $this->forceopen = true;
430         if ($this->parent !== null) {
431             $this->parent->force_open();
432         }
433     }
435     /**
436      * Adds a CSS class to this node.
437      *
438      * @param string $class
439      * @return bool
440      */
441     public function add_class($class) {
442         if (!in_array($class, $this->classes)) {
443             $this->classes[] = $class;
444         }
445         return true;
446     }
448     /**
449      * Removes a CSS class from this node.
450      *
451      * @param string $class
452      * @return bool True if the class was successfully removed.
453      */
454     public function remove_class($class) {
455         if (in_array($class, $this->classes)) {
456             $key = array_search($class,$this->classes);
457             if ($key!==false) {
458                 unset($this->classes[$key]);
459                 return true;
460             }
461         }
462         return false;
463     }
465     /**
466      * Sets the title for this node and forces Moodle to utilise it.
467      * @param string $title
468      */
469     public function title($title) {
470         $this->title = $title;
471         $this->forcetitle = true;
472     }
474     /**
475      * Resets the page specific information on this node if it is being unserialised.
476      */
477     public function __wakeup(){
478         $this->forceopen = false;
479         $this->isactive = false;
480         $this->remove_class('active_tree_node');
481     }
483     /**
484      * Checks if this node or any of its children contain the active node.
485      *
486      * Recursive.
487      *
488      * @return bool
489      */
490     public function contains_active_node() {
491         if ($this->isactive) {
492             return true;
493         } else {
494             foreach ($this->children as $child) {
495                 if ($child->isactive || $child->contains_active_node()) {
496                     return true;
497                 }
498             }
499         }
500         return false;
501     }
503     /**
504      * Finds the active node.
505      *
506      * Searches this nodes children plus all of the children for the active node
507      * and returns it if found.
508      *
509      * Recursive.
510      *
511      * @return navigation_node|false
512      */
513     public function find_active_node() {
514         if ($this->isactive) {
515             return $this;
516         } else {
517             foreach ($this->children as &$child) {
518                 $outcome = $child->find_active_node();
519                 if ($outcome !== false) {
520                     return $outcome;
521                 }
522             }
523         }
524         return false;
525     }
527     /**
528      * Searches all children for the best matching active node
529      * @return navigation_node|false
530      */
531     public function search_for_active_node() {
532         if ($this->check_if_active(URL_MATCH_BASE)) {
533             return $this;
534         } else {
535             foreach ($this->children as &$child) {
536                 $outcome = $child->search_for_active_node();
537                 if ($outcome !== false) {
538                     return $outcome;
539                 }
540             }
541         }
542         return false;
543     }
545     /**
546      * Gets the content for this node.
547      *
548      * @param bool $shorttext If true shorttext is used rather than the normal text
549      * @return string
550      */
551     public function get_content($shorttext=false) {
552         if ($shorttext && $this->shorttext!==null) {
553             return format_string($this->shorttext);
554         } else {
555             return format_string($this->text);
556         }
557     }
559     /**
560      * Gets the title to use for this node.
561      *
562      * @return string
563      */
564     public function get_title() {
565         if ($this->forcetitle || $this->action != null){
566             return $this->title;
567         } else {
568             return '';
569         }
570     }
572     /**
573      * Gets the CSS class to add to this node to describe its type
574      *
575      * @return string
576      */
577     public function get_css_type() {
578         if (array_key_exists($this->type, $this->namedtypes)) {
579             return 'type_'.$this->namedtypes[$this->type];
580         }
581         return 'type_unknown';
582     }
584     /**
585      * Finds all nodes that are expandable by AJAX
586      *
587      * @param array $expandable An array by reference to populate with expandable nodes.
588      */
589     public function find_expandable(array &$expandable) {
590         foreach ($this->children as &$child) {
591             if ($child->display && $child->has_children() && $child->children->count() == 0) {
592                 $child->id = 'expandable_branch_'.(count($expandable)+1);
593                 $this->add_class('canexpand');
594                 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
595             }
596             $child->find_expandable($expandable);
597         }
598     }
600     /**
601      * Finds all nodes of a given type (recursive)
602      *
603      * @param int $type One of navigation_node::TYPE_*
604      * @return array
605      */
606     public function find_all_of_type($type) {
607         $nodes = $this->children->type($type);
608         foreach ($this->children as &$node) {
609             $childnodes = $node->find_all_of_type($type);
610             $nodes = array_merge($nodes, $childnodes);
611         }
612         return $nodes;
613     }
615     /**
616      * Removes this node if it is empty
617      */
618     public function trim_if_empty() {
619         if ($this->children->count() == 0) {
620             $this->remove();
621         }
622     }
624     /**
625      * Creates a tab representation of this nodes children that can be used
626      * with print_tabs to produce the tabs on a page.
627      *
628      * call_user_func_array('print_tabs', $node->get_tabs_array());
629      *
630      * @param array $inactive
631      * @param bool $return
632      * @return array Array (tabs, selected, inactive, activated, return)
633      */
634     public function get_tabs_array(array $inactive=array(), $return=false) {
635         $tabs = array();
636         $rows = array();
637         $selected = null;
638         $activated = array();
639         foreach ($this->children as $node) {
640             $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
641             if ($node->contains_active_node()) {
642                 if ($node->children->count() > 0) {
643                     $activated[] = $node->key;
644                     foreach ($node->children as $child) {
645                         if ($child->contains_active_node()) {
646                             $selected = $child->key;
647                         }
648                         $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
649                     }
650                 } else {
651                     $selected = $node->key;
652                 }
653             }
654         }
655         return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
656     }
658     /**
659      * Sets the parent for this node and if this node is active ensures that the tree is properly
660      * adjusted as well.
661      *
662      * @param navigation_node $parent
663      */
664     public function set_parent(navigation_node $parent) {
665         // Set the parent (thats the easy part)
666         $this->parent = $parent;
667         // Check if this node is active (this is checked during construction)
668         if ($this->isactive) {
669             // Force all of the parent nodes open so you can see this node
670             $this->parent->force_open();
671             // Make all parents inactive so that its clear where we are.
672             $this->parent->make_inactive();
673         }
674     }
676     /**
677      * Hides the node and any children it has.
678      *
679      * @since 2.5
680      * @param array $typestohide Optional. An array of node types that should be hidden.
681      *      If null all nodes will be hidden.
682      *      If an array is given then nodes will only be hidden if their type mtatches an element in the array.
683      *          e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
684      */
685     public function hide(array $typestohide = null) {
686         if ($typestohide === null || in_array($this->type, $typestohide)) {
687             $this->display = false;
688             if ($this->has_children()) {
689                 foreach ($this->children as $child) {
690                     $child->hide($typestohide);
691                 }
692             }
693         }
694     }
697 /**
698  * Navigation node collection
699  *
700  * This class is responsible for managing a collection of navigation nodes.
701  * It is required because a node's unique identifier is a combination of both its
702  * key and its type.
703  *
704  * Originally an array was used with a string key that was a combination of the two
705  * however it was decided that a better solution would be to use a class that
706  * implements the standard IteratorAggregate interface.
707  *
708  * @package   core
709  * @category  navigation
710  * @copyright 2010 Sam Hemelryk
711  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
712  */
713 class navigation_node_collection implements IteratorAggregate {
714     /**
715      * A multidimensional array to where the first key is the type and the second
716      * key is the nodes key.
717      * @var array
718      */
719     protected $collection = array();
720     /**
721      * An array that contains references to nodes in the same order they were added.
722      * This is maintained as a progressive array.
723      * @var array
724      */
725     protected $orderedcollection = array();
726     /**
727      * A reference to the last node that was added to the collection
728      * @var navigation_node
729      */
730     protected $last = null;
731     /**
732      * The total number of items added to this array.
733      * @var int
734      */
735     protected $count = 0;
737     /**
738      * Adds a navigation node to the collection
739      *
740      * @param navigation_node $node Node to add
741      * @param string $beforekey If specified, adds before a node with this key,
742      *   otherwise adds at end
743      * @return navigation_node Added node
744      */
745     public function add(navigation_node $node, $beforekey=null) {
746         global $CFG;
747         $key = $node->key;
748         $type = $node->type;
750         // First check we have a 2nd dimension for this type
751         if (!array_key_exists($type, $this->orderedcollection)) {
752             $this->orderedcollection[$type] = array();
753         }
754         // Check for a collision and report if debugging is turned on
755         if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
756             debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
757         }
759         // Find the key to add before
760         $newindex = $this->count;
761         $last = true;
762         if ($beforekey !== null) {
763             foreach ($this->collection as $index => $othernode) {
764                 if ($othernode->key === $beforekey) {
765                     $newindex = $index;
766                     $last = false;
767                     break;
768                 }
769             }
770             if ($newindex === $this->count) {
771                 debugging('Navigation node add_before: Reference node not found ' . $beforekey .
772                         ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
773             }
774         }
776         // Add the node to the appropriate place in the by-type structure (which
777         // is not ordered, despite the variable name)
778         $this->orderedcollection[$type][$key] = $node;
779         if (!$last) {
780             // Update existing references in the ordered collection (which is the
781             // one that isn't called 'ordered') to shuffle them along if required
782             for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
783                 $this->collection[$oldindex] = $this->collection[$oldindex - 1];
784             }
785         }
786         // Add a reference to the node to the progressive collection.
787         $this->collection[$newindex] = $this->orderedcollection[$type][$key];
788         // Update the last property to a reference to this new node.
789         $this->last = $this->orderedcollection[$type][$key];
791         // Reorder the array by index if needed
792         if (!$last) {
793             ksort($this->collection);
794         }
795         $this->count++;
796         // Return the reference to the now added node
797         return $node;
798     }
800     /**
801      * Return a list of all the keys of all the nodes.
802      * @return array the keys.
803      */
804     public function get_key_list() {
805         $keys = array();
806         foreach ($this->collection as $node) {
807             $keys[] = $node->key;
808         }
809         return $keys;
810     }
812     /**
813      * Fetches a node from this collection.
814      *
815      * @param string|int $key The key of the node we want to find.
816      * @param int $type One of navigation_node::TYPE_*.
817      * @return navigation_node|null
818      */
819     public function get($key, $type=null) {
820         if ($type !== null) {
821             // If the type is known then we can simply check and fetch
822             if (!empty($this->orderedcollection[$type][$key])) {
823                 return $this->orderedcollection[$type][$key];
824             }
825         } else {
826             // Because we don't know the type we look in the progressive array
827             foreach ($this->collection as $node) {
828                 if ($node->key === $key) {
829                     return $node;
830                 }
831             }
832         }
833         return false;
834     }
836     /**
837      * Searches for a node with matching key and type.
838      *
839      * This function searches both the nodes in this collection and all of
840      * the nodes in each collection belonging to the nodes in this collection.
841      *
842      * Recursive.
843      *
844      * @param string|int $key  The key of the node we want to find.
845      * @param int $type  One of navigation_node::TYPE_*.
846      * @return navigation_node|null
847      */
848     public function find($key, $type=null) {
849         if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
850             return $this->orderedcollection[$type][$key];
851         } else {
852             $nodes = $this->getIterator();
853             // Search immediate children first
854             foreach ($nodes as &$node) {
855                 if ($node->key === $key && ($type === null || $type === $node->type)) {
856                     return $node;
857                 }
858             }
859             // Now search each childs children
860             foreach ($nodes as &$node) {
861                 $result = $node->children->find($key, $type);
862                 if ($result !== false) {
863                     return $result;
864                 }
865             }
866         }
867         return false;
868     }
870     /**
871      * Fetches the last node that was added to this collection
872      *
873      * @return navigation_node
874      */
875     public function last() {
876         return $this->last;
877     }
879     /**
880      * Fetches all nodes of a given type from this collection
881      *
882      * @param string|int $type  node type being searched for.
883      * @return array ordered collection
884      */
885     public function type($type) {
886         if (!array_key_exists($type, $this->orderedcollection)) {
887             $this->orderedcollection[$type] = array();
888         }
889         return $this->orderedcollection[$type];
890     }
891     /**
892      * Removes the node with the given key and type from the collection
893      *
894      * @param string|int $key The key of the node we want to find.
895      * @param int $type
896      * @return bool
897      */
898     public function remove($key, $type=null) {
899         $child = $this->get($key, $type);
900         if ($child !== false) {
901             foreach ($this->collection as $colkey => $node) {
902                 if ($node->key == $key && $node->type == $type) {
903                     unset($this->collection[$colkey]);
904                     break;
905                 }
906             }
907             unset($this->orderedcollection[$child->type][$child->key]);
908             $this->count--;
909             return true;
910         }
911         return false;
912     }
914     /**
915      * Gets the number of nodes in this collection
916      *
917      * This option uses an internal count rather than counting the actual options to avoid
918      * a performance hit through the count function.
919      *
920      * @return int
921      */
922     public function count() {
923         return $this->count;
924     }
925     /**
926      * Gets an array iterator for the collection.
927      *
928      * This is required by the IteratorAggregator interface and is used by routines
929      * such as the foreach loop.
930      *
931      * @return ArrayIterator
932      */
933     public function getIterator() {
934         return new ArrayIterator($this->collection);
935     }
938 /**
939  * The global navigation class used for... the global navigation
940  *
941  * This class is used by PAGE to store the global navigation for the site
942  * and is then used by the settings nav and navbar to save on processing and DB calls
943  *
944  * See
945  * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
946  * {@link lib/ajax/getnavbranch.php} Called by ajax
947  *
948  * @package   core
949  * @category  navigation
950  * @copyright 2009 Sam Hemelryk
951  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
952  */
953 class global_navigation extends navigation_node {
954     /** @var moodle_page The Moodle page this navigation object belongs to. */
955     protected $page;
956     /** @var bool switch to let us know if the navigation object is initialised*/
957     protected $initialised = false;
958     /** @var array An array of course information */
959     protected $mycourses = array();
960     /** @var array An array for containing  root navigation nodes */
961     protected $rootnodes = array();
962     /** @var bool A switch for whether to show empty sections in the navigation */
963     protected $showemptysections = true;
964     /** @var bool A switch for whether courses should be shown within categories on the navigation. */
965     protected $showcategories = null;
966     /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
967     protected $showmycategories = null;
968     /** @var array An array of stdClasses for users that the navigation is extended for */
969     protected $extendforuser = array();
970     /** @var navigation_cache */
971     protected $cache;
972     /** @var array An array of course ids that are present in the navigation */
973     protected $addedcourses = array();
974     /** @var bool */
975     protected $allcategoriesloaded = false;
976     /** @var array An array of category ids that are included in the navigation */
977     protected $addedcategories = array();
978     /** @var int expansion limit */
979     protected $expansionlimit = 0;
980     /** @var int userid to allow parent to see child's profile page navigation */
981     protected $useridtouseforparentchecks = 0;
983     /** Used when loading categories to load all top level categories [parent = 0] **/
984     const LOAD_ROOT_CATEGORIES = 0;
985     /** Used when loading categories to load all categories **/
986     const LOAD_ALL_CATEGORIES = -1;
988     /**
989      * Constructs a new global navigation
990      *
991      * @param moodle_page $page The page this navigation object belongs to
992      */
993     public function __construct(moodle_page $page) {
994         global $CFG, $SITE, $USER;
996         if (during_initial_install()) {
997             return;
998         }
1000         if (get_home_page() == HOMEPAGE_SITE) {
1001             // We are using the site home for the root element
1002             $properties = array(
1003                 'key' => 'home',
1004                 'type' => navigation_node::TYPE_SYSTEM,
1005                 'text' => get_string('home'),
1006                 'action' => new moodle_url('/')
1007             );
1008         } else {
1009             // We are using the users my moodle for the root element
1010             $properties = array(
1011                 'key' => 'myhome',
1012                 'type' => navigation_node::TYPE_SYSTEM,
1013                 'text' => get_string('myhome'),
1014                 'action' => new moodle_url('/my/')
1015             );
1016         }
1018         // Use the parents constructor.... good good reuse
1019         parent::__construct($properties);
1021         // Initalise and set defaults
1022         $this->page = $page;
1023         $this->forceopen = true;
1024         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1025     }
1027     /**
1028      * Mutator to set userid to allow parent to see child's profile
1029      * page navigation. See MDL-25805 for initial issue. Linked to it
1030      * is an issue explaining why this is a REALLY UGLY HACK thats not
1031      * for you to use!
1032      *
1033      * @param int $userid userid of profile page that parent wants to navigate around.
1034      */
1035     public function set_userid_for_parent_checks($userid) {
1036         $this->useridtouseforparentchecks = $userid;
1037     }
1040     /**
1041      * Initialises the navigation object.
1042      *
1043      * This causes the navigation object to look at the current state of the page
1044      * that it is associated with and then load the appropriate content.
1045      *
1046      * This should only occur the first time that the navigation structure is utilised
1047      * which will normally be either when the navbar is called to be displayed or
1048      * when a block makes use of it.
1049      *
1050      * @return bool
1051      */
1052     public function initialise() {
1053         global $CFG, $SITE, $USER;
1054         // Check if it has already been initialised
1055         if ($this->initialised || during_initial_install()) {
1056             return true;
1057         }
1058         $this->initialised = true;
1060         // Set up the five base root nodes. These are nodes where we will put our
1061         // content and are as follows:
1062         // site: Navigation for the front page.
1063         // myprofile: User profile information goes here.
1064         // currentcourse: The course being currently viewed.
1065         // mycourses: The users courses get added here.
1066         // courses: Additional courses are added here.
1067         // users: Other users information loaded here.
1068         $this->rootnodes = array();
1069         if (get_home_page() == HOMEPAGE_SITE) {
1070             // The home element should be my moodle because the root element is the site
1071             if (isloggedin() && !isguestuser()) {  // Makes no sense if you aren't logged in
1072                 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1073             }
1074         } else {
1075             // The home element should be the site because the root node is my moodle
1076             $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1077             if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1078                 // We need to stop automatic redirection
1079                 $this->rootnodes['home']->action->param('redirect', '0');
1080             }
1081         }
1082         $this->rootnodes['site'] = $this->add_course($SITE);
1083         $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1084         $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1085         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1086         $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1087         $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1089         // We always load the frontpage course to ensure it is available without
1090         // JavaScript enabled.
1091         $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1092         $this->load_course_sections($SITE, $this->rootnodes['site']);
1094         $course = $this->page->course;
1096         // $issite gets set to true if the current pages course is the sites frontpage course
1097         $issite = ($this->page->course->id == $SITE->id);
1098         // Determine if the user is enrolled in any course.
1099         $enrolledinanycourse = enrol_user_sees_own_courses();
1101         $this->rootnodes['currentcourse']->mainnavonly = true;
1102         if ($enrolledinanycourse) {
1103             $this->rootnodes['mycourses']->isexpandable = true;
1104             if ($CFG->navshowallcourses) {
1105                 // When we show all courses we need to show both the my courses and the regular courses branch.
1106                 $this->rootnodes['courses']->isexpandable = true;
1107             }
1108         } else {
1109             $this->rootnodes['courses']->isexpandable = true;
1110         }
1112         if ($this->rootnodes['mycourses']->isactive) {
1113             $this->load_courses_enrolled();
1114         }
1116         $canviewcourseprofile = true;
1118         // Next load context specific content into the navigation
1119         switch ($this->page->context->contextlevel) {
1120             case CONTEXT_SYSTEM :
1121                 // Nothing left to do here I feel.
1122                 break;
1123             case CONTEXT_COURSECAT :
1124                 // This is essential, we must load categories.
1125                 $this->load_all_categories($this->page->context->instanceid, true);
1126                 break;
1127             case CONTEXT_BLOCK :
1128             case CONTEXT_COURSE :
1129                 if ($issite) {
1130                     // Nothing left to do here.
1131                     break;
1132                 }
1134                 // Load the course associated with the current page into the navigation.
1135                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1136                 // If the course wasn't added then don't try going any further.
1137                 if (!$coursenode) {
1138                     $canviewcourseprofile = false;
1139                     break;
1140                 }
1142                 // If the user is not enrolled then we only want to show the
1143                 // course node and not populate it.
1145                 // Not enrolled, can't view, and hasn't switched roles
1146                 if (!can_access_course($course)) {
1147                     // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1148                     // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1149                     if (!$this->current_user_is_parent_role()) {
1150                         $coursenode->make_active();
1151                         $canviewcourseprofile = false;
1152                         break;
1153                     }
1154                 }
1156                 // Add the essentials such as reports etc...
1157                 $this->add_course_essentials($coursenode, $course);
1158                 // Extend course navigation with it's sections/activities
1159                 $this->load_course_sections($course, $coursenode);
1160                 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1161                     $coursenode->make_active();
1162                 }
1164                 break;
1165             case CONTEXT_MODULE :
1166                 if ($issite) {
1167                     // If this is the site course then most information will have
1168                     // already been loaded.
1169                     // However we need to check if there is more content that can
1170                     // yet be loaded for the specific module instance.
1171                     $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1172                     if ($activitynode) {
1173                         $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1174                     }
1175                     break;
1176                 }
1178                 $course = $this->page->course;
1179                 $cm = $this->page->cm;
1181                 // Load the course associated with the page into the navigation
1182                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1184                 // If the course wasn't added then don't try going any further.
1185                 if (!$coursenode) {
1186                     $canviewcourseprofile = false;
1187                     break;
1188                 }
1190                 // If the user is not enrolled then we only want to show the
1191                 // course node and not populate it.
1192                 if (!can_access_course($course)) {
1193                     $coursenode->make_active();
1194                     $canviewcourseprofile = false;
1195                     break;
1196                 }
1198                 $this->add_course_essentials($coursenode, $course);
1200                 // Load the course sections into the page
1201                 $this->load_course_sections($course, $coursenode, null, $cm);
1202                 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1203                 // Finally load the cm specific navigaton information
1204                 $this->load_activity($cm, $course, $activity);
1205                 // Check if we have an active ndoe
1206                 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1207                     // And make the activity node active.
1208                     $activity->make_active();
1209                 }
1210                 break;
1211             case CONTEXT_USER :
1212                 if ($issite) {
1213                     // The users profile information etc is already loaded
1214                     // for the front page.
1215                     break;
1216                 }
1217                 $course = $this->page->course;
1218                 // Load the course associated with the user into the navigation
1219                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1221                 // If the course wasn't added then don't try going any further.
1222                 if (!$coursenode) {
1223                     $canviewcourseprofile = false;
1224                     break;
1225                 }
1227                 // If the user is not enrolled then we only want to show the
1228                 // course node and not populate it.
1229                 if (!can_access_course($course)) {
1230                     $coursenode->make_active();
1231                     $canviewcourseprofile = false;
1232                     break;
1233                 }
1234                 $this->add_course_essentials($coursenode, $course);
1235                 $this->load_course_sections($course, $coursenode);
1236                 break;
1237         }
1239         // Load for the current user
1240         $this->load_for_user();
1241         if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1242             $this->load_for_user(null, true);
1243         }
1244         // Load each extending user into the navigation.
1245         foreach ($this->extendforuser as $user) {
1246             if ($user->id != $USER->id) {
1247                 $this->load_for_user($user);
1248             }
1249         }
1251         // Give the local plugins a chance to include some navigation if they want.
1252         foreach (get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1253             $function = "local_{$plugin}_extends_navigation";
1254             $oldfunction = "{$plugin}_extends_navigation";
1255             if (function_exists($function)) {
1256                 // This is the preferred function name as there is less chance of conflicts
1257                 $function($this);
1258             } else if (function_exists($oldfunction)) {
1259                 // We continue to support the old function name to ensure backwards compatibility
1260                 debugging("Deprecated local plugin navigation callback: Please rename '{$oldfunction}' to '{$function}'. Support for the old callback will be dropped after the release of 2.4", DEBUG_DEVELOPER);
1261                 $oldfunction($this);
1262             }
1263         }
1265         // Remove any empty root nodes
1266         foreach ($this->rootnodes as $node) {
1267             // Dont remove the home node
1268             if ($node->key !== 'home' && !$node->has_children()) {
1269                 $node->remove();
1270             }
1271         }
1273         if (!$this->contains_active_node()) {
1274             $this->search_for_active_node();
1275         }
1277         // If the user is not logged in modify the navigation structure as detailed
1278         // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1279         if (!isloggedin()) {
1280             $activities = clone($this->rootnodes['site']->children);
1281             $this->rootnodes['site']->remove();
1282             $children = clone($this->children);
1283             $this->children = new navigation_node_collection();
1284             foreach ($activities as $child) {
1285                 $this->children->add($child);
1286             }
1287             foreach ($children as $child) {
1288                 $this->children->add($child);
1289             }
1290         }
1291         return true;
1292     }
1294     /**
1295      * Returns true if the current user is a parent of the user being currently viewed.
1296      *
1297      * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1298      * other user being viewed this function returns false.
1299      * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1300      *
1301      * @since 2.4
1302      * @return bool
1303      */
1304     protected function current_user_is_parent_role() {
1305         global $USER, $DB;
1306         if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1307             $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1308             if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1309                 return false;
1310             }
1311             if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1312                 return true;
1313             }
1314         }
1315         return false;
1316     }
1318     /**
1319      * Returns true if courses should be shown within categories on the navigation.
1320      *
1321      * @param bool $ismycourse Set to true if you are calculating this for a course.
1322      * @return bool
1323      */
1324     protected function show_categories($ismycourse = false) {
1325         global $CFG, $DB;
1326         if ($ismycourse) {
1327             return $this->show_my_categories();
1328         }
1329         if ($this->showcategories === null) {
1330             $show = false;
1331             if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1332                 $show = true;
1333             } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1334                 $show = true;
1335             }
1336             $this->showcategories = $show;
1337         }
1338         return $this->showcategories;
1339     }
1341     /**
1342      * Returns true if we should show categories in the My Courses branch.
1343      * @return bool
1344      */
1345     protected function show_my_categories() {
1346         global $CFG, $DB;
1347         if ($this->showmycategories === null) {
1348             $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1349         }
1350         return $this->showmycategories;
1351     }
1353     /**
1354      * Loads the courses in Moodle into the navigation.
1355      *
1356      * @global moodle_database $DB
1357      * @param string|array $categoryids An array containing categories to load courses
1358      *                     for, OR null to load courses for all categories.
1359      * @return array An array of navigation_nodes one for each course
1360      */
1361     protected function load_all_courses($categoryids = null) {
1362         global $CFG, $DB, $SITE;
1364         // Work out the limit of courses.
1365         $limit = 20;
1366         if (!empty($CFG->navcourselimit)) {
1367             $limit = $CFG->navcourselimit;
1368         }
1370         $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1372         // If we are going to show all courses AND we are showing categories then
1373         // to save us repeated DB calls load all of the categories now
1374         if ($this->show_categories()) {
1375             $this->load_all_categories($toload);
1376         }
1378         // Will be the return of our efforts
1379         $coursenodes = array();
1381         // Check if we need to show categories.
1382         if ($this->show_categories()) {
1383             // Hmmm we need to show categories... this is going to be painful.
1384             // We now need to fetch up to $limit courses for each category to
1385             // be displayed.
1386             if ($categoryids !== null) {
1387                 if (!is_array($categoryids)) {
1388                     $categoryids = array($categoryids);
1389                 }
1390                 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1391                 $categorywhere = 'WHERE cc.id '.$categorywhere;
1392             } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1393                 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1394                 $categoryparams = array();
1395             } else {
1396                 $categorywhere = '';
1397                 $categoryparams = array();
1398             }
1400             // First up we are going to get the categories that we are going to
1401             // need so that we can determine how best to load the courses from them.
1402             $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1403                         FROM {course_categories} cc
1404                     LEFT JOIN {course} c ON c.category = cc.id
1405                             {$categorywhere}
1406                     GROUP BY cc.id";
1407             $categories = $DB->get_recordset_sql($sql, $categoryparams);
1408             $fullfetch = array();
1409             $partfetch = array();
1410             foreach ($categories as $category) {
1411                 if (!$this->can_add_more_courses_to_category($category->id)) {
1412                     continue;
1413                 }
1414                 if ($category->coursecount > $limit * 5) {
1415                     $partfetch[] = $category->id;
1416                 } else if ($category->coursecount > 0) {
1417                     $fullfetch[] = $category->id;
1418                 }
1419             }
1420             $categories->close();
1422             if (count($fullfetch)) {
1423                 // First up fetch all of the courses in categories where we know that we are going to
1424                 // need the majority of courses.
1425                 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1426                 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1427                 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1428                             FROM {course} c
1429                                 $ccjoin
1430                             WHERE c.category {$categoryids}
1431                         ORDER BY c.sortorder ASC";
1432                 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1433                 foreach ($coursesrs as $course) {
1434                     if ($course->id == $SITE->id) {
1435                         // This should not be necessary, frontpage is not in any category.
1436                         continue;
1437                     }
1438                     if (array_key_exists($course->id, $this->addedcourses)) {
1439                         // It is probably better to not include the already loaded courses
1440                         // directly in SQL because inequalities may confuse query optimisers
1441                         // and may interfere with query caching.
1442                         continue;
1443                     }
1444                     if (!$this->can_add_more_courses_to_category($course->category)) {
1445                         continue;
1446                     }
1447                     context_instance_preload($course);
1448                     if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1449                         continue;
1450                     }
1451                     $coursenodes[$course->id] = $this->add_course($course);
1452                 }
1453                 $coursesrs->close();
1454             }
1456             if (count($partfetch)) {
1457                 // Next we will work our way through the categories where we will likely only need a small
1458                 // proportion of the courses.
1459                 foreach ($partfetch as $categoryid) {
1460                     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1461                     $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1462                                 FROM {course} c
1463                                     $ccjoin
1464                                 WHERE c.category = :categoryid
1465                             ORDER BY c.sortorder ASC";
1466                     $courseparams = array('categoryid' => $categoryid);
1467                     $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1468                     foreach ($coursesrs as $course) {
1469                         if ($course->id == $SITE->id) {
1470                             // This should not be necessary, frontpage is not in any category.
1471                             continue;
1472                         }
1473                         if (array_key_exists($course->id, $this->addedcourses)) {
1474                             // It is probably better to not include the already loaded courses
1475                             // directly in SQL because inequalities may confuse query optimisers
1476                             // and may interfere with query caching.
1477                             // This also helps to respect expected $limit on repeated executions.
1478                             continue;
1479                         }
1480                         if (!$this->can_add_more_courses_to_category($course->category)) {
1481                             break;
1482                         }
1483                         context_instance_preload($course);
1484                         if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1485                             continue;
1486                         }
1487                         $coursenodes[$course->id] = $this->add_course($course);
1488                     }
1489                     $coursesrs->close();
1490                 }
1491             }
1492         } else {
1493             // Prepare the SQL to load the courses and their contexts
1494             list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1495             list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1496             $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1497                         FROM {course} c
1498                             $ccjoin
1499                         WHERE c.id {$courseids}
1500                     ORDER BY c.sortorder ASC";
1501             $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1502             foreach ($coursesrs as $course) {
1503                 if ($course->id == $SITE->id) {
1504                     // frotpage is not wanted here
1505                     continue;
1506                 }
1507                 if ($this->page->course && ($this->page->course->id == $course->id)) {
1508                     // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1509                     continue;
1510                 }
1511                 context_instance_preload($course);
1512                 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1513                     continue;
1514                 }
1515                 $coursenodes[$course->id] = $this->add_course($course);
1516                 if (count($coursenodes) >= $limit) {
1517                     break;
1518                 }
1519             }
1520             $coursesrs->close();
1521         }
1523         return $coursenodes;
1524     }
1526     /**
1527      * Returns true if more courses can be added to the provided category.
1528      *
1529      * @param int|navigation_node|stdClass $category
1530      * @return bool
1531      */
1532     protected function can_add_more_courses_to_category($category) {
1533         global $CFG;
1534         $limit = 20;
1535         if (!empty($CFG->navcourselimit)) {
1536             $limit = (int)$CFG->navcourselimit;
1537         }
1538         if (is_numeric($category)) {
1539             if (!array_key_exists($category, $this->addedcategories)) {
1540                 return true;
1541             }
1542             $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1543         } else if ($category instanceof navigation_node) {
1544             if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1545                 return false;
1546             }
1547             $coursecount = count($category->children->type(self::TYPE_COURSE));
1548         } else if (is_object($category) && property_exists($category,'id')) {
1549             $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1550         }
1551         return ($coursecount <= $limit);
1552     }
1554     /**
1555      * Loads all categories (top level or if an id is specified for that category)
1556      *
1557      * @param int $categoryid The category id to load or null/0 to load all base level categories
1558      * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1559      *        as the requested category and any parent categories.
1560      * @return navigation_node|void returns a navigation node if a category has been loaded.
1561      */
1562     protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1563         global $CFG, $DB;
1565         // Check if this category has already been loaded
1566         if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1567             return true;
1568         }
1570         $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1571         $sqlselect = "SELECT cc.*, $catcontextsql
1572                       FROM {course_categories} cc
1573                       JOIN {context} ctx ON cc.id = ctx.instanceid";
1574         $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1575         $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1576         $params = array();
1578         $categoriestoload = array();
1579         if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1580             // We are going to load all categories regardless... prepare to fire
1581             // on the database server!
1582         } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1583             // We are going to load all of the first level categories (categories without parents)
1584             $sqlwhere .= " AND cc.parent = 0";
1585         } else if (array_key_exists($categoryid, $this->addedcategories)) {
1586             // The category itself has been loaded already so we just need to ensure its subcategories
1587             // have been loaded
1588             list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1589             if ($showbasecategories) {
1590                 // We need to include categories with parent = 0 as well
1591                 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1592             } else {
1593                 // All we need is categories that match the parent
1594                 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1595             }
1596             $params['categoryid'] = $categoryid;
1597         } else {
1598             // This category hasn't been loaded yet so we need to fetch it, work out its category path
1599             // and load this category plus all its parents and subcategories
1600             $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1601             $categoriestoload = explode('/', trim($category->path, '/'));
1602             list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1603             // We are going to use select twice so double the params
1604             $params = array_merge($params, $params);
1605             $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1606             $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1607         }
1609         $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1610         $categories = array();
1611         foreach ($categoriesrs as $category) {
1612             // Preload the context.. we'll need it when adding the category in order
1613             // to format the category name.
1614             context_helper::preload_from_record($category);
1615             if (array_key_exists($category->id, $this->addedcategories)) {
1616                 // Do nothing, its already been added.
1617             } else if ($category->parent == '0') {
1618                 // This is a root category lets add it immediately
1619                 $this->add_category($category, $this->rootnodes['courses']);
1620             } else if (array_key_exists($category->parent, $this->addedcategories)) {
1621                 // This categories parent has already been added we can add this immediately
1622                 $this->add_category($category, $this->addedcategories[$category->parent]);
1623             } else {
1624                 $categories[] = $category;
1625             }
1626         }
1627         $categoriesrs->close();
1629         // Now we have an array of categories we need to add them to the navigation.
1630         while (!empty($categories)) {
1631             $category = reset($categories);
1632             if (array_key_exists($category->id, $this->addedcategories)) {
1633                 // Do nothing
1634             } else if ($category->parent == '0') {
1635                 $this->add_category($category, $this->rootnodes['courses']);
1636             } else if (array_key_exists($category->parent, $this->addedcategories)) {
1637                 $this->add_category($category, $this->addedcategories[$category->parent]);
1638             } else {
1639                 // This category isn't in the navigation and niether is it's parent (yet).
1640                 // We need to go through the category path and add all of its components in order.
1641                 $path = explode('/', trim($category->path, '/'));
1642                 foreach ($path as $catid) {
1643                     if (!array_key_exists($catid, $this->addedcategories)) {
1644                         // This category isn't in the navigation yet so add it.
1645                         $subcategory = $categories[$catid];
1646                         if ($subcategory->parent == '0') {
1647                             // Yay we have a root category - this likely means we will now be able
1648                             // to add categories without problems.
1649                             $this->add_category($subcategory, $this->rootnodes['courses']);
1650                         } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1651                             // The parent is in the category (as we'd expect) so add it now.
1652                             $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1653                             // Remove the category from the categories array.
1654                             unset($categories[$catid]);
1655                         } else {
1656                             // We should never ever arrive here - if we have then there is a bigger
1657                             // problem at hand.
1658                             throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1659                         }
1660                     }
1661                 }
1662             }
1663             // Remove the category from the categories array now that we know it has been added.
1664             unset($categories[$category->id]);
1665         }
1666         if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1667             $this->allcategoriesloaded = true;
1668         }
1669         // Check if there are any categories to load.
1670         if (count($categoriestoload) > 0) {
1671             $readytoloadcourses = array();
1672             foreach ($categoriestoload as $category) {
1673                 if ($this->can_add_more_courses_to_category($category)) {
1674                     $readytoloadcourses[] = $category;
1675                 }
1676             }
1677             if (count($readytoloadcourses)) {
1678                 $this->load_all_courses($readytoloadcourses);
1679             }
1680         }
1682         // Look for all categories which have been loaded
1683         if (!empty($this->addedcategories)) {
1684             $categoryids = array();
1685             foreach ($this->addedcategories as $category) {
1686                 if ($this->can_add_more_courses_to_category($category)) {
1687                     $categoryids[] = $category->key;
1688                 }
1689             }
1690             if ($categoryids) {
1691                 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1692                 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1693                 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1694                           FROM {course_categories} cc
1695                           JOIN {course} c ON c.category = cc.id
1696                          WHERE cc.id {$categoriessql}
1697                       GROUP BY cc.id
1698                         HAVING COUNT(c.id) > :limit";
1699                 $excessivecategories = $DB->get_records_sql($sql, $params);
1700                 foreach ($categories as &$category) {
1701                     if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1702                         $url = new moodle_url('/course/category.php', array('id'=>$category->key));
1703                         $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1704                     }
1705                 }
1706             }
1707         }
1708     }
1710     /**
1711      * Adds a structured category to the navigation in the correct order/place
1712      *
1713      * @param stdClass $category category to be added in navigation.
1714      * @param navigation_node $parent parent navigation node
1715      * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1716      * @return void.
1717      */
1718     protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1719         if (array_key_exists($category->id, $this->addedcategories)) {
1720             return;
1721         }
1722         $url = new moodle_url('/course/category.php', array('id' => $category->id));
1723         $context = context_coursecat::instance($category->id);
1724         $categoryname = format_string($category->name, true, array('context' => $context));
1725         $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1726         if (empty($category->visible)) {
1727             if (has_capability('moodle/category:viewhiddencategories', get_system_context())) {
1728                 $categorynode->hidden = true;
1729             } else {
1730                 $categorynode->display = false;
1731             }
1732         }
1733         $this->addedcategories[$category->id] = $categorynode;
1734     }
1736     /**
1737      * Loads the given course into the navigation
1738      *
1739      * @param stdClass $course
1740      * @return navigation_node
1741      */
1742     protected function load_course(stdClass $course) {
1743         global $SITE;
1744         if ($course->id == $SITE->id) {
1745             // This is always loaded during initialisation
1746             return $this->rootnodes['site'];
1747         } else if (array_key_exists($course->id, $this->addedcourses)) {
1748             // The course has already been loaded so return a reference
1749             return $this->addedcourses[$course->id];
1750         } else {
1751             // Add the course
1752             return $this->add_course($course);
1753         }
1754     }
1756     /**
1757      * Loads all of the courses section into the navigation.
1758      *
1759      * This function calls method from current course format, see
1760      * {@link format_base::extend_course_navigation()}
1761      * If course module ($cm) is specified but course format failed to create the node,
1762      * the activity node is created anyway.
1763      *
1764      * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1765      *
1766      * @param stdClass $course Database record for the course
1767      * @param navigation_node $coursenode The course node within the navigation
1768      * @param null|int $sectionnum If specified load the contents of section with this relative number
1769      * @param null|cm_info $cm If specified make sure that activity node is created (either
1770      *    in containg section or by calling load_stealth_activity() )
1771      */
1772     protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1773         global $CFG, $SITE;
1774         require_once($CFG->dirroot.'/course/lib.php');
1775         if (isset($cm->sectionnum)) {
1776             $sectionnum = $cm->sectionnum;
1777         }
1778         if ($sectionnum !== null) {
1779             $this->includesectionnum = $sectionnum;
1780         }
1781         course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1782         if (isset($cm->id)) {
1783             $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1784             if (empty($activity)) {
1785                 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1786             }
1787         }
1788    }
1790     /**
1791      * Generates an array of sections and an array of activities for the given course.
1792      *
1793      * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1794      *
1795      * @param stdClass $course
1796      * @return array Array($sections, $activities)
1797      */
1798     protected function generate_sections_and_activities(stdClass $course) {
1799         global $CFG;
1800         require_once($CFG->dirroot.'/course/lib.php');
1802         $modinfo = get_fast_modinfo($course);
1803         $sections = $modinfo->get_section_info_all();
1805         // For course formats using 'numsections' trim the sections list
1806         $courseformatoptions = course_get_format($course)->get_format_options();
1807         if (isset($courseformatoptions['numsections'])) {
1808             $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1809         }
1811         $activities = array();
1813         foreach ($sections as $key => $section) {
1814             // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1815             $sections[$key] = clone($section);
1816             unset($sections[$key]->summary);
1817             $sections[$key]->hasactivites = false;
1818             if (!array_key_exists($section->section, $modinfo->sections)) {
1819                 continue;
1820             }
1821             foreach ($modinfo->sections[$section->section] as $cmid) {
1822                 $cm = $modinfo->cms[$cmid];
1823                 if (!$cm->uservisible) {
1824                     continue;
1825                 }
1826                 $activity = new stdClass;
1827                 $activity->id = $cm->id;
1828                 $activity->course = $course->id;
1829                 $activity->section = $section->section;
1830                 $activity->name = $cm->name;
1831                 $activity->icon = $cm->icon;
1832                 $activity->iconcomponent = $cm->iconcomponent;
1833                 $activity->hidden = (!$cm->visible);
1834                 $activity->modname = $cm->modname;
1835                 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1836                 $activity->onclick = $cm->get_on_click();
1837                 $url = $cm->get_url();
1838                 if (!$url) {
1839                     $activity->url = null;
1840                     $activity->display = false;
1841                 } else {
1842                     $activity->url = $cm->get_url()->out();
1843                     $activity->display = true;
1844                     if (self::module_extends_navigation($cm->modname)) {
1845                         $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1846                     }
1847                 }
1848                 $activities[$cmid] = $activity;
1849                 if ($activity->display) {
1850                     $sections[$key]->hasactivites = true;
1851                 }
1852             }
1853         }
1855         return array($sections, $activities);
1856     }
1858     /**
1859      * Generically loads the course sections into the course's navigation.
1860      *
1861      * @param stdClass $course
1862      * @param navigation_node $coursenode
1863      * @return array An array of course section nodes
1864      */
1865     public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1866         global $CFG, $DB, $USER, $SITE;
1867         require_once($CFG->dirroot.'/course/lib.php');
1869         list($sections, $activities) = $this->generate_sections_and_activities($course);
1871         $navigationsections = array();
1872         foreach ($sections as $sectionid => $section) {
1873             $section = clone($section);
1874             if ($course->id == $SITE->id) {
1875                 $this->load_section_activities($coursenode, $section->section, $activities);
1876             } else {
1877                 if (!$section->uservisible || (!$this->showemptysections &&
1878                         !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1879                     continue;
1880                 }
1882                 $sectionname = get_section_name($course, $section);
1883                 $url = course_get_url($course, $section->section, array('navigation' => true));
1885                 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1886                 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1887                 $sectionnode->hidden = (!$section->visible || !$section->available);
1888                 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1889                     $this->load_section_activities($sectionnode, $section->section, $activities);
1890                 }
1891                 $section->sectionnode = $sectionnode;
1892                 $navigationsections[$sectionid] = $section;
1893             }
1894         }
1895         return $navigationsections;
1896     }
1898     /**
1899      * Loads all of the activities for a section into the navigation structure.
1900      *
1901      * @param navigation_node $sectionnode
1902      * @param int $sectionnumber
1903      * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1904      * @param stdClass $course The course object the section and activities relate to.
1905      * @return array Array of activity nodes
1906      */
1907     protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1908         global $CFG, $SITE;
1909         // A static counter for JS function naming
1910         static $legacyonclickcounter = 0;
1912         $activitynodes = array();
1913         if (empty($activities)) {
1914             return $activitynodes;
1915         }
1917         if (!is_object($course)) {
1918             $activity = reset($activities);
1919             $courseid = $activity->course;
1920         } else {
1921             $courseid = $course->id;
1922         }
1923         $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1925         foreach ($activities as $activity) {
1926             if ($activity->section != $sectionnumber) {
1927                 continue;
1928             }
1929             if ($activity->icon) {
1930                 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1931             } else {
1932                 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1933             }
1935             // Prepare the default name and url for the node
1936             $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1937             $action = new moodle_url($activity->url);
1939             // Check if the onclick property is set (puke!)
1940             if (!empty($activity->onclick)) {
1941                 // Increment the counter so that we have a unique number.
1942                 $legacyonclickcounter++;
1943                 // Generate the function name we will use
1944                 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1945                 $propogrationhandler = '';
1946                 // Check if we need to cancel propogation. Remember inline onclick
1947                 // events would return false if they wanted to prevent propogation and the
1948                 // default action.
1949                 if (strpos($activity->onclick, 'return false')) {
1950                     $propogrationhandler = 'e.halt();';
1951                 }
1952                 // Decode the onclick - it has already been encoded for display (puke)
1953                 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
1954                 // Build the JS function the click event will call
1955                 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1956                 $this->page->requires->js_init_code($jscode);
1957                 // Override the default url with the new action link
1958                 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1959             }
1961             $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1962             $activitynode->title(get_string('modulename', $activity->modname));
1963             $activitynode->hidden = $activity->hidden;
1964             $activitynode->display = $showactivities && $activity->display;
1965             $activitynode->nodetype = $activity->nodetype;
1966             $activitynodes[$activity->id] = $activitynode;
1967         }
1969         return $activitynodes;
1970     }
1971     /**
1972      * Loads a stealth module from unavailable section
1973      * @param navigation_node $coursenode
1974      * @param stdClass $modinfo
1975      * @return navigation_node or null if not accessible
1976      */
1977     protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1978         if (empty($modinfo->cms[$this->page->cm->id])) {
1979             return null;
1980         }
1981         $cm = $modinfo->cms[$this->page->cm->id];
1982         if (!$cm->uservisible) {
1983             return null;
1984         }
1985         if ($cm->icon) {
1986             $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1987         } else {
1988             $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1989         }
1990         $url = $cm->get_url();
1991         $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1992         $activitynode->title(get_string('modulename', $cm->modname));
1993         $activitynode->hidden = (!$cm->visible);
1994         if (!$url) {
1995             // Don't show activities that don't have links!
1996             $activitynode->display = false;
1997         } else if (self::module_extends_navigation($cm->modname)) {
1998             $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1999         }
2000         return $activitynode;
2001     }
2002     /**
2003      * Loads the navigation structure for the given activity into the activities node.
2004      *
2005      * This method utilises a callback within the modules lib.php file to load the
2006      * content specific to activity given.
2007      *
2008      * The callback is a method: {modulename}_extend_navigation()
2009      * Examples:
2010      *  * {@link forum_extend_navigation()}
2011      *  * {@link workshop_extend_navigation()}
2012      *
2013      * @param cm_info|stdClass $cm
2014      * @param stdClass $course
2015      * @param navigation_node $activity
2016      * @return bool
2017      */
2018     protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2019         global $CFG, $DB;
2021         // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2022         if (!($cm instanceof cm_info)) {
2023             $modinfo = get_fast_modinfo($course);
2024             $cm = $modinfo->get_cm($cm->id);
2025         }
2026         $activity->nodetype = navigation_node::NODETYPE_LEAF;
2027         $activity->make_active();
2028         $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2029         $function = $cm->modname.'_extend_navigation';
2031         if (file_exists($file)) {
2032             require_once($file);
2033             if (function_exists($function)) {
2034                 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2035                 $function($activity, $course, $activtyrecord, $cm);
2036             }
2037         }
2039         // Allow the active advanced grading method plugin to append module navigation
2040         $featuresfunc = $cm->modname.'_supports';
2041         if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2042             require_once($CFG->dirroot.'/grade/grading/lib.php');
2043             $gradingman = get_grading_manager($cm->context, $cm->modname);
2044             $gradingman->extend_navigation($this, $activity);
2045         }
2047         return $activity->has_children();
2048     }
2049     /**
2050      * Loads user specific information into the navigation in the appropriate place.
2051      *
2052      * If no user is provided the current user is assumed.
2053      *
2054      * @param stdClass $user
2055      * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2056      * @return bool
2057      */
2058     protected function load_for_user($user=null, $forceforcontext=false) {
2059         global $DB, $CFG, $USER, $SITE;
2061         if ($user === null) {
2062             // We can't require login here but if the user isn't logged in we don't
2063             // want to show anything
2064             if (!isloggedin() || isguestuser()) {
2065                 return false;
2066             }
2067             $user = $USER;
2068         } else if (!is_object($user)) {
2069             // If the user is not an object then get them from the database
2070             $select = context_helper::get_preload_record_columns_sql('ctx');
2071             $sql = "SELECT u.*, $select
2072                       FROM {user} u
2073                       JOIN {context} ctx ON u.id = ctx.instanceid
2074                      WHERE u.id = :userid AND
2075                            ctx.contextlevel = :contextlevel";
2076             $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2077             context_helper::preload_from_record($user);
2078         }
2080         $iscurrentuser = ($user->id == $USER->id);
2082         $usercontext = context_user::instance($user->id);
2084         // Get the course set against the page, by default this will be the site
2085         $course = $this->page->course;
2086         $baseargs = array('id'=>$user->id);
2087         if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2088             $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2089             $baseargs['course'] = $course->id;
2090             $coursecontext = context_course::instance($course->id);
2091             $issitecourse = false;
2092         } else {
2093             // Load all categories and get the context for the system
2094             $coursecontext = context_system::instance();
2095             $issitecourse = true;
2096         }
2098         // Create a node to add user information under.
2099         if ($iscurrentuser && !$forceforcontext) {
2100             // If it's the current user the information will go under the profile root node
2101             $usernode = $this->rootnodes['myprofile'];
2102             $course = get_site();
2103             $coursecontext = context_course::instance($course->id);
2104             $issitecourse = true;
2105         } else {
2106             if (!$issitecourse) {
2107                 // Not the current user so add it to the participants node for the current course
2108                 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2109                 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2110             } else {
2111                 // This is the site so add a users node to the root branch
2112                 $usersnode = $this->rootnodes['users'];
2113                 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2114                     $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2115                 }
2116                 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2117             }
2118             if (!$usersnode) {
2119                 // We should NEVER get here, if the course hasn't been populated
2120                 // with a participants node then the navigaiton either wasn't generated
2121                 // for it (you are missing a require_login or set_context call) or
2122                 // you don't have access.... in the interests of no leaking informatin
2123                 // we simply quit...
2124                 return false;
2125             }
2126             // Add a branch for the current user
2127             $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2128             $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2130             if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2131                 $usernode->make_active();
2132             }
2133         }
2135         // If the user is the current user or has permission to view the details of the requested
2136         // user than add a view profile link.
2137         if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2138             if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2139                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2140             } else {
2141                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2142             }
2143         }
2145         if (!empty($CFG->navadduserpostslinks)) {
2146             // Add nodes for forum posts and discussions if the user can view either or both
2147             // There are no capability checks here as the content of the page is based
2148             // purely on the forums the current user has access too.
2149             $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2150             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2151             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2152         }
2154         // Add blog nodes
2155         if (!empty($CFG->enableblogs)) {
2156             if (!$this->cache->cached('userblogoptions'.$user->id)) {
2157                 require_once($CFG->dirroot.'/blog/lib.php');
2158                 // Get all options for the user
2159                 $options = blog_get_options_for_user($user);
2160                 $this->cache->set('userblogoptions'.$user->id, $options);
2161             } else {
2162                 $options = $this->cache->{'userblogoptions'.$user->id};
2163             }
2165             if (count($options) > 0) {
2166                 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2167                 foreach ($options as $type => $option) {
2168                     if ($type == "rss") {
2169                         $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2170                     } else {
2171                         $blogs->add($option['string'], $option['link']);
2172                     }
2173                 }
2174             }
2175         }
2177         if (!empty($CFG->messaging)) {
2178             $messageargs = null;
2179             if ($USER->id != $user->id) {
2180                 $messageargs = array('user1' => $user->id);
2181             }
2182             $url = new moodle_url('/message/index.php',$messageargs);
2183             $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2184         }
2186         if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2187             $url = new moodle_url('/user/files.php');
2188             $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2189         }
2191         if (!empty($CFG->enablebadges) && $iscurrentuser &&
2192                 has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2193             $url = new moodle_url('/badges/mybadges.php');
2194             $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2195         }
2197         // Add a node to view the users notes if permitted
2198         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2199             $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2200             if ($coursecontext->instanceid) {
2201                 $url->param('course', $coursecontext->instanceid);
2202             }
2203             $usernode->add(get_string('notes', 'notes'), $url);
2204         }
2206         // If the user is the current user add the repositories for the current user
2207         $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2208         if ($iscurrentuser) {
2209             if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2210                 require_once($CFG->dirroot . '/repository/lib.php');
2211                 $editabletypes = repository::get_editable_types($usercontext);
2212                 $haseditabletypes = !empty($editabletypes);
2213                 unset($editabletypes);
2214                 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2215             } else {
2216                 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2217             }
2218             if ($haseditabletypes) {
2219                 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2220             }
2221         } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2223             // Add view grade report is permitted
2224             $reports = get_plugin_list('gradereport');
2225             arsort($reports); // user is last, we want to test it first
2227             $userscourses = enrol_get_users_courses($user->id);
2228             $userscoursesnode = $usernode->add(get_string('courses'));
2230             foreach ($userscourses as $usercourse) {
2231                 $usercoursecontext = context_course::instance($usercourse->id);
2232                 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2233                 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2235                 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2236                 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2237                     foreach ($reports as $plugin => $plugindir) {
2238                         if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2239                             //stop when the first visible plugin is found
2240                             $gradeavailable = true;
2241                             break;
2242                         }
2243                     }
2244                 }
2246                 if ($gradeavailable) {
2247                     $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2248                     $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2249                 }
2251                 // Add a node to view the users notes if permitted
2252                 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2253                     $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2254                     $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2255                 }
2257                 if (can_access_course($usercourse, $user->id)) {
2258                     $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', ''));
2259                 }
2261                 $reporttab = $usercoursenode->add(get_string('activityreports'));
2263                 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2264                 foreach ($reports as $reportfunction) {
2265                     $reportfunction($reporttab, $user, $usercourse);
2266                 }
2268                 $reporttab->trim_if_empty();
2269             }
2270         }
2271         return true;
2272     }
2274     /**
2275      * This method simply checks to see if a given module can extend the navigation.
2276      *
2277      * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2278      *
2279      * @param string $modname
2280      * @return bool
2281      */
2282     public static function module_extends_navigation($modname) {
2283         global $CFG;
2284         static $extendingmodules = array();
2285         if (!array_key_exists($modname, $extendingmodules)) {
2286             $extendingmodules[$modname] = false;
2287             $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2288             if (file_exists($file)) {
2289                 $function = $modname.'_extend_navigation';
2290                 require_once($file);
2291                 $extendingmodules[$modname] = (function_exists($function));
2292             }
2293         }
2294         return $extendingmodules[$modname];
2295     }
2296     /**
2297      * Extends the navigation for the given user.
2298      *
2299      * @param stdClass $user A user from the database
2300      */
2301     public function extend_for_user($user) {
2302         $this->extendforuser[] = $user;
2303     }
2305     /**
2306      * Returns all of the users the navigation is being extended for
2307      *
2308      * @return array An array of extending users.
2309      */
2310     public function get_extending_users() {
2311         return $this->extendforuser;
2312     }
2313     /**
2314      * Adds the given course to the navigation structure.
2315      *
2316      * @param stdClass $course
2317      * @param bool $forcegeneric
2318      * @param bool $ismycourse
2319      * @return navigation_node
2320      */
2321     public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2322         global $CFG, $SITE;
2324         // We found the course... we can return it now :)
2325         if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2326             return $this->addedcourses[$course->id];
2327         }
2329         $coursecontext = context_course::instance($course->id);
2331         if ($course->id != $SITE->id && !$course->visible) {
2332             if (is_role_switched($course->id)) {
2333                 // user has to be able to access course in order to switch, let's skip the visibility test here
2334             } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2335                 return false;
2336             }
2337         }
2339         $issite = ($course->id == $SITE->id);
2340         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2341         $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2342         // This is the name that will be shown for the course.
2343         $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2345         if ($issite) {
2346             $parent = $this;
2347             $url = null;
2348             if (empty($CFG->usesitenameforsitepages)) {
2349                 $coursename = get_string('sitepages');
2350             }
2351         } else if ($coursetype == self::COURSE_CURRENT) {
2352             $parent = $this->rootnodes['currentcourse'];
2353             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2354         } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2355             if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2356                 // Nothing to do here the above statement set $parent to the category within mycourses.
2357             } else {
2358                 $parent = $this->rootnodes['mycourses'];
2359             }
2360             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2361         } else {
2362             $parent = $this->rootnodes['courses'];
2363             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2364             if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2365                 if (!$this->is_category_fully_loaded($course->category)) {
2366                     // We need to load the category structure for this course
2367                     $this->load_all_categories($course->category, false);
2368                 }
2369                 if (array_key_exists($course->category, $this->addedcategories)) {
2370                     $parent = $this->addedcategories[$course->category];
2371                     // This could lead to the course being created so we should check whether it is the case again
2372                     if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2373                         return $this->addedcourses[$course->id];
2374                     }
2375                 }
2376             }
2377         }
2379         $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2380         $coursenode->nodetype = self::NODETYPE_BRANCH;
2381         $coursenode->hidden = (!$course->visible);
2382         $coursenode->title($fullname);
2383         if (!$forcegeneric) {
2384             $this->addedcourses[$course->id] = $coursenode;
2385         }
2387         return $coursenode;
2388     }
2390     /**
2391      * Returns true if the category has already been loaded as have any child categories
2392      *
2393      * @param int $categoryid
2394      * @return bool
2395      */
2396     protected function is_category_fully_loaded($categoryid) {
2397         return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2398     }
2400     /**
2401      * Adds essential course nodes to the navigation for the given course.
2402      *
2403      * This method adds nodes such as reports, blogs and participants
2404      *
2405      * @param navigation_node $coursenode
2406      * @param stdClass $course
2407      * @return bool returns true on successful addition of a node.
2408      */
2409     public function add_course_essentials($coursenode, stdClass $course) {
2410         global $CFG, $SITE;
2412         if ($course->id == $SITE->id) {
2413             return $this->add_front_page_course_essentials($coursenode, $course);
2414         }
2416         if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2417             return true;
2418         }
2420         //Participants
2421         if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2422             $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2423             $currentgroup = groups_get_course_group($course, true);
2424             if ($course->id == $SITE->id) {
2425                 $filtervar = 'courseid';
2426                 $filterselect = '';
2427             } else if ($course->id && !$currentgroup) {
2428                 $filtervar = 'courseid';
2429                 $filterselect = $course->id;
2430             } else {
2431                 $filtervar = 'groupid';
2432                 $filterselect = $currentgroup;
2433             }
2434             $filterselect = clean_param($filterselect, PARAM_INT);
2435             if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2436                and has_capability('moodle/blog:view', context_system::instance())) {
2437                 $blogsurls = new moodle_url('/blog/index.php', array($filtervar => $filterselect));
2438                 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2439             }
2440             if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2441                 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2442             }
2443         } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2444             $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2445         }
2447         // View course reports
2448         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
2449             $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
2450             $coursereports = get_plugin_list('coursereport'); // deprecated
2451             foreach ($coursereports as $report=>$dir) {
2452                 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
2453                 if (file_exists($libfile)) {
2454                     require_once($libfile);
2455                     $reportfunction = $report.'_report_extend_navigation';
2456                     if (function_exists($report.'_report_extend_navigation')) {
2457                         $reportfunction($reportnav, $course, $this->page->context);
2458                     }
2459                 }
2460             }
2462             $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
2463             foreach ($reports as $reportfunction) {
2464                 $reportfunction($reportnav, $course, $this->page->context);
2465             }
2466         }
2468         // Badges.
2469         if ($CFG->enablebadges && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2470             $url = new moodle_url($CFG->wwwroot . '/badges/view.php',
2471                     array('type' => 2, 'id' => $course->id));
2473             $coursenode->add(get_string('coursebadges', 'badges'), null,
2474                     navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2475             $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2476                     navigation_node::TYPE_SETTING, null, 'badgesview',
2477                     new pix_icon('i/badge', get_string('badgesview', 'badges')));
2478         }
2480         return true;
2481     }
2482     /**
2483      * This generates the structure of the course that won't be generated when
2484      * the modules and sections are added.
2485      *
2486      * Things such as the reports branch, the participants branch, blogs... get
2487      * added to the course node by this method.
2488      *
2489      * @param navigation_node $coursenode
2490      * @param stdClass $course
2491      * @return bool True for successfull generation
2492      */
2493     public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2494         global $CFG;
2496         if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2497             return true;
2498         }
2500         // Hidden node that we use to determine if the front page navigation is loaded.
2501         // This required as there are not other guaranteed nodes that may be loaded.
2502         $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2504         //Participants
2505         if (has_capability('moodle/course:viewparticipants',  get_system_context())) {
2506             $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2507         }
2509         $filterselect = 0;
2511         // Blogs
2512         if (!empty($CFG->enableblogs)
2513           and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2514           and has_capability('moodle/blog:view', context_system::instance())) {
2515             $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2516             $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2517         }
2519         //Badges
2520         if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2521             $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2522             $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2523         }
2525         // Notes
2526         if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2527             $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2528         }
2530         // Tags
2531         if (!empty($CFG->usetags) && isloggedin()) {
2532             $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2533         }
2535         if (isloggedin()) {
2536             // Calendar
2537             $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2538             $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2539         }
2541         return true;
2542     }
2544     /**
2545      * Clears the navigation cache
2546      */
2547     public function clear_cache() {
2548         $this->cache->clear();
2549     }
2551     /**
2552      * Sets an expansion limit for the navigation
2553      *
2554      * The expansion limit is used to prevent the display of content that has a type
2555      * greater than the provided $type.
2556      *
2557      * Can be used to ensure things such as activities or activity content don't get
2558      * shown on the navigation.
2559      * They are still generated in order to ensure the navbar still makes sense.
2560      *
2561      * @param int $type One of navigation_node::TYPE_*
2562      * @return bool true when complete.
2563      */
2564     public function set_expansion_limit($type) {
2565         global $SITE;
2566         $nodes = $this->find_all_of_type($type);
2568         // We only want to hide specific types of nodes.
2569         // Only nodes that represent "structure" in the navigation tree should be hidden.
2570         // If we hide all nodes then we risk hiding vital information.
2571         $typestohide = array(
2572             self::TYPE_CATEGORY,
2573             self::TYPE_COURSE,
2574             self::TYPE_SECTION,
2575             self::TYPE_ACTIVITY
2576         );
2578         foreach ($nodes as $node) {
2579             // We need to generate the full site node
2580             if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2581                 continue;
2582             }
2583             foreach ($node->children as $child) {
2584                 $child->hide($typestohide);
2585             }
2586         }
2587         return true;
2588     }
2589     /**
2590      * Attempts to get the navigation with the given key from this nodes children.
2591      *
2592      * This function only looks at this nodes children, it does NOT look recursivily.
2593      * If the node can't be found then false is returned.
2594      *
2595      * If you need to search recursivily then use the {@link global_navigation::find()} method.
2596      *
2597      * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2598      * may be of more use to you.
2599      *
2600      * @param string|int $key The key of the node you wish to receive.
2601      * @param int $type One of navigation_node::TYPE_*
2602      * @return navigation_node|false
2603      */
2604     public function get($key, $type = null) {
2605         if (!$this->initialised) {
2606             $this->initialise();
2607         }
2608         return parent::get($key, $type);
2609     }
2611     /**
2612      * Searches this nodes children and their children to find a navigation node
2613      * with the matching key and type.
2614      *
2615      * This method is recursive and searches children so until either a node is
2616      * found or there are no more nodes to search.
2617      *
2618      * If you know that the node being searched for is a child of this node
2619      * then use the {@link global_navigation::get()} method instead.
2620      *
2621      * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2622      * may be of more use to you.
2623      *
2624      * @param string|int $key The key of the node you wish to receive.
2625      * @param int $type One of navigation_node::TYPE_*
2626      * @return navigation_node|false
2627      */
2628     public function find($key, $type) {
2629         if (!$this->initialised) {
2630             $this->initialise();
2631         }
2632         if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2633             return $this->rootnodes[$key];
2634         }
2635         return parent::find($key, $type);
2636     }
2638     /**
2639      * They've expanded the 'my courses' branch.
2640      */
2641     protected function load_courses_enrolled() {
2642         global $CFG, $DB;
2643         $sortorder = 'visible DESC';
2644         // Prevent undefined $CFG->navsortmycoursessort errors.
2645         if (empty($CFG->navsortmycoursessort)) {
2646             $CFG->navsortmycoursessort = 'sortorder';
2647         }
2648         // Append the chosen sortorder.
2649         $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2650         $courses = enrol_get_my_courses(null, $sortorder);
2651         if (count($courses) && $this->show_my_categories()) {
2652             // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2653             // In order to make sure we load everything required we must first find the categories that are not
2654             // base categories and work out the bottom category in thier path.
2655             $categoryids = array();
2656             foreach ($courses as $course) {
2657                 $categoryids[] = $course->category;
2658             }
2659             $categoryids = array_unique($categoryids);
2660             list($sql, $params) = $DB->get_in_or_equal($categoryids);
2661             $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2662             foreach ($categories as $category) {
2663                 $bits = explode('/', trim($category->path,'/'));
2664                 $categoryids[] = array_shift($bits);
2665             }
2666             $categoryids = array_unique($categoryids);
2667             $categories->close();
2669             // Now we load the base categories.
2670             list($sql, $params) = $DB->get_in_or_equal($categoryids);
2671             $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2672             foreach ($categories as $category) {
2673                 $this->add_category($category, $this->rootnodes['mycourses']);
2674             }
2675             $categories->close();
2676         } else {
2677             foreach ($courses as $course) {
2678                 $this->add_course($course, false, self::COURSE_MY);
2679             }
2680         }
2681     }
2684 /**
2685  * The global navigation class used especially for AJAX requests.
2686  *
2687  * The primary methods that are used in the global navigation class have been overriden
2688  * to ensure that only the relevant branch is generated at the root of the tree.
2689  * This can be done because AJAX is only used when the backwards structure for the
2690  * requested branch exists.
2691  * This has been done only because it shortens the amounts of information that is generated
2692  * which of course will speed up the response time.. because no one likes laggy AJAX.
2693  *
2694  * @package   core
2695  * @category  navigation
2696  * @copyright 2009 Sam Hemelryk
2697  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2698  */
2699 class global_navigation_for_ajax extends global_navigation {
2701     /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2702     protected $branchtype;
2704     /** @var int the instance id */
2705     protected $instanceid;
2707     /** @var array Holds an array of expandable nodes */
2708     protected $expandable = array();
2710     /**
2711      * Constructs the navigation for use in an AJAX request
2712      *
2713      * @param moodle_page $page moodle_page object
2714      * @param int $branchtype
2715      * @param int $id
2716      */
2717     public function __construct($page, $branchtype, $id) {
2718         $this->page = $page;
2719         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2720         $this->children = new navigation_node_collection();
2721         $this->branchtype = $branchtype;
2722         $this->instanceid = $id;
2723         $this->initialise();
2724     }
2725     /**
2726      * Initialise the navigation given the type and id for the branch to expand.
2727      *
2728      * @return array An array of the expandable nodes
2729      */
2730     public function initialise() {
2731         global $DB, $SITE;
2733         if ($this->initialised || during_initial_install()) {
2734             return $this->expandable;
2735         }
2736         $this->initialised = true;
2738         $this->rootnodes = array();
2739         $this->rootnodes['site']    = $this->add_course($SITE);
2740         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2741         $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2743         // Branchtype will be one of navigation_node::TYPE_*
2744         switch ($this->branchtype) {
2745             case 0:
2746                 if ($this->instanceid === 'mycourses') {
2747                     $this->load_courses_enrolled();
2748                 } else if ($this->instanceid === 'courses') {
2749                     $this->load_courses_other();
2750                 }
2751                 break;
2752             case self::TYPE_CATEGORY :
2753                 $this->load_category($this->instanceid);
2754                 break;
2755             case self::TYPE_MY_CATEGORY :
2756                 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2757                 break;
2758             case self::TYPE_COURSE :
2759                 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
2760                 require_course_login($course, true, null, false, true);
2761                 $this->page->set_context(context_course::instance($course->id));
2762                 $coursenode = $this->add_course($course);
2763                 $this->add_course_essentials($coursenode, $course);
2764                 $this->load_course_sections($course, $coursenode);
2765                 break;
2766             case self::TYPE_SECTION :
2767                 $sql = 'SELECT c.*, cs.section AS sectionnumber
2768                         FROM {course} c
2769                         LEFT JOIN {course_sections} cs ON cs.course = c.id
2770                         WHERE cs.id = ?';
2771                 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
2772                 require_course_login($course, true, null, false, true);
2773                 $this->page->set_context(context_course::instance($course->id));
2774                 $coursenode = $this->add_course($course);
2775                 $this->add_course_essentials($coursenode, $course);
2776                 $this->load_course_sections($course, $coursenode, $course->sectionnumber);
2777                 break;
2778             case self::TYPE_ACTIVITY :
2779                 $sql = "SELECT c.*
2780                           FROM {course} c
2781                           JOIN {course_modules} cm ON cm.course = c.id
2782                          WHERE cm.id = :cmid";
2783                 $params = array('cmid' => $this->instanceid);
2784                 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2785                 $modinfo = get_fast_modinfo($course);
2786                 $cm = $modinfo->get_cm($this->instanceid);
2787                 require_course_login($course, true, $cm, false, true);
2788                 $this->page->set_context(context_module::instance($cm->id));
2789                 $coursenode = $this->load_course($course);
2790                 if ($course->id != $SITE->id) {
2791                     $this->load_course_sections($course, $coursenode, null, $cm);
2792                 }
2793                 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2794                 break;
2795             default:
2796                 throw new Exception('Unknown type');
2797                 return $this->expandable;
2798         }
2800         if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2801             $this->load_for_user(null, true);
2802         }
2804         $this->find_expandable($this->expandable);
2805         return $this->expandable;
2806     }
2808     /**
2809      * They've expanded the general 'courses' branch.
2810      */
2811     protected function load_courses_other() {
2812         $this->load_all_courses();
2813     }
2815     /**
2816      * Loads a single category into the AJAX navigation.
2817      *
2818      * This function is special in that it doesn't concern itself with the parent of
2819      * the requested category or its siblings.
2820      * This is because with the AJAX navigation we know exactly what is wanted and only need to
2821      * request that.
2822      *
2823      * @global moodle_database $DB
2824      * @param int $categoryid id of category to load in navigation.
2825      * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2826      * @return void.
2827      */
2828     protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2829         global $CFG, $DB;
2831         $limit = 20;
2832         if (!empty($CFG->navcourselimit)) {
2833             $limit = (int)$CFG->navcourselimit;
2834         }
2836         $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2837         $sql = "SELECT cc.*, $catcontextsql
2838                   FROM {course_categories} cc
2839                   JOIN {context} ctx ON cc.id = ctx.instanceid
2840                  WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2841                        (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2842               ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2843         $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2844         $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2845         $categorylist = array();
2846         $subcategories = array();
2847         $basecategory = null;
2848         foreach ($categories as $category) {
2849             $categorylist[] = $category->id;
2850             context_helper::preload_from_record($category);
2851             if ($category->id == $categoryid) {
2852                 $this->add_category($category, $this, $nodetype);
2853                 $basecategory = $this->addedcategories[$category->id];
2854             } else {
2855                 $subcategories[] = $category;
2856             }
2857         }
2858         $categories->close();
2860         if (!is_null($basecategory)) {
2861             foreach ($subcategories as $category) {
2862                 $this->add_category($category, $basecategory, $nodetype);
2863             }
2864         }
2866         // If category is shown in MyHome then only show enrolled courses, else show all courses.
2867         if ($nodetype === self::TYPE_MY_CATEGORY) {
2868             $courses = enrol_get_my_courses();
2869             foreach ($courses as $course) {
2870                 // Add course if it's in category.
2871                 if (in_array($course->category, $categorylist)) {
2872                     $this->add_course($course, true, self::COURSE_MY);
2873                 }
2874             }
2875         } else {
2876             $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2877             foreach ($courses as $course) {
2878                 $this->add_course($course);
2879             }
2880             $courses->close();
2881         }
2882     }
2884     /**
2885      * Returns an array of expandable nodes
2886      * @return array
2887      */
2888     public function get_expandable() {
2889         return $this->expandable;
2890     }
2893 /**
2894  * Navbar class
2895  *
2896  * This class is used to manage the navbar, which is initialised from the navigation
2897  * object held by PAGE
2898  *
2899  * @package   core
2900  * @category  navigation
2901  * @copyright 2009 Sam Hemelryk
2902  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2903  */
2904 class navbar extends navigation_node {
2905     /** @var bool A switch for whether the navbar is initialised or not */
2906     protected $initialised = false;
2907     /** @var mixed keys used to reference the nodes on the navbar */
2908     protected $keys = array();
2909     /** @var null|string content of the navbar */
2910     protected $content = null;
2911     /** @var moodle_page object the moodle page that this navbar belongs to */
2912     protected $page;
2913     /** @var bool A switch for whether to ignore the active navigation information */
2914     protected $ignoreactive = false;
2915     /** @var bool A switch to let us know if we are in the middle of an install */
2916     protected $duringinstall = false;
2917     /** @var bool A switch for whether the navbar has items */
2918     protected $hasitems = false;
2919     /** @var array An array of navigation nodes for the navbar */
2920     protected $items;
2921     /** @var array An array of child node objects */
2922     public $children = array();
2923     /** @var bool A switch for whether we want to include the root node in the navbar */
2924     public $includesettingsbase = false;
2925     /**
2926      * The almighty constructor
2927      *
2928      * @param moodle_page $page
2929      */
2930     public function __construct(moodle_page $page) {
2931         global $CFG;
2932         if (during_initial_install()) {
2933             $this->duringinstall = true;
2934             return false;
2935         }
2936         $this->page = $page;
2937         $this->text = get_string('home');
2938         $this->shorttext = get_string('home');
2939         $this->action = new moodle_url($CFG->wwwroot);
2940         $this->nodetype = self::NODETYPE_BRANCH;
2941         $this->type = self::TYPE_SYSTEM;
2942     }
2944     /**
2945      * Quick check to see if the navbar will have items in.
2946      *
2947      * @return bool Returns true if the navbar will have items, false otherwise
2948      */
2949     public function has_items() {
2950         if ($this->duringinstall) {
2951             return false;
2952         } else if ($this->hasitems !== false) {
2953             return true;
2954         }
2955         $this->page->navigation->initialise($this->page);
2957         $activenodefound = ($this->page->navigation->contains_active_node() ||
2958                             $this->page->settingsnav->contains_active_node());
2960         $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2961         $this->hasitems = $outcome;
2962         return $outcome;
2963     }
2965     /**
2966      * Turn on/off ignore active
2967      *
2968      * @param bool $setting
2969      */
2970     public function ignore_active($setting=true) {
2971         $this->ignoreactive = ($setting);
2972     }
2974     /**
2975      * Gets a navigation node
2976      *
2977      * @param string|int $key for referencing the navbar nodes
2978      * @param int $type navigation_node::TYPE_*
2979      * @return navigation_node|bool
2980      */
2981     public function get($key, $type = null) {
2982         foreach ($this->children as &$child) {
2983             if ($child->key === $key && ($type == null || $type == $child->type)) {
2984                 return $child;
2985             }
2986         }
2987         return false;
2988     }
2989     /**
2990      * Returns an array of navigation_node's that make up the navbar.
2991      *
2992      * @return array
2993      */
2994     public function get_items() {
2995         $items = array();
2996         // Make sure that navigation is initialised
2997         if (!$this->has_items()) {
2998             return $items;
2999         }
3000         if ($this->items !== null) {
3001             return $this->items;
3002         }
3004         if (count($this->children) > 0) {
3005             // Add the custom children
3006             $items = array_reverse($this->children);
3007         }
3009         $navigationactivenode = $this->page->navigation->find_active_node();
3010         $settingsactivenode = $this->page->settingsnav->find_active_node();
3012         // Check if navigation contains the active node
3013         if (!$this->ignoreactive) {
3015             if ($navigationactivenode && $settingsactivenode) {
3016                 // Parse a combined navigation tree
3017                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3018                     if (!$settingsactivenode->mainnavonly) {
3019                         $items[] = $settingsactivenode;
3020                     }
3021                     $settingsactivenode = $settingsactivenode->parent;
3022                 }
3023                 if (!$this->includesettingsbase) {
3024                     // Removes the first node from the settings (root node) from the list
3025                     array_pop($items);
3026                 }
3027                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3028                     if (!$navigationactivenode->mainnavonly) {
3029                         $items[] = $navigationactivenode;
3030                     }
3031                     $navigationactivenode = $navigationactivenode->parent;
3032                 }
3033             } else if ($navigationactivenode) {
3034                 // Parse the navigation tree to get the active node
3035                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3036                     if (!$navigationactivenode->mainnavonly) {
3037                         $items[] = $navigationactivenode;
3038                     }
3039                     $navigationactivenode = $navigationactivenode->parent;
3040                 }
3041             } else if ($settingsactivenode) {
3042                 // Parse the settings navigation to get the active node
3043                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3044                     if (!$settingsactivenode->mainnavonly) {
3045                         $items[] = $settingsactivenode;
3046                     }
3047                     $settingsactivenode = $settingsactivenode->parent;
3048                 }
3049             }
3050         }
3052         $items[] = new navigation_node(array(
3053             'text'=>$this->page->navigation->text,
3054             'shorttext'=>$this->page->navigation->shorttext,
3055             'key'=>$this->page->navigation->key,
3056             'action'=>$this->page->navigation->action
3057         ));
3059         $this->items = array_reverse($items);
3060         return $this->items;
3061     }
3063     /**
3064      * Add a new navigation_node to the navbar, overrides parent::add
3065      *
3066      * This function overrides {@link navigation_node::add()} so that we can change
3067      * the way nodes get added to allow us to simply call add and have the node added to the
3068      * end of the navbar
3069      *
3070      * @param string $text
3071      * @param string|moodle_url|action_link $action An action to associate with this node.
3072      * @param int $type One of navigation_node::TYPE_*
3073      * @param string $shorttext
3074      * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3075      * @param pix_icon $icon An optional icon to use for this node.
3076      * @return navigation_node
3077      */
3078     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3079         if ($this->content !== null) {
3080             debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3081         }
3083         // Properties array used when creating the new navigation node
3084         $itemarray = array(
3085             'text' => $text,
3086             'type' => $type
3087         );
3088         // Set the action if one was provided
3089         if ($action!==null) {
3090             $itemarray['action'] = $action;
3091         }
3092         // Set the shorttext if one was provided
3093         if ($shorttext!==null) {
3094             $itemarray['shorttext'] = $shorttext;
3095         }
3096         // Set the icon if one was provided
3097         if ($icon!==null) {
3098             $itemarray['icon'] = $icon;
3099         }
3100         // Default the key to the number of children if not provided
3101         if ($key === null) {
3102             $key = count($this->children);
3103         }
3104         // Set the key
3105         $itemarray['key'] = $key;
3106         // Set the parent to this node
3107         $itemarray['parent'] = $this;
3108         // Add the child using the navigation_node_collections add method
3109         $this->children[] = new navigation_node($itemarray);
3110         return $this;
3111     }
3114 /**
3115  * Class used to manage the settings option for the current page
3116  *
3117  * This class is used to manage the settings options in a tree format (recursively)
3118  * and was created initially for use with the settings blocks.
3119  *
3120  * @package   core
3121  * @category  navigation
3122  * @copyright 2009 Sam Hemelryk
3123  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3124  */
3125 class settings_navigation extends navigation_node {
3126     /** @var stdClass the current context */
3127     protected $context;
3128     /** @var moodle_page the moodle page that the navigation belongs to */
3129     protected $page;
3130     /** @var string contains administration section navigation_nodes */
3131     protected $adminsection;
3132     /** @var bool A switch to see if the navigation node is initialised */
3133     protected $initialised = false;
3134     /** @var array An array of users that the nodes can extend for. */
3135     protected $userstoextendfor = array();
3136     /** @var navigation_cache **/
3137     protected $cache;
3139     /**
3140      * Sets up the object with basic settings and preparse it for use
3141      *
3142      * @param moodle_page $page
3143      */
3144     public function __construct(moodle_page &$page) {
3145         if (during_initial_install()) {
3146             return false;
3147         }
3148         $this->page = $page;
3149         // Initialise the main navigation. It is most important that this is done
3150         // before we try anything
3151         $this->page->navigation->initialise();
3152         // Initialise the navigation cache
3153         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3154         $this->children = new navigation_node_collection();
3155     }
3156     /**
3157      * Initialise the settings navigation based on the current context
3158      *
3159      * This function initialises the settings navigation tree for a given context
3160      * by calling supporting functions to generate major parts of the tree.
3161      *
3162      */
3163     public function initialise() {
3164         global $DB, $SESSION, $SITE;
3166         if (during_initial_install()) {
3167             return false;
3168         } else if ($this->initialised) {
3169             return true;
3170         }
3171         $this->id = 'settingsnav';
3172         $this->context = $this->page->context;
3174         $context = $this->context;
3175         if ($context->contextlevel == CONTEXT_BLOCK) {
3176             $this->load_block_settings();
3177             $context = $context->get_parent_context();
3178         }
3180         switch ($context->contextlevel) {
3181             case CONTEXT_SYSTEM:
3182                 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3183                     $this->load_front_page_settings(($context->id == $this->context->id));
3184                 }
3185                 break;
3186             case CONTEXT_COURSECAT:
3187                 $this->load_category_settings();
3188                 break;
3189             case CONTEXT_COURSE:
3190                 if ($this->page->course->id != $SITE->id) {
3191                     $this->load_course_settings(($context->id == $this->context->id));
3192                 } else {
3193                     $this->load_front_page_settings(($context->id == $this->context->id));
3194                 }
3195                 break;
3196             case CONTEXT_MODULE:
3197                 $this->load_module_settings();
3198                 $this->load_course_settings();
3199                 break;
3200             case CONTEXT_USER:
3201                 if ($this->page->course->id != $SITE->id) {
3202                     $this->load_course_settings();
3203                 }
3204                 break;
3205         }
3207         $settings = $this->load_user_settings($this->page->course->id);
3209         if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3210             $admin = $this->load_administration_settings();
3211             $SESSION->load_navigation_admin = ($admin->has_children());
3212         } else {
3213             $admin = false;
3214         }
3216         if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3217             $admin->force_open();
3218         } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3219             $settings->force_open();
3220         }
3222         // Check if the user is currently logged in as another user
3223         if (session_is_loggedinas()) {
3224             // Get the actual user, we need this so we can display an informative return link
3225             $realuser = session_get_realuser();
3226             // Add the informative return to original user link
3227             $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3228             $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3229         }
3231         // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
3232         $this->load_local_plugin_settings();
3234         foreach ($this->children as $key=>$node) {
3235             if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
3236                 $node->remove();
3237             }
3238         }
3239         $this->initialised = true;
3240     }
3241     /**
3242      * Override the parent function so that we can add preceeding hr's and set a
3243      * root node class against all first level element
3244      *
3245      * It does this by first calling the parent's add method {@link navigation_node::add()}
3246      * and then proceeds to use the key to set class and hr
3247      *
3248      * @param string $text text to be used for the link.
3249      * @param string|moodle_url $url url for the new node
3250      * @param int $type the type of node navigation_node::TYPE_*
3251      * @param string $shorttext
3252      * @param string|int $key a key to access the node by.
3253      * @param pix_icon $icon An icon that appears next to the node.
3254      * @return navigation_node with the new node added to it.
3255      */
3256     public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3257         $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
3258         $node->add_class('root_node');
3259         return $node;
3260     }
3262     /**
3263      * This function allows the user to add something to the start of the settings
3264      * navigation, which means it will be at the top of the settings navigation block
3265      *
3266      * @param string $text text to be used for the link.
3267      * @param string|moodle_url $url url for the new node
3268      * @param int $type the type of node navigation_node::TYPE_*
3269      * @param string $shorttext
3270      * @param string|int $key a key to access the node by.
3271      * @param pix_icon $icon An icon that appears next to the node.
3272      * @return navigation_node $node with the new node added to it.
3273      */
3274     public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
3275         $children = $this->children;
3276         $childrenclass = get_class($children);
3277         $this->children = new $childrenclass;
3278         $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
3279         foreach ($children as $child) {
3280             $this->children->add($child);
3281         }
3282         return $node;
3283     }
3284     /**
3285      * Load the site administration tree
3286      *
3287      * This function loads the site administration tree by using the lib/adminlib library functions
3288      *
3289      * @param navigation_node $referencebranch A reference to a branch in the settings
3290      *      navigation tree
3291      * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
3292      *      tree and start at the beginning
3293      * @return mixed A key to access the admin tree by
3294      */
3295     protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
3296         global $CFG;
3298         // Check if we are just starting to generate this navigation.
3299         if ($referencebranch === null) {
3301             // Require the admin lib then get an admin structure
3302             if (!function_exists('admin_get_root')) {
3303                 require_once($CFG->dirroot.'/lib/adminlib.php');
3304             }
3305             $adminroot = admin_get_root(false, false);
3306             // This is the active section identifier