Updated the HEAD build version to 20100422
[moodle.git] / lib / navigationlib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * This file contains classes used to manage the navigation structures in Moodle
20  * and was introduced as part of the changes occuring in Moodle 2.0
21  *
22  * @since 2.0
23  * @package moodlecore
24  * @subpackage navigation
25  * @copyright 2009 Sam Hemelryk
26  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27  */
29 if (!function_exists('get_all_sections')) {
30     /** Include course lib for its functions */
31     require_once($CFG->dirroot.'/course/lib.php');
32 }
34 /**
35  * The name that will be used to separate the navigation cache within SESSION
36  */
37 define('NAVIGATION_CACHE_NAME', 'navigation');
39 /**
40  * This class is used to represent a node in a navigation tree
41  *
42  * This class is used to represent a node in a navigation tree within Moodle,
43  * the tree could be one of global navigation, settings navigation, or the navbar.
44  * Each node can be one of two types either a Leaf (default) or a branch.
45  * When a node is first created it is created as a leaf, when/if children are added
46  * the node then becomes a branch.
47  *
48  * @package moodlecore
49  * @subpackage navigation
50  * @copyright 2009 Sam Hemelryk
51  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52  */
53 class navigation_node implements renderable {
54     /** @var int Used to identify this node a leaf (default) 0 */
55     const NODETYPE_LEAF =   0;
56     /** @var int Used to identify this node a branch, happens with children  1 */
57     const NODETYPE_BRANCH = 1;
58     /** @var null Unknown node type null */
59     const TYPE_UNKNOWN =    null;
60     /** @var int System node type 0 */
61     const TYPE_ROOTNODE =   0;
62     /** @var int System node type 1 */
63     const TYPE_SYSTEM =     1;
64     /** @var int Category node type 10 */
65     const TYPE_CATEGORY =   10;
66     /** @var int Course node type 20 */
67     const TYPE_COURSE =     20;
68     /** @var int Course Structure node type 30 */
69     const TYPE_SECTION =    30;
70     /** @var int Activity node type, e.g. Forum, Quiz 40 */
71     const TYPE_ACTIVITY =   40;
72     /** @var int Resource node type, e.g. Link to a file, or label 50 */
73     const TYPE_RESOURCE =   50;
74     /** @var int A custom node type, default when adding without specifing type 60 */
75     const TYPE_CUSTOM =     60;
76     /** @var int Setting node type, used only within settings nav 70 */
77     const TYPE_SETTING =    70;
78     /** @var int Setting node type, used only within settings nav 80 */
79     const TYPE_USER =       80;
80     /** @var int Setting node type, used for containers of no importance 90 */
81     const TYPE_CONTAINER =  90;
83     /** @var int Parameter to aid the coder in tracking [optional] */
84     public $id = null;
85     /** @var string|int The identifier for the node, used to retrieve the node */
86     public $key = null;
87     /** @var string The text to use for the node */
88     public $text = null;
89     /** @var string Short text to use if requested [optional] */
90     public $shorttext = null;
91     /** @var string The title attribute for an action if one is defined */
92     public $title = null;
93     /** @var string A string that can be used to build a help button */
94     public $helpbutton = null;
95     /** @var moodle_url|action_link|null An action for the node (link) */
96     public $action = null;
97     /** @var pix_icon The path to an icon to use for this node */
98     public $icon = null;
99     /** @var int See TYPE_* constants defined for this class */
100     public $type = self::TYPE_UNKNOWN;
101     /** @var int See NODETYPE_* constants defined for this class */
102     public $nodetype = self::NODETYPE_LEAF;
103     /** @var bool If set to true the node will be collapsed by default */
104     public $collapse = false;
105     /** @var bool If set to true the node will be expanded by default */
106     public $forceopen = false;
107     /** @var array An array of CSS classes for the node */
108     public $classes = array();
109     /** @var navigation_node_collection An array of child nodes */
110     public $children = array();
111     /** @var bool If set to true the node will be recognised as active */
112     public $isactive = false;
113     /** @var bool If set to true the node will be dimmed */
114     public $hidden = false;
115     /** @var bool If set to false the node will not be displayed */
116     public $display = true;
117     /** @var bool If set to true then an HR will be printed before the node */
118     public $preceedwithhr = false;
119     /** @var bool If set to true the the navigation bar should ignore this node */
120     public $mainnavonly = false;
121     /** @var bool If set to true a title will be added to the action no matter what */
122     public $forcetitle = false;
123     /** @var navigation_node A reference to the node parent */
124     public $parent = null;
125     /** @var array */
126     protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting', 80=>'user');
127     /** @var moodle_url */
128     protected static $fullmeurl = null;
129     /** @var bool toogles auto matching of active node */
130     public static $autofindactive = true;
132     /**
133      * Constructs a new navigation_node
134      *
135      * @param array|string $properties Either an array of properties or a string to use
136      *                     as the text for the node
137      */
138     public function __construct($properties) {
139         if (is_array($properties)) {
140             // Check the array for each property that we allow to set at construction.
141             // text         - The main content for the node
142             // shorttext    - A short text if required for the node
143             // icon         - The icon to display for the node
144             // type         - The type of the node
145             // key          - The key to use to identify the node
146             // parent       - A reference to the nodes parent
147             // action       - The action to attribute to this node, usually a URL to link to
148             if (array_key_exists('text', $properties)) {
149                 $this->text = $properties['text'];
150             }
151             if (array_key_exists('shorttext', $properties)) {
152                 $this->shorttext = $properties['shorttext'];
153             }
154             if (array_key_exists('icon', $properties)) {
155                 $this->icon = $properties['icon'];
156                 if ($this->icon instanceof pix_icon) {
157                     if (empty($this->icon->attributes['class'])) {
158                         $this->icon->attributes['class'] = 'navicon';
159                     } else {
160                         $this->icon->attributes['class'] .= ' navicon';
161                     }
162                 }
163             }
164             if (array_key_exists('type', $properties)) {
165                 $this->type = $properties['type'];
166             } else {
167                 $this->type = self::TYPE_CUSTOM;
168             }
169             if (array_key_exists('key', $properties)) {
170                 $this->key = $properties['key'];
171             }
172             if (array_key_exists('parent', $properties)) {
173                 $this->parent = $properties['parent'];
174             }
175             // This needs to happen last because of the check_if_active call that occurs
176             if (array_key_exists('action', $properties)) {
177                 $this->action = $properties['action'];
178                 if (is_string($this->action)) {
179                     $this->action = new moodle_url($this->action);
180                 }
181                 if (self::$autofindactive) {
182                     $this->check_if_active();
183                 }
184             }
185         } else if (is_string($properties)) {
186             $this->text = $properties;
187         }
188         if ($this->text === null) {
189             throw new coding_exception('You must set the text for the node when you create it.');
190         }
191         // Default the title to the text
192         $this->title = $this->text;
193         // Instantiate a new navigation node collection for this nodes children
194         $this->children = new navigation_node_collection();
195     }
197     /**
198      * Checks if this node is the active node.
199      *
200      * This is determined by comparing the action for the node against the
201      * defined URL for the page. A match will see this node marked as active.
202      *
203      * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
204      * @return bool
205      */
206     public function check_if_active($strength=URL_MATCH_EXACT) {
207         global $FULLME, $PAGE;
208         // Set fullmeurl if it hasn't already been set
209         if (self::$fullmeurl == null) {
210             if ($PAGE->has_set_url()) {
211                 self::override_active_url(new moodle_url($PAGE->url));
212             } else {
213                 self::override_active_url(new moodle_url($FULLME));
214             }
215         }
217         // Compare the action of this node against the fullmeurl
218         if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
219             $this->make_active();
220             return true;
221         }
222         return false;
223     }
225     /**
226      * Overrides the fullmeurl variable providing
227      *
228      * @param moodle_url $url The url to use for the fullmeurl.
229      */
230     public static function override_active_url(moodle_url $url) {
231         self::$fullmeurl = $url;
232     }
234     /**
235      * Adds a navigation node as a child of this node.
236      * 
237      * @param string $text
238      * @param moodle_url|action_link $action
239      * @param int $type
240      * @param string $shorttext
241      * @param string|int $key
242      * @param pix_icon $icon
243      * @return navigation_node
244      */
245     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
246         // First convert the nodetype for this node to a branch as it will now have children
247         if ($this->nodetype !== self::NODETYPE_BRANCH) {
248             $this->nodetype = self::NODETYPE_BRANCH;
249         }
250         // Properties array used when creating the new navigation node
251         $itemarray = array(
252             'text' => $text,
253             'type' => $type
254         );
255         // Set the action if one was provided
256         if ($action!==null) {
257             $itemarray['action'] = $action;
258         }
259         // Set the shorttext if one was provided
260         if ($shorttext!==null) {
261             $itemarray['shorttext'] = $shorttext;
262         }
263         // Set the icon if one was provided
264         if ($icon!==null) {
265             $itemarray['icon'] = $icon;
266         }
267         // Default the key to the number of children if not provided
268         if ($key === null) {
269             $key = $this->children->count();
270         }
271         // Set the key
272         $itemarray['key'] = $key;
273         // Set the parent to this node
274         $itemarray['parent'] = $this;
275         // Add the child using the navigation_node_collections add method
276         $node = $this->children->add(new navigation_node($itemarray));
277         // If the node is a category node or the user is logged in and its a course
278         // then mark this node as a branch (makes it expandable by AJAX)
279         if (($type==self::TYPE_CATEGORY) || (isloggedin() && $type==self::TYPE_COURSE)) {
280             $node->nodetype = self::NODETYPE_BRANCH;
281         }
282         // If this node is hidden mark it's children as hidden also
283         if ($this->hidden) {
284             $node->hidden = true;
285         }
286         // Return the node (reference returned by $this->children->add()
287         return $node;
288     }
290     /**
291      * Searches for a node of the given type with the given key.
292      *
293      * This searches this node plus all of its children, and their children....
294      * If you know the node you are looking for is a child of this node then please
295      * use the get method instead.
296      *
297      * @param int|string $key The key of the node we are looking for
298      * @param int $type One of navigation_node::TYPE_*
299      * @return navigation_node|false
300      */
301     public function find($key, $type) {
302         return $this->children->find($key, $type);
303     }
305     /**
306      * Get ths child of this node that has the given key + (optional) type.
307      *
308      * If you are looking for a node and want to search all children + thier children
309      * then please use the find method instead.
310      *
311      * @param int|string $key The key of the node we are looking for
312      * @param int $type One of navigation_node::TYPE_*
313      * @return navigation_node|false
314      */
315     public function get($key, $type=null) {
316         return $this->children->get($key, $type);
317     }
319     /**
320      * Removes this node.
321      *
322      * @return bool
323      */
324     public function remove() {
325         return $this->parent->children->remove($this->key, $this->type);
326     }
328     /**
329      * Checks if this node has or could have any children
330      *
331      * @return bool Returns true if it has children or could have (by AJAX expansion)
332      */
333     public function has_children() {
334         return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0);
335     }
337     /**
338      * Marks this node as active and forces it open.
339      */
340     public function make_active() {
341         $this->isactive = true;
342         $this->add_class('active_tree_node');
343         $this->force_open();
344         if ($this->parent !== null) {
345             $this->parent->make_inactive();
346         }
347     }
349     /**
350      * Marks a node as inactive and recusised back to the base of the tree
351      * doing the same to all parents.
352      */
353     public function make_inactive() {
354         $this->isactive = false;
355         $this->remove_class('active_tree_node');
356         if ($this->parent !== null) {
357             $this->parent->make_inactive();
358         }
359     }
361     /**
362      * Forces this node to be open and at the same time forces open all
363      * parents until the root node.
364      *
365      * Recursive.
366      */
367     public function force_open() {
368         $this->forceopen = true;
369         if ($this->parent !== null) {
370             $this->parent->force_open();
371         }
372     }
374     /**
375      * Adds a CSS class to this node.
376      *
377      * @param string $class
378      * @return bool
379      */
380     public function add_class($class) {
381         if (!in_array($class, $this->classes)) {
382             $this->classes[] = $class;
383         }
384         return true;
385     }
387     /**
388      * Removes a CSS class from this node.
389      *
390      * @param string $class
391      * @return bool True if the class was successfully removed.
392      */
393     public function remove_class($class) {
394         if (in_array($class, $this->classes)) {
395             $key = array_search($class,$this->classes);
396             if ($key!==false) {
397                 unset($this->classes[$key]);
398                 return true;
399             }
400         }
401         return false;
402     }
404     /**
405      * Sets the title for this node and forces Moodle to utilise it.
406      * @param string $title
407      */
408     public function title($title) {
409         $this->title = $title;
410         $this->forcetitle = true;
411     }
413     /**
414      * Resets the page specific information on this node if it is being unserialised.
415      */
416     public function __wakeup(){
417         $this->forceopen = false;
418         $this->isactive = false;
419         $this->remove_class('active_tree_node');
420     }
422     /**
423      * Checks if this node or any of its children contain the active node.
424      * 
425      * Recursive.
426      *
427      * @return bool
428      */
429     public function contains_active_node() {
430         if ($this->isactive) {
431             return true;
432         } else {
433             foreach ($this->children as $child) {
434                 if ($child->isactive || $child->contains_active_node()) {
435                     return true;
436                 }
437             }
438         }
439         return false;
440     }
442     /**
443      * Finds the active node.
444      *
445      * Searches this nodes children plus all of the children for the active node
446      * and returns it if found.
447      *
448      * Recursive.
449      *
450      * @return navigation_node|false
451      */
452     public function find_active_node() {
453         if ($this->isactive) {
454             return $this;
455         } else {
456             foreach ($this->children as &$child) {
457                 $outcome = $child->find_active_node();
458                 if ($outcome !== false) {
459                     return $outcome;
460                 }
461             }
462         }
463         return false;
464     }
466     /**
467      * Gets the content for this node.
468      *
469      * @param bool $shorttext If true shorttext is used rather than the normal text
470      * @return string
471      */
472     public function get_content($shorttext=false) {
473         if ($shorttext && $this->shorttext!==null) {
474             return format_string($this->shorttext);
475         } else {
476             return format_string($this->text);
477         }
478     }
480     /**
481      * Gets the title to use for this node.
482      * 
483      * @return string
484      */
485     public function get_title() {
486         if ($this->forcetitle || ($this->shorttext!==null && $this->title !== $this->shorttext) || $this->title !== $this->text) {
487             return $this->title;
488         } else {
489             return '';
490         }
491     }
493     /**
494      * Gets the CSS class to add to this node to describe its type
495      * 
496      * @return string
497      */
498     public function get_css_type() {
499         if (array_key_exists($this->type, $this->namedtypes)) {
500             return 'type_'.$this->namedtypes[$this->type];
501         }
502         return 'type_unknown';
503     }
505     /**
506      * Finds all nodes that are expandable by AJAX
507      *
508      * @param array $expandable An array by reference to populate with expandable nodes.
509      */
510     public function find_expandable(array &$expandable) {
511         if (!isloggedin()) {
512             return;
513         }
514         foreach ($this->children as &$child) {
515             if ($child->nodetype == self::NODETYPE_BRANCH && $child->children->count()==0 && $child->display) {
516                 $child->id = 'expandable_branch_'.(count($expandable)+1);
517                 $this->add_class('canexpand');
518                 $expandable[] = array('id'=>$child->id,'branchid'=>$child->key,'type'=>$child->type);
519             }
520             $child->find_expandable($expandable);
521         }
522     }
524     public function find_all_of_type($type) {
525         $nodes = $this->children->type($type);
526         foreach ($this->children as &$node) {
527             $childnodes = $node->find_all_of_type($type);
528             $nodes = array_merge($nodes, $childnodes);
529         }
530         return $nodes;
531     }
534 /**
535  * Navigation node collection
536  *
537  * This class is responsible for managing a collection of navigation nodes.
538  * It is required because a node's unique identifier is a combination of both its
539  * key and its type.
540  *
541  * Originally an array was used with a string key that was a combination of the two
542  * however it was decided that a better solution would be to use a class that
543  * implements the standard IteratorAggregate interface.
544  *
545  * @package moodlecore
546  * @subpackage navigation
547  * @copyright 2010 Sam Hemelryk
548  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
549  */
550 class navigation_node_collection implements IteratorAggregate {
551     /**
552      * A multidimensional array to where the first key is the type and the second
553      * key is the nodes key.
554      * @var array
555      */
556     protected $collection = array();
557     /**
558      * An array that contains references to nodes in the same order they were added.
559      * This is maintained as a progressive array.
560      * @var array
561      */
562     protected $orderedcollection = array();
563     /**
564      * A reference to the last node that was added to the collection
565      * @var navigation_node
566      */
567     protected $last = null;
568     /**
569      * The total number of items added to this array.
570      * @var int
571      */
572     protected $count = 0;
573     /**
574      * Adds a navigation node to the collection
575      *
576      * @param navigation_node $node
577      * @return navigation_node
578      */
579     public function add(navigation_node $node) {
580         global $CFG;
581         $key = $node->key;
582         $type = $node->type;
583         // First check we have a 2nd dimension for this type
584         if (!array_key_exists($type, $this->orderedcollection)) {
585             $this->orderedcollection[$type] = array();
586         }
587         // Check for a collision and report if debugging is turned on
588         if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
589             debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
590         }
591         // Add the node to the appropriate place in the ordered structure.
592         $this->orderedcollection[$type][$key] = $node;
593         // Add a reference to the node to the progressive collection.
594         $this->collection[$this->count] = &$this->orderedcollection[$type][$key];
595         // Update the last property to a reference to this new node.
596         $this->last = &$this->orderedcollection[$type][$key];
597         $this->count++;
598         // Return the reference to the now added node
599         return $this->last;
600     }
602     /**
603      * Fetches a node from this collection.
604      *
605      * @param string|int $key The key of the node we want to find.
606      * @param int $type One of navigation_node::TYPE_*.
607      * @return navigation_node|null
608      */
609     public function get($key, $type=null) {
610         if ($type !== null) {
611             // If the type is known then we can simply check and fetch
612             if (!empty($this->orderedcollection[$type][$key])) {
613                 return $this->orderedcollection[$type][$key];
614             }
615         } else {
616             // Because we don't know the type we look in the progressive array
617             foreach ($this->collection as $node) {
618                 if ($node->key === $key) {
619                     return $node;
620                 }
621             }
622         }
623         return false;
624     }
625     /**
626      * Searches for a node with matching key and type.
627      *
628      * This function searches both the nodes in this collection and all of
629      * the nodes in each collection belonging to the nodes in this collection.
630      *
631      * Recursive.
632      *
633      * @param string|int $key  The key of the node we want to find.
634      * @param int $type  One of navigation_node::TYPE_*.
635      * @return navigation_node|null
636      */
637     public function find($key, $type=null) {
638         if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
639             return $this->orderedcollection[$type][$key];
640         } else {
641             $nodes = $this->getIterator();
642             // Search immediate children first
643             foreach ($nodes as &$node) {
644                 if ($node->key == $key && ($type == null || $type === $node->type)) {
645                     return $node;
646                 }
647             }
648             // Now search each childs children
649             foreach ($nodes as &$node) {
650                 $result = $node->children->find($key, $type);
651                 if ($result !== false) {
652                     return $result;
653                 }
654             }
655         }
656         return false;
657     }
659     /**
660      * Fetches the last node that was added to this collection
661      * 
662      * @return navigation_node
663      */
664     public function last() {
665         return $this->last;
666     }
667     /**
668      * Fetches all nodes of a given type from this collection
669      */
670     public function type($type) {
671         if (!array_key_exists($type, $this->orderedcollection)) {
672             $this->orderedcollection[$type] = array();
673         }
674         return $this->orderedcollection[$type];
675     }
676     /**
677      * Removes the node with the given key and type from the collection
678      *
679      * @param string|int $key
680      * @param int $type
681      * @return bool
682      */
683     public function remove($key, $type=null) {
684         $child = $this->get($key, $type);
685         if ($child !== false) {
686             foreach ($this->collection as $colkey => $node) {
687                 if ($node->key == $key && $node->type == $type) {
688                     unset($this->collection[$colkey]);
689                     break;
690                 }
691             }
692             unset($this->orderedcollection[$child->type][$child->key]);
693             $this->count--;
694             return true;
695         }
696         return false;
697     }
699     /**
700      * Gets the number of nodes in this collection
701      * @return int
702      */
703     public function count() {
704         return count($this->collection);
705     }
706     /**
707      * Gets an array iterator for the collection.
708      *
709      * This is required by the IteratorAggregator interface and is used by routines
710      * such as the foreach loop.
711      *
712      * @return ArrayIterator
713      */
714     public function getIterator() {
715         return new ArrayIterator($this->collection);
716     }
719 /**
720  * The global navigation class used for... the global navigation
721  *
722  * This class is used by PAGE to store the global navigation for the site
723  * and is then used by the settings nav and navbar to save on processing and DB calls
724  *
725  * See
726  * <ul>
727  * <li><b>{@link lib/pagelib.php}</b> {@link moodle_page::initialise_theme_and_output()}<li>
728  * <li><b>{@link lib/ajax/getnavbranch.php}</b> Called by ajax<li>
729  * </ul>
730  *
731  * @package moodlecore
732  * @subpackage navigation
733  * @copyright 2009 Sam Hemelryk
734  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
735  */
736 class global_navigation extends navigation_node {
737     /**
738      * The Moodle page this navigation object belongs to.
739      * @var moodle_page
740      */
741     protected $page;
742     /** @var bool */
743     protected $initialised = false;
744     /** @var array */
745     protected $mycourses = array();
746     /** @var array */
747     protected $rootnodes = array();
748     /** @var bool */
749     protected $showemptysections = false;
750     /** @var array */
751     protected $extendforuser = array();
752     /** @var navigation_cache */
753     protected $cache;
754     /** @var array */
755     protected $addedcourses = array();
756     /** @var int */
757     protected $expansionlimit = 0;
759     /**
760      * Constructs a new global navigation
761      *
762      * @param moodle_page $page The page this navigation object belongs to
763      */
764     public function __construct(moodle_page $page) {
765         global $SITE, $USER;
767         if (during_initial_install()) {
768             return;
769         }
771         // Use the parents consturctor.... good good reuse
772         $properties = array(
773             'key' => 'home',
774             'type' => navigation_node::TYPE_SYSTEM,
775             'text' => get_string('myhome'),
776             'action' => new moodle_url('/my/')
777         );
778         parent::__construct($properties);
780         // Initalise and set defaults
781         $this->page = $page;
782         $this->forceopen = true;
783         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
785         // Check if we need to clear the cache
786         $regenerate = optional_param('regenerate', null, PARAM_TEXT);
787         if ($regenerate === 'navigation') {
788             $this->cache->clear();
789         }
790     }
792     /**
793      * Initialises the navigation object.
794      *
795      * This causes the navigation object to look at the current state of the page
796      * that it is associated with and then load the appropriate content.
797      *
798      * This should only occur the first time that the navigation structure is utilised
799      * which will normally be either when the navbar is called to be displayed or
800      * when a block makes use of it.
801      *
802      * @return bool
803      */
804     public function initialise() {
805         global $SITE, $USER;
806         // Check if it has alread been initialised
807         if ($this->initialised || during_initial_install()) {
808             return true;
809         }
811         // Set up the five base root nodes. These are nodes where we will put our
812         // content and are as follows:
813         // site:        Navigation for the front page.
814         // myprofile:     User profile information goes here.
815         // mycourses:   The users courses get added here.
816         // courses:     Additional courses are added here.
817         // users:       Other users information loaded here.
818         $this->rootnodes = array();
819         $this->rootnodes['site']      = $this->add_course($SITE);
820         $this->rootnodes['myprofile']   = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile');
821         $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
822         $this->rootnodes['courses']   = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
823         $this->rootnodes['users']     = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
825         // Fetch all of the users courses.
826         $this->mycourses = get_my_courses($USER->id);
827         // Check if any courses were returned.
828         if (count($this->mycourses) > 0) {
829             // Add all of the users courses to the navigation
830             foreach ($this->mycourses as &$course) {
831               $course->coursenode = $this->add_course($course);
832             }
833         } else {
834             // The user had no specific courses! they could be no logged in, guest
835             // or admin so load all courses instead.
836             $this->load_all_courses();
837         }
839         // Next load context specific content into the navigation
840         switch ($this->page->context->contextlevel) {
841             case CONTEXT_SYSTEM :
842             case CONTEXT_COURSECAT :
843                 // Load the front page course navigation
844                 $this->load_course($SITE);
845                 break;
846             case CONTEXT_BLOCK :
847             case CONTEXT_COURSE :
848                 // Load the course associated with the page into the navigation
849                 $course = $this->page->course;
850                 $coursenode = $this->load_course($course);
851                 // Make it active
852                 $coursenode->make_active();
853                 // Add the essentials such as reports etc...
854                 $this->add_course_essentials($coursenode, $course);
855                 if ($this->format_display_course_content($course->format)) {
856                     // Load the course sections
857                     $sections = $this->load_course_sections($course, $coursenode);
858                 }
859                 break;
860             case CONTEXT_MODULE :
861                 $course = $this->page->course;
862                 $cm = $this->page->cm;
863                 // Load the course associated with the page into the navigation
864                 $coursenode = $this->load_course($course);
865                 $this->add_course_essentials($coursenode, $course);
866                 // Load the course sections into the page
867                 $sections = $this->load_course_sections($course, $coursenode);
868                 if ($course->id !== SITEID) {
869                     // Find the section for the $CM associated with the page and collect
870                     // its section number.
871                     foreach ($sections as $section) {
872                         if ($section->id == $cm->section) {
873                             $cm->sectionnumber = $section->section;
874                             break;
875                         }
876                     }
878                     // Load all of the section activities for the section the cm belongs to.
879                     $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
880                     // Finally load the cm specific navigaton information
881                 } else {
882                     $activities = array();
883                     $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY);
884                 }
885                 $this->load_activity($cm, $course, $activities[$cm->id]);
886                 // And make the activity node active.
887                 $activities[$cm->id]->make_active();
888                 break;
889             case CONTEXT_USER :
890                 $course = $this->page->course;
891                 if ($course->id != SITEID) {
892                     // Load the course associated with the user into the navigation
893                     $coursenode = $this->load_course($course);
894                     $this->add_course_essentials($coursenode, $course);
895                     $sections = $this->load_course_sections($course, $coursenode);
896                 }
897                 break;
898         }
900         // Load for the current user
901         $this->load_for_user();
902         // Load each extending user into the navigation.
903         foreach ($this->extendforuser as $user) {
904             if ($user->id !== $USER->id) {
905                 $this->load_for_user($user);
906             }
907         }
909         // Remove any empty root nodes
910         foreach ($this->rootnodes as $node) {
911             if (!$node->has_children()) {
912                 $node->remove();
913             }
914         }
916         // If the user is not logged in modify the navigation structure as detailed
917         // in {@link http://docs.moodle.org/en/Development:Navigation_2.0_structure}
918         if (!isloggedin()) {
919             $activities = clone($this->rootnodes['site']->children);
920             $this->rootnodes['site']->remove();
921             $children = clone($this->children);
922             $this->children = new navigation_node_collection();
923             foreach ($activities as $child) {
924                 $this->children->add($child);
925             }
926             foreach ($children as $child) {
927                 $this->children->add($child);
928             }
929             $this->action = new moodle_url('/');
930         }
932         $this->initialised = true;
933         return true;
934     }
935     /**
936      * Checks the course format to see whether it wants the navigation to load
937      * additional information for the course.
938      *
939      * This function utilises a callback that can exist within the course format lib.php file
940      * The callback should be a function called:
941      * callback_{formatname}_display_content()
942      * It doesn't get any arguments and should return true if additional content is
943      * desired. If the callback doesn't exist we assume additional content is wanted.
944      *
945      * @param string $format The course format
946      * @return bool
947      */
948     protected function format_display_course_content($format) {
949         global $CFG;
950         $formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
951         if (file_exists($formatlib)) {
952             require_once($formatlib);
953             $displayfunc = 'callback_'.$format.'_display_content';
954             if (function_exists($displayfunc) && !$displayfunc()) {
955                 return $displayfunc();
956             }
957         }
958         return true;
959     }
961     /**
962      * Loads of the the courses in Moodle into the navigation.
963      *
964      * @return array An array of navigation_node
965      */
966     protected function load_all_courses() {
967         global $DB, $USER;
968         list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
969         $sql = "SELECT c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.category,cat.path AS categorypath $ccselect
970                 FROM {course} c
971                 $ccjoin
972                 LEFT JOIN {course_categories} cat ON cat.id=c.category
973                 WHERE c.id != :siteid
974                 ORDER BY c.sortorder ASC";
975         $courses = $DB->get_records_sql($sql, array('siteid'=>SITEID));
976         $coursenodes = array();
977         foreach ($courses as $course) {
978             context_instance_preload($course);
979             $coursenodes[$course->id] = $this->add_course($course);
980         }
981         return $coursenodes;
982     }
984     /**
985      * Loads the given course into the navigation
986      *
987      * @param stdClass $course
988      * @return navigation_node
989      */
990     protected function load_course(stdClass $course) {
991         if ($course->id == SITEID) {
992             $coursenode = $this->rootnodes['site'];
993         } else if (array_key_exists($course->id, $this->mycourses)) {
994             if (!isset($this->mycourses[$course->id]->coursenode)) {
995                 $this->mycourses[$course->id]->coursenode = $this->add_course($course);
996             }
997             $coursenode = $this->mycourses[$course->id]->coursenode;
998         } else {
999             $coursenode = $this->add_course($course);
1000         }
1001         return $coursenode;
1002     }
1004     /**
1005      * Loads all of the courses section into the navigation.
1006      *
1007      * This function utilisies a callback that can be implemented within the course
1008      * formats lib.php file to customise the navigation that is generated at this
1009      * point for the course.
1010      *
1011      * By default (if not defined) the method {@see load_generic_course_sections} is
1012      * called instead.
1013      *
1014      * @param stdClass $course Database record for the course
1015      * @param navigation_node $coursenode The course node within the navigation
1016      * @return array Array of navigation nodes for the section with key = section id
1017      */
1018     protected function load_course_sections(stdClass $course, navigation_node $coursenode) {
1019         global $CFG;
1020         $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
1021         $structurefunc = 'callback_'.$course->format.'_load_content';
1022         if (function_exists($structurefunc)) {
1023             return $structurefunc($this, $course, $coursenode);
1024         } else if (file_exists($structurefile)) {
1025             require_once $structurefile;
1026             if (function_exists($structurefunc)) {
1027                 return $structurefunc($this, $course, $coursenode);
1028             } else {
1029                 return $this->load_generic_course_sections($course, $coursenode, get_string('topic'), 'topic');
1030             }
1031         } else {
1032             return $this->load_generic_course_sections($course, $coursenode, get_string('topic'), 'topic');
1033         }
1034     }
1036     /**
1037      * Generically loads the course sections into the course's navigation.
1038      *
1039      * @param stdClass $course
1040      * @param navigation_node $coursenode
1041      * @param string $name The string that identifies each section. e.g Topic, or Week
1042      * @param string $activeparam The url used to identify the active section
1043      * @return array An array of course section nodes
1044      */
1045     public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $name, $activeparam) {
1046         $modinfo = get_fast_modinfo($course);
1047         $sections = array_slice(get_all_sections($course->id), 0, $course->numsections+1, true);
1048         $viewhiddensections = has_capability('moodle/course:viewhiddensections', $this->page->context);
1050         $strgeneral = get_string('general');
1051         foreach ($sections as &$section) {
1052             if ($course->id == SITEID) {
1053                 $this->load_section_activities($coursenode, $section->section, $modinfo);
1054             } else {
1055                 if ((!$viewhiddensections && !$section->visible) || (!$this->showemptysections && !array_key_exists($section->section, $modinfo->sections))) {
1056                     continue;
1057                 }
1058                 if ($section->section == 0) {
1059                     $sectionname = $strgeneral;
1060                 } else {
1061                     $sectionname = $name.' '.$section->section;
1062                 }
1063                 $url = new moodle_url('/course/view.php', array('id'=>$course->id, $activeparam=>$section->section));
1064                 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
1065                 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
1066                 $sectionnode->hidden = (!$section->visible);
1067                 if ($sectionnode->isactive) {
1068                     $this->load_section_activities($sectionnode, $section->section, $modinfo);
1069                 }
1070                 $section->sectionnode = $sectionnode;
1071             }
1072         }
1073         return $sections;
1074     }
1075     /**
1076      * Loads all of the activities for a section into the navigation structure.
1077      *
1078      * @param navigation_node $sectionnode
1079      * @param int $sectionnumber
1080      * @param stdClass $modinfo Object returned from {@see get_fast_modinfo()}
1081      * @return array Array of activity nodes
1082      */
1083     protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, $modinfo) {
1084         if (!array_key_exists($sectionnumber, $modinfo->sections)) {
1085             return true;
1086         }
1088         $viewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->page->context);
1090         $activities = array();
1092         foreach ($modinfo->sections[$sectionnumber] as $cmid) {
1093             $cm = $modinfo->cms[$cmid];
1094             if (!$viewhiddenactivities && !$cm->visible) {
1095                 continue;
1096             }
1097             if ($cm->icon) {
1098                 $icon = new pix_icon($cm->icon, '', $cm->iconcomponent);
1099             } else {
1100                 $icon = new pix_icon('icon', '', $cm->modname);
1101             }
1102             $url = new moodle_url('/mod/'.$cm->modname.'/view.php', array('id'=>$cm->id));
1103             $activitynode = $sectionnode->add($cm->name, $url, navigation_node::TYPE_ACTIVITY, $cm->name, $cm->id, $icon);
1104             $activitynode->title(get_string('modulename', $cm->modname));
1105             $activitynode->hidden = (!$cm->visible);
1106             if ($this->module_extends_navigation($cm->modname)) {
1107                 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
1108             }
1109             $activities[$cmid] = $activitynode;
1110         }
1112         return $activities;
1113     }
1114     /**
1115      * Loads the navigation structure for the given activity into the activities node.
1116      *
1117      * This method utilises a callback within the modules lib.php file to load the
1118      * content specific to activity given.
1119      *
1120      * The callback is a method: {modulename}_extend_navigation()
1121      * Examples:
1122      *  * {@see forum_extend_navigation()}
1123      *  * {@see workshop_extend_navigation()}
1124      *
1125      * @param stdClass $cm
1126      * @param stdClass $course
1127      * @param navigation_node $activity
1128      * @return bool
1129      */
1130     protected function load_activity(stdClass $cm, stdClass $course, navigation_node $activity) {
1131         global $CFG, $DB;
1133         $activity->make_active();
1134         $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
1135         $function = $cm->modname.'_extend_navigation';
1137         if (file_exists($file)) {
1138             require_once($file);
1139             if (function_exists($function)) {
1140                 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1141                 $function($activity, $course, $activtyrecord, $cm);
1142                 return true;
1143             }
1144         }
1145         $activity->nodetype = navigation_node::NODETYPE_LEAF;
1146         return false;
1147     }
1148     /**
1149      * Loads user specific information into the navigation in the appopriate place.
1150      *
1151      * If no user is provided the current user is assumed.
1152      *
1153      * @param stdClass $user
1154      * @return bool
1155      */
1156     protected function load_for_user($user=null) {
1157         global $DB, $CFG, $USER;
1159         $iscurrentuser = false;
1160         if ($user === null) {
1161             // We can't require login here but if the user isn't logged in we don't
1162             // want to show anything
1163             if (!isloggedin()) {
1164                 return false;
1165             }
1166             $user = $USER;
1167             $iscurrentuser = true;
1168         } else if (!is_object($user)) {
1169             // If the user is not an object then get them from the database
1170             $user = $DB->get_record('user', array('id'=>(int)$user), '*', MUST_EXIST);
1171         }
1172         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
1174         // Get the course set against the page, by default this will be the site
1175         $course = $this->page->course;
1176         $baseargs = array('id'=>$user->id);
1177         if ($course->id !== SITEID) {
1178             if (array_key_exists($course->id, $this->mycourses)) {
1179                 $coursenode = $this->mycourses[$course->id]->coursenode;
1180             } else {
1181                 $coursenode = $this->rootnodes['courses']->find($course->id, navigation_node::TYPE_COURSE);
1182                 if (!$coursenode) {
1183                     $coursenode = $this->load_course($course);
1184                 }
1185             }
1186             $baseargs['course'] = $course->id;
1187             $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1188             $issitecourse = false;
1189         } else {
1190             // Load all categories and get the context for the system
1191             $coursecontext = get_context_instance(CONTEXT_SYSTEM);
1192             $issitecourse = true;
1193         }
1195         // Create a node to add user information under.
1196         if ($iscurrentuser) {
1197             // If it's the current user the information will go under the profile root node
1198             $usernode = $this->rootnodes['myprofile'];
1199         } else {
1200             if (!$issitecourse) {
1201                 // Not the current user so add it to the participants node for the current course
1202                 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
1203             } else {
1204                 // This is the site so add a users node to the root branch
1205                 $usersnode = $this->rootnodes['users'];
1206                 $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
1207             }
1208             // Add a branch for the current user
1209             $usernode = $usersnode->add(fullname($user, true));
1210         }
1212         if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
1213             $usernode->force_open();
1214         }
1216         // If the user is the current user or has permission to view the details of the requested
1217         // user than add a view profile link.
1218         if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
1219             $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
1220         }
1222         // Add nodes for forum posts and discussions if the user can view either or both
1223         $canviewposts = has_capability('moodle/user:readuserposts', $usercontext);
1224         $canviewdiscussions = has_capability('mod/forum:viewdiscussion', $coursecontext);
1225         if ($canviewposts || $canviewdiscussions) {
1226             $forumtab = $usernode->add(get_string('forumposts', 'forum'));
1227             if ($canviewposts) {
1228                 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
1229             }
1230             if ($canviewdiscussions) {
1231                 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
1232             }
1233         }
1235         // Add a node to view the users notes if permitted
1236         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
1237             $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
1238             if ($coursecontext->instanceid) {
1239                 $url->param('course', $coursecontext->instanceid);
1240             }
1241             $usernode->add(get_string('notes', 'notes'), $url);
1242         }
1244         // Add a reports tab and then add reports the the user has permission to see.
1245         $reporttab = $usernode->add(get_string('activityreports'));
1246         $anyreport  = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1247         $viewreports = ($anyreport || ($course->showreports && $iscurrentuser));
1248         $reportargs = array('user'=>$user->id);
1249         if (!empty($course->id)) {
1250             $reportargs['id'] = $course->id;
1251         } else {
1252             $reportargs['id'] = SITEID;
1253         }
1254         if ($viewreports || has_capability('coursereport/outline:view', $coursecontext)) {
1255             $reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
1256             $reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
1257         }
1259         if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
1260             $reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
1261         }
1263         if ($viewreports || has_capability('coursereport/log:view', $coursecontext)) {
1264             $reporttab->add(get_string('alllogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'alllogs'))));
1265         }
1267         if (!empty($CFG->enablestats)) {
1268             if ($viewreports || has_capability('coursereport/stats:view', $coursecontext)) {
1269                 $reporttab->add(get_string('stats'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'stats'))));
1270             }
1271         }
1273         $gradeaccess = false;
1274         if (has_capability('moodle/grade:viewall', $coursecontext)) {
1275             //ok - can view all course grades
1276             $gradeaccess = true;
1277         } else if ($course->showgrades) {
1278             if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1279                 //ok - can view own grades
1280                 $gradeaccess = true;
1281             } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1282                 // ok - can view grades of this user - parent most probably
1283                 $gradeaccess = true;
1284             } else if ($anyreport) {
1285                 // ok - can view grades of this user - parent most probably
1286                 $gradeaccess = true;
1287             }
1288         }
1289         if ($gradeaccess) {
1290             $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'grade'))));
1291         }
1293         // Check the number of nodes in the report node... if there are none remove
1294         // the node
1295         if (count($reporttab->children)===0) {
1296             $usernode->remove_child($reporttab);
1297         }
1299         // If the user is the current user add the repositories for the current user
1300         if ($iscurrentuser) {
1301             require_once($CFG->dirroot . '/repository/lib.php');
1302             $editabletypes = repository::get_editable_types($usercontext);
1303             if (!empty($editabletypes)) {
1304                 $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
1305             }
1306         }
1307         return true;
1308     }
1310     /**
1311      * This method simply checks to see if a given module can extend the navigation.
1312      *
1313      * @param string $modname
1314      * @return bool
1315      */
1316     protected function module_extends_navigation($modname) {
1317         global $CFG;
1318         if ($this->cache->cached($modname.'_extends_navigation')) {
1319             return $this->cache->{$modname.'_extends_navigation'};
1320         }
1321         $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
1322         $function = $modname.'_extend_navigation';
1323         if (function_exists($function)) {
1324             $this->cache->{$modname.'_extends_navigation'} = true;
1325             return true;
1326         } else if (file_exists($file)) {
1327             require_once($file);
1328             if (function_exists($function)) {
1329                 $this->cache->{$modname.'_extends_navigation'} = true;
1330                 return true;
1331             }
1332         }
1333         $this->cache->{$modname.'_extends_navigation'} = false;
1334         return false;
1335     }
1336     /**
1337      * Extends the navigation for the given user.
1338      * 
1339      * @param stdClass $user A user from the database
1340      */
1341     public function extend_for_user($user) {
1342         $this->extendforuser[] = $user;
1343     }
1344     /**
1345      * Adds the given course to the navigation structure.
1346      *
1347      * @param stdClass $course
1348      * @return navigation_node
1349      */
1350     public function add_course(stdClass $course) {
1351         if (array_key_exists($course->id, $this->addedcourses)) {
1352             return $this->addedcourses[$course->id];
1353         }
1355         $canviewhidden = has_capability('moodle/course:viewhiddencourses', $this->page->context);
1356         if ($course->id !== SITEID && !$canviewhidden && (!$course->visible || !course_parent_visible($course))) {
1357             return false;
1358         }
1360         if ($course->id == SITEID) {
1361             $parent = $this;
1362             $url = new moodle_url('/');
1363         } else if (array_key_exists($course->id, $this->mycourses)) {
1364             $parent = $this->rootnodes['mycourses'];
1365             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1366         } else {
1367             $parent = $this->rootnodes['courses'];
1368             $url = new moodle_url('/course/view.php', array('id'=>$course->id));
1369         }
1370         $coursenode = $parent->add($course->fullname, $url, self::TYPE_COURSE, $course->shortname, $course->id);
1371         $coursenode->nodetype = self::NODETYPE_BRANCH;
1372         $coursenode->hidden = (!$course->visible);
1373         $this->addedcourses[$course->id] = &$coursenode;
1374         return $coursenode;
1375     }
1376     /**
1377      * Adds essential course nodes to the navigation for the given course.
1378      *
1379      * This method adds nodes such as reports, blogs and participants
1380      *
1381      * @param navigation_node $coursenode
1382      * @param stdClass $course
1383      * @return bool
1384      */
1385     public function add_course_essentials(navigation_node $coursenode, stdClass $course) {
1386         global $CFG;
1388         if ($course->id === SITEID) {
1389             return $this->add_front_page_course_essentials($coursenode, $course);
1390         }
1392         if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
1393             return true;
1394         }
1396         //Participants
1397         if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1398             require_once($CFG->dirroot.'/blog/lib.php');
1399             $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
1400             $currentgroup = groups_get_course_group($course, true);
1401             if ($course->id == SITEID) {
1402                 $filterselect = '';
1403             } else if ($course->id && !$currentgroup) {
1404                 $filterselect = $course->id;
1405             } else {
1406                 $filterselect = $currentgroup;
1407             }
1408             $filterselect = clean_param($filterselect, PARAM_INT);
1409             if ($CFG->bloglevel >= 3) {
1410                 $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1411                 $participants->add(get_string('blogs','blog'), $blogsurls->out());
1412             }
1413             if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1414                 $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1415             }
1416         } else if (count($this->extendforuser) > 0) {
1417             $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
1418         }
1420         // View course reports
1421         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1422             $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1423             $coursereports = get_plugin_list('coursereport');
1424             foreach ($coursereports as $report=>$dir) {
1425                 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1426                 if (file_exists($libfile)) {
1427                     require_once($libfile);
1428                     $reportfunction = $report.'_report_extend_navigation';
1429                     if (function_exists($report.'_report_extend_navigation')) {
1430                         $reportfunction($reportnav, $course, $this->page->context);
1431                     }
1432                 }
1433             }
1434         }
1435         return true;
1436     }
1438     public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
1439         global $CFG;
1441         if ($coursenode == false || $coursenode->get('participants', navigation_node::TYPE_CUSTOM)) {
1442             return true;
1443         }
1445         //Participants
1446         if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
1447             require_once($CFG->dirroot.'/blog/lib.php');
1448             $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
1449         }
1450         
1451         $currentgroup = groups_get_course_group($course, true);
1452         if ($course->id == SITEID) {
1453             $filterselect = '';
1454         } else if ($course->id && !$currentgroup) {
1455             $filterselect = $course->id;
1456         } else {
1457             $filterselect = $currentgroup;
1458         }
1459         $filterselect = clean_param($filterselect, PARAM_INT);
1460         if ($CFG->bloglevel >= 3) {
1461             $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
1462             $coursenode->add(get_string('blogs','blog'), $blogsurls->out());
1463         }
1464         if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
1465             $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
1466         }
1467         if (!empty($CFG->usetags)) {
1468             $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
1469         }
1472         // View course reports
1473         if (has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
1474             $reportnav = $coursenode->add(get_string('reports'), new moodle_url('/course/report.php', array('id'=>$course->id)), self::TYPE_CONTAINER, null, null, new pix_icon('i/stats', ''));
1475             $coursereports = get_plugin_list('coursereport');
1476             foreach ($coursereports as $report=>$dir) {
1477                 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
1478                 if (file_exists($libfile)) {
1479                     require_once($libfile);
1480                     $reportfunction = $report.'_report_extend_navigation';
1481                     if (function_exists($report.'_report_extend_navigation')) {
1482                         $reportfunction($reportnav, $course, $this->page->context);
1483                     }
1484                 }
1485             }
1486         }
1487         return true;
1488     }
1490     /**
1491      * Clears the navigation cache
1492      */
1493     public function clear_cache() {
1494         $this->cache->clear();
1495     }
1497     public function set_expansion_limit($type) {
1498         $nodes = $this->find_all_of_type($type);
1499         foreach ($nodes as &$node) {
1500             foreach ($node->children as &$child) {
1501                 $child->display = false;
1502             }
1503         }
1504         return true;
1505     }
1508 /**
1509  * The limited global navigation class used for the AJAX extension of the global
1510  * navigation class.
1511  *
1512  * The primary methods that are used in the global navigation class have been overriden
1513  * to ensure that only the relevant branch is generated at the root of the tree.
1514  * This can be done because AJAX is only used when the backwards structure for the
1515  * requested branch exists.
1516  * This has been done only because it shortens the amounts of information that is generated
1517  * which of course will speed up the response time.. because no one likes laggy AJAX.
1518  *
1519  * @package moodlecore
1520  * @subpackage navigation
1521  * @copyright 2009 Sam Hemelryk
1522  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1523  */
1524 class global_navigation_for_ajax extends global_navigation {
1526     /** @var array */
1527     protected $expandable = array();
1529     /**
1530      * Constructs the navigation for use in AJAX request
1531      */
1532     public function __construct() {
1533         global $SITE;
1534         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1535         $this->children = new navigation_node_collection();
1536         $this->rootnodes = array();
1537         //$this->rootnodes['site']      = $this->add_course($SITE);
1538         $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
1539     }
1540     /**
1541      * Initialise the navigation given the type and id for the branch to expand.
1542      *
1543      * @param int $branchtype One of navigation_node::TYPE_*
1544      * @param int $id
1545      * @return array The expandable nodes
1546      */
1547     public function initialise($branchtype, $id) {
1548         global $DB, $PAGE;
1550         if ($this->initialised || during_initial_install()) {
1551             return $this->expandable;
1552         }
1554         // Branchtype will be one of navigation_node::TYPE_*
1555         switch ($branchtype) {
1556             case self::TYPE_COURSE :
1557                 $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
1558                 require_course_login($course);
1559                 $this->page = $PAGE;
1560                 $coursenode = $this->add_course($course);
1561                 $this->add_course_essentials($coursenode, $course);
1562                 if ($this->format_display_course_content($course->format)) {
1563                     $this->load_course_sections($course, $coursenode);
1564                 }
1565                 break;
1566             case self::TYPE_SECTION :
1567                 $sql = 'SELECT c.*, cs.section AS sectionnumber
1568                         FROM {course} c
1569                         LEFT JOIN {course_sections} cs ON cs.course = c.id
1570                         WHERE cs.id = ?';
1571                 $course = $DB->get_record_sql($sql, array($id), MUST_EXIST);
1572                 require_course_login($course);
1573                 $this->page = $PAGE;
1574                 $coursenode = $this->add_course($course);
1575                 $this->add_course_essentials($coursenode, $course);
1576                 $sections = $this->load_course_sections($course, $coursenode);
1577                 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course));
1578                 break;
1579             case self::TYPE_ACTIVITY :
1580                 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST);
1581                 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1582                 require_course_login($course, true, $cm);
1583                 $this->page = $PAGE;
1584                 $coursenode = $this->load_course($course);
1585                 $sections = $this->load_course_sections($course, $coursenode);
1586                 foreach ($sections as $section) {
1587                     if ($section->id == $cm->section) {
1588                         $cm->sectionnumber = $section->section;
1589                         break;
1590                     }
1591                 }
1592                 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course));
1593                 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
1594                 break;
1595             default:
1596                 throw new Exception('Unknown type');
1597                 return $this->expandable;
1598         }
1600         $this->find_expandable($this->expandable);
1601         return $this->expandable;
1602     }
1605 /**
1606  * Navbar class
1607  *
1608  * This class is used to manage the navbar, which is initialised from the navigation
1609  * object held by PAGE
1610  *
1611  * @package moodlecore
1612  * @subpackage navigation
1613  * @copyright 2009 Sam Hemelryk
1614  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1615  */
1616 class navbar extends navigation_node {
1617     /** @var bool */
1618     protected $initialised = false;
1619     /** @var mixed */
1620     protected $keys = array();
1621     /** @var null|string */
1622     protected $content = null;
1623     /** @var moodle_page object */
1624     protected $page;
1625     /** @var bool */
1626     protected $ignoreactive = false;
1627     /** @var bool */
1628     protected $duringinstall = false;
1629     /** @var bool */
1630     protected $hasitems = false;
1631     /** @var array */
1632     protected $items;
1633     /** @var array */
1634     public $children = array();
1635     /**
1636      * The almighty constructor
1637      *
1638      * @param moodle_page $page
1639      */
1640     public function __construct(moodle_page $page) {
1641         global $CFG;
1642         if (during_initial_install()) {
1643             $this->duringinstall = true;
1644             return false;
1645         }
1646         $this->page = $page;
1647         $this->text = get_string('home');
1648         $this->shorttext = get_string('home');
1649         $this->action = new moodle_url($CFG->wwwroot);
1650         $this->nodetype = self::NODETYPE_BRANCH;
1651         $this->type = self::TYPE_SYSTEM;
1652     }
1654     /**
1655      * Quick check to see if the navbar will have items in.
1656      *
1657      * @return bool Returns true if the navbar will have items, false otherwise
1658      */
1659     public function has_items() {
1660         if ($this->duringinstall) {
1661             return false;
1662         } else if ($this->hasitems !== false) {
1663             return true;
1664         }
1665         $this->page->navigation->initialise($this->page);
1667         $activenodefound = ($this->page->navigation->contains_active_node() ||
1668                             $this->page->settingsnav->contains_active_node());
1670         $outcome = (count($this->children)>0 || (!$this->ignoreactive && $activenodefound));
1671         $this->hasitems = $outcome;
1672         return $outcome;
1673     }
1675     /**
1676      * Turn on/off ignore active
1677      *
1678      * @param bool $setting
1679      */
1680     public function ignore_active($setting=true) {
1681         $this->ignoreactive = ($setting);
1682     }
1683     public function get($key, $type = null) {
1684         foreach ($this->children as &$child) {
1685             if ($child->key === $key && ($type == null || $type == $child->type)) {
1686                 return $child;
1687             }
1688         }
1689         return false;
1690     }
1691     /**
1692      * Returns an array of navigation_node's that make up the navbar.
1693      * 
1694      * @return array
1695      */
1696     public function get_items() {
1697         $items = array();
1698         // Make sure that navigation is initialised
1699         if (!$this->has_items()) {
1700             return $items;
1701         }
1702         if ($this->items !== null) {
1703             return $this->items;
1704         }
1706         if (count($this->children) > 0) {
1707             // Add the custom children
1708             $items = array_reverse($this->children);
1709         }
1711         $navigationactivenode = $this->page->navigation->find_active_node();
1712         $settingsactivenode = $this->page->settingsnav->find_active_node();
1714         // Check if navigation contains the active node
1715         if (!$this->ignoreactive) {
1716             
1717             if ($navigationactivenode && $settingsactivenode) {
1718                 // Parse a combined navigation tree
1719                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1720                     if (!$settingsactivenode->mainnavonly) {
1721                         $items[] = $settingsactivenode;
1722                     }
1723                     $settingsactivenode = $settingsactivenode->parent;
1724                 }
1725                 // Removes the first node from the settings (root node) from the list
1726                 array_pop($items);
1727                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1728                     if (!$navigationactivenode->mainnavonly) {
1729                         $items[] = $navigationactivenode;
1730                     }
1731                     $navigationactivenode = $navigationactivenode->parent;
1732                 }
1733             } else if ($navigationactivenode) {
1734                 // Parse the navigation tree to get the active node
1735                 while ($navigationactivenode && $navigationactivenode->parent !== null) {
1736                     if (!$navigationactivenode->mainnavonly) {
1737                         $items[] = $navigationactivenode;
1738                     }
1739                     $navigationactivenode = $navigationactivenode->parent;
1740                 }
1741             } else if ($settingsactivenode) {
1742                 // Parse the settings navigation to get the active node
1743                 while ($settingsactivenode && $settingsactivenode->parent !== null) {
1744                     if (!$settingsactivenode->mainnavonly) {
1745                         $items[] = $settingsactivenode;
1746                     }
1747                     $settingsactivenode = $settingsactivenode->parent;
1748                 }
1749             }
1750         }
1752         $items[] = new navigation_node(array(
1753             'text'=>$this->page->navigation->text,
1754             'shorttext'=>$this->page->navigation->shorttext,
1755             'key'=>$this->page->navigation->key,
1756             'action'=>$this->page->navigation->action
1757         ));
1759         $this->items = array_reverse($items);
1760         return $this->items;
1761     }
1763     /**
1764      * Add a new navigation_node to the navbar, overrides parent::add
1765      *
1766      * This function overrides {@link navigation_node::add()} so that we can change
1767      * the way nodes get added to allow us to simply call add and have the node added to the
1768      * end of the navbar
1769      *
1770      * @param string $text
1771      * @param string|moodle_url $action
1772      * @param int $type
1773      * @param string|int $key
1774      * @param string $shorttext
1775      * @param string $icon
1776      * @return navigation_node
1777      */
1778     public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
1779         if ($this->content !== null) {
1780             debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
1781         }
1782         
1783         // Properties array used when creating the new navigation node
1784         $itemarray = array(
1785             'text' => $text,
1786             'type' => $type
1787         );
1788         // Set the action if one was provided
1789         if ($action!==null) {
1790             $itemarray['action'] = $action;
1791         }
1792         // Set the shorttext if one was provided
1793         if ($shorttext!==null) {
1794             $itemarray['shorttext'] = $shorttext;
1795         }
1796         // Set the icon if one was provided
1797         if ($icon!==null) {
1798             $itemarray['icon'] = $icon;
1799         }
1800         // Default the key to the number of children if not provided
1801         if ($key === null) {
1802             $key = count($this->children);
1803         }
1804         // Set the key
1805         $itemarray['key'] = $key;
1806         // Set the parent to this node
1807         $itemarray['parent'] = $this;
1808         // Add the child using the navigation_node_collections add method
1809         $this->children[] = new navigation_node($itemarray);
1810         return $this;
1811     }
1814 /**
1815  * Class used to manage the settings option for the current page
1816  *
1817  * This class is used to manage the settings options in a tree format (recursively)
1818  * and was created initially for use with the settings blocks.
1819  *
1820  * @package moodlecore
1821  * @subpackage navigation
1822  * @copyright 2009 Sam Hemelryk
1823  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1824  */
1825 class settings_navigation extends navigation_node {
1826     /** @var stdClass */
1827     protected $context;
1828     /** @var navigation_cache */
1829     protected $cache;
1830     /** @var moodle_page */
1831     protected $page;
1832     /** @var string */
1833     protected $adminsection;
1834     /**
1835      * Sets up the object with basic settings and preparse it for use
1836      * 
1837      * @param moodle_page $page
1838      */
1839     public function __construct(moodle_page &$page) {
1840         if (during_initial_install()) {
1841             return false;
1842         }
1843         $this->page = $page;
1844         // Initialise the main navigation. It is most important that this is done
1845         // before we try anything
1846         $this->page->navigation->initialise();
1847         // Initialise the navigation cache
1848         $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1849         $this->children = new navigation_node_collection();
1850     }
1851     /**
1852      * Initialise the settings navigation based on the current context
1853      *
1854      * This function initialises the settings navigation tree for a given context
1855      * by calling supporting functions to generate major parts of the tree.
1856      *
1857      */
1858     public function initialise() {
1859         global $DB;
1861         if (during_initial_install()) {
1862             return false;
1863         }
1864         $this->id = 'settingsnav';
1865         $this->context = $this->page->context;
1867         $context = $this->context;
1868         if ($context->contextlevel == CONTEXT_BLOCK) {
1869             $this->load_block_settings();
1870             $context = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid));
1871         }
1873         switch ($context->contextlevel) {
1874             case CONTEXT_SYSTEM:
1875                 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
1876                     $this->load_front_page_settings(($context->id == $this->context->id));
1877                 }
1878                 break;
1879             case CONTEXT_COURSECAT:
1880                 $this->load_category_settings();
1881                 break;
1882             case CONTEXT_COURSE:
1883                 if ($this->page->course->id != SITEID) {
1884                     $this->load_course_settings(($context->id == $this->context->id));
1885                 } else {
1886                     $this->load_front_page_settings(($context->id == $this->context->id));
1887                 }
1888                 break;
1889             case CONTEXT_MODULE:
1890                 $this->load_module_settings();
1891                 $this->load_course_settings();
1892                 break;
1893             case CONTEXT_USER:
1894                 if ($this->page->course->id != SITEID) {
1895                     $this->load_course_settings();
1896                 }
1897                 break;
1898         }
1900         $settings = $this->load_user_settings($this->page->course->id);
1901         $admin = $this->load_administration_settings();
1903         if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
1904             $admin->force_open();
1905         } else if ($context->contextlevel == CONTEXT_USER && $settings) {
1906             $settings->force_open();
1907         }
1909         // Check if the user is currently logged in as another user
1910         if (session_is_loggedinas()) {
1911             // Get the actual user, we need this so we can display an informative return link
1912             $realuser = session_get_realuser();
1913             // Add the informative return to original user link
1914             $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
1915             $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
1916         }
1918         // Make sure the first child doesnt have proceed with hr set to true
1920         foreach ($this->children as $key=>$node) {
1921             if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
1922                 $node->remove();
1923             }
1924         }
1925     }
1926     /**
1927      * Override the parent function so that we can add preceeding hr's and set a
1928      * root node class against all first level element
1929      *
1930      * It does this by first calling the parent's add method {@link navigation_node::add()}
1931      * and then proceeds to use the key to set class and hr
1932      *
1933      * @param string $text
1934      * @param sting|moodle_url $url
1935      * @param string $shorttext
1936      * @param string|int $key
1937      * @param int $type
1938      * @param string $icon
1939      * @return navigation_node
1940      */
1941     public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
1942         $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
1943         $node->add_class('root_node');
1944         return $node;
1945     }
1947     /**
1948      * This function allows the user to add something to the start of the settings
1949      * navigation, which means it will be at the top of the settings navigation block
1950      *
1951      * @param string $text
1952      * @param sting|moodle_url $url
1953      * @param string $shorttext
1954      * @param string|int $key
1955      * @param int $type
1956      * @param string $icon
1957      * @return navigation_node
1958      */
1959     public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
1960         $children = $this->children;
1961         $this->children = new get_class($children);
1962         $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
1963         foreach ($children as $child) {
1964             $this->children->add($child);
1965         }
1966         return $node;
1967     }
1968     /**
1969      * Load the site administration tree
1970      *
1971      * This function loads the site administration tree by using the lib/adminlib library functions
1972      *
1973      * @param navigation_node $referencebranch A reference to a branch in the settings
1974      *      navigation tree
1975      * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
1976      *      tree and start at the beginning
1977      * @return mixed A key to access the admin tree by
1978      */
1979     protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
1980         global $CFG;
1982         // Check if we are just starting to generate this navigation.
1983         if ($referencebranch === null) {
1985             // Require the admin lib then get an admin structure
1986             if (!function_exists('admin_get_root')) {
1987                 require_once($CFG->dirroot.'/lib/adminlib.php');
1988             }
1989             $adminroot = admin_get_root(false, false);
1990             // This is the active section identifier
1991             $this->adminsection = $this->page->url->param('section');
1993             // Disable the navigation from automatically finding the active node
1994             navigation_node::$autofindactive = false;
1995             $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
1996             foreach ($adminroot->children as $adminbranch) {
1997                 $this->load_administration_settings($referencebranch, $adminbranch);
1998             }
1999             navigation_node::$autofindactive = true;
2001             // Use the admin structure to locate the active page
2002             if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
2003                 $currentnode = $this;
2004                 while (($pathkey = array_pop($current->path))!==null && $currentnode) {
2005                     $currentnode = $currentnode->get($pathkey);
2006                 }
2007                 if ($currentnode) {
2008                     $currentnode->make_active();
2009                 }
2010             }
2011             return $referencebranch;
2012         } else if ($adminbranch->check_access()) {
2013             // We have a reference branch that we can access and is not hidden `hurrah`
2014             // Now we need to display it and any children it may have
2015             $url = null;
2016             $icon = null;
2017             if ($adminbranch instanceof admin_settingpage) {
2018                 $url = new moodle_url('/admin/settings.php', array('section'=>$adminbranch->name));
2019             } else if ($adminbranch instanceof admin_externalpage) {
2020                 $url = $adminbranch->url;
2021             }
2023             // Add the branch
2024             $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
2026             if ($adminbranch->is_hidden()) {
2027                 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
2028                     $reference->add_class('hidden');
2029                 } else {
2030                     $reference->display = false;
2031                 }
2032             }
2034             // Check if we are generating the admin notifications and whether notificiations exist
2035             if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
2036                 $reference->add_class('criticalnotification');
2037             }
2038             // Check if this branch has children
2039             if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
2040                 foreach ($adminbranch->children as $branch) {
2041                     // Generate the child branches as well now using this branch as the reference
2042                     $this->load_administration_settings($reference, $branch);
2043                 }
2044             } else {
2045                 $reference->icon = new pix_icon('i/settings', '');
2046             }
2047         }
2048     }
2050     /**
2051      * Gets a navigation node given an array of keys that represent the path to
2052      * the desired node.
2053      *
2054      * @param array $path
2055      * @return navigation_node|false
2056      */
2057     protected function get_by_path(array $path) {
2058         $node = $this->get(array_shift($path));
2059         foreach ($path as $key) {
2060             $node->get($key);
2061         }
2062         return $node;
2063     }
2065     /**
2066      * Generate the list of modules for the given course.
2067      *
2068      * The array of resources and activities that can be added to a course is then
2069      * stored in the cache so that we can access it for anywhere.
2070      * It saves us generating it all the time
2071      *
2072      * <code php>
2073      * // To get resources:
2074      * $this->cache->{'course'.$courseid.'resources'}
2075      * // To get activities:
2076      * $this->cache->{'course'.$courseid.'activities'}
2077      * </code>
2078      *
2079      * @param stdClass $course The course to get modules for
2080      */
2081     protected function get_course_modules($course) {
2082         global $CFG;
2083         $mods = $modnames = $modnamesplural = $modnamesused = array();
2084         // This function is included when we include course/lib.php at the top
2085         // of this file
2086         get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
2087         $resources = array();
2088         $activities = array();
2089         foreach($modnames as $modname=>$modnamestr) {
2090             if (!course_allowed_module($course, $modname)) {
2091                 continue;
2092             }
2094             $libfile = "$CFG->dirroot/mod/$modname/lib.php";
2095             if (!file_exists($libfile)) {
2096                 continue;
2097             }
2098             include_once($libfile);
2099             $gettypesfunc =  $modname.'_get_types';
2100             if (function_exists($gettypesfunc)) {
2101                 $types = $gettypesfunc();
2102                 foreach($types as $type) {
2103                     if (!isset($type->modclass) || !isset($type->typestr)) {
2104                         debugging('Incorrect activity type in '.$modname);
2105                         continue;
2106                     }
2107                     if ($type->modclass == MOD_CLASS_RESOURCE) {
2108                         $resources[html_entity_decode($type->type)] = $type->typestr;
2109                     } else {
2110                         $activities[html_entity_decode($type->type)] = $type->typestr;
2111                     }
2112                 }
2113             } else {
2114                 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2115                 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
2116                     $resources[$modname] = $modnamestr;
2117                 } else {
2118                     // all other archetypes are considered activity
2119                     $activities[$modname] = $modnamestr;
2120                 }
2121             }
2122         }
2123         $this->cache->{'course'.$course->id.'resources'} = $resources;
2124         $this->cache->{'course'.$course->id.'activities'} = $activities;
2125     }
2127     /**
2128      * This function loads the course settings that are available for the user
2129      *
2130      * @param bool $forceopen If set to true the course node will be forced open
2131      * @return navigation_node|false
2132      */
2133     protected function load_course_settings($forceopen = false) {
2134         global $CFG, $USER, $SESSION, $OUTPUT;
2136         $course = $this->page->course;
2137         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2138         if (!$this->cache->cached('canviewcourse'.$course->id)) {
2139             $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
2140         }
2141         if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
2142             return false;
2143         }
2145         $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
2146         if ($forceopen) {
2147             $coursenode->force_open();
2148         }
2150         if (has_capability('moodle/course:update', $coursecontext)) {
2151             // Add the turn on/off settings
2152             $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2153             if ($this->page->user_is_editing()) {
2154                 $url->param('edit', 'off');
2155                 $editstring = get_string('turneditingoff');
2156             } else {
2157                 $url->param('edit', 'on');
2158                 $editstring = get_string('turneditingon');
2159             }
2160             $coursenode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2162             if ($this->page->user_is_editing()) {
2163                 // Add `add` resources|activities branches
2164                 $structurefile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
2165                 if (file_exists($structurefile)) {
2166                     require_once($structurefile);
2167                     $formatstring = call_user_func('callback_'.$course->format.'_definition');
2168                     $formatidentifier = optional_param(call_user_func('callback_'.$course->format.'_request_key'), 0, PARAM_INT);
2169                 } else {
2170                     $formatstring = get_string('topic');
2171                     $formatidentifier = optional_param('topic', 0, PARAM_INT);
2172                 }
2173                 if (!$this->cache->cached('coursesections'.$course->id)) {
2174                     $this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
2175                 }
2176                 $sections = $this->cache->{'coursesections'.$course->id};
2178                 $addresource = $this->add(get_string('addresource'));
2179                 $addactivity = $this->add(get_string('addactivity'));
2180                 if ($formatidentifier!==0) {
2181                     $addresource->force_open();
2182                     $addactivity->force_open();
2183                 }
2185                 if (!$this->cache->cached('course'.$course->id.'resources')) {
2186                     $this->get_course_modules($course);
2187                 }
2188                 $resources = $this->cache->{'course'.$course->id.'resources'};
2189                 $activities = $this->cache->{'course'.$course->id.'activities'};
2191                 $textlib = textlib_get_instance();
2193                 foreach ($sections as $section) {
2194                     if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
2195                         continue;
2196                     }
2197                     $sectionurl = new moodle_url('/course/view.php', array('id'=>$course->id, $formatstring=>$section->section));
2198                     if ($section->section == 0) {
2199                         $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2200                         $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING);
2201                     } else {
2202                         $sectionresources = $addresource->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2203                         $sectionactivities = $addactivity->add($formatstring.' '.$section->section, $sectionurl, self::TYPE_SETTING);
2204                     }
2205                     foreach ($resources as $value=>$resource) {
2206                         $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2207                         $pos = strpos($value, '&type=');
2208                         if ($pos!==false) {
2209                             $url->param('add', $textlib->substr($value, 0,$pos));
2210                             $url->param('type', $textlib->substr($value, $pos+6));
2211                         } else {
2212                             $url->param('add', $value);
2213                         }
2214                         $sectionresources->add($resource, $url, self::TYPE_SETTING);
2215                     }
2216                     $subbranch = false;
2217                     foreach ($activities as $activityname=>$activity) {
2218                         if ($activity==='--') {
2219                             $subbranch = false;
2220                             continue;
2221                         }
2222                         if (strpos($activity, '--')===0) {
2223                             $subbranch = $sectionresources->add(trim($activity, '-'));
2224                             continue;
2225                         }
2226                         $url = new moodle_url('/course/mod.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'section'=>$section->section));
2227                         $pos = strpos($activityname, '&type=');
2228                         if ($pos!==false) {
2229                             $url->param('add', $textlib->substr($activityname, 0,$pos));
2230                             $url->param('type', $textlib->substr($activityname, $pos+6));
2231                         } else {
2232                             $url->param('add', $activityname);
2233                         }
2234                         if ($subbranch !== false) {
2235                             $subbranch->add($activity, $url, self::TYPE_SETTING);
2236                         } else {
2237                             $sectionresources->add($activity, $url, self::TYPE_SETTING);
2238                         }
2239                     }
2240                 }
2241             }
2243             // Add the course settings link
2244             $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
2245             $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2246         }
2248         if (has_capability('moodle/role:assign', $coursecontext)) {
2249             // Add assign or override roles if allowed
2250             $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
2251             $coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2252             // Override roles
2253             if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2254                 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
2255                 $coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2256             }
2257             // Check role permissions
2258             if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2259                 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
2260                 $coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2261             }
2262             // Manage filters
2263             if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2264                 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2265                 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2266             }
2267         }
2269         // Add view grade report is permitted
2270         $reportavailable = false;
2271         if (has_capability('moodle/grade:viewall', $coursecontext)) {
2272             $reportavailable = true;
2273         } else if (!empty($course->showgrades)) {
2274             $reports = get_plugin_list('gradereport');
2275             if (is_array($reports) && count($reports)>0) {     // Get all installed reports
2276                 arsort($reports); // user is last, we want to test it first
2277                 foreach ($reports as $plugin => $plugindir) {
2278                     if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
2279                         //stop when the first visible plugin is found
2280                         $reportavailable = true;
2281                         break;
2282                     }
2283                 }
2284             }
2285         }
2286         if ($reportavailable) {
2287             $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
2288             $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
2289         }
2291         //  Add outcome if permitted
2292         if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
2293             $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
2294             $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/outcomes', ''));
2295         }
2297         // Add meta course links
2298         if ($course->metacourse) {
2299             if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
2300                 $url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
2301                 $coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2302             } else if (has_capability('moodle/role:assign', $coursecontext)) {
2303                 $roleassign = $coursenode->add(get_string('childcourses'), null,  self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
2304                 $roleassign->hidden = true;
2305             }
2306         }
2308         // Manage groups in this course
2309         if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
2310             $url = new moodle_url('/group/index.php', array('id'=>$course->id));
2311             $coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/group', ''));
2312         }
2314         // Backup this course
2315         if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2316             $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2317             $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2318         }
2320         // Restore to this course
2321         if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2322             $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2323             $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2324         }
2326         // Import data from other courses
2327         if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
2328             $url = new moodle_url('/course/import.php', array('id'=>$course->id));
2329             $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2330         }
2332         // Reset this course
2333         if (has_capability('moodle/course:reset', $coursecontext)) {
2334             $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
2335             $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
2336         }
2338         // Manage questions
2339         $questioncaps = array('moodle/question:add',
2340                               'moodle/question:editmine',
2341                               'moodle/question:editall',
2342                               'moodle/question:viewmine',
2343                               'moodle/question:viewall',
2344                               'moodle/question:movemine',
2345                               'moodle/question:moveall');
2346         if (has_any_capability($questioncaps, $this->context)) {
2347             $questionlink = $CFG->wwwroot.'/question/edit.php';
2348         } else if (has_capability('moodle/question:managecategory', $this->context)) {
2349             $questionlink = $CFG->wwwroot.'/question/category.php';
2350         }
2351         if (isset($questionlink)) {
2352             $url = new moodle_url($questionlink, array('courseid'=>$course->id));
2353             $coursenode->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
2354         }
2356         // Repository Instances
2357         require_once($CFG->dirroot.'/repository/lib.php');
2358         $editabletypes = repository::get_editable_types($this->context);
2359         if (has_capability('moodle/course:update', $this->context) && !empty($editabletypes)) {
2360             $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$this->context->id));
2361             $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
2362         }
2364         // Manage files
2365         if (has_capability('moodle/course:managefiles', $this->context)) {
2366             $url = new moodle_url('/files/index.php', array('id'=>$course->id));
2367             $coursenode->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
2368         }
2370         // Authorize hooks
2371         if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize')) {
2372             require_once($CFG->dirroot.'/enrol/authorize/const.php');
2373             $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id));
2374             $coursenode->add(get_string('payments'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2375             if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
2376                 $cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id));
2377                 if ($cnt) {
2378                     $url = new moodle_url('/enrol/authorize/index.php', array('course'=>$course->id,'status'=>AN_STATUS_AUTH));
2379                     $coursenode->add(get_string('paymentpending', 'moodle', $cnt), $url, self::TYPE_SETTING, null, null, new pix_icon('i/payment', ''));
2380                 }
2381             }
2382         }
2384         // Unenrol link
2385         if (empty($course->metacourse) && ($course->id!==SITEID)) {
2386             if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
2387                 if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) {  // Have some role
2388                     $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
2389                     $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2390                 }
2392             } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
2393                 // inspector, manager, etc. - do not show anything
2394             } else {
2395                 // access because otherwise they would not get into this course at all
2396                 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
2397                 $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
2398             }
2399         }
2401         // Switch roles
2402         $roles = array();
2403         $assumedrole = $this->in_alternative_role();
2404         if ($assumedrole!==false) {
2405             $roles[0] = get_string('switchrolereturn');
2406         }
2407         if (has_capability('moodle/role:switchroles', $this->context)) {
2408             $availableroles = get_switchable_roles($this->context);
2409             if (is_array($availableroles)) {
2410                 foreach ($availableroles as $key=>$role) {
2411                     if ($key == $CFG->guestroleid || $assumedrole===(int)$key) {
2412                         continue;
2413                     }
2414                     $roles[$key] = $role;
2415                 }
2416             }
2417         }
2418         if (is_array($roles) && count($roles)>0) {
2419             $switchroles = $this->add(get_string('switchroleto'));
2420             if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
2421                 $switchroles->force_open();
2422             }
2423             $returnurl = $this->page->url;
2424             $returnurl->param('sesskey', sesskey());
2425             $SESSION->returnurl = serialize($returnurl);
2426             foreach ($roles as $key=>$name) {
2427                 $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>'1'));
2428                 $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/roles', ''));
2429             }
2430         }
2431         // Return we are done
2432         return $coursenode;
2433     }
2435     /**
2436      * This function calls the module function to inject module settings into the
2437      * settings navigation tree.
2438      *
2439      * This only gets called if there is a corrosponding function in the modules
2440      * lib file.
2441      *
2442      * For examples mod/forum/lib.php ::: forum_extend_settings_navigation()
2443      *
2444      * @return navigation_node|false
2445      */
2446     protected function load_module_settings() {
2447         global $CFG;
2449         if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
2450             $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
2451             $this->page->set_cm($cm, $this->page->course);
2452         }
2454         $modulenode = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
2455         $modulenode->force_open();
2457         // Settings for the module
2458         if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
2459             $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
2460             $modulenode->add(get_string('settings'), $url, navigation_node::TYPE_SETTING);
2461         }
2462         // Assign local roles
2463         if (count(get_assignable_roles($this->page->cm->context))>0) {
2464             $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
2465             $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING);
2466         }
2467         // Override roles
2468         if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
2469             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
2470             $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2471         }
2472         // Check role permissions
2473         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
2474             $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
2475             $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2476         }
2477         // Manage filters
2478         if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
2479             $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
2480             $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2481         }
2483         $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
2484         $function = $this->page->activityname.'_extend_settings_navigation';
2486         if (file_exists($file)) {
2487             require_once($file);
2488         }
2489         if (!function_exists($function)) {
2490             return $modulenode;
2491         }
2493         $function($this, $modulenode);
2495         // Remove the module node if there are no children
2496         if (empty($modulenode->children)) {
2497             $modulenode->remove();
2498         }
2500         return $modulenode;
2501     }
2503     /**
2504      * Loads the user settings block of the settings nav
2505      *
2506      * This function is simply works out the userid and whether we need to load
2507      * just the current users profile settings, or the current user and the user the
2508      * current user is viewing.
2509      *
2510      * This function has some very ugly code to work out the user, if anyone has
2511      * any bright ideas please feel free to intervene.
2512      *
2513      * @param int $courseid The course id of the current course
2514      * @return navigation_node|false
2515      */
2516     protected function load_user_settings($courseid=SITEID) {
2517         global $USER, $FULLME, $CFG;
2519         if (isguestuser() || !isloggedin()) {
2520             return false;
2521         }
2523         // This is terribly ugly code, but I couldn't see a better way around it
2524         // we need to pick up the user id, it can be the current user or someone else
2525         // and the key depends on the current location
2526         // Default to look at id
2527         $userkey='id';
2528         if (strpos($FULLME,'/blog/') || strpos($FULLME, $CFG->admin.'/roles/')) {
2529             // And blog and roles just do thier own thing using `userid`
2530             $userkey = 'userid';
2531         } else if ($this->context->contextlevel >= CONTEXT_COURSECAT && strpos($FULLME, '/message/')===false && strpos($FULLME, '/mod/forum/user')===false && strpos($FULLME, '/user/editadvanced')===false) {
2532             // If we have a course context and we are not in message or forum
2533             // Message and forum both pick the user up from `id`
2534             $userkey = 'user';
2535         }
2537         $userid = optional_param($userkey, $USER->id, PARAM_INT);
2538         if ($userid!=$USER->id) {
2539             $usernode = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
2540             $this->generate_user_settings($courseid, $USER->id);
2541         } else {
2542             $usernode = $this->generate_user_settings($courseid, $USER->id);
2543         }
2544         return $usernode;
2545     }
2547     /**
2548      * This function gets called by {@link load_user_settings()} and actually works out
2549      * what can be shown/done
2550      *
2551      * @param int $courseid The current course' id
2552      * @param int $userid The user id to load for
2553      * @param string $gstitle The string to pass to get_string for the branch title
2554      * @return navigation_node|false
2555      */
2556     protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
2557         global $DB, $CFG, $USER, $SITE;
2559         if ($courseid != SITEID) {
2560             if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
2561                 $course = $this->page->course;
2562             } else {
2563                 $course = $DB->get_record("course", array("id"=>$courseid), '*', MUST_EXIST);
2564             }
2565         } else {
2566             $course = $SITE;
2567         }
2569         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);   // Course context
2570         $systemcontext   = get_system_context();
2571         $currentuser = ($USER->id == $userid);
2573         if ($currentuser) {
2574             $user = $USER;
2575             $usercontext = get_context_instance(CONTEXT_USER, $user->id);       // User context
2576         } else {
2577             if (!$user = $DB->get_record('user', array('id'=>$userid))) {
2578                 return false;
2579             }
2580             // Check that the user can view the profile
2581             $usercontext = get_context_instance(CONTEXT_USER, $user->id);       // User context
2582             if ($course->id==SITEID) {
2583                 if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) {  // Reduce possibility of "browsing" userbase at site level
2584                     // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
2585                     return false;
2586                 }
2587             } else {
2588                 if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
2589                     return false;
2590                 }
2591                 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
2592                     // If groups are in use, make sure we can see that group
2593                     return false;
2594                 }
2595             }
2596         }
2598         $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
2600         // Add a user setting branch
2601         $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname));
2602         $usersetting->id = 'usersettings';
2604         // Check if the user has been deleted
2605         if ($user->deleted) {
2606             if (!has_capability('moodle/user:update', $coursecontext)) {
2607                 // We can't edit the user so just show the user deleted message
2608                 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
2609             } else {
2610                 // We can edit the user so show the user deleted message and link it to the profile
2611                 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
2612                 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
2613             }
2614             return true;
2615         }
2617         // Add the profile edit link
2618         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
2619             if (($currentuser || !is_primary_admin($user->id)) && has_capability('moodle/user:update', $systemcontext)) {
2620                 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
2621                 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
2622             } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_primary_admin($user->id)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
2623                 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
2624                 $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
2625             }
2626         }
2628         // Change password link
2629         if (!empty($user->auth)) {
2630             $userauth = get_auth_plugin($user->auth);
2631             if ($currentuser && !session_is_loggedinas() && $userauth->can_change_password() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext)) {
2632                 $passwordchangeurl = $userauth->change_password_url();
2633                 if (!$passwordchangeurl) {
2634                     if (empty($CFG->loginhttps)) {
2635                         $wwwroot = $CFG->wwwroot;
2636                     } else {
2637                         $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2638                     }
2639                     $passwordchangeurl = new moodle_url('/login/change_password.php');
2640                 } else {
2641                     $urlbits = explode($passwordchangeurl. '?', 1);
2642                     $passwordchangeurl = new moodle_url($urlbits[0]);
2643                     if (count($urlbits)==2 && preg_match_all('#\&([^\=]*?)\=([^\&]*)#si', '&'.$urlbits[1], $matches)) {
2644                         foreach ($matches as $pair) {
2645                             $fullmeurl->param($pair[1],$pair[2]);
2646                         }
2647                     }
2648                 }
2649                 $passwordchangeurl->param('id', $course->id);
2650                 $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
2651             }
2652         }
2654         // View the roles settings
2655         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
2656             $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
2658             $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
2659             $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
2661             $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
2663             if (!empty($assignableroles)) {
2664                 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2665                 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
2666             }
2668             if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
2669                 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2670                 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2671             }
2673             $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
2674             $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2675         }
2677         // Portfolio
2678         if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
2679             require_once($CFG->libdir . '/portfoliolib.php');
2680             if (portfolio_instances(true, false)) {
2681                 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
2682                 $portfolio->add(get_string('configure', 'portfolio'), new moodle_url('/user/portfolio.php'), self::TYPE_SETTING);
2683                 $portfolio->add(get_string('logs', 'portfolio'), new moodle_url('/user/portfoliologs.php'), self::TYPE_SETTING);
2684             }
2685         }
2687         // Security keys
2688         if ($currentuser && !is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $systemcontext)) {
2689             $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
2690             $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
2691         }
2693         // Repository
2694         if (!$currentuser) {
2695             require_once($CFG->dirroot . '/repository/lib.php');
2696             $editabletypes = repository::get_editable_types($usercontext);
2697             if ($usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
2698                 $url = new moodle_url('/repository/manage_instances.php', array('contextid'=>$usercontext->id));
2699                 $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
2700             }
2701         }
2703         // Messaging
2704         if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
2705             $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
2706             $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
2707         }
2709         return $usersetting;
2710     }
2712     /**
2713      * Loads block specific settings in the navigation
2714      *
2715      * @return navigation_node
2716      */
2717     protected function load_block_settings() {
2718         global $CFG;
2720         $blocknode = $this->add(print_context_name($this->context));
2721         $blocknode->force_open();
2723         // Assign local roles
2724         $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2725         $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2727         // Override roles
2728         if (has_capability('moodle/role:review', $this->context) or  count(get_overridable_roles($this->context))>0) {
2729             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2730             $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2731         }
2732         // Check role permissions
2733         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2734             $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2735             $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2736         }
2738         return $blocknode;
2739     }
2741     /**
2742      * Loads category specific settings in the navigation
2743      *
2744      * @return navigation_node
2745      */
2746     protected function load_category_settings() {
2747         global $CFG;
2749         $categorynode = $this->add(print_context_name($this->context));
2750         $categorynode->force_open();
2752         if ($this->page->user_is_editing() && has_capability('moodle/category:manage', $this->context)) {
2753             $categorynode->add(get_string('editcategorythis'), new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid)));
2754             $categorynode->add(get_string('addsubcategory'), new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid)));
2755         }
2757         // Assign local roles
2758         $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
2759         $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
2761         // Override roles
2762         if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
2763             $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
2764             $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
2765         }
2766         // Check role permissions
2767         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
2768             $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
2769             $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
2770         }
2771         // Manage filters
2772         if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
2773             $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
2774             $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
2775         }
2777         return $categorynode;
2778     }
2780     /**
2781      * Determine whether the user is assuming another role
2782      *
2783      * This function checks to see if the user is assuming another role by means of
2784      * role switching. In doing this we compare each RSW key (context path) against
2785      * the current context path. This ensures that we can provide the switching
2786      * options against both the course and any page shown under the course.
2787      *
2788      * @return bool|int The role(int) if the user is in another role, false otherwise
2789      */
2790     protected function in_alternative_role() {
2791         global $USER;
2792         if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
2793             if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
2794                 return $USER->access['rsw'][$this->page->context->path];
2795             }
2796             foreach ($USER->access['rsw'] as $key=>$role) {
2797                 if (strpos($this->context->path,$key)===0) {
2798                     return $role;
2799                 }
2800             }
2801         }
2802         return false;
2803     }
2805     /**
2806      * This function loads all of the front page settings into the settings navigation.
2807      * This function is called when the user is on the front page, or $COURSE==$SITE
2808      * @return navigation_node
2809      */
2810     protected function load_front_page_settings($forceopen = false) {
2811         global $SITE, $CFG;
2813         $course = clone($SITE);
2814         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);   // Course context
2816         $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
2817         if ($forceopen) {
2818             $frontpage->force_open();
2819         }
2820         $frontpage->id = 'frontpagesettings';
2822         if (has_capability('moodle/course:update', $coursecontext)) {
2824             // Add the turn on/off settings
2825             $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
2826             if ($this->page->user_is_editing()) {
2827                 $url->param('edit', 'off');
2828                 $editstring = get_string('turneditingoff');
2829             } else {
2830                 $url->param('edit', 'on');
2831                 $editstring = get_string('turneditingon');
2832             }
2833             $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
2835             // Add the course settings link
2836             $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
2837             $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
2838         }
2840         //Participants
2841         if (has_capability('moodle/site:viewparticipants', $coursecontext)) {
2842             $url = new moodle_url('/user/index.php', array('contextid'=>$coursecontext->id));
2843             $frontpage->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/users', ''));
2844         }
2846         // Roles
2847         if (has_capability('moodle/role:assign', $coursecontext)) {
2848             // Add assign or override roles if allowed
2849             $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
2850             $frontpage->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2851             // Override roles
2852             if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
2853                 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
2854                 $frontpage->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2855             }
2856             // Check role permissions
2857             if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
2858                 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
2859                 $frontpage->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
2860             }
2861             // Manage filters
2862             if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
2863                 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
2864                 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
2865             }
2866         }
2868         // Backup this course
2869         if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
2870             $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
2871             $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
2872         }
2874         // Restore to this course
2875         if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
2876             $url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
2877             $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
2878         }
2880         // Manage questions
2881         $questioncaps = array('moodle/question:add',
2882                               'moodle/question:editmine',
2883                               'moodle/question:editall',
2884                               'moodle/question:viewmine',
2885                               'moodle/question:viewall',
2886                               'moodle/question:movemine',
2887                               'moodle/question:moveall');
2888         if (has_any_capability($questioncaps, $this->context)) {
2889             $questionlink = $CFG->wwwroot.'/question/edit.php';
2890         } else if (has_capability('moodle/question:managecategory', $this->context)) {
2891             $questionlink = $CFG->wwwroot.'/question/category.php';
2892         }
2893         if (isset($questionlink)) {
2894             $url = new moodle_url($questionlink, array('courseid'=>$course->id));
2895             $frontpage->add(get_string('questions','quiz'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/questions', ''));
2896         }
2898         // Manage files
2899         if (has_capability('moodle/course:managefiles', $this->context)) {
2900             $url = new moodle_url('/files/index.php', array('id'=>$course->id));
2901             $frontpage->add(get_string('files'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/files', ''));
2902         }
2903         return $frontpage;
2904     }
2906     /**
2907      * This function marks the cache as volatile so it is cleared during shutdown
2908      */
2909     public function clear_cache() {
2910         $this->cache->volatile();
2911     }
2914 /**
2915  * Simple class used to output a navigation branch in XML
2916  *
2917  * @package moodlecore
2918  * @subpackage navigation
2919  * @copyright 2009 Sam Hemelryk
2920  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2921  */
2922 class navigation_json {
2923     /** @var array */
2924     protected $nodetype = array('node','branch');
2925     /** @var array */
2926     protected $expandable = array();
2927     /**
2928      * Turns a branch and all of its children into XML
2929      *
2930      * @param navigation_node $branch
2931      * @return string XML string
2932      */
2933     public function convert($branch) {
2934         $xml = $this->convert_child($branch);
2935         return $xml;
2936     }
2937     /**
2938      * Set the expandable items in the array so that we have enough information
2939      * to attach AJAX events
2940      * @param array $expandable
2941      */
2942     public function set_expandable($expandable) {
2943         foreach ($expandable as $node) {
2944             $this->expandable[(string)$node['branchid']] = $node;
2945         }
2946     }
2947     /**
2948      * Recusively converts a child node and its children to XML for output
2949      *
2950      * @param navigation_node $child The child to convert
2951      * @param int $depth Pointlessly used to track the depth of the XML structure
2952      * @return string JSON
2953      */
2954     protected function convert_child($child, $depth=1) {
2955         global $OUTPUT;
2957         if (!$child->display) {
2958             return '';
2959         }
2960         $attributes = array();
2961         $attributes['id'] = $child->id;
2962         $attributes['name'] = $child->text;
2963         $attributes['type'] = $child->type;
2964         $attributes['key'] = $child->key;
2965         $attributes['class'] = $child->get_css_type();
2967         if ($child->icon instanceof pix_icon) {
2968             $attributes['icon'] = array(
2969                 'component' => $child->icon->component,
2970                 'pix' => $child->icon->pix,
2971             );
2972             foreach ($child->icon->attributes as $key=>$value) {
2973                 if ($key == 'class') {
2974                     $attributes['icon']['classes'] = explode(' ', $value);
2975                 } else if (!array_key_exists($key, $attributes['icon'])) {
2976                     $attributes['icon'][$key] = $value;
2977                 }
2979             }
2980         } else if (!empty($child->icon)) {
2981             $attributes['icon'] = (string)$child->icon;
2982         }
2984         if ($child->forcetitle || $child->title !== $child->text) {
2985             $attributes['title'] = htmlentities($child->title);
2986         }
2987         if (array_key_exists((string)$child->key, $this->expandable)) {
2988             $attributes['expandable'] = $child->key;
2989             $child->add_class($this->expandable[$child->key]['id']);
2990         }
2992         if (count($child->classes)>0) {
2993             $attributes['class'] .= ' '.join(' ',$child->classes);
2994         }
2995         if (is_string($child->action)) {
2996             $attributes['link'] = $child->action;
2997         } else if ($child->action instanceof moodle_url) {
2998             $attributes['link'] = $child->action->out();
2999         }
3000         $attributes['hidden'] = ($child->hidden);
3001         $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
3003         if (count($child->children)>0) {
3004             $attributes['children'] = array();
3005             foreach ($child->children as $subchild) {
3006                 $attributes['children'][] = $this->convert_child($subchild, $depth+1);
3007             }
3008         }
3010         if ($depth > 1) {
3011             return $attributes;
3012         } else {
3013             return json_encode($attributes);
3014         }
3015     }
3018 /**
3019  * The cache class used by global navigation and settings navigation to cache bits
3020  * and bobs that are used during their generation.
3021  *
3022  * It is basically an easy access point to session with a bit of smarts to make
3023  * sure that the information that is cached is valid still.
3024  *
3025  * Example use:
3026  * <code php>
3027  * if (!$cache->viewdiscussion()) {
3028  *     // Code to do stuff and produce cachable content
3029  *     $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
3030  * }
3031  * $content = $cache->viewdiscussion;
3032  * </code>
3033  *
3034  * @package moodlecore
3035  * @subpackage navigation
3036  * @copyright 2009 Sam Hemelryk
3037  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3038  */
3039 class navigation_cache {
3040     /** @var int */
3041     protected $creation;
3042     /** @var array */
3043     protected $session;
3044     /** @var string */
3045     protected $area;
3046     /** @var int */
3047     protected $timeout;
3048     /** @var stdClass */
3049     protected $currentcontext;
3050     /** @var int */
3051     const CACHETIME = 0;
3052     /** @var int */
3053     const CACHEUSERID = 1;
3054     /** @var int */
3055     const CACHEVALUE = 2;
3056     /** @var null|array An array of navigation cache areas to expire on shutdown */
3057     public static $volatilecaches;
3059     /**
3060      * Contructor for the cache. Requires two arguments
3061      *
3062      * @param string $area The string to use to segregate this particular cache
3063      *                it can either be unique to start a fresh cache or if you want
3064      *                to share a cache then make it the string used in the original
3065      *                cache
3066      * @param int $timeout The number of seconds to time the information out after
3067      */
3068     public function __construct($area, $timeout=60) {
3069         global $SESSION;
3070         $this->creation = time();
3071         $this->area = $area;
3073         if (!isset($SESSION->navcache)) {
3074             $SESSION->navcache = new stdClass;
3075         }
3077         if (!isset($SESSION->navcache->{$area})) {
3078             $SESSION->navcache->{$area} = array();
3079         }
3080         $this->session = &$SESSION->navcache->{$area};
3081         $this->timeout = time()-$timeout;
3082         if (rand(0,10)===0) {
3083             $this->garbage_collection();
3084         }
3085     }
3087     /**
3088      * Magic Method to retrieve something by simply calling using = cache->key
3089      *
3090      * @param mixed $key The identifier for the information you want out again
3091      * @return void|mixed Either void or what ever was put in
3092      */
3093     public function __get($key) {
3094         if (!$this->cached($key)) {
3095             return;
3096         }
3097         $information = $this->session[$key][self::CACHEVALUE];
3098         return unserialize($information);
3099     }
3101     /**
3102      * Magic method that simply uses {@link set();} to store something in the cache
3103      *
3104      * @param string|int $key
3105      * @param mixed $information
3106      */
3107     public function __set($key, $information) {
3108         $this->set($key, $information);
3109     }
3111     /**
3112      * Sets some information against the cache (session) for later retrieval
3113      *
3114      * @param string|int $key
3115      * @param mixed $information
3116      */
3117     public function set($key, $information) {
3118         global $USER;
3119         $information = serialize($information);
3120         $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
3121     }
3122     /**
3123      * Check the existence of the identifier in the cache
3124      *
3125      * @param string|int $key
3126      * @return bool
3127      */
3128     public function cached($key) {
3129         global $USER;
3130         if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) {
3131             return false;
3132         }
3133         return true;
3134     }
3135     /**
3136      * Compare something to it's equivilant in the cache
3137      *
3138      * @param string $key
3139      * @param mixed $value
3140      * @param bool $serialise Whether to serialise the value before comparison
3141      *              this should only be set to false if the value is already
3142      *              serialised
3143      * @return bool If the value is the same false if it is not set or doesn't match
3144      */
3145     public function compare($key, $value, $serialise=true) {
3146         if ($this->cached($key)) {
3147             if ($serialise) {
3148                 $value = serialize($value);
3149             }
3150             if ($this->session[$key][self::CACHEVALUE] === $value) {
3151                 return true;
3152             }
3153         }
3154         return false;
3155     }
3156     /**
3157      * Wipes the entire cache, good to force regeneration
3158      */
3159     public function clear() {
3160         $this->session = array();
3161     }
3162     /**
3163      * Checks all cache entries and removes any that have expired, good ole cleanup
3164      */
3165     protected function garbage_collection() {
3166         foreach ($this->session as $key=>$cachedinfo) {
3167             if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
3168                 unset($this->session[$key]);
3169             }
3170         }
3171     }
3173     /**
3174      * Marks the cache as being volatile (likely to change)
3175      *
3176      * Any caches marked as volatile will be destroyed at the on shutdown by
3177      * {@link navigation_node::destroy_volatile_caches()} which is registered
3178      * as a shutdown function if any caches are marked as volatile.
3179      *
3180      * @param bool $setting True to destroy the cache false not too
3181      */
3182     public function volatile($setting = true) {
3183         if (self::$volatilecaches===null) {
3184             self::$volatilecaches = array();
3185             register_shutdown_function(array('navigation_cache','destroy_volatile_caches'));
3186         }
3188         if ($setting) {
3189             self::$volatilecaches[$this->area] = $this->area;
3190         } else if (array_key_exists($this->area, self::$volatilecaches)) {
3191             unset(self::$volatilecaches[$this->area]);
3192         }
3193     }
3195     /**
3196      * Destroys all caches marked as volatile
3197      *
3198      * This function is static and works in conjunction with the static volatilecaches
3199      * property of navigation cache.
3200      * Because this function is static it manually resets the cached areas back to an
3201      * empty array.
3202      */
3203     public static function destroy_volatile_caches() {
3204         global $SESSION;
3205         if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
3206             foreach (self::$volatilecaches as $area) {
3207                 $SESSION->navcache->{$area} = array();
3208             }
3209         }
3210     }