Merge branch 'wip-MDL-32191-m26' of git://github.com/samhemelryk/moodle
[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_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
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                     $this->collection = array_values($this->collection);
905                     break;
906                 }
907             }
908             unset($this->orderedcollection[$child->type][$child->key]);
909             $this->count--;
910             return true;
911         }
912         return false;
913     }
915     /**
916      * Gets the number of nodes in this collection
917      *
918      * This option uses an internal count rather than counting the actual options to avoid
919      * a performance hit through the count function.
920      *
921      * @return int
922      */
923     public function count() {
924         return $this->count;
925     }
926     /**
927      * Gets an array iterator for the collection.
928      *
929      * This is required by the IteratorAggregator interface and is used by routines
930      * such as the foreach loop.
931      *
932      * @return ArrayIterator
933      */
934     public function getIterator() {
935         return new ArrayIterator($this->collection);
936     }
939 /**
940  * The global navigation class used for... the global navigation
941  *
942  * This class is used by PAGE to store the global navigation for the site
943  * and is then used by the settings nav and navbar to save on processing and DB calls
944  *
945  * See
946  * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
947  * {@link lib/ajax/getnavbranch.php} Called by ajax
948  *
949  * @package   core
950  * @category  navigation
951  * @copyright 2009 Sam Hemelryk
952  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
953  */
954 class global_navigation extends navigation_node {
955     /** @var moodle_page The Moodle page this navigation object belongs to. */
956     protected $page;
957     /** @var bool switch to let us know if the navigation object is initialised*/
958     protected $initialised = false;
959     /** @var array An array of course information */
960     protected $mycourses = array();
961     /** @var array An array for containing  root navigation nodes */
962     protected $rootnodes = array();
963     /** @var bool A switch for whether to show empty sections in the navigation */
964     protected $showemptysections = true;
965     /** @var bool A switch for whether courses should be shown within categories on the navigation. */
966     protected $showcategories = null;
967     /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
968     protected $showmycategories = null;
969     /** @var array An array of stdClasses for users that the navigation is extended for */
970     protected $extendforuser = array();
971     /** @var navigation_cache */
972     protected $cache;
973     /** @var array An array of course ids that are present in the navigation */
974     protected $addedcourses = array();
975     /** @var bool */
976     protected $allcategoriesloaded = false;
977     /** @var array An array of category ids that are included in the navigation */
978     protected $addedcategories = array();
979     /** @var int expansion limit */
980     protected $expansionlimit = 0;
981     /** @var int userid to allow parent to see child's profile page navigation */
982     protected $useridtouseforparentchecks = 0;
984     /** Used when loading categories to load all top level categories [parent = 0] **/
985     const LOAD_ROOT_CATEGORIES = 0;
986     /** Used when loading categories to load all categories **/
987     const LOAD_ALL_CATEGORIES = -1;
989     /**
990      * Constructs a new global navigation
991      *
992      * @param moodle_page $page The page this navigation object belongs to
993      */
994     public function __construct(moodle_page $page) {
995         global $CFG, $SITE, $USER;
997         if (during_initial_install()) {
998             return;
999         }
1001         if (get_home_page() == HOMEPAGE_SITE) {
1002             // We are using the site home for the root element
1003             $properties = array(
1004                 'key' => 'home',
1005                 'type' => navigation_node::TYPE_SYSTEM,
1006                 'text' => get_string('home'),
1007                 'action' => new moodle_url('/')
1008             );
1009         } else {
1010             // We are using the users my moodle for the root element
1011             $properties = array(
1012                 'key' => 'myhome',
1013                 'type' => navigation_node::TYPE_SYSTEM,
1014                 'text' => get_string('myhome'),
1015                 'action' => new moodle_url('/my/')
1016             );
1017         }
1019         // Use the parents constructor.... good good reuse
1020         parent::__construct($properties);
1022         // Initalise and set defaults
1023         $this->page = $page;
1024         $this->forceopen = true;
1025         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1026     }
1028     /**
1029      * Mutator to set userid to allow parent to see child's profile
1030      * page navigation. See MDL-25805 for initial issue. Linked to it
1031      * is an issue explaining why this is a REALLY UGLY HACK thats not
1032      * for you to use!
1033      *
1034      * @param int $userid userid of profile page that parent wants to navigate around.
1035      */
1036     public function set_userid_for_parent_checks($userid) {
1037         $this->useridtouseforparentchecks = $userid;
1038     }
1041     /**
1042      * Initialises the navigation object.
1043      *
1044      * This causes the navigation object to look at the current state of the page
1045      * that it is associated with and then load the appropriate content.
1046      *
1047      * This should only occur the first time that the navigation structure is utilised
1048      * which will normally be either when the navbar is called to be displayed or
1049      * when a block makes use of it.
1050      *
1051      * @return bool
1052      */
1053     public function initialise() {
1054         global $CFG, $SITE, $USER;
1055         // Check if it has already been initialised
1056         if ($this->initialised || during_initial_install()) {
1057             return true;
1058         }
1059         $this->initialised = true;
1061         // Set up the five base root nodes. These are nodes where we will put our
1062         // content and are as follows:
1063         // site: Navigation for the front page.
1064         // myprofile: User profile information goes here.
1065         // currentcourse: The course being currently viewed.
1066         // mycourses: The users courses get added here.
1067         // courses: Additional courses are added here.
1068         // users: Other users information loaded here.
1069         $this->rootnodes = array();
1070         if (get_home_page() == HOMEPAGE_SITE) {
1071             // The home element should be my moodle because the root element is the site
1072             if (isloggedin() && !isguestuser()) {  // Makes no sense if you aren't logged in
1073                 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1074             }
1075         } else {
1076             // The home element should be the site because the root node is my moodle
1077             $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1078             if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1079                 // We need to stop automatic redirection
1080                 $this->rootnodes['home']->action->param('redirect', '0');
1081             }
1082         }
1083         $this->rootnodes['site'] = $this->add_course($SITE);
1084         $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
1085         $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1086         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my/'), self::TYPE_ROOTNODE, null, 'mycourses');
1087         $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1088         $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1090         // We always load the frontpage course to ensure it is available without
1091         // JavaScript enabled.
1092         $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1093         $this->load_course_sections($SITE, $this->rootnodes['site']);
1095         $course = $this->page->course;
1097         // $issite gets set to true if the current pages course is the sites frontpage course
1098         $issite = ($this->page->course->id == $SITE->id);
1099         // Determine if the user is enrolled in any course.
1100         $enrolledinanycourse = enrol_user_sees_own_courses();
1102         $this->rootnodes['currentcourse']->mainnavonly = true;
1103         if ($enrolledinanycourse) {
1104             $this->rootnodes['mycourses']->isexpandable = true;
1105             if ($CFG->navshowallcourses) {
1106                 // When we show all courses we need to show both the my courses and the regular courses branch.
1107                 $this->rootnodes['courses']->isexpandable = true;
1108             }
1109         } else {
1110             $this->rootnodes['courses']->isexpandable = true;
1111         }
1113         if ($this->rootnodes['mycourses']->isactive) {
1114             $this->load_courses_enrolled();
1115         }
1117         $canviewcourseprofile = true;
1119         // Next load context specific content into the navigation
1120         switch ($this->page->context->contextlevel) {
1121             case CONTEXT_SYSTEM :
1122                 // Nothing left to do here I feel.
1123                 break;
1124             case CONTEXT_COURSECAT :
1125                 // This is essential, we must load categories.
1126                 $this->load_all_categories($this->page->context->instanceid, true);
1127                 break;
1128             case CONTEXT_BLOCK :
1129             case CONTEXT_COURSE :
1130                 if ($issite) {
1131                     // Nothing left to do here.
1132                     break;
1133                 }
1135                 // Load the course associated with the current page into the navigation.
1136                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1137                 // If the course wasn't added then don't try going any further.
1138                 if (!$coursenode) {
1139                     $canviewcourseprofile = false;
1140                     break;
1141                 }
1143                 // If the user is not enrolled then we only want to show the
1144                 // course node and not populate it.
1146                 // Not enrolled, can't view, and hasn't switched roles
1147                 if (!can_access_course($course)) {
1148                     // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1149                     // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1150                     if (!$this->current_user_is_parent_role()) {
1151                         $coursenode->make_active();
1152                         $canviewcourseprofile = false;
1153                         break;
1154                     }
1155                 }
1157                 // Add the essentials such as reports etc...
1158                 $this->add_course_essentials($coursenode, $course);
1159                 // Extend course navigation with it's sections/activities
1160                 $this->load_course_sections($course, $coursenode);
1161                 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1162                     $coursenode->make_active();
1163                 }
1165                 break;
1166             case CONTEXT_MODULE :
1167                 if ($issite) {
1168                     // If this is the site course then most information will have
1169                     // already been loaded.
1170                     // However we need to check if there is more content that can
1171                     // yet be loaded for the specific module instance.
1172                     $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1173                     if ($activitynode) {
1174                         $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1175                     }
1176                     break;
1177                 }
1179                 $course = $this->page->course;
1180                 $cm = $this->page->cm;
1182                 // Load the course associated with the page into the navigation
1183                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1185                 // If the course wasn't added then don't try going any further.
1186                 if (!$coursenode) {
1187                     $canviewcourseprofile = false;
1188                     break;
1189                 }
1191                 // If the user is not enrolled then we only want to show the
1192                 // course node and not populate it.
1193                 if (!can_access_course($course)) {
1194                     $coursenode->make_active();
1195                     $canviewcourseprofile = false;
1196                     break;
1197                 }
1199                 $this->add_course_essentials($coursenode, $course);
1201                 // Load the course sections into the page
1202                 $this->load_course_sections($course, $coursenode, null, $cm);
1203                 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1204                 // Finally load the cm specific navigaton information
1205                 $this->load_activity($cm, $course, $activity);
1206                 // Check if we have an active ndoe
1207                 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1208                     // And make the activity node active.
1209                     $activity->make_active();
1210                 }
1211                 break;
1212             case CONTEXT_USER :
1213                 if ($issite) {
1214                     // The users profile information etc is already loaded
1215                     // for the front page.
1216                     break;
1217                 }
1218                 $course = $this->page->course;
1219                 // Load the course associated with the user into the navigation
1220                 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1222                 // If the course wasn't added then don't try going any further.
1223                 if (!$coursenode) {
1224                     $canviewcourseprofile = false;
1225                     break;
1226                 }
1228                 // If the user is not enrolled then we only want to show the
1229                 // course node and not populate it.
1230                 if (!can_access_course($course)) {
1231                     $coursenode->make_active();
1232                     $canviewcourseprofile = false;
1233                     break;
1234                 }
1235                 $this->add_course_essentials($coursenode, $course);
1236                 $this->load_course_sections($course, $coursenode);
1237                 break;
1238         }
1240         // Load for the current user
1241         $this->load_for_user();
1242         if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
1243             $this->load_for_user(null, true);
1244         }
1245         // Load each extending user into the navigation.
1246         foreach ($this->extendforuser as $user) {
1247             if ($user->id != $USER->id) {
1248                 $this->load_for_user($user);
1249             }
1250         }
1252         // Give the local plugins a chance to include some navigation if they want.
1253         foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
1254             $function = "local_{$plugin}_extends_navigation";
1255             $oldfunction = "{$plugin}_extends_navigation";
1256             if (function_exists($function)) {
1257                 // This is the preferred function name as there is less chance of conflicts
1258                 $function($this);
1259             } else if (function_exists($oldfunction)) {
1260                 // We continue to support the old function name to ensure backwards compatibility
1261                 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);
1262                 $oldfunction($this);
1263             }
1264         }
1266         // Remove any empty root nodes
1267         foreach ($this->rootnodes as $node) {
1268             // Dont remove the home node
1269             /** @var navigation_node $node */
1270             if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
1271                 $node->remove();
1272             }
1273         }
1275         if (!$this->contains_active_node()) {
1276             $this->search_for_active_node();
1277         }
1279         // If the user is not logged in modify the navigation structure as detailed
1280         // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
1281         if (!isloggedin()) {
1282             $activities = clone($this->rootnodes['site']->children);
1283             $this->rootnodes['site']->remove();
1284             $children = clone($this->children);
1285             $this->children = new navigation_node_collection();
1286             foreach ($activities as $child) {
1287                 $this->children->add($child);
1288             }
1289             foreach ($children as $child) {
1290                 $this->children->add($child);
1291             }
1292         }
1293         return true;
1294     }
1296     /**
1297      * Returns true if the current user is a parent of the user being currently viewed.
1298      *
1299      * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
1300      * other user being viewed this function returns false.
1301      * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
1302      *
1303      * @since 2.4
1304      * @return bool
1305      */
1306     protected function current_user_is_parent_role() {
1307         global $USER, $DB;
1308         if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
1309             $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
1310             if (!has_capability('moodle/user:viewdetails', $usercontext)) {
1311                 return false;
1312             }
1313             if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
1314                 return true;
1315             }
1316         }
1317         return false;
1318     }
1320     /**
1321      * Returns true if courses should be shown within categories on the navigation.
1322      *
1323      * @param bool $ismycourse Set to true if you are calculating this for a course.
1324      * @return bool
1325      */
1326     protected function show_categories($ismycourse = false) {
1327         global $CFG, $DB;
1328         if ($ismycourse) {
1329             return $this->show_my_categories();
1330         }
1331         if ($this->showcategories === null) {
1332             $show = false;
1333             if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
1334                 $show = true;
1335             } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
1336                 $show = true;
1337             }
1338             $this->showcategories = $show;
1339         }
1340         return $this->showcategories;
1341     }
1343     /**
1344      * Returns true if we should show categories in the My Courses branch.
1345      * @return bool
1346      */
1347     protected function show_my_categories() {
1348         global $CFG, $DB;
1349         if ($this->showmycategories === null) {
1350             $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
1351         }
1352         return $this->showmycategories;
1353     }
1355     /**
1356      * Loads the courses in Moodle into the navigation.
1357      *
1358      * @global moodle_database $DB
1359      * @param string|array $categoryids An array containing categories to load courses
1360      *                     for, OR null to load courses for all categories.
1361      * @return array An array of navigation_nodes one for each course
1362      */
1363     protected function load_all_courses($categoryids = null) {
1364         global $CFG, $DB, $SITE;
1366         // Work out the limit of courses.
1367         $limit = 20;
1368         if (!empty($CFG->navcourselimit)) {
1369             $limit = $CFG->navcourselimit;
1370         }
1372         $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
1374         // If we are going to show all courses AND we are showing categories then
1375         // to save us repeated DB calls load all of the categories now
1376         if ($this->show_categories()) {
1377             $this->load_all_categories($toload);
1378         }
1380         // Will be the return of our efforts
1381         $coursenodes = array();
1383         // Check if we need to show categories.
1384         if ($this->show_categories()) {
1385             // Hmmm we need to show categories... this is going to be painful.
1386             // We now need to fetch up to $limit courses for each category to
1387             // be displayed.
1388             if ($categoryids !== null) {
1389                 if (!is_array($categoryids)) {
1390                     $categoryids = array($categoryids);
1391                 }
1392                 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
1393                 $categorywhere = 'WHERE cc.id '.$categorywhere;
1394             } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
1395                 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
1396                 $categoryparams = array();
1397             } else {
1398                 $categorywhere = '';
1399                 $categoryparams = array();
1400             }
1402             // First up we are going to get the categories that we are going to
1403             // need so that we can determine how best to load the courses from them.
1404             $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1405                         FROM {course_categories} cc
1406                     LEFT JOIN {course} c ON c.category = cc.id
1407                             {$categorywhere}
1408                     GROUP BY cc.id";
1409             $categories = $DB->get_recordset_sql($sql, $categoryparams);
1410             $fullfetch = array();
1411             $partfetch = array();
1412             foreach ($categories as $category) {
1413                 if (!$this->can_add_more_courses_to_category($category->id)) {
1414                     continue;
1415                 }
1416                 if ($category->coursecount > $limit * 5) {
1417                     $partfetch[] = $category->id;
1418                 } else if ($category->coursecount > 0) {
1419                     $fullfetch[] = $category->id;
1420                 }
1421             }
1422             $categories->close();
1424             if (count($fullfetch)) {
1425                 // First up fetch all of the courses in categories where we know that we are going to
1426                 // need the majority of courses.
1427                 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
1428                 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1429                 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1430                 $categoryparams['contextlevel'] = CONTEXT_COURSE;
1431                 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1432                             FROM {course} c
1433                                 $ccjoin
1434                             WHERE c.category {$categoryids}
1435                         ORDER BY c.sortorder ASC";
1436                 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
1437                 foreach ($coursesrs as $course) {
1438                     if ($course->id == $SITE->id) {
1439                         // This should not be necessary, frontpage is not in any category.
1440                         continue;
1441                     }
1442                     if (array_key_exists($course->id, $this->addedcourses)) {
1443                         // It is probably better to not include the already loaded courses
1444                         // directly in SQL because inequalities may confuse query optimisers
1445                         // and may interfere with query caching.
1446                         continue;
1447                     }
1448                     if (!$this->can_add_more_courses_to_category($course->category)) {
1449                         continue;
1450                     }
1451                     context_helper::preload_from_record($course);
1452                     if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1453                         continue;
1454                     }
1455                     $coursenodes[$course->id] = $this->add_course($course);
1456                 }
1457                 $coursesrs->close();
1458             }
1460             if (count($partfetch)) {
1461                 // Next we will work our way through the categories where we will likely only need a small
1462                 // proportion of the courses.
1463                 foreach ($partfetch as $categoryid) {
1464                     $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1465                     $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1466                     $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1467                                 FROM {course} c
1468                                     $ccjoin
1469                                 WHERE c.category = :categoryid
1470                             ORDER BY c.sortorder ASC";
1471                     $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
1472                     $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
1473                     foreach ($coursesrs as $course) {
1474                         if ($course->id == $SITE->id) {
1475                             // This should not be necessary, frontpage is not in any category.
1476                             continue;
1477                         }
1478                         if (array_key_exists($course->id, $this->addedcourses)) {
1479                             // It is probably better to not include the already loaded courses
1480                             // directly in SQL because inequalities may confuse query optimisers
1481                             // and may interfere with query caching.
1482                             // This also helps to respect expected $limit on repeated executions.
1483                             continue;
1484                         }
1485                         if (!$this->can_add_more_courses_to_category($course->category)) {
1486                             break;
1487                         }
1488                         context_helper::preload_from_record($course);
1489                         if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1490                             continue;
1491                         }
1492                         $coursenodes[$course->id] = $this->add_course($course);
1493                     }
1494                     $coursesrs->close();
1495                 }
1496             }
1497         } else {
1498             // Prepare the SQL to load the courses and their contexts
1499             list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
1500             $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1501             $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1502             $courseparams['contextlevel'] = CONTEXT_COURSE;
1503             $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
1504                         FROM {course} c
1505                             $ccjoin
1506                         WHERE c.id {$courseids}
1507                     ORDER BY c.sortorder ASC";
1508             $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
1509             foreach ($coursesrs as $course) {
1510                 if ($course->id == $SITE->id) {
1511                     // frotpage is not wanted here
1512                     continue;
1513                 }
1514                 if ($this->page->course && ($this->page->course->id == $course->id)) {
1515                     // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
1516                     continue;
1517                 }
1518                 context_helper::preload_from_record($course);
1519                 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1520                     continue;
1521                 }
1522                 $coursenodes[$course->id] = $this->add_course($course);
1523                 if (count($coursenodes) >= $limit) {
1524                     break;
1525                 }
1526             }
1527             $coursesrs->close();
1528         }
1530         return $coursenodes;
1531     }
1533     /**
1534      * Returns true if more courses can be added to the provided category.
1535      *
1536      * @param int|navigation_node|stdClass $category
1537      * @return bool
1538      */
1539     protected function can_add_more_courses_to_category($category) {
1540         global $CFG;
1541         $limit = 20;
1542         if (!empty($CFG->navcourselimit)) {
1543             $limit = (int)$CFG->navcourselimit;
1544         }
1545         if (is_numeric($category)) {
1546             if (!array_key_exists($category, $this->addedcategories)) {
1547                 return true;
1548             }
1549             $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
1550         } else if ($category instanceof navigation_node) {
1551             if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
1552                 return false;
1553             }
1554             $coursecount = count($category->children->type(self::TYPE_COURSE));
1555         } else if (is_object($category) && property_exists($category,'id')) {
1556             $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
1557         }
1558         return ($coursecount <= $limit);
1559     }
1561     /**
1562      * Loads all categories (top level or if an id is specified for that category)
1563      *
1564      * @param int $categoryid The category id to load or null/0 to load all base level categories
1565      * @param bool $showbasecategories If set to true all base level categories will be loaded as well
1566      *        as the requested category and any parent categories.
1567      * @return navigation_node|void returns a navigation node if a category has been loaded.
1568      */
1569     protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
1570         global $CFG, $DB;
1572         // Check if this category has already been loaded
1573         if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
1574             return true;
1575         }
1577         $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
1578         $sqlselect = "SELECT cc.*, $catcontextsql
1579                       FROM {course_categories} cc
1580                       JOIN {context} ctx ON cc.id = ctx.instanceid";
1581         $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
1582         $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
1583         $params = array();
1585         $categoriestoload = array();
1586         if ($categoryid == self::LOAD_ALL_CATEGORIES) {
1587             // We are going to load all categories regardless... prepare to fire
1588             // on the database server!
1589         } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
1590             // We are going to load all of the first level categories (categories without parents)
1591             $sqlwhere .= " AND cc.parent = 0";
1592         } else if (array_key_exists($categoryid, $this->addedcategories)) {
1593             // The category itself has been loaded already so we just need to ensure its subcategories
1594             // have been loaded
1595             list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
1596             if ($showbasecategories) {
1597                 // We need to include categories with parent = 0 as well
1598                 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
1599             } else {
1600                 // All we need is categories that match the parent
1601                 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
1602             }
1603             $params['categoryid'] = $categoryid;
1604         } else {
1605             // This category hasn't been loaded yet so we need to fetch it, work out its category path
1606             // and load this category plus all its parents and subcategories
1607             $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
1608             $categoriestoload = explode('/', trim($category->path, '/'));
1609             list($select, $params) = $DB->get_in_or_equal($categoriestoload);
1610             // We are going to use select twice so double the params
1611             $params = array_merge($params, $params);
1612             $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
1613             $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
1614         }
1616         $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
1617         $categories = array();
1618         foreach ($categoriesrs as $category) {
1619             // Preload the context.. we'll need it when adding the category in order
1620             // to format the category name.
1621             context_helper::preload_from_record($category);
1622             if (array_key_exists($category->id, $this->addedcategories)) {
1623                 // Do nothing, its already been added.
1624             } else if ($category->parent == '0') {
1625                 // This is a root category lets add it immediately
1626                 $this->add_category($category, $this->rootnodes['courses']);
1627             } else if (array_key_exists($category->parent, $this->addedcategories)) {
1628                 // This categories parent has already been added we can add this immediately
1629                 $this->add_category($category, $this->addedcategories[$category->parent]);
1630             } else {
1631                 $categories[] = $category;
1632             }
1633         }
1634         $categoriesrs->close();
1636         // Now we have an array of categories we need to add them to the navigation.
1637         while (!empty($categories)) {
1638             $category = reset($categories);
1639             if (array_key_exists($category->id, $this->addedcategories)) {
1640                 // Do nothing
1641             } else if ($category->parent == '0') {
1642                 $this->add_category($category, $this->rootnodes['courses']);
1643             } else if (array_key_exists($category->parent, $this->addedcategories)) {
1644                 $this->add_category($category, $this->addedcategories[$category->parent]);
1645             } else {
1646                 // This category isn't in the navigation and niether is it's parent (yet).
1647                 // We need to go through the category path and add all of its components in order.
1648                 $path = explode('/', trim($category->path, '/'));
1649                 foreach ($path as $catid) {
1650                     if (!array_key_exists($catid, $this->addedcategories)) {
1651                         // This category isn't in the navigation yet so add it.
1652                         $subcategory = $categories[$catid];
1653                         if ($subcategory->parent == '0') {
1654                             // Yay we have a root category - this likely means we will now be able
1655                             // to add categories without problems.
1656                             $this->add_category($subcategory, $this->rootnodes['courses']);
1657                         } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
1658                             // The parent is in the category (as we'd expect) so add it now.
1659                             $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
1660                             // Remove the category from the categories array.
1661                             unset($categories[$catid]);
1662                         } else {
1663                             // We should never ever arrive here - if we have then there is a bigger
1664                             // problem at hand.
1665                             throw new coding_exception('Category path order is incorrect and/or there are missing categories');
1666                         }
1667                     }
1668                 }
1669             }
1670             // Remove the category from the categories array now that we know it has been added.
1671             unset($categories[$category->id]);
1672         }
1673         if ($categoryid === self::LOAD_ALL_CATEGORIES) {
1674             $this->allcategoriesloaded = true;
1675         }
1676         // Check if there are any categories to load.
1677         if (count($categoriestoload) > 0) {
1678             $readytoloadcourses = array();
1679             foreach ($categoriestoload as $category) {
1680                 if ($this->can_add_more_courses_to_category($category)) {
1681                     $readytoloadcourses[] = $category;
1682                 }
1683             }
1684             if (count($readytoloadcourses)) {
1685                 $this->load_all_courses($readytoloadcourses);
1686             }
1687         }
1689         // Look for all categories which have been loaded
1690         if (!empty($this->addedcategories)) {
1691             $categoryids = array();
1692             foreach ($this->addedcategories as $category) {
1693                 if ($this->can_add_more_courses_to_category($category)) {
1694                     $categoryids[] = $category->key;
1695                 }
1696             }
1697             if ($categoryids) {
1698                 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
1699                 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
1700                 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
1701                           FROM {course_categories} cc
1702                           JOIN {course} c ON c.category = cc.id
1703                          WHERE cc.id {$categoriessql}
1704                       GROUP BY cc.id
1705                         HAVING COUNT(c.id) > :limit";
1706                 $excessivecategories = $DB->get_records_sql($sql, $params);
1707                 foreach ($categories as &$category) {
1708                     if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
1709                         $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
1710                         $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
1711                     }
1712                 }
1713             }
1714         }
1715     }
1717     /**
1718      * Adds a structured category to the navigation in the correct order/place
1719      *
1720      * @param stdClass $category category to be added in navigation.
1721      * @param navigation_node $parent parent navigation node
1722      * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
1723      * @return void.
1724      */
1725     protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
1726         if (array_key_exists($category->id, $this->addedcategories)) {
1727             return;
1728         }
1729         $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
1730         $context = context_coursecat::instance($category->id);
1731         $categoryname = format_string($category->name, true, array('context' => $context));
1732         $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
1733         if (empty($category->visible)) {
1734             if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
1735                 $categorynode->hidden = true;
1736             } else {
1737                 $categorynode->display = false;
1738             }
1739         }
1740         $this->addedcategories[$category->id] = $categorynode;
1741     }
1743     /**
1744      * Loads the given course into the navigation
1745      *
1746      * @param stdClass $course
1747      * @return navigation_node
1748      */
1749     protected function load_course(stdClass $course) {
1750         global $SITE;
1751         if ($course->id == $SITE->id) {
1752             // This is always loaded during initialisation
1753             return $this->rootnodes['site'];
1754         } else if (array_key_exists($course->id, $this->addedcourses)) {
1755             // The course has already been loaded so return a reference
1756             return $this->addedcourses[$course->id];
1757         } else {
1758             // Add the course
1759             return $this->add_course($course);
1760         }
1761     }
1763     /**
1764      * Loads all of the courses section into the navigation.
1765      *
1766      * This function calls method from current course format, see
1767      * {@link format_base::extend_course_navigation()}
1768      * If course module ($cm) is specified but course format failed to create the node,
1769      * the activity node is created anyway.
1770      *
1771      * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
1772      *
1773      * @param stdClass $course Database record for the course
1774      * @param navigation_node $coursenode The course node within the navigation
1775      * @param null|int $sectionnum If specified load the contents of section with this relative number
1776      * @param null|cm_info $cm If specified make sure that activity node is created (either
1777      *    in containg section or by calling load_stealth_activity() )
1778      */
1779     protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
1780         global $CFG, $SITE;
1781         require_once($CFG->dirroot.'/course/lib.php');
1782         if (isset($cm->sectionnum)) {
1783             $sectionnum = $cm->sectionnum;
1784         }
1785         if ($sectionnum !== null) {
1786             $this->includesectionnum = $sectionnum;
1787         }
1788         course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
1789         if (isset($cm->id)) {
1790             $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
1791             if (empty($activity)) {
1792                 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
1793             }
1794         }
1795    }
1797     /**
1798      * Generates an array of sections and an array of activities for the given course.
1799      *
1800      * This method uses the cache to improve performance and avoid the get_fast_modinfo call
1801      *
1802      * @param stdClass $course
1803      * @return array Array($sections, $activities)
1804      */
1805     protected function generate_sections_and_activities(stdClass $course) {
1806         global $CFG;
1807         require_once($CFG->dirroot.'/course/lib.php');
1809         $modinfo = get_fast_modinfo($course);
1810         $sections = $modinfo->get_section_info_all();
1812         // For course formats using 'numsections' trim the sections list
1813         $courseformatoptions = course_get_format($course)->get_format_options();
1814         if (isset($courseformatoptions['numsections'])) {
1815             $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
1816         }
1818         $activities = array();
1820         foreach ($sections as $key => $section) {
1821             // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
1822             $sections[$key] = clone($section);
1823             unset($sections[$key]->summary);
1824             $sections[$key]->hasactivites = false;
1825             if (!array_key_exists($section->section, $modinfo->sections)) {
1826                 continue;
1827             }
1828             foreach ($modinfo->sections[$section->section] as $cmid) {
1829                 $cm = $modinfo->cms[$cmid];
1830                 if (!$cm->uservisible) {
1831                     continue;
1832                 }
1833                 $activity = new stdClass;
1834                 $activity->id = $cm->id;
1835                 $activity->course = $course->id;
1836                 $activity->section = $section->section;
1837                 $activity->name = $cm->name;
1838                 $activity->icon = $cm->icon;
1839                 $activity->iconcomponent = $cm->iconcomponent;
1840                 $activity->hidden = (!$cm->visible);
1841                 $activity->modname = $cm->modname;
1842                 $activity->nodetype = navigation_node::NODETYPE_LEAF;
1843                 $activity->onclick = $cm->get_on_click();
1844                 $url = $cm->get_url();
1845                 if (!$url) {
1846                     $activity->url = null;
1847                     $activity->display = false;
1848                 } else {
1849                     $activity->url = $cm->get_url()->out();
1850                     $activity->display = true;
1851                     if (self::module_extends_navigation($cm->modname)) {
1852                         $activity->nodetype = navigation_node::NODETYPE_BRANCH;
1853                     }
1854                 }
1855                 $activities[$cmid] = $activity;
1856                 if ($activity->display) {
1857                     $sections[$key]->hasactivites = true;
1858                 }
1859             }
1860         }
1862         return array($sections, $activities);
1863     }
1865     /**
1866      * Generically loads the course sections into the course's navigation.
1867      *
1868      * @param stdClass $course
1869      * @param navigation_node $coursenode
1870      * @return array An array of course section nodes
1871      */
1872     public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
1873         global $CFG, $DB, $USER, $SITE;
1874         require_once($CFG->dirroot.'/course/lib.php');
1876         list($sections, $activities) = $this->generate_sections_and_activities($course);
1878         $navigationsections = array();
1879         foreach ($sections as $sectionid => $section) {
1880             $section = clone($section);
1881             if ($course->id == $SITE->id) {
1882                 $this->load_section_activities($coursenode, $section->section, $activities);
1883             } else {
1884                 if (!$section->uservisible || (!$this->showemptysections &&
1885                         !$section->hasactivites && $this->includesectionnum !== $section->section)) {
1886                     continue;
1887                 }
1889                 $sectionname = get_section_name($course, $section);
1890                 $url = course_get_url($course, $section->section, array('navigation' => true));
1892                 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1893                 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1894                 $sectionnode->hidden = (!$section->visible || !$section->available);
1895                 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
1896                     $this->load_section_activities($sectionnode, $section->section, $activities);
1897                 }
1898                 $section->sectionnode = $sectionnode;
1899                 $navigationsections[$sectionid] = $section;
1900             }
1901         }
1902         return $navigationsections;
1903     }
1905     /**
1906      * Loads all of the activities for a section into the navigation structure.
1907      *
1908      * @param navigation_node $sectionnode
1909      * @param int $sectionnumber
1910      * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
1911      * @param stdClass $course The course object the section and activities relate to.
1912      * @return array Array of activity nodes
1913      */
1914     protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
1915         global $CFG, $SITE;
1916         // A static counter for JS function naming
1917         static $legacyonclickcounter = 0;
1919         $activitynodes = array();
1920         if (empty($activities)) {
1921             return $activitynodes;
1922         }
1924         if (!is_object($course)) {
1925             $activity = reset($activities);
1926             $courseid = $activity->course;
1927         } else {
1928             $courseid = $course->id;
1929         }
1930         $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
1932         foreach ($activities as $activity) {
1933             if ($activity->section != $sectionnumber) {
1934                 continue;
1935             }
1936             if ($activity->icon) {
1937                 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
1938             } else {
1939                 $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
1940             }
1942             // Prepare the default name and url for the node
1943             $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
1944             $action = new moodle_url($activity->url);
1946             // Check if the onclick property is set (puke!)
1947             if (!empty($activity->onclick)) {
1948                 // Increment the counter so that we have a unique number.
1949                 $legacyonclickcounter++;
1950                 // Generate the function name we will use
1951                 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
1952                 $propogrationhandler = '';
1953                 // Check if we need to cancel propogation. Remember inline onclick
1954                 // events would return false if they wanted to prevent propogation and the
1955                 // default action.
1956                 if (strpos($activity->onclick, 'return false')) {
1957                     $propogrationhandler = 'e.halt();';
1958                 }
1959                 // Decode the onclick - it has already been encoded for display (puke)
1960                 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
1961                 // Build the JS function the click event will call
1962                 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
1963                 $this->page->requires->js_init_code($jscode);
1964                 // Override the default url with the new action link
1965                 $action = new action_link($action, $activityname, new component_action('click', $functionname));
1966             }
1968             $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
1969             $activitynode->title(get_string('modulename', $activity->modname));
1970             $activitynode->hidden = $activity->hidden;
1971             $activitynode->display = $showactivities && $activity->display;
1972             $activitynode->nodetype = $activity->nodetype;
1973             $activitynodes[$activity->id] = $activitynode;
1974         }
1976         return $activitynodes;
1977     }
1978     /**
1979      * Loads a stealth module from unavailable section
1980      * @param navigation_node $coursenode
1981      * @param stdClass $modinfo
1982      * @return navigation_node or null if not accessible
1983      */
1984     protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
1985         if (empty($modinfo->cms[$this->page->cm->id])) {
1986             return null;
1987         }
1988         $cm = $modinfo->cms[$this->page->cm->id];
1989         if (!$cm->uservisible) {
1990             return null;
1991         }
1992         if ($cm->icon) {
1993             $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
1994         } else {
1995             $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
1996         }
1997         $url = $cm->get_url();
1998         $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
1999         $activitynode->title(get_string('modulename', $cm->modname));
2000         $activitynode->hidden = (!$cm->visible);
2001         if (!$url) {
2002             // Don't show activities that don't have links!
2003             $activitynode->display = false;
2004         } else if (self::module_extends_navigation($cm->modname)) {
2005             $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
2006         }
2007         return $activitynode;
2008     }
2009     /**
2010      * Loads the navigation structure for the given activity into the activities node.
2011      *
2012      * This method utilises a callback within the modules lib.php file to load the
2013      * content specific to activity given.
2014      *
2015      * The callback is a method: {modulename}_extend_navigation()
2016      * Examples:
2017      *  * {@link forum_extend_navigation()}
2018      *  * {@link workshop_extend_navigation()}
2019      *
2020      * @param cm_info|stdClass $cm
2021      * @param stdClass $course
2022      * @param navigation_node $activity
2023      * @return bool
2024      */
2025     protected function load_activity($cm, stdClass $course, navigation_node $activity) {
2026         global $CFG, $DB;
2028         // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2029         if (!($cm instanceof cm_info)) {
2030             $modinfo = get_fast_modinfo($course);
2031             $cm = $modinfo->get_cm($cm->id);
2032         }
2033         $activity->nodetype = navigation_node::NODETYPE_LEAF;
2034         $activity->make_active();
2035         $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
2036         $function = $cm->modname.'_extend_navigation';
2038         if (file_exists($file)) {
2039             require_once($file);
2040             if (function_exists($function)) {
2041                 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
2042                 $function($activity, $course, $activtyrecord, $cm);
2043             }
2044         }
2046         // Allow the active advanced grading method plugin to append module navigation
2047         $featuresfunc = $cm->modname.'_supports';
2048         if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
2049             require_once($CFG->dirroot.'/grade/grading/lib.php');
2050             $gradingman = get_grading_manager($cm->context, $cm->modname);
2051             $gradingman->extend_navigation($this, $activity);
2052         }
2054         return $activity->has_children();
2055     }
2056     /**
2057      * Loads user specific information into the navigation in the appropriate place.
2058      *
2059      * If no user is provided the current user is assumed.
2060      *
2061      * @param stdClass $user
2062      * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
2063      * @return bool
2064      */
2065     protected function load_for_user($user=null, $forceforcontext=false) {
2066         global $DB, $CFG, $USER, $SITE;
2068         if ($user === null) {
2069             // We can't require login here but if the user isn't logged in we don't
2070             // want to show anything
2071             if (!isloggedin() || isguestuser()) {
2072                 return false;
2073             }
2074             $user = $USER;
2075         } else if (!is_object($user)) {
2076             // If the user is not an object then get them from the database
2077             $select = context_helper::get_preload_record_columns_sql('ctx');
2078             $sql = "SELECT u.*, $select
2079                       FROM {user} u
2080                       JOIN {context} ctx ON u.id = ctx.instanceid
2081                      WHERE u.id = :userid AND
2082                            ctx.contextlevel = :contextlevel";
2083             $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
2084             context_helper::preload_from_record($user);
2085         }
2087         $iscurrentuser = ($user->id == $USER->id);
2089         $usercontext = context_user::instance($user->id);
2091         // Get the course set against the page, by default this will be the site
2092         $course = $this->page->course;
2093         $baseargs = array('id'=>$user->id);
2094         if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
2095             $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
2096             $baseargs['course'] = $course->id;
2097             $coursecontext = context_course::instance($course->id);
2098             $issitecourse = false;
2099         } else {
2100             // Load all categories and get the context for the system
2101             $coursecontext = context_system::instance();
2102             $issitecourse = true;
2103         }
2105         // Create a node to add user information under.
2106         if ($iscurrentuser && !$forceforcontext) {
2107             // If it's the current user the information will go under the profile root node
2108             $usernode = $this->rootnodes['myprofile'];
2109             $course = get_site();
2110             $coursecontext = context_course::instance($course->id);
2111             $issitecourse = true;
2112         } else {
2113             if (!$issitecourse) {
2114                 // Not the current user so add it to the participants node for the current course
2115                 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
2116                 $userviewurl = new moodle_url('/user/view.php', $baseargs);
2117             } else {
2118                 // This is the site so add a users node to the root branch
2119                 $usersnode = $this->rootnodes['users'];
2120                 if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
2121                     $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
2122                 }
2123                 $userviewurl = new moodle_url('/user/profile.php', $baseargs);
2124             }
2125             if (!$usersnode) {
2126                 // We should NEVER get here, if the course hasn't been populated
2127                 // with a participants node then the navigaiton either wasn't generated
2128                 // for it (you are missing a require_login or set_context call) or
2129                 // you don't have access.... in the interests of no leaking informatin
2130                 // we simply quit...
2131                 return false;
2132             }
2133             // Add a branch for the current user
2134             $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
2135             $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
2137             if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
2138                 $usernode->make_active();
2139             }
2140         }
2142         // If the user is the current user or has permission to view the details of the requested
2143         // user than add a view profile link.
2144         if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
2145             if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
2146                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
2147             } else {
2148                 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
2149             }
2150         }
2152         if (!empty($CFG->navadduserpostslinks)) {
2153             // Add nodes for forum posts and discussions if the user can view either or both
2154             // There are no capability checks here as the content of the page is based
2155             // purely on the forums the current user has access too.
2156             $forumtab = $usernode->add(get_string('forumposts', 'forum'));
2157             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
2158             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
2159         }
2161         // Add blog nodes
2162         if (!empty($CFG->enableblogs)) {
2163             if (!$this->cache->cached('userblogoptions'.$user->id)) {
2164                 require_once($CFG->dirroot.'/blog/lib.php');
2165                 // Get all options for the user
2166                 $options = blog_get_options_for_user($user);
2167                 $this->cache->set('userblogoptions'.$user->id, $options);
2168             } else {
2169                 $options = $this->cache->{'userblogoptions'.$user->id};
2170             }
2172             if (count($options) > 0) {
2173                 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
2174                 foreach ($options as $type => $option) {
2175                     if ($type == "rss") {
2176                         $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
2177                     } else {
2178                         $blogs->add($option['string'], $option['link']);
2179                     }
2180                 }
2181             }
2182         }
2184         if (!empty($CFG->messaging)) {
2185             $messageargs = null;
2186             if ($USER->id != $user->id) {
2187                 $messageargs = array('user1' => $user->id);
2188             }
2189             $url = new moodle_url('/message/index.php',$messageargs);
2190             $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
2191         }
2193         if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
2194             $url = new moodle_url('/user/files.php');
2195             $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
2196         }
2198         if (!empty($CFG->enablebadges) && $iscurrentuser &&
2199                 has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
2200             $url = new moodle_url('/badges/mybadges.php');
2201             $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
2202         }
2204         // Add a node to view the users notes if permitted
2205         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
2206             $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
2207             if ($coursecontext->instanceid) {
2208                 $url->param('course', $coursecontext->instanceid);
2209             }
2210             $usernode->add(get_string('notes', 'notes'), $url);
2211         }
2213         // If the user is the current user add the repositories for the current user
2214         $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
2215         if ($iscurrentuser) {
2216             if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
2217                 require_once($CFG->dirroot . '/repository/lib.php');
2218                 $editabletypes = repository::get_editable_types($usercontext);
2219                 $haseditabletypes = !empty($editabletypes);
2220                 unset($editabletypes);
2221                 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
2222             } else {
2223                 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
2224             }
2225             if ($haseditabletypes) {
2226                 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
2227             }
2228         } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
2230             // Add view grade report is permitted
2231             $reports = core_component::get_plugin_list('gradereport');
2232             arsort($reports); // user is last, we want to test it first
2234             $userscourses = enrol_get_users_courses($user->id);
2235             $userscoursesnode = $usernode->add(get_string('courses'));
2237             foreach ($userscourses as $usercourse) {
2238                 $usercoursecontext = context_course::instance($usercourse->id);
2239                 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
2240                 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
2242                 $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
2243                 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
2244                     foreach ($reports as $plugin => $plugindir) {
2245                         if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
2246                             //stop when the first visible plugin is found
2247                             $gradeavailable = true;
2248                             break;
2249                         }
2250                     }
2251                 }
2253                 if ($gradeavailable) {
2254                     $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
2255                     $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2256                 }
2258                 // Add a node to view the users notes if permitted
2259                 if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
2260                     $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
2261                     $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
2262                 }
2264                 if (can_access_course($usercourse, $user->id)) {
2265                     $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', ''));
2266                 }
2268                 $reporttab = $usercoursenode->add(get_string('activityreports'));
2270                 $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
2271                 foreach ($reports as $reportfunction) {
2272                     $reportfunction($reporttab, $user, $usercourse);
2273                 }
2275                 $reporttab->trim_if_empty();
2276             }
2277         }
2278         return true;
2279     }
2281     /**
2282      * This method simply checks to see if a given module can extend the navigation.
2283      *
2284      * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
2285      *
2286      * @param string $modname
2287      * @return bool
2288      */
2289     public static function module_extends_navigation($modname) {
2290         global $CFG;
2291         static $extendingmodules = array();
2292         if (!array_key_exists($modname, $extendingmodules)) {
2293             $extendingmodules[$modname] = false;
2294             $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
2295             if (file_exists($file)) {
2296                 $function = $modname.'_extend_navigation';
2297                 require_once($file);
2298                 $extendingmodules[$modname] = (function_exists($function));
2299             }
2300         }
2301         return $extendingmodules[$modname];
2302     }
2303     /**
2304      * Extends the navigation for the given user.
2305      *
2306      * @param stdClass $user A user from the database
2307      */
2308     public function extend_for_user($user) {
2309         $this->extendforuser[] = $user;
2310     }
2312     /**
2313      * Returns all of the users the navigation is being extended for
2314      *
2315      * @return array An array of extending users.
2316      */
2317     public function get_extending_users() {
2318         return $this->extendforuser;
2319     }
2320     /**
2321      * Adds the given course to the navigation structure.
2322      *
2323      * @param stdClass $course
2324      * @param bool $forcegeneric
2325      * @param bool $ismycourse
2326      * @return navigation_node
2327      */
2328     public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
2329         global $CFG, $SITE;
2331         // We found the course... we can return it now :)
2332         if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2333             return $this->addedcourses[$course->id];
2334         }
2336         $coursecontext = context_course::instance($course->id);
2338         if ($course->id != $SITE->id && !$course->visible) {
2339             if (is_role_switched($course->id)) {
2340                 // user has to be able to access course in order to switch, let's skip the visibility test here
2341             } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2342                 return false;
2343             }
2344         }
2346         $issite = ($course->id == $SITE->id);
2347         $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
2348         $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
2349         // This is the name that will be shown for the course.
2350         $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
2352         if ($issite) {
2353             $parent = $this;
2354             $url = null;
2355             if (empty($CFG->usesitenameforsitepages)) {
2356                 $coursename = get_string('sitepages');
2357             }
2358         } else if ($coursetype == self::COURSE_CURRENT) {
2359             $parent = $this->rootnodes['currentcourse'];
2360             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2361         } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
2362             if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
2363                 // Nothing to do here the above statement set $parent to the category within mycourses.
2364             } else {
2365                 $parent = $this->rootnodes['mycourses'];
2366             }
2367             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2368         } else {
2369             $parent = $this->rootnodes['courses'];
2370             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
2371             if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
2372                 if (!$this->is_category_fully_loaded($course->category)) {
2373                     // We need to load the category structure for this course
2374                     $this->load_all_categories($course->category, false);
2375                 }
2376                 if (array_key_exists($course->category, $this->addedcategories)) {
2377                     $parent = $this->addedcategories[$course->category];
2378                     // This could lead to the course being created so we should check whether it is the case again
2379                     if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
2380                         return $this->addedcourses[$course->id];
2381                     }
2382                 }
2383             }
2384         }
2386         $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
2387         $coursenode->nodetype = self::NODETYPE_BRANCH;
2388         $coursenode->hidden = (!$course->visible);
2389         // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
2390         // later.
2391         $coursenode->title(str_replace('&amp;', '&', $fullname));
2392         if (!$forcegeneric) {
2393             $this->addedcourses[$course->id] = $coursenode;
2394         }
2396         return $coursenode;
2397     }
2399     /**
2400      * Returns true if the category has already been loaded as have any child categories
2401      *
2402      * @param int $categoryid
2403      * @return bool
2404      */
2405     protected function is_category_fully_loaded($categoryid) {
2406         return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
2407     }
2409     /**
2410      * Adds essential course nodes to the navigation for the given course.
2411      *
2412      * This method adds nodes such as reports, blogs and participants
2413      *
2414      * @param navigation_node $coursenode
2415      * @param stdClass $course
2416      * @return bool returns true on successful addition of a node.
2417      */
2418     public function add_course_essentials($coursenode, stdClass $course) {
2419         global $CFG, $SITE;
2421         if ($course->id == $SITE->id) {
2422             return $this->add_front_page_course_essentials($coursenode, $course);
2423         }
2425         if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
2426             return true;
2427         }
2429         //Participants
2430         if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
2431             $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
2432             $currentgroup = groups_get_course_group($course, true);
2433             if ($course->id == $SITE->id) {
2434                 $filtervar = 'courseid';
2435                 $filterselect = '';
2436             } else if ($course->id && !$currentgroup) {
2437                 $filtervar = 'courseid';
2438                 $filterselect = $course->id;
2439             } else {
2440                 $filtervar = 'groupid';
2441                 $filterselect = $currentgroup;
2442             }
2443             $filterselect = clean_param($filterselect, PARAM_INT);
2444             if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2445                and has_capability('moodle/blog:view', context_system::instance())) {
2446                 $blogsurls = new moodle_url('/blog/index.php', array($filtervar => $filterselect));
2447                 $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
2448             }
2449             if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2450                 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
2451             }
2452         } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
2453             $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
2454         }
2456         // Badges.
2457         if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
2458             has_capability('moodle/badges:viewbadges', $this->page->context)) {
2459             $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
2461             $coursenode->add(get_string('coursebadges', 'badges'), null,
2462                     navigation_node::TYPE_CONTAINER, null, 'coursebadges');
2463             $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
2464                     navigation_node::TYPE_SETTING, null, 'badgesview',
2465                     new pix_icon('i/badge', get_string('badgesview', 'badges')));
2466         }
2468         return true;
2469     }
2470     /**
2471      * This generates the structure of the course that won't be generated when
2472      * the modules and sections are added.
2473      *
2474      * Things such as the reports branch, the participants branch, blogs... get
2475      * added to the course node by this method.
2476      *
2477      * @param navigation_node $coursenode
2478      * @param stdClass $course
2479      * @return bool True for successfull generation
2480      */
2481     public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
2482         global $CFG;
2484         if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
2485             return true;
2486         }
2488         // Hidden node that we use to determine if the front page navigation is loaded.
2489         // This required as there are not other guaranteed nodes that may be loaded.
2490         $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
2492         //Participants
2493         if (has_capability('moodle/course:viewparticipants',  context_system::instance())) {
2494             $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
2495         }
2497         $filterselect = 0;
2499         // Blogs
2500         if (!empty($CFG->enableblogs)
2501           and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
2502           and has_capability('moodle/blog:view', context_system::instance())) {
2503             $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
2504             $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
2505         }
2507         //Badges
2508         if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
2509             $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
2510             $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
2511         }
2513         // Notes
2514         if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
2515             $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
2516         }
2518         // Tags
2519         if (!empty($CFG->usetags) && isloggedin()) {
2520             $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
2521         }
2523         if (isloggedin()) {
2524             // Calendar
2525             $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
2526             $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
2527         }
2529         return true;
2530     }
2532     /**
2533      * Clears the navigation cache
2534      */
2535     public function clear_cache() {
2536         $this->cache->clear();
2537     }
2539     /**
2540      * Sets an expansion limit for the navigation
2541      *
2542      * The expansion limit is used to prevent the display of content that has a type
2543      * greater than the provided $type.
2544      *
2545      * Can be used to ensure things such as activities or activity content don't get
2546      * shown on the navigation.
2547      * They are still generated in order to ensure the navbar still makes sense.
2548      *
2549      * @param int $type One of navigation_node::TYPE_*
2550      * @return bool true when complete.
2551      */
2552     public function set_expansion_limit($type) {
2553         global $SITE;
2554         $nodes = $this->find_all_of_type($type);
2556         // We only want to hide specific types of nodes.
2557         // Only nodes that represent "structure" in the navigation tree should be hidden.
2558         // If we hide all nodes then we risk hiding vital information.
2559         $typestohide = array(
2560             self::TYPE_CATEGORY,
2561             self::TYPE_COURSE,
2562             self::TYPE_SECTION,
2563             self::TYPE_ACTIVITY
2564         );
2566         foreach ($nodes as $node) {
2567             // We need to generate the full site node
2568             if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
2569                 continue;
2570             }
2571             foreach ($node->children as $child) {
2572                 $child->hide($typestohide);
2573             }
2574         }
2575         return true;
2576     }
2577     /**
2578      * Attempts to get the navigation with the given key from this nodes children.
2579      *
2580      * This function only looks at this nodes children, it does NOT look recursivily.
2581      * If the node can't be found then false is returned.
2582      *
2583      * If you need to search recursivily then use the {@link global_navigation::find()} method.
2584      *
2585      * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2586      * may be of more use to you.
2587      *
2588      * @param string|int $key The key of the node you wish to receive.
2589      * @param int $type One of navigation_node::TYPE_*
2590      * @return navigation_node|false
2591      */
2592     public function get($key, $type = null) {
2593         if (!$this->initialised) {
2594             $this->initialise();
2595         }
2596         return parent::get($key, $type);
2597     }
2599     /**
2600      * Searches this nodes children and their children to find a navigation node
2601      * with the matching key and type.
2602      *
2603      * This method is recursive and searches children so until either a node is
2604      * found or there are no more nodes to search.
2605      *
2606      * If you know that the node being searched for is a child of this node
2607      * then use the {@link global_navigation::get()} method instead.
2608      *
2609      * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
2610      * may be of more use to you.
2611      *
2612      * @param string|int $key The key of the node you wish to receive.
2613      * @param int $type One of navigation_node::TYPE_*
2614      * @return navigation_node|false
2615      */
2616     public function find($key, $type) {
2617         if (!$this->initialised) {
2618             $this->initialise();
2619         }
2620         if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
2621             return $this->rootnodes[$key];
2622         }
2623         return parent::find($key, $type);
2624     }
2626     /**
2627      * They've expanded the 'my courses' branch.
2628      */
2629     protected function load_courses_enrolled() {
2630         global $CFG, $DB;
2631         $sortorder = 'visible DESC';
2632         // Prevent undefined $CFG->navsortmycoursessort errors.
2633         if (empty($CFG->navsortmycoursessort)) {
2634             $CFG->navsortmycoursessort = 'sortorder';
2635         }
2636         // Append the chosen sortorder.
2637         $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
2638         $courses = enrol_get_my_courses(null, $sortorder);
2639         if (count($courses) && $this->show_my_categories()) {
2640             // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
2641             // In order to make sure we load everything required we must first find the categories that are not
2642             // base categories and work out the bottom category in thier path.
2643             $categoryids = array();
2644             foreach ($courses as $course) {
2645                 $categoryids[] = $course->category;
2646             }
2647             $categoryids = array_unique($categoryids);
2648             list($sql, $params) = $DB->get_in_or_equal($categoryids);
2649             $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
2650             foreach ($categories as $category) {
2651                 $bits = explode('/', trim($category->path,'/'));
2652                 $categoryids[] = array_shift($bits);
2653             }
2654             $categoryids = array_unique($categoryids);
2655             $categories->close();
2657             // Now we load the base categories.
2658             list($sql, $params) = $DB->get_in_or_equal($categoryids);
2659             $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
2660             foreach ($categories as $category) {
2661                 $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
2662             }
2663             $categories->close();
2664         } else {
2665             foreach ($courses as $course) {
2666                 $this->add_course($course, false, self::COURSE_MY);
2667             }
2668         }
2669     }
2672 /**
2673  * The global navigation class used especially for AJAX requests.
2674  *
2675  * The primary methods that are used in the global navigation class have been overriden
2676  * to ensure that only the relevant branch is generated at the root of the tree.
2677  * This can be done because AJAX is only used when the backwards structure for the
2678  * requested branch exists.
2679  * This has been done only because it shortens the amounts of information that is generated
2680  * which of course will speed up the response time.. because no one likes laggy AJAX.
2681  *
2682  * @package   core
2683  * @category  navigation
2684  * @copyright 2009 Sam Hemelryk
2685  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2686  */
2687 class global_navigation_for_ajax extends global_navigation {
2689     /** @var int used for determining what type of navigation_node::TYPE_* is being used */
2690     protected $branchtype;
2692     /** @var int the instance id */
2693     protected $instanceid;
2695     /** @var array Holds an array of expandable nodes */
2696     protected $expandable = array();
2698     /**
2699      * Constructs the navigation for use in an AJAX request
2700      *
2701      * @param moodle_page $page moodle_page object
2702      * @param int $branchtype
2703      * @param int $id
2704      */
2705     public function __construct($page, $branchtype, $id) {
2706         $this->page = $page;
2707         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
2708         $this->children = new navigation_node_collection();
2709         $this->branchtype = $branchtype;
2710         $this->instanceid = $id;
2711         $this->initialise();
2712     }
2713     /**
2714      * Initialise the navigation given the type and id for the branch to expand.
2715      *
2716      * @return array An array of the expandable nodes
2717      */
2718     public function initialise() {
2719         global $DB, $SITE;
2721         if ($this->initialised || during_initial_install()) {
2722             return $this->expandable;
2723         }
2724         $this->initialised = true;
2726         $this->rootnodes = array();
2727         $this->rootnodes['site']    = $this->add_course($SITE);
2728         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
2729         $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
2731         // Branchtype will be one of navigation_node::TYPE_*
2732         switch ($this->branchtype) {
2733             case 0:
2734                 if ($this->instanceid === 'mycourses') {
2735                     $this->load_courses_enrolled();
2736                 } else if ($this->instanceid === 'courses') {
2737                     $this->load_courses_other();
2738                 }
2739                 break;
2740             case self::TYPE_CATEGORY :
2741                 $this->load_category($this->instanceid);
2742                 break;
2743             case self::TYPE_MY_CATEGORY :
2744                 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
2745                 break;
2746             case self::TYPE_COURSE :
2747                 $course = get_course($this->instanceid);
2748                 require_course_login($course, true, null, false, true);
2749                 $this->page->set_context(context_course::instance($course->id));
2750                 $coursenode = $this->add_course($course);
2751                 $this->add_course_essentials($coursenode, $course);
2752                 $this->load_course_sections($course, $coursenode);
2753                 break;
2754             case self::TYPE_SECTION :
2755                 $sql = 'SELECT c.*, cs.section AS sectionnumber
2756                         FROM {course} c
2757                         LEFT JOIN {course_sections} cs ON cs.course = c.id
2758                         WHERE cs.id = ?';
2759                 $course = $DB->get_record_sql($sql, array($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, $course->sectionnumber);
2765                 break;
2766             case self::TYPE_ACTIVITY :
2767                 $sql = "SELECT c.*
2768                           FROM {course} c
2769                           JOIN {course_modules} cm ON cm.course = c.id
2770                          WHERE cm.id = :cmid";
2771                 $params = array('cmid' => $this->instanceid);
2772                 $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
2773                 $modinfo = get_fast_modinfo($course);
2774                 $cm = $modinfo->get_cm($this->instanceid);
2775                 require_course_login($course, true, $cm, false, true);
2776                 $this->page->set_context(context_module::instance($cm->id));
2777                 $coursenode = $this->load_course($course);
2778                 if ($course->id != $SITE->id) {
2779                     $this->load_course_sections($course, $coursenode, null, $cm);
2780                 }
2781                 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
2782                 break;
2783             default:
2784                 throw new Exception('Unknown type');
2785                 return $this->expandable;
2786         }
2788         if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
2789             $this->load_for_user(null, true);
2790         }
2792         $this->find_expandable($this->expandable);
2793         return $this->expandable;
2794     }
2796     /**
2797      * They've expanded the general 'courses' branch.
2798      */
2799     protected function load_courses_other() {
2800         $this->load_all_courses();
2801     }
2803     /**
2804      * Loads a single category into the AJAX navigation.
2805      *
2806      * This function is special in that it doesn't concern itself with the parent of
2807      * the requested category or its siblings.
2808      * This is because with the AJAX navigation we know exactly what is wanted and only need to
2809      * request that.
2810      *
2811      * @global moodle_database $DB
2812      * @param int $categoryid id of category to load in navigation.
2813      * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
2814      * @return void.
2815      */
2816     protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
2817         global $CFG, $DB;
2819         $limit = 20;
2820         if (!empty($CFG->navcourselimit)) {
2821             $limit = (int)$CFG->navcourselimit;
2822         }
2824         $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
2825         $sql = "SELECT cc.*, $catcontextsql
2826                   FROM {course_categories} cc
2827                   JOIN {context} ctx ON cc.id = ctx.instanceid
2828                  WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
2829                        (cc.id = :categoryid1 OR cc.parent = :categoryid2)
2830               ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
2831         $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
2832         $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
2833         $categorylist = array();
2834         $subcategories = array();
2835         $basecategory = null;
2836         foreach ($categories as $category) {
2837             $categorylist[] = $category->id;
2838             context_helper::preload_from_record($category);
2839             if ($category->id == $categoryid) {
2840                 $this->add_category($category, $this, $nodetype);
2841                 $basecategory = $this->addedcategories[$category->id];
2842             } else {
2843                 $subcategories[$category->id] = $category;
2844             }
2845         }
2846         $categories->close();
2849         // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
2850         // else show all courses.
2851         if ($nodetype === self::TYPE_MY_CATEGORY) {
2852             $courses = enrol_get_my_courses();
2853             $categoryids = array();
2855             // Only search for categories if basecategory was found.
2856             if (!is_null($basecategory)) {
2857                 // Get course parent category ids.
2858                 foreach ($courses as $course) {
2859                     $categoryids[] = $course->category;
2860                 }
2862                 // Get a unique list of category ids which a part of the path
2863                 // to user's courses.
2864                 $coursesubcategories = array();
2865                 $addedsubcategories = array();
2867                 list($sql, $params) = $DB->get_in_or_equal($categoryids);
2868                 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
2870                 foreach ($categories as $category){
2871                     $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
2872                 }
2873                 $coursesubcategories = array_unique($coursesubcategories);
2875                 // Only add a subcategory if it is part of the path to user's course and
2876                 // wasn't already added.
2877                 foreach ($subcategories as $subid => $subcategory) {
2878                     if (in_array($subid, $coursesubcategories) &&
2879                             !in_array($subid, $addedsubcategories)) {
2880                             $this->add_category($subcategory, $basecategory, $nodetype);
2881                             $addedsubcategories[] = $subid;
2882                     }
2883                 }
2884             }
2886             foreach ($courses as $course) {
2887                 // Add course if it's in category.
2888                 if (in_array($course->category, $categorylist)) {
2889                     $this->add_course($course, true, self::COURSE_MY);
2890                 }
2891             }
2892         } else {
2893             if (!is_null($basecategory)) {
2894                 foreach ($subcategories as $key=>$category) {
2895                     $this->add_category($category, $basecategory, $nodetype);
2896                 }
2897             }
2898             $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
2899             foreach ($courses as $course) {
2900                 $this->add_course($course);
2901             }
2902             $courses->close();
2903         }
2904     }
2906     /**
2907      * Returns an array of expandable nodes
2908      * @return array
2909      */
2910     public function get_expandable() {
2911         return $this->expandable;
2912     }
2915 /**
2916  * Navbar class
2917  *
2918  * This class is used to manage the navbar, which is initialised from the navigation
2919  * object held by PAGE
2920  *
2921  * @package   core
2922  * @category  navigation
2923  * @copyright 2009 Sam Hemelryk
2924  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2925  */
2926 class navbar extends navigation_node {
2927     /** @var bool A switch for whether the navbar is initialised or not */
2928     protected $initialised = false;
2929     /** @var mixed keys used to reference the nodes on the navbar */
2930     protected $keys = array();
2931     /** @var null|string content of the navbar */
2932     protected $content = null;
2933     /** @var moodle_page object the moodle page that this navbar belongs to */
2934     protected $page;
2935     /** @var bool A switch for whether to ignore the active navigation information */
2936     protected $ignoreactive = false;
2937     /** @var bool A switch to let us know if we are in the middle of an install */
2938     protected $duringinstall = false;
2939     /** @var bool A switch for whether the navbar has items */
2940     protected $hasitems = false;
2941     /** @var array An array of navigation nodes for the navbar */
2942     protected $items;
2943     /** @var array An array of child node objects */
2944     public $children = array();
2945     /** @var bool A switch for whether we want to include the root node in the navbar */
2946     public $includesettingsbase = false;
2947     /**
2948      * The almighty constructor
2949      *
2950      * @param moodle_page $page
2951      */
2952     public function __construct(moodle_page $page) {
2953         global $CFG;
2954         if (during_initial_install()) {
2955             $this->duringinstall = true;
2956             return false;
2957         }
2958         $this->page = $page;
2959         $this->text = get_string('home');
2960         $this->shorttext = get_string('home');
2961         $this->action = new moodle_url($CFG->wwwroot);
2962         $this->nodetype = self::NODETYPE_BRANCH;
2963         $this->type = self::TYPE_SYSTEM;
2964     }
2966     /**
2967      * Quick check to see if the navbar will have items in.
2968      *
2969      * @return bool Returns true if the navbar will have items, false otherwise
2970      */
2971     public function has_items() {
2972         if ($this->duringinstall) {
2973             return false;
2974         } else if ($this->hasitems !== false) {
2975             return true;
2976         }
2977         $this->page->navigation->initialise($this->page);
2979         $activenodefound = ($this->page->navigation->contains_active_node() ||
2980                             $this->page->settingsnav->contains_active_node());
2982         $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
2983         $this->hasitems = $outcome;
2984         return $outcome;
2985     }
2987     /**
2988      * Turn on/off ignore active
2989      *
2990      * @param bool $setting
2991      */
2992     public function ignore_active($setting=true) {
2993         $this->ignoreactive = ($setting);
2994     }
2996     /**
2997      * Gets a navigation node
2998      *
2999      * @param string|int $key for referencing the navbar nodes
3000      * @param int $type navigation_node::TYPE_*
3001      * @return navigation_node|bool
3002      */
3003     public function get($key, $type = null) {
3004         foreach ($this->children as &$child) {
3005             if ($child->key === $key && ($type == null || $type == $child->type)) {
3006                 return $child;
3007             }
3008         }
3009         return false;
3010     }
3011     /**
3012      * Returns an array of navigation_node's that make up the navbar.
3013      *
3014      * @return array
3015      */
3016     public function get_items() {
3017         global $CFG;
3018         $items = array();
3019         // Make sure that navigation is initialised
3020         if (!$this->has_items()) {
3021             return $items;
3022         }
3023         if ($this->items !== null) {
3024             return $this->items;
3025         }
3027         if (count($this->children) > 0) {
3028             // Add the custom children
3029             $items = array_reverse($this->children);
3030         }
3032         $navigationactivenode = $this->page->navigation->find_active_node();
3033         $settingsactivenode = $this->page->settingsnav->find_active_node();
3035         // Check if navigation contains the active node
3036         if (!$this->ignoreactive) {
3038             if ($navigationactivenode && $settingsactivenode) {
3039                 // Parse a combined navigation tree
3040                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3041                     if (!$settingsactivenode->mainnavonly) {
3042                         $items[] = $settingsactivenode;
3043                     }
3044                     $settingsactivenode = $settingsactivenode->parent;
3045                 }
3046                 if (!$this->includesettingsbase) {
3047                     // Removes the first node from the settings (root node) from the list
3048                     array_pop($items);
3049                 }
3050                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3051                     if (!$navigationactivenode->mainnavonly) {
3052                         $items[] = $navigationactivenode;
3053                     }
3054                     if (!empty($CFG->navshowcategories) &&
3055                             $navigationactivenode->type === self::TYPE_COURSE &&
3056                             $navigationactivenode->parent->key === 'currentcourse') {
3057                         $items = array_merge($items, $this->get_course_categories());
3058                     }
3059                     $navigationactivenode = $navigationactivenode->parent;
3060                 }
3061             } else if ($navigationactivenode) {
3062                 // Parse the navigation tree to get the active node
3063                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
3064                     if (!$navigationactivenode->mainnavonly) {
3065                         $items[] = $navigationactivenode;
3066                     }
3067                     if (!empty($CFG->navshowcategories) &&
3068                             $navigationactivenode->type === self::TYPE_COURSE &&
3069                             $navigationactivenode->parent->key === 'currentcourse') {
3070                         $items = array_merge($items, $this->get_course_categories());
3071                     }
3072                     $navigationactivenode = $navigationactivenode->parent;
3073                 }
3074             } else if ($settingsactivenode) {
3075                 // Parse the settings navigation to get the active node
3076                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
3077                     if (!$settingsactivenode->mainnavonly) {
3078                         $items[] = $settingsactivenode;
3079                     }
3080                     $settingsactivenode = $settingsactivenode->parent;
3081                 }
3082             }
3083         }
3085         $items[] = new navigation_node(array(
3086             'text'=>$this->page->navigation->text,
3087             'shorttext'=>$this->page->navigation->shorttext,
3088             'key'=>$this->page->navigation->key,
3089             'action'=>$this->page->navigation->action
3090         ));
3092         $this->items = array_reverse($items);
3093         return $this->items;
3094     }
3096     /**
3097      * Get the list of categories leading to this course.
3098      *
3099      * This function is used by {@link navbar::get_items()} to add back the "courses"
3100      * node and category chain leading to the current course.  Note that this is only ever
3101      * called for the current course, so we don't need to bother taking in any parameters.
3102      *
3103      * @return array
3104      */
3105     private function get_course_categories() {
3106         $categories = array();
3107         foreach ($this->page->categories as $category) {
3108             $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
3109             $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
3110             $categories[] = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
3111             $id = $category->parent;
3112         }
3113         if (is_enrolled(context_course::instance($this->page->course->id))) {
3114             $courses = $this->page->navigation->get('mycourses');
3115         } else {
3116             $courses = $this->page->navigation->get('courses');
3117         }
3118         if (!$courses) {
3119             // Courses node may not be present.
3120             $courses = navigation_node::create(
3121                 get_string('courses'),
3122                 new moodle_url('/course/index.php'),
3123                 self::TYPE_CONTAINER
3124             );
3125         }
3126         $categories[] = $courses;
3127         return $categories;
3128     }
3130     /**
3131      * Add a new navigation_node to the navbar, overrides parent::add
3132      *
3133      * This function overrides {@link navigation_node::add()} so that we can change
3134      * the way nodes get added to allow us to simply call add and have the node added to the
3135      * end of the navbar
3136      *
3137      * @param string $text
3138      * @param string|moodle_url|action_link $action An action to associate with this node.
3139      * @param int $type One of navigation_node::TYPE_*
3140      * @param string $shorttext
3141      * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
3142      * @param pix_icon $icon An optional icon to use for this node.
3143      * @return navigation_node
3144      */
3145     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
3146         if ($this->content !== null) {
3147             debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
3148         }
3150         // Properties array used when creating the new navigation node
3151         $itemarray = array(
3152             'text' => $text,
3153             'type' => $type
3154         );
3155         // Set the action if one was provided
3156         if ($action!==null) {
3157             $itemarray['action'] = $action;
3158         }
3159         // Set the shorttext if one was provided
3160         if ($shorttext!==null) {
3161             $itemarray['shorttext'] = $shorttext;
3162         }
3163         // Set the icon if one was provided
3164         if ($icon!==null) {
3165             $itemarray['icon'] = $icon;
3166         }
3167         // Default the key to the number of children if not provided
3168         if ($key === null) {
3169             $key = count($this->children);
3170         }
3171         // Set the key
3172         $itemarray['key'] = $key;
3173         // Set the parent to this node
3174         $itemarray['parent'] = $this;
3175         // Add the child using the navigation_node_collections add method
3176         $this->children[] = new navigation_node($itemarray);
3177         return $this;
3178     }
3181 /**
3182  * Class used to manage the settings option for the current page
3183  *
3184  * This class is used to manage the settings options in a tree format (recursively)
3185  * and was created initially for use with the settings blocks.
3186  *
3187  * @package   core
3188  * @category  navigation
3189  * @copyright 2009 Sam Hemelryk
3190  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3191  */
3192 class settings_navigation extends navigation_node {
3193     /** @var stdClass the current context */
3194     protected $context;
3195     /** @var moodle_page the moodle page that the navigation belongs to */
3196     protected $page;
3197     /** @var string contains administration section navigation_nodes */
3198     protected $adminsection;
3199     /** @var bool A switch to see if the navigation node is initialised */
3200     protected $initialised = false;
3201     /** @var array An array of users that the nodes can extend for. */
3202     protected $userstoextendfor = array();
3203     /** @var navigation_cache **/
3204     protected $cache;
3206     /**
3207      * Sets up the object with basic settings and preparse it for use
3208      *
3209      * @param moodle_page $page
3210      */
3211     public function __construct(moodle_page &$page) {
3212         if (during_initial_install()) {
3213             return false;
3214         }
3215         $this->page = $page;
3216         // Initialise the main navigation. It is most important that this is done
3217         // before we try anything
3218         $this->page->navigation->initialise();
3219         // Initialise the navigation cache
3220         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
3221         $this->children = new navigation_node_collection();
3222     }
3223     /**
3224      * Initialise the settings navigation based on the current context
3225      *
3226      * This function initialises the settings navigation tree for a given context
3227      * by calling supporting functions to generate major parts of the tree.
3228      *
3229      */
3230     public function initialise() {
3231         global $DB, $SESSION, $SITE;
3233         if (during_initial_install()) {
3234             return false;
3235         } else if ($this->initialised) {
3236             return true;
3237         }
3238         $this->id = 'settingsnav';
3239         $this->context = $this->page->context;
3241         $context = $this->context;
3242         if ($context->contextlevel == CONTEXT_BLOCK) {
3243             $this->load_block_settings();
3244             $context = $context->get_parent_context();
3245         }
3247         switch ($context->contextlevel) {
3248             case CONTEXT_SYSTEM:
3249                 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
3250                     $this->load_front_page_settings(($context->id == $this->context->id));
3251                 }
3252                 break;
3253             case CONTEXT_COURSECAT:
3254                 $this->load_category_settings();
3255                 break;
3256             case CONTEXT_COURSE:
3257                 if ($this->page->course->id != $SITE->id) {
3258                     $this->load_course_settings(($context->id == $this->context->id));
3259                 } else {
3260                     $this->load_front_page_settings(($context->id == $this->context->id));
3261                 }
3262                 break;
3263             case CONTEXT_MODULE:
3264                 $this->load_module_settings();
3265                 $this->load_course_settings();
3266                 break;
3267             case CONTEXT_USER:
3268                 if ($this->page->course->id != $SITE->id) {
3269                     $this->load_course_settings();
3270                 }
3271                 break;
3272         }
3274         $settings = $this->load_user_settings($this->page->course->id);
3276         if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
3277             $admin = $this->load_administration_settings();
3278             $SESSION->load_navigation_admin = ($admin->has_children());
3279         } else {
3280             $admin = false;
3281         }
3283         if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
3284             $admin->force_open();
3285         } else if ($context->contextlevel == CONTEXT_USER && $settings) {
3286             $settings->force_open();
3287         }
3289         // Check if the user is currently logged in as another user
3290         if (session_is_loggedinas()) {
3291             // Get the actual user, we need this so we can display an informative return link
3292             $realuser = session_get_realuser();
3293             // Add the informative return to original user link
3294             $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
3295             $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
3296         }
3298         // At this point we give any local&nb