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 {
47 * Should users whose enrolment has been suspended be ignored?
49 protected $onlyactive = false;
54 * @param object $course A course object
55 * @param array $grade_items array of grade items, if not specified only user info returned
56 * @param int $groupid iterate only group users if present
57 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
58 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
59 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
60 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
62 public function graded_users_iterator($course, $grade_items=null, $groupid=0,
63 $sortfield1='lastname', $sortorder1='ASC',
64 $sortfield2='firstname', $sortorder2='ASC') {
65 $this->course = $course;
66 $this->grade_items = $grade_items;
67 $this->groupid = $groupid;
68 $this->sortfield1 = $sortfield1;
69 $this->sortorder1 = $sortorder1;
70 $this->sortfield2 = $sortfield2;
71 $this->sortorder2 = $sortorder2;
73 $this->gradestack = array();
77 * Initialise the iterator
78 * @return boolean success
80 public function init() {
85 grade_regrade_final_grades($this->course->id);
86 $course_item = grade_item::fetch_course_item($this->course->id);
87 if ($course_item->needsupdate) {
88 // can not calculate all final grades - sorry
92 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
93 $relatedcontexts = get_related_contexts_string($coursecontext);
95 list($gradebookroles_sql, $params) =
96 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
97 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
99 $params = array_merge($params, $enrolledparams);
101 if ($this->groupid) {
102 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
103 $groupwheresql = "AND gm.groupid = :groupid";
104 // $params contents: gradebookroles
105 $params['groupid'] = $this->groupid;
111 if (empty($this->sortfield1)) {
112 // we must do some sorting even if not specified
113 $ofields = ", u.id AS usrt";
117 $ofields = ", u.$this->sortfield1 AS usrt1";
118 $order = "usrt1 $this->sortorder1";
119 if (!empty($this->sortfield2)) {
120 $ofields .= ", u.$this->sortfield2 AS usrt2";
121 $order .= ", usrt2 $this->sortorder2";
123 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
124 // user order MUST be the same in both queries,
125 // must include the only unique user->id if not already present
126 $ofields .= ", u.id AS usrt";
127 $order .= ", usrt ASC";
131 // $params contents: gradebookroles and groupid (for $groupwheresql)
132 $users_sql = "SELECT u.* $ofields
134 JOIN ($enrolledsql) je ON je.id = u.id
137 SELECT DISTINCT ra.userid
138 FROM {role_assignments} ra
139 WHERE ra.roleid $gradebookroles_sql
140 AND ra.contextid $relatedcontexts
141 ) rainner ON rainner.userid = u.id
145 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
147 if (!empty($this->grade_items)) {
148 $itemids = array_keys($this->grade_items);
149 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
150 $params = array_merge($params, $grades_params);
151 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
153 $grades_sql = "SELECT g.* $ofields
154 FROM {grade_grades} g
155 JOIN {user} u ON g.userid = u.id
156 JOIN ($enrolledsql) je ON je.id = u.id
159 SELECT DISTINCT ra.userid
160 FROM {role_assignments} ra
161 WHERE ra.roleid $gradebookroles_sql
162 AND ra.contextid $relatedcontexts
163 ) rainner ON rainner.userid = u.id
165 AND g.itemid $itemidsql
167 ORDER BY $order, g.itemid ASC";
168 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
170 $this->grades_rs = false;
177 * Returns information about the next user
178 * @return mixed array of user info, all grades and feedback or null when no more users found
180 function next_user() {
181 if (!$this->users_rs) {
182 return false; // no users present
185 if (!$this->users_rs->valid()) {
186 if ($current = $this->_pop()) {
187 // this is not good - user or grades updated between the two reads above :-(
190 return false; // no more users
192 $user = $this->users_rs->current();
193 $this->users_rs->next();
196 // find grades of this user
197 $grade_records = array();
199 if (!$current = $this->_pop()) {
200 break; // no more grades
203 if (empty($current->userid)) {
207 if ($current->userid != $user->id) {
208 // grade of the next user, we have all for this user
209 $this->_push($current);
213 $grade_records[$current->itemid] = $current;
217 $feedbacks = array();
219 if (!empty($this->grade_items)) {
220 foreach ($this->grade_items as $grade_item) {
221 if (array_key_exists($grade_item->id, $grade_records)) {
222 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
223 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
224 unset($grade_records[$grade_item->id]->feedback);
225 unset($grade_records[$grade_item->id]->feedbackformat);
226 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
228 $feedbacks[$grade_item->id]->feedback = '';
229 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
230 $grades[$grade_item->id] =
231 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
236 $result = new stdClass();
237 $result->user = $user;
238 $result->grades = $grades;
239 $result->feedbacks = $feedbacks;
244 * Close the iterator, do not forget to call this function.
248 if ($this->users_rs) {
249 $this->users_rs->close();
250 $this->users_rs = null;
252 if ($this->grades_rs) {
253 $this->grades_rs->close();
254 $this->grades_rs = null;
256 $this->gradestack = array();
260 * Should all enrolled users be exported or just those with an active enrolment?
262 * @param bool $onlyactive True to limit the export to users with an active enrolment
264 public function require_active_enrolment($onlyactive = true) {
265 if (!empty($this->users_rs)) {
266 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
268 $this->onlyactive = $onlyactive;
275 * @param grade_grade $grade Grade object
279 function _push($grade) {
280 array_push($this->gradestack, $grade);
287 * @return object current grade object
291 if (empty($this->gradestack)) {
292 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
293 return null; // no grades present
296 $current = $this->grades_rs->current();
298 $this->grades_rs->next();
302 return array_pop($this->gradestack);
308 * Print a selection popup form of the graded users in a course.
310 * @deprecated since 2.0
312 * @param int $course id of the course
313 * @param string $actionpage The page receiving the data from the popoup form
314 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
315 * @param int $groupid id of requested group, 0 means all
316 * @param int $includeall bool include all option
317 * @param bool $return If true, will return the HTML, otherwise, will print directly
320 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
321 global $CFG, $USER, $OUTPUT;
322 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
325 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
328 if (is_null($userid)) {
332 $menu = array(); // Will be a list of userid => user name
333 $gui = new graded_users_iterator($course, null, $groupid);
335 $label = get_string('selectauser', 'grades');
337 $menu[0] = get_string('allusers', 'grades');
338 $label = get_string('selectalloroneuser', 'grades');
340 while ($userdata = $gui->next_user()) {
341 $user = $userdata->user;
342 $menu[$user->id] = fullname($user);
347 $menu[0] .= " (" . (count($menu) - 1) . ")";
349 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
350 $select->label = $label;
351 $select->formid = 'choosegradeuser';
356 * Print grading plugin selection popup form.
358 * @param array $plugin_info An array of plugins containing information for the selector
359 * @param boolean $return return as string
361 * @return nothing or string if $return true
363 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
364 global $CFG, $OUTPUT, $PAGE;
370 foreach ($plugin_info as $plugin_type => $plugins) {
371 if ($plugin_type == 'strings') {
375 $first_plugin = reset($plugins);
377 $sectionname = $plugin_info['strings'][$plugin_type];
380 foreach ($plugins as $plugin) {
381 $link = $plugin->link->out(false);
382 $section[$link] = $plugin->string;
384 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
390 $menu[] = array($sectionname=>$section);
394 // finally print/return the popup form
396 $select = new url_select($menu, $active, null, 'choosepluginreport');
399 return $OUTPUT->render($select);
401 echo $OUTPUT->render($select);
404 // only one option - no plugin selector needed
410 * Print grading plugin selection tab-based navigation.
412 * @param string $active_type type of plugin on current page - import, export, report or edit
413 * @param string $active_plugin active plugin type - grader, user, cvs, ...
414 * @param array $plugin_info Array of plugins
415 * @param boolean $return return as string
417 * @return nothing or string if $return true
419 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
420 global $CFG, $COURSE;
422 if (!isset($currenttab)) { //TODO: this is weird
428 $bottom_row = array();
429 $inactive = array($active_plugin);
430 $activated = array();
435 foreach ($plugin_info as $plugin_type => $plugins) {
436 if ($plugin_type == 'strings') {
440 // If $plugins is actually the definition of a child-less parent link:
441 if (!empty($plugins->id)) {
442 $string = $plugins->string;
443 if (!empty($plugin_info[$active_type]->parent)) {
444 $string = $plugin_info[$active_type]->parent->string;
447 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
451 $first_plugin = reset($plugins);
452 $url = $first_plugin->link;
454 if ($plugin_type == 'report') {
455 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
458 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
460 if ($active_type == $plugin_type) {
461 foreach ($plugins as $plugin) {
462 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
463 if ($plugin->id == $active_plugin) {
464 $inactive = array($plugin->id);
471 $tabs[] = $bottom_row;
474 return print_tabs($tabs, $active_type, $inactive, $activated, true);
476 print_tabs($tabs, $active_type, $inactive, $activated);
481 * grade_get_plugin_info
483 * @param int $courseid The course id
484 * @param string $active_type type of plugin on current page - import, export, report or edit
485 * @param string $active_plugin active plugin type - grader, user, cvs, ...
489 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
492 $context = get_context_instance(CONTEXT_COURSE, $courseid);
494 $plugin_info = array();
497 $url_prefix = $CFG->wwwroot . '/grade/';
500 $plugin_info['strings'] = grade_helper::get_plugin_strings();
502 if ($reports = grade_helper::get_plugins_reports($courseid)) {
503 $plugin_info['report'] = $reports;
506 //showing grade categories and items make no sense if we're not within a course
507 if ($courseid!=$SITE->id) {
508 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
509 $plugin_info['edittree'] = $edittree;
513 if ($scale = grade_helper::get_info_scales($courseid)) {
514 $plugin_info['scale'] = array('view'=>$scale);
517 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
518 $plugin_info['outcome'] = $outcomes;
521 if ($letters = grade_helper::get_info_letters($courseid)) {
522 $plugin_info['letter'] = $letters;
525 if ($imports = grade_helper::get_plugins_import($courseid)) {
526 $plugin_info['import'] = $imports;
529 if ($exports = grade_helper::get_plugins_export($courseid)) {
530 $plugin_info['export'] = $exports;
533 foreach ($plugin_info as $plugin_type => $plugins) {
534 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
535 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
538 foreach ($plugins as $plugin) {
539 if (is_a($plugin, 'grade_plugin_info')) {
540 if ($active_plugin == $plugin->id) {
541 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
547 //hide course settings if we're not in a course
548 if ($courseid!=$SITE->id) {
549 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
550 $plugin_info['settings'] = array('course'=>$setting);
554 // Put preferences last
555 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
556 $plugin_info['preferences'] = $preferences;
559 foreach ($plugin_info as $plugin_type => $plugins) {
560 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
561 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
564 foreach ($plugins as $plugin) {
565 if (is_a($plugin, 'grade_plugin_info')) {
566 if ($active_plugin == $plugin->id) {
567 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
577 * A simple class containing info about grade plugins.
578 * Can be subclassed for special rules
580 * @package core_grades
581 * @copyright 2009 Nicolas Connault
582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
584 class grade_plugin_info {
586 * A unique id for this plugin
592 * A URL to access this plugin
598 * The name of this plugin
604 * Another grade_plugin_info object, parent of the current one
613 * @param int $id A unique id for this plugin
614 * @param string $link A URL to access this plugin
615 * @param string $string The name of this plugin
616 * @param object $parent Another grade_plugin_info object, parent of the current one
620 public function __construct($id, $link, $string, $parent=null) {
623 $this->string = $string;
624 $this->parent = $parent;
629 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
630 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
631 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
632 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
633 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
635 * @param int $courseid Course id
636 * @param string $active_type The type of the current page (report, settings,
637 * import, export, scales, outcomes, letters)
638 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
639 * @param string $heading The heading of the page. Tries to guess if none is given
640 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
641 * @param string $bodytags Additional attributes that will be added to the <body> tag
642 * @param string $buttons Additional buttons to display on the page
643 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
645 * @return string HTML code or nothing if $return == false
647 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
648 $heading = false, $return=false,
649 $buttons=false, $shownavigation=true) {
650 global $CFG, $OUTPUT, $PAGE;
652 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
654 // Determine the string of the active plugin
655 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
656 $stractive_type = $plugin_info['strings'][$active_type];
658 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
659 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
661 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
664 if ($active_type == 'report') {
665 $PAGE->set_pagelayout('report');
667 $PAGE->set_pagelayout('admin');
669 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
670 $PAGE->set_heading($title);
671 if ($buttons instanceof single_button) {
672 $buttons = $OUTPUT->render($buttons);
674 $PAGE->set_button($buttons);
675 grade_extend_settings($plugin_info, $courseid);
677 $returnval = $OUTPUT->header();
682 // Guess heading if not given explicitly
684 $heading = $stractive_plugin;
687 if ($shownavigation) {
688 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
689 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
693 $returnval .= $OUTPUT->heading($heading);
695 echo $OUTPUT->heading($heading);
698 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
699 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
709 * Utility class used for return tracking when using edit and other forms in grade plugins
711 * @package core_grades
712 * @copyright 2009 Nicolas Connault
713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
715 class grade_plugin_return {
725 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
727 public function grade_plugin_return($params = null) {
728 if (empty($params)) {
729 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
730 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
731 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
732 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
733 $this->page = optional_param('gpr_page', null, PARAM_INT);
736 foreach ($params as $key=>$value) {
737 if (property_exists($this, $key)) {
738 $this->$key = $value;
745 * Returns return parameters as options array suitable for buttons.
746 * @return array options
748 public function get_options() {
749 if (empty($this->type)) {
755 if (!empty($this->plugin)) {
756 $params['plugin'] = $this->plugin;
759 if (!empty($this->courseid)) {
760 $params['id'] = $this->courseid;
763 if (!empty($this->userid)) {
764 $params['userid'] = $this->userid;
767 if (!empty($this->page)) {
768 $params['page'] = $this->page;
777 * @param string $default default url when params not set
778 * @param array $extras Extra URL parameters
782 public function get_return_url($default, $extras=null) {
785 if (empty($this->type) or empty($this->plugin)) {
789 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
792 if (!empty($this->courseid)) {
793 $url .= $glue.'id='.$this->courseid;
797 if (!empty($this->userid)) {
798 $url .= $glue.'userid='.$this->userid;
802 if (!empty($this->page)) {
803 $url .= $glue.'page='.$this->page;
807 if (!empty($extras)) {
808 foreach ($extras as $key=>$value) {
809 $url .= $glue.$key.'='.$value;
818 * Returns string with hidden return tracking form elements.
821 public function get_form_fields() {
822 if (empty($this->type)) {
826 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
828 if (!empty($this->plugin)) {
829 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
832 if (!empty($this->courseid)) {
833 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
836 if (!empty($this->userid)) {
837 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
840 if (!empty($this->page)) {
841 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
846 * Add hidden elements into mform
848 * @param object &$mform moodle form object
852 public function add_mform_elements(&$mform) {
853 if (empty($this->type)) {
857 $mform->addElement('hidden', 'gpr_type', $this->type);
858 $mform->setType('gpr_type', PARAM_SAFEDIR);
860 if (!empty($this->plugin)) {
861 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
862 $mform->setType('gpr_plugin', PARAM_PLUGIN);
865 if (!empty($this->courseid)) {
866 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
867 $mform->setType('gpr_courseid', PARAM_INT);
870 if (!empty($this->userid)) {
871 $mform->addElement('hidden', 'gpr_userid', $this->userid);
872 $mform->setType('gpr_userid', PARAM_INT);
875 if (!empty($this->page)) {
876 $mform->addElement('hidden', 'gpr_page', $this->page);
877 $mform->setType('gpr_page', PARAM_INT);
882 * Add return tracking params into url
884 * @param moodle_url $url A URL
886 * @return string $url with return tracking params
888 public function add_url_params(moodle_url $url) {
889 if (empty($this->type)) {
893 $url->param('gpr_type', $this->type);
895 if (!empty($this->plugin)) {
896 $url->param('gpr_plugin', $this->plugin);
899 if (!empty($this->courseid)) {
900 $url->param('gpr_courseid' ,$this->courseid);
903 if (!empty($this->userid)) {
904 $url->param('gpr_userid', $this->userid);
907 if (!empty($this->page)) {
908 $url->param('gpr_page', $this->page);
916 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
918 * @param string $path The path of the calling script (using __FILE__?)
919 * @param string $pagename The language string to use as the last part of the navigation (non-link)
920 * @param mixed $id Either a plain integer (assuming the key is 'id') or
921 * an array of keys and values (e.g courseid => $courseid, itemid...)
925 function grade_build_nav($path, $pagename=null, $id=null) {
926 global $CFG, $COURSE, $PAGE;
928 $strgrades = get_string('grades', 'grades');
930 // Parse the path and build navlinks from its elements
931 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
932 $path = substr($path, $dirroot_length);
933 $path = str_replace('\\', '/', $path);
935 $path_elements = explode('/', $path);
937 $path_elements_count = count($path_elements);
939 // First link is always 'grade'
940 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
943 $numberofelements = 3;
945 // Prepare URL params string
946 $linkparams = array();
949 foreach ($id as $idkey => $idvalue) {
950 $linkparams[$idkey] = $idvalue;
953 $linkparams['id'] = $id;
959 // Remove file extensions from filenames
960 foreach ($path_elements as $key => $filename) {
961 $path_elements[$key] = str_replace('.php', '', $filename);
964 // Second level links
965 switch ($path_elements[1]) {
966 case 'edit': // No link
967 if ($path_elements[3] != 'index.php') {
968 $numberofelements = 4;
971 case 'import': // No link
973 case 'export': // No link
976 // $id is required for this link. Do not print it if $id isn't given
978 $link = new moodle_url('/grade/report/index.php', $linkparams);
981 if ($path_elements[2] == 'grader') {
982 $numberofelements = 4;
987 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
988 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
989 " as the second path element after 'grade'.");
992 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
995 if (empty($pagename)) {
996 $pagename = get_string($path_elements[2], 'grades');
999 switch ($numberofelements) {
1001 $PAGE->navbar->add($pagename, $link);
1004 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1005 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1007 $PAGE->navbar->add($pagename);
1015 * General structure representing grade items in course
1017 * @package core_grades
1018 * @copyright 2009 Nicolas Connault
1019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1021 class grade_structure {
1027 * Reference to modinfo for current course (for performance, to save
1028 * retrieving it from courseid every time). Not actually set except for
1029 * the grade_tree type.
1030 * @var course_modinfo
1035 * 1D array of grade items only
1040 * Returns icon of element
1042 * @param array &$element An array representing an element in the grade_tree
1043 * @param bool $spacerifnone return spacer if no icon found
1045 * @return string icon or spacer
1047 public function get_element_icon(&$element, $spacerifnone=false) {
1048 global $CFG, $OUTPUT;
1050 switch ($element['type']) {
1053 case 'categoryitem':
1054 $is_course = $element['object']->is_course_item();
1055 $is_category = $element['object']->is_category_item();
1056 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1057 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1058 $is_outcome = !empty($element['object']->outcomeid);
1060 if ($element['object']->is_calculated()) {
1061 $strcalc = get_string('calculatedgrade', 'grades');
1062 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1063 s($strcalc).'" alt="'.s($strcalc).'"/>';
1065 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1066 if ($category = $element['object']->get_item_category()) {
1067 switch ($category->aggregation) {
1068 case GRADE_AGGREGATE_MEAN:
1069 case GRADE_AGGREGATE_MEDIAN:
1070 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1071 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1072 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1073 $stragg = get_string('aggregation', 'grades');
1074 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1075 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1076 case GRADE_AGGREGATE_SUM:
1077 $stragg = get_string('aggregation', 'grades');
1078 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1079 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1083 } else if ($element['object']->itemtype == 'mod') {
1084 //prevent outcomes being displaying the same icon as the activity they are attached to
1086 $stroutcome = s(get_string('outcome', 'grades'));
1087 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1088 'class="icon itemicon" title="'.$stroutcome.
1089 '" alt="'.$stroutcome.'"/>';
1091 $strmodname = get_string('modulename', $element['object']->itemmodule);
1092 return '<img src="'.$OUTPUT->pix_url('icon',
1093 $element['object']->itemmodule) . '" ' .
1094 'class="icon itemicon" title="' .s($strmodname).
1095 '" alt="' .s($strmodname).'"/>';
1097 } else if ($element['object']->itemtype == 'manual') {
1098 if ($element['object']->is_outcome_item()) {
1099 $stroutcome = get_string('outcome', 'grades');
1100 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1101 'class="icon itemicon" title="'.s($stroutcome).
1102 '" alt="'.s($stroutcome).'"/>';
1104 $strmanual = get_string('manualitem', 'grades');
1105 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1106 'class="icon itemicon" title="'.s($strmanual).
1107 '" alt="'.s($strmanual).'"/>';
1113 $strcat = get_string('category', 'grades');
1114 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1115 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1118 if ($spacerifnone) {
1119 return $OUTPUT->spacer().' ';
1126 * Returns name of element optionally with icon and link
1128 * @param array &$element An array representing an element in the grade_tree
1129 * @param bool $withlink Whether or not this header has a link
1130 * @param bool $icon Whether or not to display an icon with this header
1131 * @param bool $spacerifnone return spacer if no icon found
1133 * @return string header
1135 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1139 $header .= $this->get_element_icon($element, $spacerifnone);
1142 $header .= $element['object']->get_name();
1144 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1145 $element['type'] != 'courseitem') {
1150 $url = $this->get_activity_link($element);
1152 $a = new stdClass();
1153 $a->name = get_string('modulename', $element['object']->itemmodule);
1154 $title = get_string('linktoactivity', 'grades', $a);
1156 $header = html_writer::link($url, $header, array('title' => $title));
1163 private function get_activity_link($element) {
1165 /** @var array static cache of the grade.php file existence flags */
1166 static $hasgradephp = array();
1168 $itemtype = $element['object']->itemtype;
1169 $itemmodule = $element['object']->itemmodule;
1170 $iteminstance = $element['object']->iteminstance;
1171 $itemnumber = $element['object']->itemnumber;
1173 // Links only for module items that have valid instance, module and are
1174 // called from grade_tree with valid modinfo
1175 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1179 // Get $cm efficiently and with visibility information using modinfo
1180 $instances = $this->modinfo->get_instances();
1181 if (empty($instances[$itemmodule][$iteminstance])) {
1184 $cm = $instances[$itemmodule][$iteminstance];
1186 // Do not add link if activity is not visible to the current user
1187 if (!$cm->uservisible) {
1191 if (!array_key_exists($itemmodule, $hasgradephp)) {
1192 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1193 $hasgradephp[$itemmodule] = true;
1195 $hasgradephp[$itemmodule] = false;
1199 // If module has grade.php, link to that, otherwise view.php
1200 if ($hasgradephp[$itemmodule]) {
1201 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1202 if (isset($element['userid'])) {
1203 $args['userid'] = $element['userid'];
1205 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1207 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1212 * Returns URL of a page that is supposed to contain detailed grade analysis
1214 * At the moment, only activity modules are supported. The method generates link
1215 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1216 * gradeid and userid. If the grade.php does not exist, null is returned.
1218 * @return moodle_url|null URL or null if unable to construct it
1220 public function get_grade_analysis_url(grade_grade $grade) {
1222 /** @var array static cache of the grade.php file existence flags */
1223 static $hasgradephp = array();
1225 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1226 throw new coding_exception('Passed grade without the associated grade item');
1228 $item = $grade->grade_item;
1230 if (!$item->is_external_item()) {
1231 // at the moment, only activity modules are supported
1234 if ($item->itemtype !== 'mod') {
1235 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1237 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1241 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1242 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1243 $hasgradephp[$item->itemmodule] = true;
1245 $hasgradephp[$item->itemmodule] = false;
1249 if (!$hasgradephp[$item->itemmodule]) {
1253 $instances = $this->modinfo->get_instances();
1254 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1257 $cm = $instances[$item->itemmodule][$item->iteminstance];
1258 if (!$cm->uservisible) {
1262 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1264 'itemid' => $item->id,
1265 'itemnumber' => $item->itemnumber,
1266 'gradeid' => $grade->id,
1267 'userid' => $grade->userid,
1274 * Returns an action icon leading to the grade analysis page
1276 * @param grade_grade $grade
1279 public function get_grade_analysis_icon(grade_grade $grade) {
1282 $url = $this->get_grade_analysis_url($grade);
1283 if (is_null($url)) {
1287 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1288 get_string('gradeanalysis', 'core_grades')));
1292 * Returns the grade eid - the grade may not exist yet.
1294 * @param grade_grade $grade_grade A grade_grade object
1296 * @return string eid
1298 public function get_grade_eid($grade_grade) {
1299 if (empty($grade_grade->id)) {
1300 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1302 return 'g'.$grade_grade->id;
1307 * Returns the grade_item eid
1308 * @param grade_item $grade_item A grade_item object
1309 * @return string eid
1311 public function get_item_eid($grade_item) {
1312 return 'i'.$grade_item->id;
1316 * Given a grade_tree element, returns an array of parameters
1317 * used to build an icon for that element.
1319 * @param array $element An array representing an element in the grade_tree
1323 public function get_params_for_iconstr($element) {
1324 $strparams = new stdClass();
1325 $strparams->category = '';
1326 $strparams->itemname = '';
1327 $strparams->itemmodule = '';
1329 if (!method_exists($element['object'], 'get_name')) {
1333 $strparams->itemname = html_to_text($element['object']->get_name());
1335 // If element name is categorytotal, get the name of the parent category
1336 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1337 $parent = $element['object']->get_parent_category();
1338 $strparams->category = $parent->get_name() . ' ';
1340 $strparams->category = '';
1343 $strparams->itemmodule = null;
1344 if (isset($element['object']->itemmodule)) {
1345 $strparams->itemmodule = $element['object']->itemmodule;
1351 * Return edit icon for give element
1353 * @param array $element An array representing an element in the grade_tree
1354 * @param object $gpr A grade_plugin_return object
1358 public function get_edit_icon($element, $gpr) {
1359 global $CFG, $OUTPUT;
1361 if (!has_capability('moodle/grade:manage', $this->context)) {
1362 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1363 // oki - let them override grade
1369 static $strfeedback = null;
1370 static $streditgrade = null;
1371 if (is_null($streditgrade)) {
1372 $streditgrade = get_string('editgrade', 'grades');
1373 $strfeedback = get_string('feedback');
1376 $strparams = $this->get_params_for_iconstr($element);
1378 $object = $element['object'];
1380 switch ($element['type']) {
1382 case 'categoryitem':
1384 $stredit = get_string('editverbose', 'grades', $strparams);
1385 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1386 $url = new moodle_url('/grade/edit/tree/item.php',
1387 array('courseid' => $this->courseid, 'id' => $object->id));
1389 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1390 array('courseid' => $this->courseid, 'id' => $object->id));
1395 $stredit = get_string('editverbose', 'grades', $strparams);
1396 $url = new moodle_url('/grade/edit/tree/category.php',
1397 array('courseid' => $this->courseid, 'id' => $object->id));
1401 $stredit = $streditgrade;
1402 if (empty($object->id)) {
1403 $url = new moodle_url('/grade/edit/tree/grade.php',
1404 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1406 $url = new moodle_url('/grade/edit/tree/grade.php',
1407 array('courseid' => $this->courseid, 'id' => $object->id));
1409 if (!empty($object->feedback)) {
1410 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1419 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1427 * Return hiding icon for give element
1429 * @param array $element An array representing an element in the grade_tree
1430 * @param object $gpr A grade_plugin_return object
1434 public function get_hiding_icon($element, $gpr) {
1435 global $CFG, $OUTPUT;
1437 if (!has_capability('moodle/grade:manage', $this->context) and
1438 !has_capability('moodle/grade:hide', $this->context)) {
1442 $strparams = $this->get_params_for_iconstr($element);
1443 $strshow = get_string('showverbose', 'grades', $strparams);
1444 $strhide = get_string('hideverbose', 'grades', $strparams);
1446 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1447 $url = $gpr->add_url_params($url);
1449 if ($element['object']->is_hidden()) {
1451 $tooltip = $strshow;
1453 // Change the icon and add a tooltip showing the date
1454 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1455 $type = 'hiddenuntil';
1456 $tooltip = get_string('hiddenuntildate', 'grades',
1457 userdate($element['object']->get_hidden()));
1460 $url->param('action', 'show');
1462 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1465 $url->param('action', 'hide');
1466 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1473 * Return locking icon for given element
1475 * @param array $element An array representing an element in the grade_tree
1476 * @param object $gpr A grade_plugin_return object
1480 public function get_locking_icon($element, $gpr) {
1481 global $CFG, $OUTPUT;
1483 $strparams = $this->get_params_for_iconstr($element);
1484 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1485 $strlock = get_string('lockverbose', 'grades', $strparams);
1487 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1488 $url = $gpr->add_url_params($url);
1490 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1491 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1492 $strparamobj = new stdClass();
1493 $strparamobj->itemname = $element['object']->grade_item->itemname;
1494 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1496 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1498 } else if ($element['object']->is_locked()) {
1500 $tooltip = $strunlock;
1502 // Change the icon and add a tooltip showing the date
1503 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1505 $tooltip = get_string('locktimedate', 'grades',
1506 userdate($element['object']->get_locktime()));
1509 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1512 $url->param('action', 'unlock');
1513 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1517 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1520 $url->param('action', 'lock');
1521 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1529 * Return calculation icon for given element
1531 * @param array $element An array representing an element in the grade_tree
1532 * @param object $gpr A grade_plugin_return object
1536 public function get_calculation_icon($element, $gpr) {
1537 global $CFG, $OUTPUT;
1538 if (!has_capability('moodle/grade:manage', $this->context)) {
1542 $type = $element['type'];
1543 $object = $element['object'];
1545 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1546 $strparams = $this->get_params_for_iconstr($element);
1547 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1549 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1550 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1552 // show calculation icon only when calculation possible
1553 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1554 if ($object->is_calculated()) {
1557 $icon = 't/calc_off';
1560 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1561 $url = $gpr->add_url_params($url);
1562 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1571 * Flat structure similar to grade tree.
1573 * @uses grade_structure
1574 * @package core_grades
1575 * @copyright 2009 Nicolas Connault
1576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1578 class grade_seq extends grade_structure {
1581 * 1D array of elements
1586 * Constructor, retrieves and stores array of all grade_category and grade_item
1587 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1589 * @param int $courseid The course id
1590 * @param bool $category_grade_last category grade item is the last child
1591 * @param bool $nooutcomes Whether or not outcomes should be included
1593 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1596 $this->courseid = $courseid;
1597 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1599 // get course grade tree
1600 $top_element = grade_category::fetch_course_tree($courseid, true);
1602 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1604 foreach ($this->elements as $key=>$unused) {
1605 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1610 * Static recursive helper - makes the grade_item for category the last children
1612 * @param array &$element The seed of the recursion
1613 * @param bool $category_grade_last category grade item is the last child
1614 * @param bool $nooutcomes Whether or not outcomes should be included
1618 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1619 if (empty($element['children'])) {
1622 $children = array();
1624 foreach ($element['children'] as $sortorder=>$unused) {
1625 if ($nooutcomes and $element['type'] != 'category' and
1626 $element['children'][$sortorder]['object']->is_outcome_item()) {
1629 $children[] = $element['children'][$sortorder];
1631 unset($element['children']);
1633 if ($category_grade_last and count($children) > 1) {
1634 $cat_item = array_shift($children);
1635 array_push($children, $cat_item);
1639 foreach ($children as $child) {
1640 if ($child['type'] == 'category') {
1641 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1643 $child['eid'] = 'i'.$child['object']->id;
1644 $result[$child['object']->id] = $child;
1652 * Parses the array in search of a given eid and returns a element object with
1653 * information about the element it has found.
1655 * @param int $eid Gradetree Element ID
1657 * @return object element
1659 public function locate_element($eid) {
1660 // it is a grade - construct a new object
1661 if (strpos($eid, 'n') === 0) {
1662 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1666 $itemid = $matches[1];
1667 $userid = $matches[2];
1669 //extra security check - the grade item must be in this tree
1670 if (!$item_el = $this->locate_element('i'.$itemid)) {
1674 // $gradea->id may be null - means does not exist yet
1675 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1677 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1678 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1680 } else if (strpos($eid, 'g') === 0) {
1681 $id = (int) substr($eid, 1);
1682 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1685 //extra security check - the grade item must be in this tree
1686 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1689 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1690 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1693 // it is a category or item
1694 foreach ($this->elements as $element) {
1695 if ($element['eid'] == $eid) {
1705 * This class represents a complete tree of categories, grade_items and final grades,
1706 * organises as an array primarily, but which can also be converted to other formats.
1707 * It has simple method calls with complex implementations, allowing for easy insertion,
1708 * deletion and moving of items and categories within the tree.
1710 * @uses grade_structure
1711 * @package core_grades
1712 * @copyright 2009 Nicolas Connault
1713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1715 class grade_tree extends grade_structure {
1718 * The basic representation of the tree as a hierarchical, 3-tiered array.
1719 * @var object $top_element
1721 public $top_element;
1724 * 2D array of grade items and categories
1725 * @var array $levels
1736 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1737 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1739 * @param int $courseid The Course ID
1740 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1741 * @param bool $category_grade_last category grade item is the last child
1742 * @param array $collapsed array of collapsed categories
1743 * @param bool $nooutcomes Whether or not outcomes should be included
1745 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1746 $collapsed=null, $nooutcomes=false) {
1747 global $USER, $CFG, $COURSE, $DB;
1749 $this->courseid = $courseid;
1750 $this->levels = array();
1751 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1753 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1756 $course = $DB->get_record('course', array('id' => $this->courseid));
1758 $this->modinfo = get_fast_modinfo($course);
1760 // get course grade tree
1761 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1763 // collapse the categories if requested
1764 if (!empty($collapsed)) {
1765 grade_tree::category_collapse($this->top_element, $collapsed);
1768 // no otucomes if requested
1769 if (!empty($nooutcomes)) {
1770 grade_tree::no_outcomes($this->top_element);
1773 // move category item to last position in category
1774 if ($category_grade_last) {
1775 grade_tree::category_grade_last($this->top_element);
1779 // inject fake categories == fillers
1780 grade_tree::inject_fillers($this->top_element, 0);
1781 // add colspans to categories and fillers
1782 grade_tree::inject_colspans($this->top_element);
1785 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1790 * Static recursive helper - removes items from collapsed categories
1792 * @param array &$element The seed of the recursion
1793 * @param array $collapsed array of collapsed categories
1797 public function category_collapse(&$element, $collapsed) {
1798 if ($element['type'] != 'category') {
1801 if (empty($element['children']) or count($element['children']) < 2) {
1805 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1806 $category_item = reset($element['children']); //keep only category item
1807 $element['children'] = array(key($element['children'])=>$category_item);
1810 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1811 reset($element['children']);
1812 $first_key = key($element['children']);
1813 unset($element['children'][$first_key]);
1815 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1816 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1822 * Static recursive helper - removes all outcomes
1824 * @param array &$element The seed of the recursion
1828 public function no_outcomes(&$element) {
1829 if ($element['type'] != 'category') {
1832 foreach ($element['children'] as $sortorder=>$child) {
1833 if ($element['children'][$sortorder]['type'] == 'item'
1834 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1835 unset($element['children'][$sortorder]);
1837 } else if ($element['children'][$sortorder]['type'] == 'category') {
1838 grade_tree::no_outcomes($element['children'][$sortorder]);
1844 * Static recursive helper - makes the grade_item for category the last children
1846 * @param array &$element The seed of the recursion
1850 public function category_grade_last(&$element) {
1851 if (empty($element['children'])) {
1854 if (count($element['children']) < 2) {
1857 $first_item = reset($element['children']);
1858 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1859 // the category item might have been already removed
1860 $order = key($element['children']);
1861 unset($element['children'][$order]);
1862 $element['children'][$order] =& $first_item;
1864 foreach ($element['children'] as $sortorder => $child) {
1865 grade_tree::category_grade_last($element['children'][$sortorder]);
1870 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1872 * @param array &$levels The levels of the grade tree through which to recurse
1873 * @param array &$element The seed of the recursion
1874 * @param int $depth How deep are we?
1877 public function fill_levels(&$levels, &$element, $depth) {
1878 if (!array_key_exists($depth, $levels)) {
1879 $levels[$depth] = array();
1882 // prepare unique identifier
1883 if ($element['type'] == 'category') {
1884 $element['eid'] = 'c'.$element['object']->id;
1885 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1886 $element['eid'] = 'i'.$element['object']->id;
1887 $this->items[$element['object']->id] =& $element['object'];
1890 $levels[$depth][] =& $element;
1892 if (empty($element['children'])) {
1896 foreach ($element['children'] as $sortorder=>$child) {
1897 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1898 $element['children'][$sortorder]['prev'] = $prev;
1899 $element['children'][$sortorder]['next'] = 0;
1901 $element['children'][$prev]['next'] = $sortorder;
1908 * Static recursive helper - makes full tree (all leafes are at the same level)
1910 * @param array &$element The seed of the recursion
1911 * @param int $depth How deep are we?
1915 public function inject_fillers(&$element, $depth) {
1918 if (empty($element['children'])) {
1921 $chdepths = array();
1922 $chids = array_keys($element['children']);
1923 $last_child = end($chids);
1924 $first_child = reset($chids);
1926 foreach ($chids as $chid) {
1927 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1931 $maxdepth = reset($chdepths);
1932 foreach ($chdepths as $chid=>$chd) {
1933 if ($chd == $maxdepth) {
1936 for ($i=0; $i < $maxdepth-$chd; $i++) {
1937 if ($chid == $first_child) {
1938 $type = 'fillerfirst';
1939 } else if ($chid == $last_child) {
1940 $type = 'fillerlast';
1944 $oldchild =& $element['children'][$chid];
1945 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1946 'eid'=>'', 'depth'=>$element['object']->depth,
1947 'children'=>array($oldchild));
1955 * Static recursive helper - add colspan information into categories
1957 * @param array &$element The seed of the recursion
1961 public function inject_colspans(&$element) {
1962 if (empty($element['children'])) {
1966 foreach ($element['children'] as $key=>$child) {
1967 $count += grade_tree::inject_colspans($element['children'][$key]);
1969 $element['colspan'] = $count;
1974 * Parses the array in search of a given eid and returns a element object with
1975 * information about the element it has found.
1976 * @param int $eid Gradetree Element ID
1977 * @return object element
1979 public function locate_element($eid) {
1980 // it is a grade - construct a new object
1981 if (strpos($eid, 'n') === 0) {
1982 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1986 $itemid = $matches[1];
1987 $userid = $matches[2];
1989 //extra security check - the grade item must be in this tree
1990 if (!$item_el = $this->locate_element('i'.$itemid)) {
1994 // $gradea->id may be null - means does not exist yet
1995 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1997 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1998 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2000 } else if (strpos($eid, 'g') === 0) {
2001 $id = (int) substr($eid, 1);
2002 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2005 //extra security check - the grade item must be in this tree
2006 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2009 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2010 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2013 // it is a category or item
2014 foreach ($this->levels as $row) {
2015 foreach ($row as $element) {
2016 if ($element['type'] == 'filler') {
2019 if ($element['eid'] == $eid) {
2029 * Returns a well-formed XML representation of the grade-tree using recursion.
2031 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2032 * @param string $tabs The control character to use for tabs
2034 * @return string $xml
2036 public function exporttoxml($root=null, $tabs="\t") {
2039 if (is_null($root)) {
2040 $root = $this->top_element;
2041 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2042 $xml .= "<gradetree>\n";
2046 $type = 'undefined';
2047 if (strpos($root['object']->table, 'grade_categories') !== false) {
2049 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2051 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2055 $xml .= "$tabs<element type=\"$type\">\n";
2056 foreach ($root['object'] as $var => $value) {
2057 if (!is_object($value) && !is_array($value) && !empty($value)) {
2058 $xml .= "$tabs\t<$var>$value</$var>\n";
2062 if (!empty($root['children'])) {
2063 $xml .= "$tabs\t<children>\n";
2064 foreach ($root['children'] as $sortorder => $child) {
2065 $xml .= $this->exportToXML($child, $tabs."\t\t");
2067 $xml .= "$tabs\t</children>\n";
2070 $xml .= "$tabs</element>\n";
2073 $xml .= "</gradetree>";
2080 * Returns a JSON representation of the grade-tree using recursion.
2082 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2083 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2087 public function exporttojson($root=null, $tabs="\t") {
2090 if (is_null($root)) {
2091 $root = $this->top_element;
2098 if (strpos($root['object']->table, 'grade_categories') !== false) {
2099 $name = $root['object']->fullname;
2101 $name = $root['object']->get_name();
2103 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2104 $name = $root['object']->itemname;
2105 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2106 $name = $root['object']->itemname;
2109 $json .= "$tabs {\n";
2110 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2111 $json .= "$tabs\t \"name\": \"$name\",\n";
2113 foreach ($root['object'] as $var => $value) {
2114 if (!is_object($value) && !is_array($value) && !empty($value)) {
2115 $json .= "$tabs\t \"$var\": \"$value\",\n";
2119 $json = substr($json, 0, strrpos($json, ','));
2121 if (!empty($root['children'])) {
2122 $json .= ",\n$tabs\t\"children\": [\n";
2123 foreach ($root['children'] as $sortorder => $child) {
2124 $json .= $this->exportToJSON($child, $tabs."\t\t");
2126 $json = substr($json, 0, strrpos($json, ','));
2127 $json .= "\n$tabs\t]\n";
2133 $json .= "\n$tabs},\n";
2140 * Returns the array of levels
2144 public function get_levels() {
2145 return $this->levels;
2149 * Returns the array of grade items
2153 public function get_items() {
2154 return $this->items;
2158 * Returns a specific Grade Item
2160 * @param int $itemid The ID of the grade_item object
2162 * @return grade_item
2164 public function get_item($itemid) {
2165 if (array_key_exists($itemid, $this->items)) {
2166 return $this->items[$itemid];
2174 * Local shortcut function for creating an edit/delete button for a grade_* object.
2175 * @param string $type 'edit' or 'delete'
2176 * @param int $courseid The Course ID
2177 * @param grade_* $object The grade_* object
2178 * @return string html
2180 function grade_button($type, $courseid, $object) {
2181 global $CFG, $OUTPUT;
2182 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2183 $objectidstring = $matches[1] . 'id';
2185 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2188 $strdelete = get_string('delete');
2189 $stredit = get_string('edit');
2191 if ($type == 'delete') {
2192 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2193 } else if ($type == 'edit') {
2194 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2197 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2202 * This method adds settings to the settings block for the grade system and its
2205 * @global moodle_page $PAGE
2207 function grade_extend_settings($plugininfo, $courseid) {
2210 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2212 $strings = array_shift($plugininfo);
2214 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2215 foreach ($reports as $report) {
2216 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2220 if ($imports = grade_helper::get_plugins_import($courseid)) {
2221 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2222 foreach ($imports as $import) {
2223 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2227 if ($exports = grade_helper::get_plugins_export($courseid)) {
2228 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2229 foreach ($exports as $export) {
2230 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2234 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2235 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2238 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2239 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2240 foreach ($preferences as $preference) {
2241 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2245 if ($letters = grade_helper::get_info_letters($courseid)) {
2246 $letters = array_shift($letters);
2247 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2250 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2251 $outcomes = array_shift($outcomes);
2252 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2255 if ($scales = grade_helper::get_info_scales($courseid)) {
2256 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2259 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2260 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2261 foreach ($categories as $category) {
2262 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2266 if ($gradenode->contains_active_node()) {
2267 // If the gradenode is active include the settings base node (gradeadministration) in
2268 // the navbar, typcially this is ignored.
2269 $PAGE->navbar->includesettingsbase = true;
2271 // If we can get the course admin node make sure it is closed by default
2272 // as in this case the gradenode will be opened
2273 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2274 $coursenode->make_inactive();
2275 $coursenode->forceopen = false;
2281 * Grade helper class
2283 * This class provides several helpful functions that work irrespective of any
2286 * @copyright 2010 Sam Hemelryk
2287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2289 abstract class grade_helper {
2291 * Cached manage settings info {@see get_info_settings}
2292 * @var grade_plugin_info|false
2294 protected static $managesetting = null;
2296 * Cached grade report plugins {@see get_plugins_reports}
2299 protected static $gradereports = null;
2301 * Cached grade report plugins preferences {@see get_info_scales}
2304 protected static $gradereportpreferences = null;
2306 * Cached scale info {@see get_info_scales}
2307 * @var grade_plugin_info|false
2309 protected static $scaleinfo = null;
2311 * Cached outcome info {@see get_info_outcomes}
2312 * @var grade_plugin_info|false
2314 protected static $outcomeinfo = null;
2316 * Cached info on edit structure {@see get_info_edit_structure}
2319 protected static $edittree = null;
2321 * Cached leftter info {@see get_info_letters}
2322 * @var grade_plugin_info|false
2324 protected static $letterinfo = null;
2326 * Cached grade import plugins {@see get_plugins_import}
2329 protected static $importplugins = null;
2331 * Cached grade export plugins {@see get_plugins_export}
2334 protected static $exportplugins = null;
2336 * Cached grade plugin strings
2339 protected static $pluginstrings = null;
2342 * Gets strings commonly used by the describe plugins
2344 * report => get_string('view'),
2345 * edittree => get_string('edittree', 'grades'),
2346 * scale => get_string('scales'),
2347 * outcome => get_string('outcomes', 'grades'),
2348 * letter => get_string('letters', 'grades'),
2349 * export => get_string('export', 'grades'),
2350 * import => get_string('import'),
2351 * preferences => get_string('mypreferences', 'grades'),
2352 * settings => get_string('settings')
2356 public static function get_plugin_strings() {
2357 if (self::$pluginstrings === null) {
2358 self::$pluginstrings = array(
2359 'report' => get_string('view'),
2360 'edittree' => get_string('edittree', 'grades'),
2361 'scale' => get_string('scales'),
2362 'outcome' => get_string('outcomes', 'grades'),
2363 'letter' => get_string('letters', 'grades'),
2364 'export' => get_string('export', 'grades'),
2365 'import' => get_string('import'),
2366 'preferences' => get_string('mypreferences', 'grades'),
2367 'settings' => get_string('settings')
2370 return self::$pluginstrings;
2373 * Get grade_plugin_info object for managing settings if the user can
2375 * @param int $courseid
2376 * @return grade_plugin_info
2378 public static function get_info_manage_settings($courseid) {
2379 if (self::$managesetting !== null) {
2380 return self::$managesetting;
2382 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2383 if (has_capability('moodle/course:update', $context)) {
2384 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2386 self::$managesetting = false;
2388 return self::$managesetting;
2391 * Returns an array of plugin reports as grade_plugin_info objects
2393 * @param int $courseid
2396 public static function get_plugins_reports($courseid) {
2399 if (self::$gradereports !== null) {
2400 return self::$gradereports;
2402 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2403 $gradereports = array();
2404 $gradepreferences = array();
2405 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2406 //some reports make no sense if we're not within a course
2407 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2411 // Remove ones we can't see
2412 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2416 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2417 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2418 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2420 // Add link to preferences tab if such a page exists
2421 if (file_exists($plugindir.'/preferences.php')) {
2422 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2423 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2426 if (count($gradereports) == 0) {
2427 $gradereports = false;
2428 $gradepreferences = false;
2429 } else if (count($gradepreferences) == 0) {
2430 $gradepreferences = false;
2431 asort($gradereports);
2433 asort($gradereports);
2434 asort($gradepreferences);
2436 self::$gradereports = $gradereports;
2437 self::$gradereportpreferences = $gradepreferences;
2438 return self::$gradereports;
2441 * Returns an array of grade plugin report preferences for plugin reports that
2442 * support preferences
2443 * @param int $courseid
2446 public static function get_plugins_report_preferences($courseid) {
2447 if (self::$gradereportpreferences !== null) {
2448 return self::$gradereportpreferences;
2450 self::get_plugins_reports($courseid);
2451 return self::$gradereportpreferences;
2454 * Get information on scales
2455 * @param int $courseid
2456 * @return grade_plugin_info
2458 public static function get_info_scales($courseid) {
2459 if (self::$scaleinfo !== null) {
2460 return self::$scaleinfo;
2462 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2463 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2464 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2466 self::$scaleinfo = false;
2468 return self::$scaleinfo;
2471 * Get information on outcomes
2472 * @param int $courseid
2473 * @return grade_plugin_info
2475 public static function get_info_outcomes($courseid) {
2478 if (self::$outcomeinfo !== null) {
2479 return self::$outcomeinfo;
2481 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2482 $canmanage = has_capability('moodle/grade:manage', $context);
2483 $canupdate = has_capability('moodle/course:update', $context);
2484 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2485 $outcomes = array();
2487 if ($courseid!=$SITE->id) {
2488 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2489 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2491 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2492 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2493 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2494 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2496 if ($courseid!=$SITE->id) {
2497 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2498 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2501 self::$outcomeinfo = $outcomes;
2503 self::$outcomeinfo = false;
2505 return self::$outcomeinfo;
2508 * Get information on editing structures
2509 * @param int $courseid
2512 public static function get_info_edit_structure($courseid) {
2513 if (self::$edittree !== null) {
2514 return self::$edittree;
2516 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2517 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2518 self::$edittree = array(
2519 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2520 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2523 self::$edittree = false;
2525 return self::$edittree;
2528 * Get information on letters
2529 * @param int $courseid
2532 public static function get_info_letters($courseid) {
2533 if (self::$letterinfo !== null) {
2534 return self::$letterinfo;
2536 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2537 $canmanage = has_capability('moodle/grade:manage', $context);
2538 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2539 if ($canmanage || $canmanageletters) {
2540 self::$letterinfo = array(
2541 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2542 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2545 self::$letterinfo = false;
2547 return self::$letterinfo;
2550 * Get information import plugins
2551 * @param int $courseid
2554 public static function get_plugins_import($courseid) {
2557 if (self::$importplugins !== null) {
2558 return self::$importplugins;
2560 $importplugins = array();
2561 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2563 if (has_capability('moodle/grade:import', $context)) {
2564 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2565 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2568 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2569 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2570 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2574 if ($CFG->gradepublishing) {
2575 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2576 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2580 if (count($importplugins) > 0) {
2581 asort($importplugins);
2582 self::$importplugins = $importplugins;
2584 self::$importplugins = false;
2586 return self::$importplugins;
2589 * Get information export plugins
2590 * @param int $courseid
2593 public static function get_plugins_export($courseid) {
2596 if (self::$exportplugins !== null) {
2597 return self::$exportplugins;
2599 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2600 $exportplugins = array();
2601 if (has_capability('moodle/grade:export', $context)) {
2602 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2603 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2606 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2607 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2608 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2611 if ($CFG->gradepublishing) {
2612 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2613 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2616 if (count($exportplugins) > 0) {
2617 asort($exportplugins);
2618 self::$exportplugins = $exportplugins;
2620 self::$exportplugins = false;
2622 return self::$exportplugins;