2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once $CFG->libdir.'/gradelib.php';
28 * This class iterates over all users that are graded in a course.
29 * Returns detailed info about users and their grades.
31 * @author Petr Skoda <skodak@moodle.org>
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 class graded_users_iterator {
37 * The couse whose users we are interested in
42 * An array of grade items or null if only user data was requested
44 protected $grade_items;
47 * The group ID we are interested in. 0 means all groups.
52 * A recordset of graded users
57 * A recordset of user grades (grade_grade instances)
62 * Array used when moving to next user while iterating through the grades recordset
64 protected $gradestack;
67 * The first field of the users table by which the array of users will be sorted
69 protected $sortfield1;
72 * Should sortfield1 be ASC or DESC
74 protected $sortorder1;
77 * The second field of the users table by which the array of users will be sorted
79 protected $sortfield2;
82 * Should sortfield2 be ASC or DESC
84 protected $sortorder2;
89 * @param object $course A course object
90 * @param array $grade_items array of grade items, if not specified only user info returned
91 * @param int $groupid iterate only group users if present
92 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
93 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
94 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
95 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
97 public function __construct($course, $grade_items=null, $groupid=0,
98 $sortfield1='lastname', $sortorder1='ASC',
99 $sortfield2='firstname', $sortorder2='ASC') {
100 $this->course = $course;
101 $this->grade_items = $grade_items;
102 $this->groupid = $groupid;
103 $this->sortfield1 = $sortfield1;
104 $this->sortorder1 = $sortorder1;
105 $this->sortfield2 = $sortfield2;
106 $this->sortorder2 = $sortorder2;
108 $this->gradestack = array();
112 * Initialise the iterator
114 * @return boolean success
116 public function init() {
121 grade_regrade_final_grades($this->course->id);
122 $course_item = grade_item::fetch_course_item($this->course->id);
123 if ($course_item->needsupdate) {
124 // can not calculate all final grades - sorry
128 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
129 $relatedcontexts = get_related_contexts_string($coursecontext);
131 list($gradebookroles_sql, $params) =
132 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
134 //limit to users with an active enrolment
135 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext);
137 $params = array_merge($params, $enrolledparams);
139 if ($this->groupid) {
140 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
141 $groupwheresql = "AND gm.groupid = :groupid";
142 // $params contents: gradebookroles
143 $params['groupid'] = $this->groupid;
149 if (empty($this->sortfield1)) {
150 // we must do some sorting even if not specified
151 $ofields = ", u.id AS usrt";
155 $ofields = ", u.$this->sortfield1 AS usrt1";
156 $order = "usrt1 $this->sortorder1";
157 if (!empty($this->sortfield2)) {
158 $ofields .= ", u.$this->sortfield2 AS usrt2";
159 $order .= ", usrt2 $this->sortorder2";
161 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
162 // user order MUST be the same in both queries,
163 // must include the only unique user->id if not already present
164 $ofields .= ", u.id AS usrt";
165 $order .= ", usrt ASC";
169 // $params contents: gradebookroles and groupid (for $groupwheresql)
170 $users_sql = "SELECT u.* $ofields
172 JOIN ($enrolledsql) je ON je.id = u.id
175 SELECT DISTINCT ra.userid
176 FROM {role_assignments} ra
177 WHERE ra.roleid $gradebookroles_sql
178 AND ra.contextid $relatedcontexts
179 ) rainner ON rainner.userid = u.id
183 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
185 if (!empty($this->grade_items)) {
186 $itemids = array_keys($this->grade_items);
187 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
188 $params = array_merge($params, $grades_params);
189 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
191 $grades_sql = "SELECT g.* $ofields
192 FROM {grade_grades} g
193 JOIN {user} u ON g.userid = u.id
194 JOIN ($enrolledsql) je ON je.id = u.id
197 SELECT DISTINCT ra.userid
198 FROM {role_assignments} ra
199 WHERE ra.roleid $gradebookroles_sql
200 AND ra.contextid $relatedcontexts
201 ) rainner ON rainner.userid = u.id
203 AND g.itemid $itemidsql
205 ORDER BY $order, g.itemid ASC";
206 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
208 $this->grades_rs = false;
215 * Returns information about the next user
216 * @return mixed array of user info, all grades and feedback or null when no more users found
218 public function next_user() {
219 if (!$this->users_rs) {
220 return false; // no users present
223 if (!$this->users_rs->valid()) {
224 if ($current = $this->_pop()) {
225 // this is not good - user or grades updated between the two reads above :-(
228 return false; // no more users
230 $user = $this->users_rs->current();
231 $this->users_rs->next();
234 // find grades of this user
235 $grade_records = array();
237 if (!$current = $this->_pop()) {
238 break; // no more grades
241 if (empty($current->userid)) {
245 if ($current->userid != $user->id) {
246 // grade of the next user, we have all for this user
247 $this->_push($current);
251 $grade_records[$current->itemid] = $current;
255 $feedbacks = array();
257 if (!empty($this->grade_items)) {
258 foreach ($this->grade_items as $grade_item) {
259 if (array_key_exists($grade_item->id, $grade_records)) {
260 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
261 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
262 unset($grade_records[$grade_item->id]->feedback);
263 unset($grade_records[$grade_item->id]->feedbackformat);
264 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
266 $feedbacks[$grade_item->id]->feedback = '';
267 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
268 $grades[$grade_item->id] =
269 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
274 $result = new stdClass();
275 $result->user = $user;
276 $result->grades = $grades;
277 $result->feedbacks = $feedbacks;
282 * Close the iterator, do not forget to call this function
284 public function close() {
285 if ($this->users_rs) {
286 $this->users_rs->close();
287 $this->users_rs = null;
289 if ($this->grades_rs) {
290 $this->grades_rs->close();
291 $this->grades_rs = null;
293 $this->gradestack = array();
298 * Add a grade_grade instance to the grade stack
300 * @param grade_grade $grade Grade object
304 private function _push($grade) {
305 array_push($this->gradestack, $grade);
310 * Remove a grade_grade instance from the grade stack
312 * @return grade_grade current grade object
314 private function _pop() {
316 if (empty($this->gradestack)) {
317 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
318 return null; // no grades present
321 $current = $this->grades_rs->current();
323 $this->grades_rs->next();
327 return array_pop($this->gradestack);
333 * Print a selection popup form of the graded users in a course.
335 * @deprecated since 2.0
337 * @param int $course id of the course
338 * @param string $actionpage The page receiving the data from the popoup form
339 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
340 * @param int $groupid id of requested group, 0 means all
341 * @param int $includeall bool include all option
342 * @param bool $return If true, will return the HTML, otherwise, will print directly
345 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
346 global $CFG, $USER, $OUTPUT;
347 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
350 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
353 if (is_null($userid)) {
357 $menu = array(); // Will be a list of userid => user name
358 $gui = new graded_users_iterator($course, null, $groupid);
360 $label = get_string('selectauser', 'grades');
362 $menu[0] = get_string('allusers', 'grades');
363 $label = get_string('selectalloroneuser', 'grades');
365 while ($userdata = $gui->next_user()) {
366 $user = $userdata->user;
367 $menu[$user->id] = fullname($user);
372 $menu[0] .= " (" . (count($menu) - 1) . ")";
374 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
375 $select->label = $label;
376 $select->formid = 'choosegradeuser';
381 * Print grading plugin selection popup form.
383 * @param array $plugin_info An array of plugins containing information for the selector
384 * @param boolean $return return as string
386 * @return nothing or string if $return true
388 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
389 global $CFG, $OUTPUT, $PAGE;
395 foreach ($plugin_info as $plugin_type => $plugins) {
396 if ($plugin_type == 'strings') {
400 $first_plugin = reset($plugins);
402 $sectionname = $plugin_info['strings'][$plugin_type];
405 foreach ($plugins as $plugin) {
406 $link = $plugin->link->out(false);
407 $section[$link] = $plugin->string;
409 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
415 $menu[] = array($sectionname=>$section);
419 // finally print/return the popup form
421 $select = new url_select($menu, $active, null, 'choosepluginreport');
424 return $OUTPUT->render($select);
426 echo $OUTPUT->render($select);
429 // only one option - no plugin selector needed
435 * Print grading plugin selection tab-based navigation.
437 * @param string $active_type type of plugin on current page - import, export, report or edit
438 * @param string $active_plugin active plugin type - grader, user, cvs, ...
439 * @param array $plugin_info Array of plugins
440 * @param boolean $return return as string
442 * @return nothing or string if $return true
444 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
445 global $CFG, $COURSE;
447 if (!isset($currenttab)) { //TODO: this is weird
453 $bottom_row = array();
454 $inactive = array($active_plugin);
455 $activated = array();
460 foreach ($plugin_info as $plugin_type => $plugins) {
461 if ($plugin_type == 'strings') {
465 // If $plugins is actually the definition of a child-less parent link:
466 if (!empty($plugins->id)) {
467 $string = $plugins->string;
468 if (!empty($plugin_info[$active_type]->parent)) {
469 $string = $plugin_info[$active_type]->parent->string;
472 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
476 $first_plugin = reset($plugins);
477 $url = $first_plugin->link;
479 if ($plugin_type == 'report') {
480 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
483 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
485 if ($active_type == $plugin_type) {
486 foreach ($plugins as $plugin) {
487 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
488 if ($plugin->id == $active_plugin) {
489 $inactive = array($plugin->id);
496 $tabs[] = $bottom_row;
499 return print_tabs($tabs, $active_type, $inactive, $activated, true);
501 print_tabs($tabs, $active_type, $inactive, $activated);
506 * grade_get_plugin_info
508 * @param int $courseid The course id
509 * @param string $active_type type of plugin on current page - import, export, report or edit
510 * @param string $active_plugin active plugin type - grader, user, cvs, ...
514 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
517 $context = get_context_instance(CONTEXT_COURSE, $courseid);
519 $plugin_info = array();
522 $url_prefix = $CFG->wwwroot . '/grade/';
525 $plugin_info['strings'] = grade_helper::get_plugin_strings();
527 if ($reports = grade_helper::get_plugins_reports($courseid)) {
528 $plugin_info['report'] = $reports;
531 //showing grade categories and items make no sense if we're not within a course
532 if ($courseid!=$SITE->id) {
533 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
534 $plugin_info['edittree'] = $edittree;
538 if ($scale = grade_helper::get_info_scales($courseid)) {
539 $plugin_info['scale'] = array('view'=>$scale);
542 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
543 $plugin_info['outcome'] = $outcomes;
546 if ($letters = grade_helper::get_info_letters($courseid)) {
547 $plugin_info['letter'] = $letters;
550 if ($imports = grade_helper::get_plugins_import($courseid)) {
551 $plugin_info['import'] = $imports;
554 if ($exports = grade_helper::get_plugins_export($courseid)) {
555 $plugin_info['export'] = $exports;
558 foreach ($plugin_info as $plugin_type => $plugins) {
559 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
560 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
563 foreach ($plugins as $plugin) {
564 if (is_a($plugin, 'grade_plugin_info')) {
565 if ($active_plugin == $plugin->id) {
566 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
572 //hide course settings if we're not in a course
573 if ($courseid!=$SITE->id) {
574 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
575 $plugin_info['settings'] = array('course'=>$setting);
579 // Put preferences last
580 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
581 $plugin_info['preferences'] = $preferences;
584 foreach ($plugin_info as $plugin_type => $plugins) {
585 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
586 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
589 foreach ($plugins as $plugin) {
590 if (is_a($plugin, 'grade_plugin_info')) {
591 if ($active_plugin == $plugin->id) {
592 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
602 * A simple class containing info about grade plugins.
603 * Can be subclassed for special rules
605 * @package core_grades
606 * @copyright 2009 Nicolas Connault
607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
609 class grade_plugin_info {
611 * A unique id for this plugin
617 * A URL to access this plugin
623 * The name of this plugin
629 * Another grade_plugin_info object, parent of the current one
638 * @param int $id A unique id for this plugin
639 * @param string $link A URL to access this plugin
640 * @param string $string The name of this plugin
641 * @param object $parent Another grade_plugin_info object, parent of the current one
645 public function __construct($id, $link, $string, $parent=null) {
648 $this->string = $string;
649 $this->parent = $parent;
654 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
655 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
656 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
657 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
658 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
660 * @param int $courseid Course id
661 * @param string $active_type The type of the current page (report, settings,
662 * import, export, scales, outcomes, letters)
663 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
664 * @param string $heading The heading of the page. Tries to guess if none is given
665 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
666 * @param string $bodytags Additional attributes that will be added to the <body> tag
667 * @param string $buttons Additional buttons to display on the page
668 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
670 * @return string HTML code or nothing if $return == false
672 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
673 $heading = false, $return=false,
674 $buttons=false, $shownavigation=true) {
675 global $CFG, $OUTPUT, $PAGE;
677 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
679 // Determine the string of the active plugin
680 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
681 $stractive_type = $plugin_info['strings'][$active_type];
683 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
684 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
686 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
689 if ($active_type == 'report') {
690 $PAGE->set_pagelayout('report');
692 $PAGE->set_pagelayout('admin');
694 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
695 $PAGE->set_heading($title);
696 if ($buttons instanceof single_button) {
697 $buttons = $OUTPUT->render($buttons);
699 $PAGE->set_button($buttons);
700 grade_extend_settings($plugin_info, $courseid);
702 $returnval = $OUTPUT->header();
707 // Guess heading if not given explicitly
709 $heading = $stractive_plugin;
712 if ($shownavigation) {
713 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
714 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
718 $returnval .= $OUTPUT->heading($heading);
720 echo $OUTPUT->heading($heading);
723 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
724 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
734 * Utility class used for return tracking when using edit and other forms in grade plugins
736 * @package core_grades
737 * @copyright 2009 Nicolas Connault
738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
740 class grade_plugin_return {
750 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
752 public function grade_plugin_return($params = null) {
753 if (empty($params)) {
754 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
755 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
756 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
757 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
758 $this->page = optional_param('gpr_page', null, PARAM_INT);
761 foreach ($params as $key=>$value) {
762 if (property_exists($this, $key)) {
763 $this->$key = $value;
770 * Returns return parameters as options array suitable for buttons.
771 * @return array options
773 public function get_options() {
774 if (empty($this->type)) {
780 if (!empty($this->plugin)) {
781 $params['plugin'] = $this->plugin;
784 if (!empty($this->courseid)) {
785 $params['id'] = $this->courseid;
788 if (!empty($this->userid)) {
789 $params['userid'] = $this->userid;
792 if (!empty($this->page)) {
793 $params['page'] = $this->page;
802 * @param string $default default url when params not set
803 * @param array $extras Extra URL parameters
807 public function get_return_url($default, $extras=null) {
810 if (empty($this->type) or empty($this->plugin)) {
814 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
817 if (!empty($this->courseid)) {
818 $url .= $glue.'id='.$this->courseid;
822 if (!empty($this->userid)) {
823 $url .= $glue.'userid='.$this->userid;
827 if (!empty($this->page)) {
828 $url .= $glue.'page='.$this->page;
832 if (!empty($extras)) {
833 foreach ($extras as $key=>$value) {
834 $url .= $glue.$key.'='.$value;
843 * Returns string with hidden return tracking form elements.
846 public function get_form_fields() {
847 if (empty($this->type)) {
851 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
853 if (!empty($this->plugin)) {
854 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
857 if (!empty($this->courseid)) {
858 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
861 if (!empty($this->userid)) {
862 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
865 if (!empty($this->page)) {
866 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
871 * Add hidden elements into mform
873 * @param object &$mform moodle form object
877 public function add_mform_elements(&$mform) {
878 if (empty($this->type)) {
882 $mform->addElement('hidden', 'gpr_type', $this->type);
883 $mform->setType('gpr_type', PARAM_SAFEDIR);
885 if (!empty($this->plugin)) {
886 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
887 $mform->setType('gpr_plugin', PARAM_PLUGIN);
890 if (!empty($this->courseid)) {
891 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
892 $mform->setType('gpr_courseid', PARAM_INT);
895 if (!empty($this->userid)) {
896 $mform->addElement('hidden', 'gpr_userid', $this->userid);
897 $mform->setType('gpr_userid', PARAM_INT);
900 if (!empty($this->page)) {
901 $mform->addElement('hidden', 'gpr_page', $this->page);
902 $mform->setType('gpr_page', PARAM_INT);
907 * Add return tracking params into url
909 * @param moodle_url $url A URL
911 * @return string $url with return tracking params
913 public function add_url_params(moodle_url $url) {
914 if (empty($this->type)) {
918 $url->param('gpr_type', $this->type);
920 if (!empty($this->plugin)) {
921 $url->param('gpr_plugin', $this->plugin);
924 if (!empty($this->courseid)) {
925 $url->param('gpr_courseid' ,$this->courseid);
928 if (!empty($this->userid)) {
929 $url->param('gpr_userid', $this->userid);
932 if (!empty($this->page)) {
933 $url->param('gpr_page', $this->page);
941 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
943 * @param string $path The path of the calling script (using __FILE__?)
944 * @param string $pagename The language string to use as the last part of the navigation (non-link)
945 * @param mixed $id Either a plain integer (assuming the key is 'id') or
946 * an array of keys and values (e.g courseid => $courseid, itemid...)
950 function grade_build_nav($path, $pagename=null, $id=null) {
951 global $CFG, $COURSE, $PAGE;
953 $strgrades = get_string('grades', 'grades');
955 // Parse the path and build navlinks from its elements
956 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
957 $path = substr($path, $dirroot_length);
958 $path = str_replace('\\', '/', $path);
960 $path_elements = explode('/', $path);
962 $path_elements_count = count($path_elements);
964 // First link is always 'grade'
965 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
968 $numberofelements = 3;
970 // Prepare URL params string
971 $linkparams = array();
974 foreach ($id as $idkey => $idvalue) {
975 $linkparams[$idkey] = $idvalue;
978 $linkparams['id'] = $id;
984 // Remove file extensions from filenames
985 foreach ($path_elements as $key => $filename) {
986 $path_elements[$key] = str_replace('.php', '', $filename);
989 // Second level links
990 switch ($path_elements[1]) {
991 case 'edit': // No link
992 if ($path_elements[3] != 'index.php') {
993 $numberofelements = 4;
996 case 'import': // No link
998 case 'export': // No link
1001 // $id is required for this link. Do not print it if $id isn't given
1002 if (!is_null($id)) {
1003 $link = new moodle_url('/grade/report/index.php', $linkparams);
1006 if ($path_elements[2] == 'grader') {
1007 $numberofelements = 4;
1012 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1013 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1014 " as the second path element after 'grade'.");
1017 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1019 // Third level links
1020 if (empty($pagename)) {
1021 $pagename = get_string($path_elements[2], 'grades');
1024 switch ($numberofelements) {
1026 $PAGE->navbar->add($pagename, $link);
1029 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1030 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1032 $PAGE->navbar->add($pagename);
1040 * General structure representing grade items in course
1042 * @package core_grades
1043 * @copyright 2009 Nicolas Connault
1044 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1046 class grade_structure {
1052 * Reference to modinfo for current course (for performance, to save
1053 * retrieving it from courseid every time). Not actually set except for
1054 * the grade_tree type.
1055 * @var course_modinfo
1060 * 1D array of grade items only
1065 * Returns icon of element
1067 * @param array &$element An array representing an element in the grade_tree
1068 * @param bool $spacerifnone return spacer if no icon found
1070 * @return string icon or spacer
1072 public function get_element_icon(&$element, $spacerifnone=false) {
1073 global $CFG, $OUTPUT;
1075 switch ($element['type']) {
1078 case 'categoryitem':
1079 $is_course = $element['object']->is_course_item();
1080 $is_category = $element['object']->is_category_item();
1081 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1082 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1083 $is_outcome = !empty($element['object']->outcomeid);
1085 if ($element['object']->is_calculated()) {
1086 $strcalc = get_string('calculatedgrade', 'grades');
1087 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1088 s($strcalc).'" alt="'.s($strcalc).'"/>';
1090 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1091 if ($category = $element['object']->get_item_category()) {
1092 switch ($category->aggregation) {
1093 case GRADE_AGGREGATE_MEAN:
1094 case GRADE_AGGREGATE_MEDIAN:
1095 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1096 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1097 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1098 $stragg = get_string('aggregation', 'grades');
1099 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1100 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1101 case GRADE_AGGREGATE_SUM:
1102 $stragg = get_string('aggregation', 'grades');
1103 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1104 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1108 } else if ($element['object']->itemtype == 'mod') {
1109 //prevent outcomes being displaying the same icon as the activity they are attached to
1111 $stroutcome = s(get_string('outcome', 'grades'));
1112 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1113 'class="icon itemicon" title="'.$stroutcome.
1114 '" alt="'.$stroutcome.'"/>';
1116 $strmodname = get_string('modulename', $element['object']->itemmodule);
1117 return '<img src="'.$OUTPUT->pix_url('icon',
1118 $element['object']->itemmodule) . '" ' .
1119 'class="icon itemicon" title="' .s($strmodname).
1120 '" alt="' .s($strmodname).'"/>';
1122 } else if ($element['object']->itemtype == 'manual') {
1123 if ($element['object']->is_outcome_item()) {
1124 $stroutcome = get_string('outcome', 'grades');
1125 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1126 'class="icon itemicon" title="'.s($stroutcome).
1127 '" alt="'.s($stroutcome).'"/>';
1129 $strmanual = get_string('manualitem', 'grades');
1130 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1131 'class="icon itemicon" title="'.s($strmanual).
1132 '" alt="'.s($strmanual).'"/>';
1138 $strcat = get_string('category', 'grades');
1139 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1140 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1143 if ($spacerifnone) {
1144 return $OUTPUT->spacer().' ';
1151 * Returns name of element optionally with icon and link
1153 * @param array &$element An array representing an element in the grade_tree
1154 * @param bool $withlink Whether or not this header has a link
1155 * @param bool $icon Whether or not to display an icon with this header
1156 * @param bool $spacerifnone return spacer if no icon found
1158 * @return string header
1160 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1164 $header .= $this->get_element_icon($element, $spacerifnone);
1167 $header .= $element['object']->get_name();
1169 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1170 $element['type'] != 'courseitem') {
1175 $url = $this->get_activity_link($element);
1177 $a = new stdClass();
1178 $a->name = get_string('modulename', $element['object']->itemmodule);
1179 $title = get_string('linktoactivity', 'grades', $a);
1181 $header = html_writer::link($url, $header, array('title' => $title));
1188 private function get_activity_link($element) {
1190 /** @var array static cache of the grade.php file existence flags */
1191 static $hasgradephp = array();
1193 $itemtype = $element['object']->itemtype;
1194 $itemmodule = $element['object']->itemmodule;
1195 $iteminstance = $element['object']->iteminstance;
1196 $itemnumber = $element['object']->itemnumber;
1198 // Links only for module items that have valid instance, module and are
1199 // called from grade_tree with valid modinfo
1200 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1204 // Get $cm efficiently and with visibility information using modinfo
1205 $instances = $this->modinfo->get_instances();
1206 if (empty($instances[$itemmodule][$iteminstance])) {
1209 $cm = $instances[$itemmodule][$iteminstance];
1211 // Do not add link if activity is not visible to the current user
1212 if (!$cm->uservisible) {
1216 if (!array_key_exists($itemmodule, $hasgradephp)) {
1217 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1218 $hasgradephp[$itemmodule] = true;
1220 $hasgradephp[$itemmodule] = false;
1224 // If module has grade.php, link to that, otherwise view.php
1225 if ($hasgradephp[$itemmodule]) {
1226 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1227 if (isset($element['userid'])) {
1228 $args['userid'] = $element['userid'];
1230 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1232 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1237 * Returns URL of a page that is supposed to contain detailed grade analysis
1239 * At the moment, only activity modules are supported. The method generates link
1240 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1241 * gradeid and userid. If the grade.php does not exist, null is returned.
1243 * @return moodle_url|null URL or null if unable to construct it
1245 public function get_grade_analysis_url(grade_grade $grade) {
1247 /** @var array static cache of the grade.php file existence flags */
1248 static $hasgradephp = array();
1250 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1251 throw new coding_exception('Passed grade without the associated grade item');
1253 $item = $grade->grade_item;
1255 if (!$item->is_external_item()) {
1256 // at the moment, only activity modules are supported
1259 if ($item->itemtype !== 'mod') {
1260 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1262 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1266 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1267 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1268 $hasgradephp[$item->itemmodule] = true;
1270 $hasgradephp[$item->itemmodule] = false;
1274 if (!$hasgradephp[$item->itemmodule]) {
1278 $instances = $this->modinfo->get_instances();
1279 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1282 $cm = $instances[$item->itemmodule][$item->iteminstance];
1283 if (!$cm->uservisible) {
1287 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1289 'itemid' => $item->id,
1290 'itemnumber' => $item->itemnumber,
1291 'gradeid' => $grade->id,
1292 'userid' => $grade->userid,
1299 * Returns an action icon leading to the grade analysis page
1301 * @param grade_grade $grade
1304 public function get_grade_analysis_icon(grade_grade $grade) {
1307 $url = $this->get_grade_analysis_url($grade);
1308 if (is_null($url)) {
1312 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1313 get_string('gradeanalysis', 'core_grades')));
1317 * Returns the grade eid - the grade may not exist yet.
1319 * @param grade_grade $grade_grade A grade_grade object
1321 * @return string eid
1323 public function get_grade_eid($grade_grade) {
1324 if (empty($grade_grade->id)) {
1325 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1327 return 'g'.$grade_grade->id;
1332 * Returns the grade_item eid
1333 * @param grade_item $grade_item A grade_item object
1334 * @return string eid
1336 public function get_item_eid($grade_item) {
1337 return 'i'.$grade_item->id;
1341 * Given a grade_tree element, returns an array of parameters
1342 * used to build an icon for that element.
1344 * @param array $element An array representing an element in the grade_tree
1348 public function get_params_for_iconstr($element) {
1349 $strparams = new stdClass();
1350 $strparams->category = '';
1351 $strparams->itemname = '';
1352 $strparams->itemmodule = '';
1354 if (!method_exists($element['object'], 'get_name')) {
1358 $strparams->itemname = html_to_text($element['object']->get_name());
1360 // If element name is categorytotal, get the name of the parent category
1361 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1362 $parent = $element['object']->get_parent_category();
1363 $strparams->category = $parent->get_name() . ' ';
1365 $strparams->category = '';
1368 $strparams->itemmodule = null;
1369 if (isset($element['object']->itemmodule)) {
1370 $strparams->itemmodule = $element['object']->itemmodule;
1376 * Return edit icon for give element
1378 * @param array $element An array representing an element in the grade_tree
1379 * @param object $gpr A grade_plugin_return object
1383 public function get_edit_icon($element, $gpr) {
1384 global $CFG, $OUTPUT;
1386 if (!has_capability('moodle/grade:manage', $this->context)) {
1387 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1388 // oki - let them override grade
1394 static $strfeedback = null;
1395 static $streditgrade = null;
1396 if (is_null($streditgrade)) {
1397 $streditgrade = get_string('editgrade', 'grades');
1398 $strfeedback = get_string('feedback');
1401 $strparams = $this->get_params_for_iconstr($element);
1403 $object = $element['object'];
1405 switch ($element['type']) {
1407 case 'categoryitem':
1409 $stredit = get_string('editverbose', 'grades', $strparams);
1410 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1411 $url = new moodle_url('/grade/edit/tree/item.php',
1412 array('courseid' => $this->courseid, 'id' => $object->id));
1414 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1415 array('courseid' => $this->courseid, 'id' => $object->id));
1420 $stredit = get_string('editverbose', 'grades', $strparams);
1421 $url = new moodle_url('/grade/edit/tree/category.php',
1422 array('courseid' => $this->courseid, 'id' => $object->id));
1426 $stredit = $streditgrade;
1427 if (empty($object->id)) {
1428 $url = new moodle_url('/grade/edit/tree/grade.php',
1429 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1431 $url = new moodle_url('/grade/edit/tree/grade.php',
1432 array('courseid' => $this->courseid, 'id' => $object->id));
1434 if (!empty($object->feedback)) {
1435 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1444 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1452 * Return hiding icon for give element
1454 * @param array $element An array representing an element in the grade_tree
1455 * @param object $gpr A grade_plugin_return object
1459 public function get_hiding_icon($element, $gpr) {
1460 global $CFG, $OUTPUT;
1462 if (!has_capability('moodle/grade:manage', $this->context) and
1463 !has_capability('moodle/grade:hide', $this->context)) {
1467 $strparams = $this->get_params_for_iconstr($element);
1468 $strshow = get_string('showverbose', 'grades', $strparams);
1469 $strhide = get_string('hideverbose', 'grades', $strparams);
1471 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1472 $url = $gpr->add_url_params($url);
1474 if ($element['object']->is_hidden()) {
1476 $tooltip = $strshow;
1478 // Change the icon and add a tooltip showing the date
1479 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1480 $type = 'hiddenuntil';
1481 $tooltip = get_string('hiddenuntildate', 'grades',
1482 userdate($element['object']->get_hidden()));
1485 $url->param('action', 'show');
1487 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1490 $url->param('action', 'hide');
1491 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1498 * Return locking icon for given element
1500 * @param array $element An array representing an element in the grade_tree
1501 * @param object $gpr A grade_plugin_return object
1505 public function get_locking_icon($element, $gpr) {
1506 global $CFG, $OUTPUT;
1508 $strparams = $this->get_params_for_iconstr($element);
1509 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1510 $strlock = get_string('lockverbose', 'grades', $strparams);
1512 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1513 $url = $gpr->add_url_params($url);
1515 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1516 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1517 $strparamobj = new stdClass();
1518 $strparamobj->itemname = $element['object']->grade_item->itemname;
1519 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1521 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1523 } else if ($element['object']->is_locked()) {
1525 $tooltip = $strunlock;
1527 // Change the icon and add a tooltip showing the date
1528 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1530 $tooltip = get_string('locktimedate', 'grades',
1531 userdate($element['object']->get_locktime()));
1534 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1537 $url->param('action', 'unlock');
1538 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1542 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1545 $url->param('action', 'lock');
1546 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1554 * Return calculation icon for given element
1556 * @param array $element An array representing an element in the grade_tree
1557 * @param object $gpr A grade_plugin_return object
1561 public function get_calculation_icon($element, $gpr) {
1562 global $CFG, $OUTPUT;
1563 if (!has_capability('moodle/grade:manage', $this->context)) {
1567 $type = $element['type'];
1568 $object = $element['object'];
1570 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1571 $strparams = $this->get_params_for_iconstr($element);
1572 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1574 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1575 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1577 // show calculation icon only when calculation possible
1578 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1579 if ($object->is_calculated()) {
1582 $icon = 't/calc_off';
1585 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1586 $url = $gpr->add_url_params($url);
1587 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1596 * Flat structure similar to grade tree.
1598 * @uses grade_structure
1599 * @package core_grades
1600 * @copyright 2009 Nicolas Connault
1601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1603 class grade_seq extends grade_structure {
1606 * 1D array of elements
1611 * Constructor, retrieves and stores array of all grade_category and grade_item
1612 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1614 * @param int $courseid The course id
1615 * @param bool $category_grade_last category grade item is the last child
1616 * @param bool $nooutcomes Whether or not outcomes should be included
1618 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1621 $this->courseid = $courseid;
1622 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1624 // get course grade tree
1625 $top_element = grade_category::fetch_course_tree($courseid, true);
1627 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1629 foreach ($this->elements as $key=>$unused) {
1630 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1635 * Static recursive helper - makes the grade_item for category the last children
1637 * @param array &$element The seed of the recursion
1638 * @param bool $category_grade_last category grade item is the last child
1639 * @param bool $nooutcomes Whether or not outcomes should be included
1643 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1644 if (empty($element['children'])) {
1647 $children = array();
1649 foreach ($element['children'] as $sortorder=>$unused) {
1650 if ($nooutcomes and $element['type'] != 'category' and
1651 $element['children'][$sortorder]['object']->is_outcome_item()) {
1654 $children[] = $element['children'][$sortorder];
1656 unset($element['children']);
1658 if ($category_grade_last and count($children) > 1) {
1659 $cat_item = array_shift($children);
1660 array_push($children, $cat_item);
1664 foreach ($children as $child) {
1665 if ($child['type'] == 'category') {
1666 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1668 $child['eid'] = 'i'.$child['object']->id;
1669 $result[$child['object']->id] = $child;
1677 * Parses the array in search of a given eid and returns a element object with
1678 * information about the element it has found.
1680 * @param int $eid Gradetree Element ID
1682 * @return object element
1684 public function locate_element($eid) {
1685 // it is a grade - construct a new object
1686 if (strpos($eid, 'n') === 0) {
1687 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1691 $itemid = $matches[1];
1692 $userid = $matches[2];
1694 //extra security check - the grade item must be in this tree
1695 if (!$item_el = $this->locate_element('i'.$itemid)) {
1699 // $gradea->id may be null - means does not exist yet
1700 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1702 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1703 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1705 } else if (strpos($eid, 'g') === 0) {
1706 $id = (int) substr($eid, 1);
1707 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1710 //extra security check - the grade item must be in this tree
1711 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1714 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1715 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1718 // it is a category or item
1719 foreach ($this->elements as $element) {
1720 if ($element['eid'] == $eid) {
1730 * This class represents a complete tree of categories, grade_items and final grades,
1731 * organises as an array primarily, but which can also be converted to other formats.
1732 * It has simple method calls with complex implementations, allowing for easy insertion,
1733 * deletion and moving of items and categories within the tree.
1735 * @uses grade_structure
1736 * @package core_grades
1737 * @copyright 2009 Nicolas Connault
1738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1740 class grade_tree extends grade_structure {
1743 * The basic representation of the tree as a hierarchical, 3-tiered array.
1744 * @var object $top_element
1746 public $top_element;
1749 * 2D array of grade items and categories
1750 * @var array $levels
1761 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1762 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1764 * @param int $courseid The Course ID
1765 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1766 * @param bool $category_grade_last category grade item is the last child
1767 * @param array $collapsed array of collapsed categories
1768 * @param bool $nooutcomes Whether or not outcomes should be included
1770 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1771 $collapsed=null, $nooutcomes=false) {
1772 global $USER, $CFG, $COURSE, $DB;
1774 $this->courseid = $courseid;
1775 $this->levels = array();
1776 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1778 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1781 $course = $DB->get_record('course', array('id' => $this->courseid));
1783 $this->modinfo = get_fast_modinfo($course);
1785 // get course grade tree
1786 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1788 // collapse the categories if requested
1789 if (!empty($collapsed)) {
1790 grade_tree::category_collapse($this->top_element, $collapsed);
1793 // no otucomes if requested
1794 if (!empty($nooutcomes)) {
1795 grade_tree::no_outcomes($this->top_element);
1798 // move category item to last position in category
1799 if ($category_grade_last) {
1800 grade_tree::category_grade_last($this->top_element);
1804 // inject fake categories == fillers
1805 grade_tree::inject_fillers($this->top_element, 0);
1806 // add colspans to categories and fillers
1807 grade_tree::inject_colspans($this->top_element);
1810 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1815 * Static recursive helper - removes items from collapsed categories
1817 * @param array &$element The seed of the recursion
1818 * @param array $collapsed array of collapsed categories
1822 public function category_collapse(&$element, $collapsed) {
1823 if ($element['type'] != 'category') {
1826 if (empty($element['children']) or count($element['children']) < 2) {
1830 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1831 $category_item = reset($element['children']); //keep only category item
1832 $element['children'] = array(key($element['children'])=>$category_item);
1835 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1836 reset($element['children']);
1837 $first_key = key($element['children']);
1838 unset($element['children'][$first_key]);
1840 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1841 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1847 * Static recursive helper - removes all outcomes
1849 * @param array &$element The seed of the recursion
1853 public function no_outcomes(&$element) {
1854 if ($element['type'] != 'category') {
1857 foreach ($element['children'] as $sortorder=>$child) {
1858 if ($element['children'][$sortorder]['type'] == 'item'
1859 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1860 unset($element['children'][$sortorder]);
1862 } else if ($element['children'][$sortorder]['type'] == 'category') {
1863 grade_tree::no_outcomes($element['children'][$sortorder]);
1869 * Static recursive helper - makes the grade_item for category the last children
1871 * @param array &$element The seed of the recursion
1875 public function category_grade_last(&$element) {
1876 if (empty($element['children'])) {
1879 if (count($element['children']) < 2) {
1882 $first_item = reset($element['children']);
1883 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1884 // the category item might have been already removed
1885 $order = key($element['children']);
1886 unset($element['children'][$order]);
1887 $element['children'][$order] =& $first_item;
1889 foreach ($element['children'] as $sortorder => $child) {
1890 grade_tree::category_grade_last($element['children'][$sortorder]);
1895 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1897 * @param array &$levels The levels of the grade tree through which to recurse
1898 * @param array &$element The seed of the recursion
1899 * @param int $depth How deep are we?
1902 public function fill_levels(&$levels, &$element, $depth) {
1903 if (!array_key_exists($depth, $levels)) {
1904 $levels[$depth] = array();
1907 // prepare unique identifier
1908 if ($element['type'] == 'category') {
1909 $element['eid'] = 'c'.$element['object']->id;
1910 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1911 $element['eid'] = 'i'.$element['object']->id;
1912 $this->items[$element['object']->id] =& $element['object'];
1915 $levels[$depth][] =& $element;
1917 if (empty($element['children'])) {
1921 foreach ($element['children'] as $sortorder=>$child) {
1922 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1923 $element['children'][$sortorder]['prev'] = $prev;
1924 $element['children'][$sortorder]['next'] = 0;
1926 $element['children'][$prev]['next'] = $sortorder;
1933 * Static recursive helper - makes full tree (all leafes are at the same level)
1935 * @param array &$element The seed of the recursion
1936 * @param int $depth How deep are we?
1940 public function inject_fillers(&$element, $depth) {
1943 if (empty($element['children'])) {
1946 $chdepths = array();
1947 $chids = array_keys($element['children']);
1948 $last_child = end($chids);
1949 $first_child = reset($chids);
1951 foreach ($chids as $chid) {
1952 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1956 $maxdepth = reset($chdepths);
1957 foreach ($chdepths as $chid=>$chd) {
1958 if ($chd == $maxdepth) {
1961 for ($i=0; $i < $maxdepth-$chd; $i++) {
1962 if ($chid == $first_child) {
1963 $type = 'fillerfirst';
1964 } else if ($chid == $last_child) {
1965 $type = 'fillerlast';
1969 $oldchild =& $element['children'][$chid];
1970 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1971 'eid'=>'', 'depth'=>$element['object']->depth,
1972 'children'=>array($oldchild));
1980 * Static recursive helper - add colspan information into categories
1982 * @param array &$element The seed of the recursion
1986 public function inject_colspans(&$element) {
1987 if (empty($element['children'])) {
1991 foreach ($element['children'] as $key=>$child) {
1992 $count += grade_tree::inject_colspans($element['children'][$key]);
1994 $element['colspan'] = $count;
1999 * Parses the array in search of a given eid and returns a element object with
2000 * information about the element it has found.
2001 * @param int $eid Gradetree Element ID
2002 * @return object element
2004 public function locate_element($eid) {
2005 // it is a grade - construct a new object
2006 if (strpos($eid, 'n') === 0) {
2007 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2011 $itemid = $matches[1];
2012 $userid = $matches[2];
2014 //extra security check - the grade item must be in this tree
2015 if (!$item_el = $this->locate_element('i'.$itemid)) {
2019 // $gradea->id may be null - means does not exist yet
2020 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2022 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2023 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2025 } else if (strpos($eid, 'g') === 0) {
2026 $id = (int) substr($eid, 1);
2027 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2030 //extra security check - the grade item must be in this tree
2031 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2034 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2035 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2038 // it is a category or item
2039 foreach ($this->levels as $row) {
2040 foreach ($row as $element) {
2041 if ($element['type'] == 'filler') {
2044 if ($element['eid'] == $eid) {
2054 * Returns a well-formed XML representation of the grade-tree using recursion.
2056 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2057 * @param string $tabs The control character to use for tabs
2059 * @return string $xml
2061 public function exporttoxml($root=null, $tabs="\t") {
2064 if (is_null($root)) {
2065 $root = $this->top_element;
2066 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2067 $xml .= "<gradetree>\n";
2071 $type = 'undefined';
2072 if (strpos($root['object']->table, 'grade_categories') !== false) {
2074 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2076 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2080 $xml .= "$tabs<element type=\"$type\">\n";
2081 foreach ($root['object'] as $var => $value) {
2082 if (!is_object($value) && !is_array($value) && !empty($value)) {
2083 $xml .= "$tabs\t<$var>$value</$var>\n";
2087 if (!empty($root['children'])) {
2088 $xml .= "$tabs\t<children>\n";
2089 foreach ($root['children'] as $sortorder => $child) {
2090 $xml .= $this->exportToXML($child, $tabs."\t\t");
2092 $xml .= "$tabs\t</children>\n";
2095 $xml .= "$tabs</element>\n";
2098 $xml .= "</gradetree>";
2105 * Returns a JSON representation of the grade-tree using recursion.
2107 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2108 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2112 public function exporttojson($root=null, $tabs="\t") {
2115 if (is_null($root)) {
2116 $root = $this->top_element;
2123 if (strpos($root['object']->table, 'grade_categories') !== false) {
2124 $name = $root['object']->fullname;
2126 $name = $root['object']->get_name();
2128 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2129 $name = $root['object']->itemname;
2130 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2131 $name = $root['object']->itemname;
2134 $json .= "$tabs {\n";
2135 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2136 $json .= "$tabs\t \"name\": \"$name\",\n";
2138 foreach ($root['object'] as $var => $value) {
2139 if (!is_object($value) && !is_array($value) && !empty($value)) {
2140 $json .= "$tabs\t \"$var\": \"$value\",\n";
2144 $json = substr($json, 0, strrpos($json, ','));
2146 if (!empty($root['children'])) {
2147 $json .= ",\n$tabs\t\"children\": [\n";
2148 foreach ($root['children'] as $sortorder => $child) {
2149 $json .= $this->exportToJSON($child, $tabs."\t\t");
2151 $json = substr($json, 0, strrpos($json, ','));
2152 $json .= "\n$tabs\t]\n";
2158 $json .= "\n$tabs},\n";
2165 * Returns the array of levels
2169 public function get_levels() {
2170 return $this->levels;
2174 * Returns the array of grade items
2178 public function get_items() {
2179 return $this->items;
2183 * Returns a specific Grade Item
2185 * @param int $itemid The ID of the grade_item object
2187 * @return grade_item
2189 public function get_item($itemid) {
2190 if (array_key_exists($itemid, $this->items)) {
2191 return $this->items[$itemid];
2199 * Local shortcut function for creating an edit/delete button for a grade_* object.
2200 * @param string $type 'edit' or 'delete'
2201 * @param int $courseid The Course ID
2202 * @param grade_* $object The grade_* object
2203 * @return string html
2205 function grade_button($type, $courseid, $object) {
2206 global $CFG, $OUTPUT;
2207 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2208 $objectidstring = $matches[1] . 'id';
2210 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2213 $strdelete = get_string('delete');
2214 $stredit = get_string('edit');
2216 if ($type == 'delete') {
2217 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2218 } else if ($type == 'edit') {
2219 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2222 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2227 * This method adds settings to the settings block for the grade system and its
2230 * @global moodle_page $PAGE
2232 function grade_extend_settings($plugininfo, $courseid) {
2235 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2237 $strings = array_shift($plugininfo);
2239 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2240 foreach ($reports as $report) {
2241 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2245 if ($imports = grade_helper::get_plugins_import($courseid)) {
2246 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2247 foreach ($imports as $import) {
2248 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2252 if ($exports = grade_helper::get_plugins_export($courseid)) {
2253 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2254 foreach ($exports as $export) {
2255 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2259 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2260 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2263 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2264 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2265 foreach ($preferences as $preference) {
2266 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2270 if ($letters = grade_helper::get_info_letters($courseid)) {
2271 $letters = array_shift($letters);
2272 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2275 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2276 $outcomes = array_shift($outcomes);
2277 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2280 if ($scales = grade_helper::get_info_scales($courseid)) {
2281 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2284 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2285 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2286 foreach ($categories as $category) {
2287 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2291 if ($gradenode->contains_active_node()) {
2292 // If the gradenode is active include the settings base node (gradeadministration) in
2293 // the navbar, typcially this is ignored.
2294 $PAGE->navbar->includesettingsbase = true;
2296 // If we can get the course admin node make sure it is closed by default
2297 // as in this case the gradenode will be opened
2298 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2299 $coursenode->make_inactive();
2300 $coursenode->forceopen = false;
2306 * Grade helper class
2308 * This class provides several helpful functions that work irrespective of any
2311 * @copyright 2010 Sam Hemelryk
2312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2314 abstract class grade_helper {
2316 * Cached manage settings info {@see get_info_settings}
2317 * @var grade_plugin_info|false
2319 protected static $managesetting = null;
2321 * Cached grade report plugins {@see get_plugins_reports}
2324 protected static $gradereports = null;
2326 * Cached grade report plugins preferences {@see get_info_scales}
2329 protected static $gradereportpreferences = null;
2331 * Cached scale info {@see get_info_scales}
2332 * @var grade_plugin_info|false
2334 protected static $scaleinfo = null;
2336 * Cached outcome info {@see get_info_outcomes}
2337 * @var grade_plugin_info|false
2339 protected static $outcomeinfo = null;
2341 * Cached info on edit structure {@see get_info_edit_structure}
2344 protected static $edittree = null;
2346 * Cached leftter info {@see get_info_letters}
2347 * @var grade_plugin_info|false
2349 protected static $letterinfo = null;
2351 * Cached grade import plugins {@see get_plugins_import}
2354 protected static $importplugins = null;
2356 * Cached grade export plugins {@see get_plugins_export}
2359 protected static $exportplugins = null;
2361 * Cached grade plugin strings
2364 protected static $pluginstrings = null;
2367 * Gets strings commonly used by the describe plugins
2369 * report => get_string('view'),
2370 * edittree => get_string('edittree', 'grades'),
2371 * scale => get_string('scales'),
2372 * outcome => get_string('outcomes', 'grades'),
2373 * letter => get_string('letters', 'grades'),
2374 * export => get_string('export', 'grades'),
2375 * import => get_string('import'),
2376 * preferences => get_string('mypreferences', 'grades'),
2377 * settings => get_string('settings')
2381 public static function get_plugin_strings() {
2382 if (self::$pluginstrings === null) {
2383 self::$pluginstrings = array(
2384 'report' => get_string('view'),
2385 'edittree' => get_string('edittree', 'grades'),
2386 'scale' => get_string('scales'),
2387 'outcome' => get_string('outcomes', 'grades'),
2388 'letter' => get_string('letters', 'grades'),
2389 'export' => get_string('export', 'grades'),
2390 'import' => get_string('import'),
2391 'preferences' => get_string('mypreferences', 'grades'),
2392 'settings' => get_string('settings')
2395 return self::$pluginstrings;
2398 * Get grade_plugin_info object for managing settings if the user can
2400 * @param int $courseid
2401 * @return grade_plugin_info
2403 public static function get_info_manage_settings($courseid) {
2404 if (self::$managesetting !== null) {
2405 return self::$managesetting;
2407 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2408 if (has_capability('moodle/course:update', $context)) {
2409 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2411 self::$managesetting = false;
2413 return self::$managesetting;
2416 * Returns an array of plugin reports as grade_plugin_info objects
2418 * @param int $courseid
2421 public static function get_plugins_reports($courseid) {
2424 if (self::$gradereports !== null) {
2425 return self::$gradereports;
2427 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2428 $gradereports = array();
2429 $gradepreferences = array();
2430 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2431 //some reports make no sense if we're not within a course
2432 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2436 // Remove ones we can't see
2437 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2441 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2442 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2443 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2445 // Add link to preferences tab if such a page exists
2446 if (file_exists($plugindir.'/preferences.php')) {
2447 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2448 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2451 if (count($gradereports) == 0) {
2452 $gradereports = false;
2453 $gradepreferences = false;
2454 } else if (count($gradepreferences) == 0) {
2455 $gradepreferences = false;
2456 asort($gradereports);
2458 asort($gradereports);
2459 asort($gradepreferences);
2461 self::$gradereports = $gradereports;
2462 self::$gradereportpreferences = $gradepreferences;
2463 return self::$gradereports;
2466 * Returns an array of grade plugin report preferences for plugin reports that
2467 * support preferences
2468 * @param int $courseid
2471 public static function get_plugins_report_preferences($courseid) {
2472 if (self::$gradereportpreferences !== null) {
2473 return self::$gradereportpreferences;
2475 self::get_plugins_reports($courseid);
2476 return self::$gradereportpreferences;
2479 * Get information on scales
2480 * @param int $courseid
2481 * @return grade_plugin_info
2483 public static function get_info_scales($courseid) {
2484 if (self::$scaleinfo !== null) {
2485 return self::$scaleinfo;
2487 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2488 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2489 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2491 self::$scaleinfo = false;
2493 return self::$scaleinfo;
2496 * Get information on outcomes
2497 * @param int $courseid
2498 * @return grade_plugin_info
2500 public static function get_info_outcomes($courseid) {
2503 if (self::$outcomeinfo !== null) {
2504 return self::$outcomeinfo;
2506 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2507 $canmanage = has_capability('moodle/grade:manage', $context);
2508 $canupdate = has_capability('moodle/course:update', $context);
2509 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2510 $outcomes = array();
2512 if ($courseid!=$SITE->id) {
2513 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2514 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2516 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2517 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2518 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2519 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2521 if ($courseid!=$SITE->id) {
2522 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2523 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2526 self::$outcomeinfo = $outcomes;
2528 self::$outcomeinfo = false;
2530 return self::$outcomeinfo;
2533 * Get information on editing structures
2534 * @param int $courseid
2537 public static function get_info_edit_structure($courseid) {
2538 if (self::$edittree !== null) {
2539 return self::$edittree;
2541 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2542 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2543 self::$edittree = array(
2544 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2545 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2548 self::$edittree = false;
2550 return self::$edittree;
2553 * Get information on letters
2554 * @param int $courseid
2557 public static function get_info_letters($courseid) {
2558 if (self::$letterinfo !== null) {
2559 return self::$letterinfo;
2561 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2562 $canmanage = has_capability('moodle/grade:manage', $context);
2563 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2564 if ($canmanage || $canmanageletters) {
2565 self::$letterinfo = array(
2566 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2567 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2570 self::$letterinfo = false;
2572 return self::$letterinfo;
2575 * Get information import plugins
2576 * @param int $courseid
2579 public static function get_plugins_import($courseid) {
2582 if (self::$importplugins !== null) {
2583 return self::$importplugins;
2585 $importplugins = array();
2586 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2588 if (has_capability('moodle/grade:import', $context)) {
2589 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2590 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2593 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2594 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2595 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2599 if ($CFG->gradepublishing) {
2600 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2601 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2605 if (count($importplugins) > 0) {
2606 asort($importplugins);
2607 self::$importplugins = $importplugins;
2609 self::$importplugins = false;
2611 return self::$importplugins;
2614 * Get information export plugins
2615 * @param int $courseid
2618 public static function get_plugins_export($courseid) {
2621 if (self::$exportplugins !== null) {
2622 return self::$exportplugins;
2624 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2625 $exportplugins = array();
2626 if (has_capability('moodle/grade:export', $context)) {
2627 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2628 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2631 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2632 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2633 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2636 if ($CFG->gradepublishing) {
2637 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2638 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2641 if (count($exportplugins) > 0) {
2642 asort($exportplugins);
2643 self::$exportplugins = $exportplugins;
2645 self::$exportplugins = false;
2647 return self::$exportplugins;