MDL-28471 better question flag icons.
[moodle.git] / grade / lib.php
blob392eed0d35638a844453f55650740142bd2a6c54
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions used by gradebook plugins and reports.
21 * @package moodlecore
22 * @copyright 2009 Petr Skoda and Nicolas Connault
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require_once $CFG->libdir.'/gradelib.php';
28 /**
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator {
36 public $course;
37 public $grade_items;
38 public $groupid;
39 public $users_rs;
40 public $grades_rs;
41 public $gradestack;
42 public $sortfield1;
43 public $sortorder1;
44 public $sortfield2;
45 public $sortorder2;
47 /**
48 * Constructor
50 * @param object $course A course object
51 * @param array $grade_items array of grade items, if not specified only user info returned
52 * @param int $groupid iterate only group users if present
53 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
54 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
55 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
56 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
58 public function graded_users_iterator($course, $grade_items=null, $groupid=0,
59 $sortfield1='lastname', $sortorder1='ASC',
60 $sortfield2='firstname', $sortorder2='ASC') {
61 $this->course = $course;
62 $this->grade_items = $grade_items;
63 $this->groupid = $groupid;
64 $this->sortfield1 = $sortfield1;
65 $this->sortorder1 = $sortorder1;
66 $this->sortfield2 = $sortfield2;
67 $this->sortorder2 = $sortorder2;
69 $this->gradestack = array();
72 /**
73 * Initialise the iterator
74 * @return boolean success
76 public function init() {
77 global $CFG, $DB;
79 $this->close();
81 grade_regrade_final_grades($this->course->id);
82 $course_item = grade_item::fetch_course_item($this->course->id);
83 if ($course_item->needsupdate) {
84 // can not calculate all final grades - sorry
85 return false;
88 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
89 $relatedcontexts = get_related_contexts_string($coursecontext);
91 list($gradebookroles_sql, $params) =
92 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
94 //limit to users with an active enrolment
95 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext);
97 $params = array_merge($params, $enrolledparams);
99 if ($this->groupid) {
100 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
101 $groupwheresql = "AND gm.groupid = :groupid";
102 // $params contents: gradebookroles
103 $params['groupid'] = $this->groupid;
104 } else {
105 $groupsql = "";
106 $groupwheresql = "";
109 if (empty($this->sortfield1)) {
110 // we must do some sorting even if not specified
111 $ofields = ", u.id AS usrt";
112 $order = "usrt ASC";
114 } else {
115 $ofields = ", u.$this->sortfield1 AS usrt1";
116 $order = "usrt1 $this->sortorder1";
117 if (!empty($this->sortfield2)) {
118 $ofields .= ", u.$this->sortfield2 AS usrt2";
119 $order .= ", usrt2 $this->sortorder2";
121 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
122 // user order MUST be the same in both queries,
123 // must include the only unique user->id if not already present
124 $ofields .= ", u.id AS usrt";
125 $order .= ", usrt ASC";
129 // $params contents: gradebookroles and groupid (for $groupwheresql)
130 $users_sql = "SELECT u.* $ofields
131 FROM {user} u
132 JOIN ($enrolledsql) je ON je.id = u.id
133 $groupsql
134 JOIN (
135 SELECT DISTINCT ra.userid
136 FROM {role_assignments} ra
137 WHERE ra.roleid $gradebookroles_sql
138 AND ra.contextid $relatedcontexts
139 ) rainner ON rainner.userid = u.id
140 WHERE u.deleted = 0
141 $groupwheresql
142 ORDER BY $order";
143 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
145 if (!empty($this->grade_items)) {
146 $itemids = array_keys($this->grade_items);
147 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
148 $params = array_merge($params, $grades_params);
149 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
151 $grades_sql = "SELECT g.* $ofields
152 FROM {grade_grades} g
153 JOIN {user} u ON g.userid = u.id
154 JOIN ($enrolledsql) je ON je.id = u.id
155 $groupsql
156 JOIN (
157 SELECT DISTINCT ra.userid
158 FROM {role_assignments} ra
159 WHERE ra.roleid $gradebookroles_sql
160 AND ra.contextid $relatedcontexts
161 ) rainner ON rainner.userid = u.id
162 WHERE u.deleted = 0
163 AND g.itemid $itemidsql
164 $groupwheresql
165 ORDER BY $order, g.itemid ASC";
166 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
167 } else {
168 $this->grades_rs = false;
171 return true;
175 * Returns information about the next user
176 * @return mixed array of user info, all grades and feedback or null when no more users found
178 function next_user() {
179 if (!$this->users_rs) {
180 return false; // no users present
183 if (!$this->users_rs->valid()) {
184 if ($current = $this->_pop()) {
185 // this is not good - user or grades updated between the two reads above :-(
188 return false; // no more users
189 } else {
190 $user = $this->users_rs->current();
191 $this->users_rs->next();
194 // find grades of this user
195 $grade_records = array();
196 while (true) {
197 if (!$current = $this->_pop()) {
198 break; // no more grades
201 if (empty($current->userid)) {
202 break;
205 if ($current->userid != $user->id) {
206 // grade of the next user, we have all for this user
207 $this->_push($current);
208 break;
211 $grade_records[$current->itemid] = $current;
214 $grades = array();
215 $feedbacks = array();
217 if (!empty($this->grade_items)) {
218 foreach ($this->grade_items as $grade_item) {
219 if (array_key_exists($grade_item->id, $grade_records)) {
220 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
221 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
222 unset($grade_records[$grade_item->id]->feedback);
223 unset($grade_records[$grade_item->id]->feedbackformat);
224 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
225 } else {
226 $feedbacks[$grade_item->id]->feedback = '';
227 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
228 $grades[$grade_item->id] =
229 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
234 $result = new stdClass();
235 $result->user = $user;
236 $result->grades = $grades;
237 $result->feedbacks = $feedbacks;
238 return $result;
242 * Close the iterator, do not forget to call this function.
243 * @return void
245 function close() {
246 if ($this->users_rs) {
247 $this->users_rs->close();
248 $this->users_rs = null;
250 if ($this->grades_rs) {
251 $this->grades_rs->close();
252 $this->grades_rs = null;
254 $this->gradestack = array();
259 * _push
261 * @param grade_grade $grade Grade object
263 * @return void
265 function _push($grade) {
266 array_push($this->gradestack, $grade);
271 * _pop
273 * @return object current grade object
275 function _pop() {
276 global $DB;
277 if (empty($this->gradestack)) {
278 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
279 return null; // no grades present
282 $current = $this->grades_rs->current();
284 $this->grades_rs->next();
286 return $current;
287 } else {
288 return array_pop($this->gradestack);
294 * Print a selection popup form of the graded users in a course.
296 * @deprecated since 2.0
298 * @param int $course id of the course
299 * @param string $actionpage The page receiving the data from the popoup form
300 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
301 * @param int $groupid id of requested group, 0 means all
302 * @param int $includeall bool include all option
303 * @param bool $return If true, will return the HTML, otherwise, will print directly
304 * @return null
306 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
307 global $CFG, $USER, $OUTPUT;
308 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
311 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
312 global $USER;
314 if (is_null($userid)) {
315 $userid = $USER->id;
318 $menu = array(); // Will be a list of userid => user name
319 $gui = new graded_users_iterator($course, null, $groupid);
320 $gui->init();
321 $label = get_string('selectauser', 'grades');
322 if ($includeall) {
323 $menu[0] = get_string('allusers', 'grades');
324 $label = get_string('selectalloroneuser', 'grades');
326 while ($userdata = $gui->next_user()) {
327 $user = $userdata->user;
328 $menu[$user->id] = fullname($user);
330 $gui->close();
332 if ($includeall) {
333 $menu[0] .= " (" . (count($menu) - 1) . ")";
335 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
336 $select->label = $label;
337 $select->formid = 'choosegradeuser';
338 return $select;
342 * Print grading plugin selection popup form.
344 * @param array $plugin_info An array of plugins containing information for the selector
345 * @param boolean $return return as string
347 * @return nothing or string if $return true
349 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
350 global $CFG, $OUTPUT, $PAGE;
352 $menu = array();
353 $count = 0;
354 $active = '';
356 foreach ($plugin_info as $plugin_type => $plugins) {
357 if ($plugin_type == 'strings') {
358 continue;
361 $first_plugin = reset($plugins);
363 $sectionname = $plugin_info['strings'][$plugin_type];
364 $section = array();
366 foreach ($plugins as $plugin) {
367 $link = $plugin->link->out(false);
368 $section[$link] = $plugin->string;
369 $count++;
370 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
371 $active = $link;
375 if ($section) {
376 $menu[] = array($sectionname=>$section);
380 // finally print/return the popup form
381 if ($count > 1) {
382 $select = new url_select($menu, $active, null, 'choosepluginreport');
384 if ($return) {
385 return $OUTPUT->render($select);
386 } else {
387 echo $OUTPUT->render($select);
389 } else {
390 // only one option - no plugin selector needed
391 return '';
396 * Print grading plugin selection tab-based navigation.
398 * @param string $active_type type of plugin on current page - import, export, report or edit
399 * @param string $active_plugin active plugin type - grader, user, cvs, ...
400 * @param array $plugin_info Array of plugins
401 * @param boolean $return return as string
403 * @return nothing or string if $return true
405 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
406 global $CFG, $COURSE;
408 if (!isset($currenttab)) { //TODO: this is weird
409 $currenttab = '';
412 $tabs = array();
413 $top_row = array();
414 $bottom_row = array();
415 $inactive = array($active_plugin);
416 $activated = array();
418 $count = 0;
419 $active = '';
421 foreach ($plugin_info as $plugin_type => $plugins) {
422 if ($plugin_type == 'strings') {
423 continue;
426 // If $plugins is actually the definition of a child-less parent link:
427 if (!empty($plugins->id)) {
428 $string = $plugins->string;
429 if (!empty($plugin_info[$active_type]->parent)) {
430 $string = $plugin_info[$active_type]->parent->string;
433 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
434 continue;
437 $first_plugin = reset($plugins);
438 $url = $first_plugin->link;
440 if ($plugin_type == 'report') {
441 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
444 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
446 if ($active_type == $plugin_type) {
447 foreach ($plugins as $plugin) {
448 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
449 if ($plugin->id == $active_plugin) {
450 $inactive = array($plugin->id);
456 $tabs[] = $top_row;
457 $tabs[] = $bottom_row;
459 if ($return) {
460 return print_tabs($tabs, $active_type, $inactive, $activated, true);
461 } else {
462 print_tabs($tabs, $active_type, $inactive, $activated);
467 * grade_get_plugin_info
469 * @param int $courseid The course id
470 * @param string $active_type type of plugin on current page - import, export, report or edit
471 * @param string $active_plugin active plugin type - grader, user, cvs, ...
473 * @return array
475 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
476 global $CFG, $SITE;
478 $context = get_context_instance(CONTEXT_COURSE, $courseid);
480 $plugin_info = array();
481 $count = 0;
482 $active = '';
483 $url_prefix = $CFG->wwwroot . '/grade/';
485 // Language strings
486 $plugin_info['strings'] = grade_helper::get_plugin_strings();
488 if ($reports = grade_helper::get_plugins_reports($courseid)) {
489 $plugin_info['report'] = $reports;
492 //showing grade categories and items make no sense if we're not within a course
493 if ($courseid!=$SITE->id) {
494 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
495 $plugin_info['edittree'] = $edittree;
499 if ($scale = grade_helper::get_info_scales($courseid)) {
500 $plugin_info['scale'] = array('view'=>$scale);
503 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
504 $plugin_info['outcome'] = $outcomes;
507 if ($letters = grade_helper::get_info_letters($courseid)) {
508 $plugin_info['letter'] = $letters;
511 if ($imports = grade_helper::get_plugins_import($courseid)) {
512 $plugin_info['import'] = $imports;
515 if ($exports = grade_helper::get_plugins_export($courseid)) {
516 $plugin_info['export'] = $exports;
519 foreach ($plugin_info as $plugin_type => $plugins) {
520 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
521 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
522 break;
524 foreach ($plugins as $plugin) {
525 if (is_a($plugin, 'grade_plugin_info')) {
526 if ($active_plugin == $plugin->id) {
527 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
533 //hide course settings if we're not in a course
534 if ($courseid!=$SITE->id) {
535 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
536 $plugin_info['settings'] = array('course'=>$setting);
540 // Put preferences last
541 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
542 $plugin_info['preferences'] = $preferences;
545 foreach ($plugin_info as $plugin_type => $plugins) {
546 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
547 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
548 break;
550 foreach ($plugins as $plugin) {
551 if (is_a($plugin, 'grade_plugin_info')) {
552 if ($active_plugin == $plugin->id) {
553 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
559 return $plugin_info;
563 * A simple class containing info about grade plugins.
564 * Can be subclassed for special rules
566 * @package moodlecore
567 * @copyright 2009 Nicolas Connault
568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
570 class grade_plugin_info {
572 * A unique id for this plugin
574 * @var mixed
576 public $id;
578 * A URL to access this plugin
580 * @var mixed
582 public $link;
584 * The name of this plugin
586 * @var mixed
588 public $string;
590 * Another grade_plugin_info object, parent of the current one
592 * @var mixed
594 public $parent;
597 * Constructor
599 * @param int $id A unique id for this plugin
600 * @param string $link A URL to access this plugin
601 * @param string $string The name of this plugin
602 * @param object $parent Another grade_plugin_info object, parent of the current one
604 * @return void
606 public function __construct($id, $link, $string, $parent=null) {
607 $this->id = $id;
608 $this->link = $link;
609 $this->string = $string;
610 $this->parent = $parent;
615 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
616 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
617 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
618 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
619 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
621 * @param int $courseid Course id
622 * @param string $active_type The type of the current page (report, settings,
623 * import, export, scales, outcomes, letters)
624 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
625 * @param string $heading The heading of the page. Tries to guess if none is given
626 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
627 * @param string $bodytags Additional attributes that will be added to the <body> tag
628 * @param string $buttons Additional buttons to display on the page
630 * @return string HTML code or nothing if $return == false
632 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
633 $heading = false, $return=false,
634 $buttons=false, $shownavigation=true) {
635 global $CFG, $OUTPUT, $PAGE;
637 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
639 // Determine the string of the active plugin
640 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
641 $stractive_type = $plugin_info['strings'][$active_type];
643 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
644 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
645 } else {
646 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
649 if ($active_type == 'report') {
650 $PAGE->set_pagelayout('report');
651 } else {
652 $PAGE->set_pagelayout('admin');
654 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
655 $PAGE->set_heading($title);
656 if ($buttons instanceof single_button) {
657 $buttons = $OUTPUT->render($buttons);
659 $PAGE->set_button($buttons);
660 grade_extend_settings($plugin_info, $courseid);
662 $returnval = $OUTPUT->header();
663 if (!$return) {
664 echo $returnval;
667 // Guess heading if not given explicitly
668 if (!$heading) {
669 $heading = $stractive_plugin;
672 if ($shownavigation) {
673 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
674 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
676 $returnval .= $OUTPUT->heading($heading);
677 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
678 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
682 if ($return) {
683 return $returnval;
688 * Utility class used for return tracking when using edit and other forms in grade plugins
690 * @package moodlecore
691 * @copyright 2009 Nicolas Connault
692 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
694 class grade_plugin_return {
695 public $type;
696 public $plugin;
697 public $courseid;
698 public $userid;
699 public $page;
702 * Constructor
704 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
706 public function grade_plugin_return($params = null) {
707 if (empty($params)) {
708 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
709 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
710 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
711 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
712 $this->page = optional_param('gpr_page', null, PARAM_INT);
714 } else {
715 foreach ($params as $key=>$value) {
716 if (property_exists($this, $key)) {
717 $this->$key = $value;
724 * Returns return parameters as options array suitable for buttons.
725 * @return array options
727 public function get_options() {
728 if (empty($this->type)) {
729 return array();
732 $params = array();
734 if (!empty($this->plugin)) {
735 $params['plugin'] = $this->plugin;
738 if (!empty($this->courseid)) {
739 $params['id'] = $this->courseid;
742 if (!empty($this->userid)) {
743 $params['userid'] = $this->userid;
746 if (!empty($this->page)) {
747 $params['page'] = $this->page;
750 return $params;
754 * Returns return url
756 * @param string $default default url when params not set
757 * @param array $extras Extra URL parameters
759 * @return string url
761 public function get_return_url($default, $extras=null) {
762 global $CFG;
764 if (empty($this->type) or empty($this->plugin)) {
765 return $default;
768 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
769 $glue = '?';
771 if (!empty($this->courseid)) {
772 $url .= $glue.'id='.$this->courseid;
773 $glue = '&amp;';
776 if (!empty($this->userid)) {
777 $url .= $glue.'userid='.$this->userid;
778 $glue = '&amp;';
781 if (!empty($this->page)) {
782 $url .= $glue.'page='.$this->page;
783 $glue = '&amp;';
786 if (!empty($extras)) {
787 foreach ($extras as $key=>$value) {
788 $url .= $glue.$key.'='.$value;
789 $glue = '&amp;';
793 return $url;
797 * Returns string with hidden return tracking form elements.
798 * @return string
800 public function get_form_fields() {
801 if (empty($this->type)) {
802 return '';
805 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
807 if (!empty($this->plugin)) {
808 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
811 if (!empty($this->courseid)) {
812 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
815 if (!empty($this->userid)) {
816 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
819 if (!empty($this->page)) {
820 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
825 * Add hidden elements into mform
827 * @param object &$mform moodle form object
829 * @return void
831 public function add_mform_elements(&$mform) {
832 if (empty($this->type)) {
833 return;
836 $mform->addElement('hidden', 'gpr_type', $this->type);
837 $mform->setType('gpr_type', PARAM_SAFEDIR);
839 if (!empty($this->plugin)) {
840 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
841 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
844 if (!empty($this->courseid)) {
845 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
846 $mform->setType('gpr_courseid', PARAM_INT);
849 if (!empty($this->userid)) {
850 $mform->addElement('hidden', 'gpr_userid', $this->userid);
851 $mform->setType('gpr_userid', PARAM_INT);
854 if (!empty($this->page)) {
855 $mform->addElement('hidden', 'gpr_page', $this->page);
856 $mform->setType('gpr_page', PARAM_INT);
861 * Add return tracking params into url
863 * @param moodle_url $url A URL
865 * @return string $url with return tracking params
867 public function add_url_params(moodle_url $url) {
868 if (empty($this->type)) {
869 return $url;
872 $url->param('gpr_type', $this->type);
874 if (!empty($this->plugin)) {
875 $url->param('gpr_plugin', $this->plugin);
878 if (!empty($this->courseid)) {
879 $url->param('gpr_courseid' ,$this->courseid);
882 if (!empty($this->userid)) {
883 $url->param('gpr_userid', $this->userid);
886 if (!empty($this->page)) {
887 $url->param('gpr_page', $this->page);
890 return $url;
895 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
897 * @param string $path The path of the calling script (using __FILE__?)
898 * @param string $pagename The language string to use as the last part of the navigation (non-link)
899 * @param mixed $id Either a plain integer (assuming the key is 'id') or
900 * an array of keys and values (e.g courseid => $courseid, itemid...)
902 * @return string
904 function grade_build_nav($path, $pagename=null, $id=null) {
905 global $CFG, $COURSE, $PAGE;
907 $strgrades = get_string('grades', 'grades');
909 // Parse the path and build navlinks from its elements
910 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
911 $path = substr($path, $dirroot_length);
912 $path = str_replace('\\', '/', $path);
914 $path_elements = explode('/', $path);
916 $path_elements_count = count($path_elements);
918 // First link is always 'grade'
919 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
921 $link = null;
922 $numberofelements = 3;
924 // Prepare URL params string
925 $linkparams = array();
926 if (!is_null($id)) {
927 if (is_array($id)) {
928 foreach ($id as $idkey => $idvalue) {
929 $linkparams[$idkey] = $idvalue;
931 } else {
932 $linkparams['id'] = $id;
936 $navlink4 = null;
938 // Remove file extensions from filenames
939 foreach ($path_elements as $key => $filename) {
940 $path_elements[$key] = str_replace('.php', '', $filename);
943 // Second level links
944 switch ($path_elements[1]) {
945 case 'edit': // No link
946 if ($path_elements[3] != 'index.php') {
947 $numberofelements = 4;
949 break;
950 case 'import': // No link
951 break;
952 case 'export': // No link
953 break;
954 case 'report':
955 // $id is required for this link. Do not print it if $id isn't given
956 if (!is_null($id)) {
957 $link = new moodle_url('/grade/report/index.php', $linkparams);
960 if ($path_elements[2] == 'grader') {
961 $numberofelements = 4;
963 break;
965 default:
966 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
967 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
968 " as the second path element after 'grade'.");
969 return false;
971 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
973 // Third level links
974 if (empty($pagename)) {
975 $pagename = get_string($path_elements[2], 'grades');
978 switch ($numberofelements) {
979 case 3:
980 $PAGE->navbar->add($pagename, $link);
981 break;
982 case 4:
983 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
984 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
986 $PAGE->navbar->add($pagename);
987 break;
990 return '';
994 * General structure representing grade items in course
996 * @package moodlecore
997 * @copyright 2009 Nicolas Connault
998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1000 class grade_structure {
1001 public $context;
1003 public $courseid;
1006 * 1D array of grade items only
1008 public $items;
1011 * Returns icon of element
1013 * @param array &$element An array representing an element in the grade_tree
1014 * @param bool $spacerifnone return spacer if no icon found
1016 * @return string icon or spacer
1018 public function get_element_icon(&$element, $spacerifnone=false) {
1019 global $CFG, $OUTPUT;
1021 switch ($element['type']) {
1022 case 'item':
1023 case 'courseitem':
1024 case 'categoryitem':
1025 $is_course = $element['object']->is_course_item();
1026 $is_category = $element['object']->is_category_item();
1027 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1028 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1029 $is_outcome = !empty($element['object']->outcomeid);
1031 if ($element['object']->is_calculated()) {
1032 $strcalc = get_string('calculatedgrade', 'grades');
1033 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1034 s($strcalc).'" alt="'.s($strcalc).'"/>';
1036 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1037 if ($category = $element['object']->get_item_category()) {
1038 switch ($category->aggregation) {
1039 case GRADE_AGGREGATE_MEAN:
1040 case GRADE_AGGREGATE_MEDIAN:
1041 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1042 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1043 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1044 $stragg = get_string('aggregation', 'grades');
1045 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1046 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1047 case GRADE_AGGREGATE_SUM:
1048 $stragg = get_string('aggregation', 'grades');
1049 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1050 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1054 } else if ($element['object']->itemtype == 'mod') {
1055 //prevent outcomes being displaying the same icon as the activity they are attached to
1056 if ($is_outcome) {
1057 $stroutcome = s(get_string('outcome', 'grades'));
1058 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1059 'class="icon itemicon" title="'.$stroutcome.
1060 '" alt="'.$stroutcome.'"/>';
1061 } else {
1062 $strmodname = get_string('modulename', $element['object']->itemmodule);
1063 return '<img src="'.$OUTPUT->pix_url('icon',
1064 $element['object']->itemmodule) . '" ' .
1065 'class="icon itemicon" title="' .s($strmodname).
1066 '" alt="' .s($strmodname).'"/>';
1068 } else if ($element['object']->itemtype == 'manual') {
1069 if ($element['object']->is_outcome_item()) {
1070 $stroutcome = get_string('outcome', 'grades');
1071 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1072 'class="icon itemicon" title="'.s($stroutcome).
1073 '" alt="'.s($stroutcome).'"/>';
1074 } else {
1075 $strmanual = get_string('manualitem', 'grades');
1076 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1077 'class="icon itemicon" title="'.s($strmanual).
1078 '" alt="'.s($strmanual).'"/>';
1081 break;
1083 case 'category':
1084 $strcat = get_string('category', 'grades');
1085 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1086 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1089 if ($spacerifnone) {
1090 return $OUTPUT->spacer().' ';
1091 } else {
1092 return '';
1097 * Returns name of element optionally with icon and link
1099 * @param array &$element An array representing an element in the grade_tree
1100 * @param bool $withlink Whether or not this header has a link
1101 * @param bool $icon Whether or not to display an icon with this header
1102 * @param bool $spacerifnone return spacer if no icon found
1104 * @return string header
1106 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1107 global $CFG;
1109 $header = '';
1111 if ($icon) {
1112 $header .= $this->get_element_icon($element, $spacerifnone);
1115 $header .= $element['object']->get_name();
1117 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1118 $element['type'] != 'courseitem') {
1119 return $header;
1122 $itemtype = $element['object']->itemtype;
1123 $itemmodule = $element['object']->itemmodule;
1124 $iteminstance = $element['object']->iteminstance;
1126 if ($withlink and $itemtype=='mod' and $iteminstance and $itemmodule) {
1127 if ($cm = get_coursemodule_from_instance($itemmodule, $iteminstance, $this->courseid)) {
1129 $a = new stdClass();
1130 $a->name = get_string('modulename', $element['object']->itemmodule);
1131 $title = get_string('linktoactivity', 'grades', $a);
1132 $dir = $CFG->dirroot.'/mod/'.$itemmodule;
1134 if (file_exists($dir.'/grade.php')) {
1135 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/grade.php?id='.$cm->id;
1136 } else {
1137 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/view.php?id='.$cm->id;
1140 $header = '<a href="'.$url.'" title="'.s($title).'">'.$header.'</a>';
1144 return $header;
1148 * Returns the grade eid - the grade may not exist yet.
1150 * @param grade_grade $grade_grade A grade_grade object
1152 * @return string eid
1154 public function get_grade_eid($grade_grade) {
1155 if (empty($grade_grade->id)) {
1156 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1157 } else {
1158 return 'g'.$grade_grade->id;
1163 * Returns the grade_item eid
1164 * @param grade_item $grade_item A grade_item object
1165 * @return string eid
1167 public function get_item_eid($grade_item) {
1168 return 'i'.$grade_item->id;
1172 * Given a grade_tree element, returns an array of parameters
1173 * used to build an icon for that element.
1175 * @param array $element An array representing an element in the grade_tree
1177 * @return array
1179 public function get_params_for_iconstr($element) {
1180 $strparams = new stdClass();
1181 $strparams->category = '';
1182 $strparams->itemname = '';
1183 $strparams->itemmodule = '';
1185 if (!method_exists($element['object'], 'get_name')) {
1186 return $strparams;
1189 $strparams->itemname = html_to_text($element['object']->get_name());
1191 // If element name is categorytotal, get the name of the parent category
1192 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1193 $parent = $element['object']->get_parent_category();
1194 $strparams->category = $parent->get_name() . ' ';
1195 } else {
1196 $strparams->category = '';
1199 $strparams->itemmodule = null;
1200 if (isset($element['object']->itemmodule)) {
1201 $strparams->itemmodule = $element['object']->itemmodule;
1203 return $strparams;
1207 * Return edit icon for give element
1209 * @param array $element An array representing an element in the grade_tree
1210 * @param object $gpr A grade_plugin_return object
1212 * @return string
1214 public function get_edit_icon($element, $gpr) {
1215 global $CFG, $OUTPUT;
1217 if (!has_capability('moodle/grade:manage', $this->context)) {
1218 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1219 // oki - let them override grade
1220 } else {
1221 return '';
1225 static $strfeedback = null;
1226 static $streditgrade = null;
1227 if (is_null($streditgrade)) {
1228 $streditgrade = get_string('editgrade', 'grades');
1229 $strfeedback = get_string('feedback');
1232 $strparams = $this->get_params_for_iconstr($element);
1234 $object = $element['object'];
1236 switch ($element['type']) {
1237 case 'item':
1238 case 'categoryitem':
1239 case 'courseitem':
1240 $stredit = get_string('editverbose', 'grades', $strparams);
1241 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1242 $url = new moodle_url('/grade/edit/tree/item.php',
1243 array('courseid' => $this->courseid, 'id' => $object->id));
1244 } else {
1245 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1246 array('courseid' => $this->courseid, 'id' => $object->id));
1248 break;
1250 case 'category':
1251 $stredit = get_string('editverbose', 'grades', $strparams);
1252 $url = new moodle_url('/grade/edit/tree/category.php',
1253 array('courseid' => $this->courseid, 'id' => $object->id));
1254 break;
1256 case 'grade':
1257 $stredit = $streditgrade;
1258 if (empty($object->id)) {
1259 $url = new moodle_url('/grade/edit/tree/grade.php',
1260 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1261 } else {
1262 $url = new moodle_url('/grade/edit/tree/grade.php',
1263 array('courseid' => $this->courseid, 'id' => $object->id));
1265 if (!empty($object->feedback)) {
1266 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1268 break;
1270 default:
1271 $url = null;
1274 if ($url) {
1275 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1277 } else {
1278 return '';
1283 * Return hiding icon for give element
1285 * @param array $element An array representing an element in the grade_tree
1286 * @param object $gpr A grade_plugin_return object
1288 * @return string
1290 public function get_hiding_icon($element, $gpr) {
1291 global $CFG, $OUTPUT;
1293 if (!has_capability('moodle/grade:manage', $this->context) and
1294 !has_capability('moodle/grade:hide', $this->context)) {
1295 return '';
1298 $strparams = $this->get_params_for_iconstr($element);
1299 $strshow = get_string('showverbose', 'grades', $strparams);
1300 $strhide = get_string('hideverbose', 'grades', $strparams);
1302 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1303 $url = $gpr->add_url_params($url);
1305 if ($element['object']->is_hidden()) {
1306 $type = 'show';
1307 $tooltip = $strshow;
1309 // Change the icon and add a tooltip showing the date
1310 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1311 $type = 'hiddenuntil';
1312 $tooltip = get_string('hiddenuntildate', 'grades',
1313 userdate($element['object']->get_hidden()));
1316 $url->param('action', 'show');
1318 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1320 } else {
1321 $url->param('action', 'hide');
1322 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1325 return $hideicon;
1329 * Return locking icon for given element
1331 * @param array $element An array representing an element in the grade_tree
1332 * @param object $gpr A grade_plugin_return object
1334 * @return string
1336 public function get_locking_icon($element, $gpr) {
1337 global $CFG, $OUTPUT;
1339 $strparams = $this->get_params_for_iconstr($element);
1340 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1341 $strlock = get_string('lockverbose', 'grades', $strparams);
1343 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1344 $url = $gpr->add_url_params($url);
1346 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1347 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1348 $strparamobj = new stdClass();
1349 $strparamobj->itemname = $element['object']->grade_item->itemname;
1350 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1352 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1354 } else if ($element['object']->is_locked()) {
1355 $type = 'unlock';
1356 $tooltip = $strunlock;
1358 // Change the icon and add a tooltip showing the date
1359 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1360 $type = 'locktime';
1361 $tooltip = get_string('locktimedate', 'grades',
1362 userdate($element['object']->get_locktime()));
1365 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1366 $action = '';
1367 } else {
1368 $url->param('action', 'unlock');
1369 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1372 } else {
1373 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1374 $action = '';
1375 } else {
1376 $url->param('action', 'lock');
1377 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1381 return $action;
1385 * Return calculation icon for given element
1387 * @param array $element An array representing an element in the grade_tree
1388 * @param object $gpr A grade_plugin_return object
1390 * @return string
1392 public function get_calculation_icon($element, $gpr) {
1393 global $CFG, $OUTPUT;
1394 if (!has_capability('moodle/grade:manage', $this->context)) {
1395 return '';
1398 $type = $element['type'];
1399 $object = $element['object'];
1401 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1402 $strparams = $this->get_params_for_iconstr($element);
1403 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1405 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1406 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1408 // show calculation icon only when calculation possible
1409 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1410 if ($object->is_calculated()) {
1411 $icon = 't/calc';
1412 } else {
1413 $icon = 't/calc_off';
1416 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1417 $url = $gpr->add_url_params($url);
1418 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1422 return '';
1427 * Flat structure similar to grade tree.
1429 * @uses grade_structure
1430 * @package moodlecore
1431 * @copyright 2009 Nicolas Connault
1432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1434 class grade_seq extends grade_structure {
1437 * 1D array of elements
1439 public $elements;
1442 * Constructor, retrieves and stores array of all grade_category and grade_item
1443 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1445 * @param int $courseid The course id
1446 * @param bool $category_grade_last category grade item is the last child
1447 * @param bool $nooutcomes Whether or not outcomes should be included
1449 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1450 global $USER, $CFG;
1452 $this->courseid = $courseid;
1453 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1455 // get course grade tree
1456 $top_element = grade_category::fetch_course_tree($courseid, true);
1458 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1460 foreach ($this->elements as $key=>$unused) {
1461 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1466 * Static recursive helper - makes the grade_item for category the last children
1468 * @param array &$element The seed of the recursion
1469 * @param bool $category_grade_last category grade item is the last child
1470 * @param bool $nooutcomes Whether or not outcomes should be included
1472 * @return array
1474 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1475 if (empty($element['children'])) {
1476 return array();
1478 $children = array();
1480 foreach ($element['children'] as $sortorder=>$unused) {
1481 if ($nooutcomes and $element['type'] != 'category' and
1482 $element['children'][$sortorder]['object']->is_outcome_item()) {
1483 continue;
1485 $children[] = $element['children'][$sortorder];
1487 unset($element['children']);
1489 if ($category_grade_last and count($children) > 1) {
1490 $cat_item = array_shift($children);
1491 array_push($children, $cat_item);
1494 $result = array();
1495 foreach ($children as $child) {
1496 if ($child['type'] == 'category') {
1497 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1498 } else {
1499 $child['eid'] = 'i'.$child['object']->id;
1500 $result[$child['object']->id] = $child;
1504 return $result;
1508 * Parses the array in search of a given eid and returns a element object with
1509 * information about the element it has found.
1511 * @param int $eid Gradetree Element ID
1513 * @return object element
1515 public function locate_element($eid) {
1516 // it is a grade - construct a new object
1517 if (strpos($eid, 'n') === 0) {
1518 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1519 return null;
1522 $itemid = $matches[1];
1523 $userid = $matches[2];
1525 //extra security check - the grade item must be in this tree
1526 if (!$item_el = $this->locate_element('i'.$itemid)) {
1527 return null;
1530 // $gradea->id may be null - means does not exist yet
1531 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1533 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1534 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1536 } else if (strpos($eid, 'g') === 0) {
1537 $id = (int) substr($eid, 1);
1538 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1539 return null;
1541 //extra security check - the grade item must be in this tree
1542 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1543 return null;
1545 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1546 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1549 // it is a category or item
1550 foreach ($this->elements as $element) {
1551 if ($element['eid'] == $eid) {
1552 return $element;
1556 return null;
1561 * This class represents a complete tree of categories, grade_items and final grades,
1562 * organises as an array primarily, but which can also be converted to other formats.
1563 * It has simple method calls with complex implementations, allowing for easy insertion,
1564 * deletion and moving of items and categories within the tree.
1566 * @uses grade_structure
1567 * @package moodlecore
1568 * @copyright 2009 Nicolas Connault
1569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1571 class grade_tree extends grade_structure {
1574 * The basic representation of the tree as a hierarchical, 3-tiered array.
1575 * @var object $top_element
1577 public $top_element;
1580 * 2D array of grade items and categories
1581 * @var array $levels
1583 public $levels;
1586 * Grade items
1587 * @var array $items
1589 public $items;
1592 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1593 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1595 * @param int $courseid The Course ID
1596 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1597 * @param bool $category_grade_last category grade item is the last child
1598 * @param array $collapsed array of collapsed categories
1599 * @param bool $nooutcomes Whether or not outcomes should be included
1601 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1602 $collapsed=null, $nooutcomes=false) {
1603 global $USER, $CFG;
1605 $this->courseid = $courseid;
1606 $this->levels = array();
1607 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1609 // get course grade tree
1610 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1612 // collapse the categories if requested
1613 if (!empty($collapsed)) {
1614 grade_tree::category_collapse($this->top_element, $collapsed);
1617 // no otucomes if requested
1618 if (!empty($nooutcomes)) {
1619 grade_tree::no_outcomes($this->top_element);
1622 // move category item to last position in category
1623 if ($category_grade_last) {
1624 grade_tree::category_grade_last($this->top_element);
1627 if ($fillers) {
1628 // inject fake categories == fillers
1629 grade_tree::inject_fillers($this->top_element, 0);
1630 // add colspans to categories and fillers
1631 grade_tree::inject_colspans($this->top_element);
1634 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1639 * Static recursive helper - removes items from collapsed categories
1641 * @param array &$element The seed of the recursion
1642 * @param array $collapsed array of collapsed categories
1644 * @return void
1646 public function category_collapse(&$element, $collapsed) {
1647 if ($element['type'] != 'category') {
1648 return;
1650 if (empty($element['children']) or count($element['children']) < 2) {
1651 return;
1654 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1655 $category_item = reset($element['children']); //keep only category item
1656 $element['children'] = array(key($element['children'])=>$category_item);
1658 } else {
1659 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1660 reset($element['children']);
1661 $first_key = key($element['children']);
1662 unset($element['children'][$first_key]);
1664 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1665 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1671 * Static recursive helper - removes all outcomes
1673 * @param array &$element The seed of the recursion
1675 * @return void
1677 public function no_outcomes(&$element) {
1678 if ($element['type'] != 'category') {
1679 return;
1681 foreach ($element['children'] as $sortorder=>$child) {
1682 if ($element['children'][$sortorder]['type'] == 'item'
1683 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1684 unset($element['children'][$sortorder]);
1686 } else if ($element['children'][$sortorder]['type'] == 'category') {
1687 grade_tree::no_outcomes($element['children'][$sortorder]);
1693 * Static recursive helper - makes the grade_item for category the last children
1695 * @param array &$element The seed of the recursion
1697 * @return void
1699 public function category_grade_last(&$element) {
1700 if (empty($element['children'])) {
1701 return;
1703 if (count($element['children']) < 2) {
1704 return;
1706 $first_item = reset($element['children']);
1707 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1708 // the category item might have been already removed
1709 $order = key($element['children']);
1710 unset($element['children'][$order]);
1711 $element['children'][$order] =& $first_item;
1713 foreach ($element['children'] as $sortorder => $child) {
1714 grade_tree::category_grade_last($element['children'][$sortorder]);
1719 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1721 * @param array &$levels The levels of the grade tree through which to recurse
1722 * @param array &$element The seed of the recursion
1723 * @param int $depth How deep are we?
1724 * @return void
1726 public function fill_levels(&$levels, &$element, $depth) {
1727 if (!array_key_exists($depth, $levels)) {
1728 $levels[$depth] = array();
1731 // prepare unique identifier
1732 if ($element['type'] == 'category') {
1733 $element['eid'] = 'c'.$element['object']->id;
1734 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1735 $element['eid'] = 'i'.$element['object']->id;
1736 $this->items[$element['object']->id] =& $element['object'];
1739 $levels[$depth][] =& $element;
1740 $depth++;
1741 if (empty($element['children'])) {
1742 return;
1744 $prev = 0;
1745 foreach ($element['children'] as $sortorder=>$child) {
1746 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1747 $element['children'][$sortorder]['prev'] = $prev;
1748 $element['children'][$sortorder]['next'] = 0;
1749 if ($prev) {
1750 $element['children'][$prev]['next'] = $sortorder;
1752 $prev = $sortorder;
1757 * Static recursive helper - makes full tree (all leafes are at the same level)
1759 * @param array &$element The seed of the recursion
1760 * @param int $depth How deep are we?
1762 * @return int
1764 public function inject_fillers(&$element, $depth) {
1765 $depth++;
1767 if (empty($element['children'])) {
1768 return $depth;
1770 $chdepths = array();
1771 $chids = array_keys($element['children']);
1772 $last_child = end($chids);
1773 $first_child = reset($chids);
1775 foreach ($chids as $chid) {
1776 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1778 arsort($chdepths);
1780 $maxdepth = reset($chdepths);
1781 foreach ($chdepths as $chid=>$chd) {
1782 if ($chd == $maxdepth) {
1783 continue;
1785 for ($i=0; $i < $maxdepth-$chd; $i++) {
1786 if ($chid == $first_child) {
1787 $type = 'fillerfirst';
1788 } else if ($chid == $last_child) {
1789 $type = 'fillerlast';
1790 } else {
1791 $type = 'filler';
1793 $oldchild =& $element['children'][$chid];
1794 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1795 'eid'=>'', 'depth'=>$element['object']->depth,
1796 'children'=>array($oldchild));
1800 return $maxdepth;
1804 * Static recursive helper - add colspan information into categories
1806 * @param array &$element The seed of the recursion
1808 * @return int
1810 public function inject_colspans(&$element) {
1811 if (empty($element['children'])) {
1812 return 1;
1814 $count = 0;
1815 foreach ($element['children'] as $key=>$child) {
1816 $count += grade_tree::inject_colspans($element['children'][$key]);
1818 $element['colspan'] = $count;
1819 return $count;
1823 * Parses the array in search of a given eid and returns a element object with
1824 * information about the element it has found.
1825 * @param int $eid Gradetree Element ID
1826 * @return object element
1828 public function locate_element($eid) {
1829 // it is a grade - construct a new object
1830 if (strpos($eid, 'n') === 0) {
1831 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1832 return null;
1835 $itemid = $matches[1];
1836 $userid = $matches[2];
1838 //extra security check - the grade item must be in this tree
1839 if (!$item_el = $this->locate_element('i'.$itemid)) {
1840 return null;
1843 // $gradea->id may be null - means does not exist yet
1844 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1846 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1847 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1849 } else if (strpos($eid, 'g') === 0) {
1850 $id = (int) substr($eid, 1);
1851 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1852 return null;
1854 //extra security check - the grade item must be in this tree
1855 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1856 return null;
1858 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1859 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1862 // it is a category or item
1863 foreach ($this->levels as $row) {
1864 foreach ($row as $element) {
1865 if ($element['type'] == 'filler') {
1866 continue;
1868 if ($element['eid'] == $eid) {
1869 return $element;
1874 return null;
1878 * Returns a well-formed XML representation of the grade-tree using recursion.
1880 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1881 * @param string $tabs The control character to use for tabs
1883 * @return string $xml
1885 public function exporttoxml($root=null, $tabs="\t") {
1886 $xml = null;
1887 $first = false;
1888 if (is_null($root)) {
1889 $root = $this->top_element;
1890 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
1891 $xml .= "<gradetree>\n";
1892 $first = true;
1895 $type = 'undefined';
1896 if (strpos($root['object']->table, 'grade_categories') !== false) {
1897 $type = 'category';
1898 } else if (strpos($root['object']->table, 'grade_items') !== false) {
1899 $type = 'item';
1900 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
1901 $type = 'outcome';
1904 $xml .= "$tabs<element type=\"$type\">\n";
1905 foreach ($root['object'] as $var => $value) {
1906 if (!is_object($value) && !is_array($value) && !empty($value)) {
1907 $xml .= "$tabs\t<$var>$value</$var>\n";
1911 if (!empty($root['children'])) {
1912 $xml .= "$tabs\t<children>\n";
1913 foreach ($root['children'] as $sortorder => $child) {
1914 $xml .= $this->exportToXML($child, $tabs."\t\t");
1916 $xml .= "$tabs\t</children>\n";
1919 $xml .= "$tabs</element>\n";
1921 if ($first) {
1922 $xml .= "</gradetree>";
1925 return $xml;
1929 * Returns a JSON representation of the grade-tree using recursion.
1931 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1932 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
1934 * @return string
1936 public function exporttojson($root=null, $tabs="\t") {
1937 $json = null;
1938 $first = false;
1939 if (is_null($root)) {
1940 $root = $this->top_element;
1941 $first = true;
1944 $name = '';
1947 if (strpos($root['object']->table, 'grade_categories') !== false) {
1948 $name = $root['object']->fullname;
1949 if ($name == '?') {
1950 $name = $root['object']->get_name();
1952 } else if (strpos($root['object']->table, 'grade_items') !== false) {
1953 $name = $root['object']->itemname;
1954 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
1955 $name = $root['object']->itemname;
1958 $json .= "$tabs {\n";
1959 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
1960 $json .= "$tabs\t \"name\": \"$name\",\n";
1962 foreach ($root['object'] as $var => $value) {
1963 if (!is_object($value) && !is_array($value) && !empty($value)) {
1964 $json .= "$tabs\t \"$var\": \"$value\",\n";
1968 $json = substr($json, 0, strrpos($json, ','));
1970 if (!empty($root['children'])) {
1971 $json .= ",\n$tabs\t\"children\": [\n";
1972 foreach ($root['children'] as $sortorder => $child) {
1973 $json .= $this->exportToJSON($child, $tabs."\t\t");
1975 $json = substr($json, 0, strrpos($json, ','));
1976 $json .= "\n$tabs\t]\n";
1979 if ($first) {
1980 $json .= "\n}";
1981 } else {
1982 $json .= "\n$tabs},\n";
1985 return $json;
1989 * Returns the array of levels
1991 * @return array
1993 public function get_levels() {
1994 return $this->levels;
1998 * Returns the array of grade items
2000 * @return array
2002 public function get_items() {
2003 return $this->items;
2007 * Returns a specific Grade Item
2009 * @param int $itemid The ID of the grade_item object
2011 * @return grade_item
2013 public function get_item($itemid) {
2014 if (array_key_exists($itemid, $this->items)) {
2015 return $this->items[$itemid];
2016 } else {
2017 return false;
2023 * Local shortcut function for creating an edit/delete button for a grade_* object.
2024 * @param string $type 'edit' or 'delete'
2025 * @param int $courseid The Course ID
2026 * @param grade_* $object The grade_* object
2027 * @return string html
2029 function grade_button($type, $courseid, $object) {
2030 global $CFG, $OUTPUT;
2031 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2032 $objectidstring = $matches[1] . 'id';
2033 } else {
2034 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2037 $strdelete = get_string('delete');
2038 $stredit = get_string('edit');
2040 if ($type == 'delete') {
2041 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2042 } else if ($type == 'edit') {
2043 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2046 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2051 * This method adds settings to the settings block for the grade system and its
2052 * plugins
2054 * @global moodle_page $PAGE
2056 function grade_extend_settings($plugininfo, $courseid) {
2057 global $PAGE;
2059 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2061 $strings = array_shift($plugininfo);
2063 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2064 foreach ($reports as $report) {
2065 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2069 if ($imports = grade_helper::get_plugins_import($courseid)) {
2070 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2071 foreach ($imports as $import) {
2072 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2076 if ($exports = grade_helper::get_plugins_export($courseid)) {
2077 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2078 foreach ($exports as $export) {
2079 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2083 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2084 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2087 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2088 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2089 foreach ($preferences as $preference) {
2090 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2094 if ($letters = grade_helper::get_info_letters($courseid)) {
2095 $letters = array_shift($letters);
2096 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2099 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2100 $outcomes = array_shift($outcomes);
2101 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2104 if ($scales = grade_helper::get_info_scales($courseid)) {
2105 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2108 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2109 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2110 foreach ($categories as $category) {
2111 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2115 if ($gradenode->contains_active_node()) {
2116 // If the gradenode is active include the settings base node (gradeadministration) in
2117 // the navbar, typcially this is ignored.
2118 $PAGE->navbar->includesettingsbase = true;
2120 // If we can get the course admin node make sure it is closed by default
2121 // as in this case the gradenode will be opened
2122 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2123 $coursenode->make_inactive();
2124 $coursenode->forceopen = false;
2130 * Grade helper class
2132 * This class provides several helpful functions that work irrespective of any
2133 * current state.
2135 * @copyright 2010 Sam Hemelryk
2136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2138 abstract class grade_helper {
2140 * Cached manage settings info {@see get_info_settings}
2141 * @var grade_plugin_info|false
2143 protected static $managesetting = null;
2145 * Cached grade report plugins {@see get_plugins_reports}
2146 * @var array|false
2148 protected static $gradereports = null;
2150 * Cached grade report plugins preferences {@see get_info_scales}
2151 * @var array|false
2153 protected static $gradereportpreferences = null;
2155 * Cached scale info {@see get_info_scales}
2156 * @var grade_plugin_info|false
2158 protected static $scaleinfo = null;
2160 * Cached outcome info {@see get_info_outcomes}
2161 * @var grade_plugin_info|false
2163 protected static $outcomeinfo = null;
2165 * Cached info on edit structure {@see get_info_edit_structure}
2166 * @var array|false
2168 protected static $edittree = null;
2170 * Cached leftter info {@see get_info_letters}
2171 * @var grade_plugin_info|false
2173 protected static $letterinfo = null;
2175 * Cached grade import plugins {@see get_plugins_import}
2176 * @var array|false
2178 protected static $importplugins = null;
2180 * Cached grade export plugins {@see get_plugins_export}
2181 * @var array|false
2183 protected static $exportplugins = null;
2185 * Cached grade plugin strings
2186 * @var array
2188 protected static $pluginstrings = null;
2191 * Gets strings commonly used by the describe plugins
2193 * report => get_string('view'),
2194 * edittree => get_string('edittree', 'grades'),
2195 * scale => get_string('scales'),
2196 * outcome => get_string('outcomes', 'grades'),
2197 * letter => get_string('letters', 'grades'),
2198 * export => get_string('export', 'grades'),
2199 * import => get_string('import'),
2200 * preferences => get_string('mypreferences', 'grades'),
2201 * settings => get_string('settings')
2203 * @return array
2205 public static function get_plugin_strings() {
2206 if (self::$pluginstrings === null) {
2207 self::$pluginstrings = array(
2208 'report' => get_string('view'),
2209 'edittree' => get_string('edittree', 'grades'),
2210 'scale' => get_string('scales'),
2211 'outcome' => get_string('outcomes', 'grades'),
2212 'letter' => get_string('letters', 'grades'),
2213 'export' => get_string('export', 'grades'),
2214 'import' => get_string('import'),
2215 'preferences' => get_string('mypreferences', 'grades'),
2216 'settings' => get_string('settings')
2219 return self::$pluginstrings;
2222 * Get grade_plugin_info object for managing settings if the user can
2224 * @param int $courseid
2225 * @return grade_plugin_info
2227 public static function get_info_manage_settings($courseid) {
2228 if (self::$managesetting !== null) {
2229 return self::$managesetting;
2231 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2232 if (has_capability('moodle/course:update', $context)) {
2233 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2234 } else {
2235 self::$managesetting = false;
2237 return self::$managesetting;
2240 * Returns an array of plugin reports as grade_plugin_info objects
2242 * @param int $courseid
2243 * @return array
2245 public static function get_plugins_reports($courseid) {
2246 global $SITE;
2248 if (self::$gradereports !== null) {
2249 return self::$gradereports;
2251 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2252 $gradereports = array();
2253 $gradepreferences = array();
2254 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2255 //some reports make no sense if we're not within a course
2256 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2257 continue;
2260 // Remove ones we can't see
2261 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2262 continue;
2265 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2266 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2267 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2269 // Add link to preferences tab if such a page exists
2270 if (file_exists($plugindir.'/preferences.php')) {
2271 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2272 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2275 if (count($gradereports) == 0) {
2276 $gradereports = false;
2277 $gradepreferences = false;
2278 } else if (count($gradepreferences) == 0) {
2279 $gradepreferences = false;
2280 asort($gradereports);
2281 } else {
2282 asort($gradereports);
2283 asort($gradepreferences);
2285 self::$gradereports = $gradereports;
2286 self::$gradereportpreferences = $gradepreferences;
2287 return self::$gradereports;
2290 * Returns an array of grade plugin report preferences for plugin reports that
2291 * support preferences
2292 * @param int $courseid
2293 * @return array
2295 public static function get_plugins_report_preferences($courseid) {
2296 if (self::$gradereportpreferences !== null) {
2297 return self::$gradereportpreferences;
2299 self::get_plugins_reports($courseid);
2300 return self::$gradereportpreferences;
2303 * Get information on scales
2304 * @param int $courseid
2305 * @return grade_plugin_info
2307 public static function get_info_scales($courseid) {
2308 if (self::$scaleinfo !== null) {
2309 return self::$scaleinfo;
2311 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2312 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2313 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2314 } else {
2315 self::$scaleinfo = false;
2317 return self::$scaleinfo;
2320 * Get information on outcomes
2321 * @param int $courseid
2322 * @return grade_plugin_info
2324 public static function get_info_outcomes($courseid) {
2325 global $CFG, $SITE;
2327 if (self::$outcomeinfo !== null) {
2328 return self::$outcomeinfo;
2330 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2331 $canmanage = has_capability('moodle/grade:manage', $context);
2332 $canupdate = has_capability('moodle/course:update', $context);
2333 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2334 $outcomes = array();
2335 if ($canupdate) {
2336 if ($courseid!=$SITE->id) {
2337 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2338 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2340 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2341 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2342 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2343 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2344 } else {
2345 if ($courseid!=$SITE->id) {
2346 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2347 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2350 self::$outcomeinfo = $outcomes;
2351 } else {
2352 self::$outcomeinfo = false;
2354 return self::$outcomeinfo;
2357 * Get information on editing structures
2358 * @param int $courseid
2359 * @return array
2361 public static function get_info_edit_structure($courseid) {
2362 if (self::$edittree !== null) {
2363 return self::$edittree;
2365 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2366 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2367 self::$edittree = array(
2368 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2369 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2371 } else {
2372 self::$edittree = false;
2374 return self::$edittree;
2377 * Get information on letters
2378 * @param int $courseid
2379 * @return array
2381 public static function get_info_letters($courseid) {
2382 if (self::$letterinfo !== null) {
2383 return self::$letterinfo;
2385 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2386 $canmanage = has_capability('moodle/grade:manage', $context);
2387 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2388 if ($canmanage || $canmanageletters) {
2389 self::$letterinfo = array(
2390 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2391 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2393 } else {
2394 self::$letterinfo = false;
2396 return self::$letterinfo;
2399 * Get information import plugins
2400 * @param int $courseid
2401 * @return array
2403 public static function get_plugins_import($courseid) {
2404 global $CFG;
2406 if (self::$importplugins !== null) {
2407 return self::$importplugins;
2409 $importplugins = array();
2410 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2412 if (has_capability('moodle/grade:import', $context)) {
2413 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2414 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2415 continue;
2417 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2418 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2419 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2423 if ($CFG->gradepublishing) {
2424 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2425 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2429 if (count($importplugins) > 0) {
2430 asort($importplugins);
2431 self::$importplugins = $importplugins;
2432 } else {
2433 self::$importplugins = false;
2435 return self::$importplugins;
2438 * Get information export plugins
2439 * @param int $courseid
2440 * @return array
2442 public static function get_plugins_export($courseid) {
2443 global $CFG;
2445 if (self::$exportplugins !== null) {
2446 return self::$exportplugins;
2448 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2449 $exportplugins = array();
2450 if (has_capability('moodle/grade:export', $context)) {
2451 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2452 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2453 continue;
2455 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2456 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2457 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2460 if ($CFG->gradepublishing) {
2461 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2462 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2465 if (count($exportplugins) > 0) {
2466 asort($exportplugins);
2467 self::$exportplugins = $exportplugins;
2468 } else {
2469 self::$exportplugins = false;
2471 return self::$exportplugins;