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