Merge branch 'MDL-30683' of git://github.com/timhunt/moodle
[moodle.git] / grade / lib.php
blob593a250a16f3ad63b45d520f561ae154de72e2f7
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_PLUGIN);
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_PLUGIN);
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 * Reference to modinfo for current course (for performance, to save
1007 * retrieving it from courseid every time). Not actually set except for
1008 * the grade_tree type.
1009 * @var course_modinfo
1011 public $modinfo;
1014 * 1D array of grade items only
1016 public $items;
1019 * Returns icon of element
1021 * @param array &$element An array representing an element in the grade_tree
1022 * @param bool $spacerifnone return spacer if no icon found
1024 * @return string icon or spacer
1026 public function get_element_icon(&$element, $spacerifnone=false) {
1027 global $CFG, $OUTPUT;
1029 switch ($element['type']) {
1030 case 'item':
1031 case 'courseitem':
1032 case 'categoryitem':
1033 $is_course = $element['object']->is_course_item();
1034 $is_category = $element['object']->is_category_item();
1035 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1036 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1037 $is_outcome = !empty($element['object']->outcomeid);
1039 if ($element['object']->is_calculated()) {
1040 $strcalc = get_string('calculatedgrade', 'grades');
1041 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1042 s($strcalc).'" alt="'.s($strcalc).'"/>';
1044 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1045 if ($category = $element['object']->get_item_category()) {
1046 switch ($category->aggregation) {
1047 case GRADE_AGGREGATE_MEAN:
1048 case GRADE_AGGREGATE_MEDIAN:
1049 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1050 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1051 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1052 $stragg = get_string('aggregation', 'grades');
1053 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1054 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1055 case GRADE_AGGREGATE_SUM:
1056 $stragg = get_string('aggregation', 'grades');
1057 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1058 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1062 } else if ($element['object']->itemtype == 'mod') {
1063 //prevent outcomes being displaying the same icon as the activity they are attached to
1064 if ($is_outcome) {
1065 $stroutcome = s(get_string('outcome', 'grades'));
1066 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1067 'class="icon itemicon" title="'.$stroutcome.
1068 '" alt="'.$stroutcome.'"/>';
1069 } else {
1070 $strmodname = get_string('modulename', $element['object']->itemmodule);
1071 return '<img src="'.$OUTPUT->pix_url('icon',
1072 $element['object']->itemmodule) . '" ' .
1073 'class="icon itemicon" title="' .s($strmodname).
1074 '" alt="' .s($strmodname).'"/>';
1076 } else if ($element['object']->itemtype == 'manual') {
1077 if ($element['object']->is_outcome_item()) {
1078 $stroutcome = get_string('outcome', 'grades');
1079 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1080 'class="icon itemicon" title="'.s($stroutcome).
1081 '" alt="'.s($stroutcome).'"/>';
1082 } else {
1083 $strmanual = get_string('manualitem', 'grades');
1084 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1085 'class="icon itemicon" title="'.s($strmanual).
1086 '" alt="'.s($strmanual).'"/>';
1089 break;
1091 case 'category':
1092 $strcat = get_string('category', 'grades');
1093 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1094 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1097 if ($spacerifnone) {
1098 return $OUTPUT->spacer().' ';
1099 } else {
1100 return '';
1105 * Returns name of element optionally with icon and link
1107 * @param array &$element An array representing an element in the grade_tree
1108 * @param bool $withlink Whether or not this header has a link
1109 * @param bool $icon Whether or not to display an icon with this header
1110 * @param bool $spacerifnone return spacer if no icon found
1112 * @return string header
1114 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1115 $header = '';
1117 if ($icon) {
1118 $header .= $this->get_element_icon($element, $spacerifnone);
1121 $header .= $element['object']->get_name();
1123 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1124 $element['type'] != 'courseitem') {
1125 return $header;
1128 if ($withlink) {
1129 $url = $this->get_activity_link($element);
1130 if ($url) {
1131 $a = new stdClass();
1132 $a->name = get_string('modulename', $element['object']->itemmodule);
1133 $title = get_string('linktoactivity', 'grades', $a);
1135 $header = html_writer::link($url, $header, array('title' => $title));
1139 return $header;
1142 private function get_activity_link($element) {
1143 global $CFG;
1144 /** @var array static cache of the grade.php file existence flags */
1145 static $hasgradephp = array();
1147 $itemtype = $element['object']->itemtype;
1148 $itemmodule = $element['object']->itemmodule;
1149 $iteminstance = $element['object']->iteminstance;
1150 $itemnumber = $element['object']->itemnumber;
1152 // Links only for module items that have valid instance, module and are
1153 // called from grade_tree with valid modinfo
1154 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1155 return null;
1158 // Get $cm efficiently and with visibility information using modinfo
1159 $instances = $this->modinfo->get_instances();
1160 if (empty($instances[$itemmodule][$iteminstance])) {
1161 return null;
1163 $cm = $instances[$itemmodule][$iteminstance];
1165 // Do not add link if activity is not visible to the current user
1166 if (!$cm->uservisible) {
1167 return null;
1170 if (!array_key_exists($itemmodule, $hasgradephp)) {
1171 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1172 $hasgradephp[$itemmodule] = true;
1173 } else {
1174 $hasgradephp[$itemmodule] = false;
1178 // If module has grade.php, link to that, otherwise view.php
1179 if ($hasgradephp[$itemmodule]) {
1180 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1181 if (isset($element['userid'])) {
1182 $args['userid'] = $element['userid'];
1184 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1185 } else {
1186 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1191 * Returns URL of a page that is supposed to contain detailed grade analysis
1193 * At the moment, only activity modules are supported. The method generates link
1194 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1195 * gradeid and userid. If the grade.php does not exist, null is returned.
1197 * @return moodle_url|null URL or null if unable to construct it
1199 public function get_grade_analysis_url(grade_grade $grade) {
1200 global $CFG;
1201 /** @var array static cache of the grade.php file existence flags */
1202 static $hasgradephp = array();
1204 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1205 throw new coding_exception('Passed grade without the associated grade item');
1207 $item = $grade->grade_item;
1209 if (!$item->is_external_item()) {
1210 // at the moment, only activity modules are supported
1211 return null;
1213 if ($item->itemtype !== 'mod') {
1214 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1216 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1217 return null;
1220 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1221 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1222 $hasgradephp[$item->itemmodule] = true;
1223 } else {
1224 $hasgradephp[$item->itemmodule] = false;
1228 if (!$hasgradephp[$item->itemmodule]) {
1229 return null;
1232 $instances = $this->modinfo->get_instances();
1233 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1234 return null;
1236 $cm = $instances[$item->itemmodule][$item->iteminstance];
1237 if (!$cm->uservisible) {
1238 return null;
1241 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1242 'id' => $cm->id,
1243 'itemid' => $item->id,
1244 'itemnumber' => $item->itemnumber,
1245 'gradeid' => $grade->id,
1246 'userid' => $grade->userid,
1249 return $url;
1253 * Returns an action icon leading to the grade analysis page
1255 * @param grade_grade $grade
1256 * @return string
1258 public function get_grade_analysis_icon(grade_grade $grade) {
1259 global $OUTPUT;
1261 $url = $this->get_grade_analysis_url($grade);
1262 if (is_null($url)) {
1263 return '';
1266 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1267 get_string('gradeanalysis', 'core_grades')));
1271 * Returns the grade eid - the grade may not exist yet.
1273 * @param grade_grade $grade_grade A grade_grade object
1275 * @return string eid
1277 public function get_grade_eid($grade_grade) {
1278 if (empty($grade_grade->id)) {
1279 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1280 } else {
1281 return 'g'.$grade_grade->id;
1286 * Returns the grade_item eid
1287 * @param grade_item $grade_item A grade_item object
1288 * @return string eid
1290 public function get_item_eid($grade_item) {
1291 return 'i'.$grade_item->id;
1295 * Given a grade_tree element, returns an array of parameters
1296 * used to build an icon for that element.
1298 * @param array $element An array representing an element in the grade_tree
1300 * @return array
1302 public function get_params_for_iconstr($element) {
1303 $strparams = new stdClass();
1304 $strparams->category = '';
1305 $strparams->itemname = '';
1306 $strparams->itemmodule = '';
1308 if (!method_exists($element['object'], 'get_name')) {
1309 return $strparams;
1312 $strparams->itemname = html_to_text($element['object']->get_name());
1314 // If element name is categorytotal, get the name of the parent category
1315 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1316 $parent = $element['object']->get_parent_category();
1317 $strparams->category = $parent->get_name() . ' ';
1318 } else {
1319 $strparams->category = '';
1322 $strparams->itemmodule = null;
1323 if (isset($element['object']->itemmodule)) {
1324 $strparams->itemmodule = $element['object']->itemmodule;
1326 return $strparams;
1330 * Return edit icon for give element
1332 * @param array $element An array representing an element in the grade_tree
1333 * @param object $gpr A grade_plugin_return object
1335 * @return string
1337 public function get_edit_icon($element, $gpr) {
1338 global $CFG, $OUTPUT;
1340 if (!has_capability('moodle/grade:manage', $this->context)) {
1341 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1342 // oki - let them override grade
1343 } else {
1344 return '';
1348 static $strfeedback = null;
1349 static $streditgrade = null;
1350 if (is_null($streditgrade)) {
1351 $streditgrade = get_string('editgrade', 'grades');
1352 $strfeedback = get_string('feedback');
1355 $strparams = $this->get_params_for_iconstr($element);
1357 $object = $element['object'];
1359 switch ($element['type']) {
1360 case 'item':
1361 case 'categoryitem':
1362 case 'courseitem':
1363 $stredit = get_string('editverbose', 'grades', $strparams);
1364 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1365 $url = new moodle_url('/grade/edit/tree/item.php',
1366 array('courseid' => $this->courseid, 'id' => $object->id));
1367 } else {
1368 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1369 array('courseid' => $this->courseid, 'id' => $object->id));
1371 break;
1373 case 'category':
1374 $stredit = get_string('editverbose', 'grades', $strparams);
1375 $url = new moodle_url('/grade/edit/tree/category.php',
1376 array('courseid' => $this->courseid, 'id' => $object->id));
1377 break;
1379 case 'grade':
1380 $stredit = $streditgrade;
1381 if (empty($object->id)) {
1382 $url = new moodle_url('/grade/edit/tree/grade.php',
1383 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1384 } else {
1385 $url = new moodle_url('/grade/edit/tree/grade.php',
1386 array('courseid' => $this->courseid, 'id' => $object->id));
1388 if (!empty($object->feedback)) {
1389 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1391 break;
1393 default:
1394 $url = null;
1397 if ($url) {
1398 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1400 } else {
1401 return '';
1406 * Return hiding icon for give element
1408 * @param array $element An array representing an element in the grade_tree
1409 * @param object $gpr A grade_plugin_return object
1411 * @return string
1413 public function get_hiding_icon($element, $gpr) {
1414 global $CFG, $OUTPUT;
1416 if (!has_capability('moodle/grade:manage', $this->context) and
1417 !has_capability('moodle/grade:hide', $this->context)) {
1418 return '';
1421 $strparams = $this->get_params_for_iconstr($element);
1422 $strshow = get_string('showverbose', 'grades', $strparams);
1423 $strhide = get_string('hideverbose', 'grades', $strparams);
1425 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1426 $url = $gpr->add_url_params($url);
1428 if ($element['object']->is_hidden()) {
1429 $type = 'show';
1430 $tooltip = $strshow;
1432 // Change the icon and add a tooltip showing the date
1433 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1434 $type = 'hiddenuntil';
1435 $tooltip = get_string('hiddenuntildate', 'grades',
1436 userdate($element['object']->get_hidden()));
1439 $url->param('action', 'show');
1441 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1443 } else {
1444 $url->param('action', 'hide');
1445 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1448 return $hideicon;
1452 * Return locking icon for given element
1454 * @param array $element An array representing an element in the grade_tree
1455 * @param object $gpr A grade_plugin_return object
1457 * @return string
1459 public function get_locking_icon($element, $gpr) {
1460 global $CFG, $OUTPUT;
1462 $strparams = $this->get_params_for_iconstr($element);
1463 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1464 $strlock = get_string('lockverbose', 'grades', $strparams);
1466 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1467 $url = $gpr->add_url_params($url);
1469 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1470 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1471 $strparamobj = new stdClass();
1472 $strparamobj->itemname = $element['object']->grade_item->itemname;
1473 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1475 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1477 } else if ($element['object']->is_locked()) {
1478 $type = 'unlock';
1479 $tooltip = $strunlock;
1481 // Change the icon and add a tooltip showing the date
1482 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1483 $type = 'locktime';
1484 $tooltip = get_string('locktimedate', 'grades',
1485 userdate($element['object']->get_locktime()));
1488 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1489 $action = '';
1490 } else {
1491 $url->param('action', 'unlock');
1492 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1495 } else {
1496 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1497 $action = '';
1498 } else {
1499 $url->param('action', 'lock');
1500 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1504 return $action;
1508 * Return calculation icon for given element
1510 * @param array $element An array representing an element in the grade_tree
1511 * @param object $gpr A grade_plugin_return object
1513 * @return string
1515 public function get_calculation_icon($element, $gpr) {
1516 global $CFG, $OUTPUT;
1517 if (!has_capability('moodle/grade:manage', $this->context)) {
1518 return '';
1521 $type = $element['type'];
1522 $object = $element['object'];
1524 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1525 $strparams = $this->get_params_for_iconstr($element);
1526 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1528 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1529 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1531 // show calculation icon only when calculation possible
1532 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1533 if ($object->is_calculated()) {
1534 $icon = 't/calc';
1535 } else {
1536 $icon = 't/calc_off';
1539 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1540 $url = $gpr->add_url_params($url);
1541 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1545 return '';
1550 * Flat structure similar to grade tree.
1552 * @uses grade_structure
1553 * @package moodlecore
1554 * @copyright 2009 Nicolas Connault
1555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1557 class grade_seq extends grade_structure {
1560 * 1D array of elements
1562 public $elements;
1565 * Constructor, retrieves and stores array of all grade_category and grade_item
1566 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1568 * @param int $courseid The course id
1569 * @param bool $category_grade_last category grade item is the last child
1570 * @param bool $nooutcomes Whether or not outcomes should be included
1572 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1573 global $USER, $CFG;
1575 $this->courseid = $courseid;
1576 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1578 // get course grade tree
1579 $top_element = grade_category::fetch_course_tree($courseid, true);
1581 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1583 foreach ($this->elements as $key=>$unused) {
1584 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1589 * Static recursive helper - makes the grade_item for category the last children
1591 * @param array &$element The seed of the recursion
1592 * @param bool $category_grade_last category grade item is the last child
1593 * @param bool $nooutcomes Whether or not outcomes should be included
1595 * @return array
1597 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1598 if (empty($element['children'])) {
1599 return array();
1601 $children = array();
1603 foreach ($element['children'] as $sortorder=>$unused) {
1604 if ($nooutcomes and $element['type'] != 'category' and
1605 $element['children'][$sortorder]['object']->is_outcome_item()) {
1606 continue;
1608 $children[] = $element['children'][$sortorder];
1610 unset($element['children']);
1612 if ($category_grade_last and count($children) > 1) {
1613 $cat_item = array_shift($children);
1614 array_push($children, $cat_item);
1617 $result = array();
1618 foreach ($children as $child) {
1619 if ($child['type'] == 'category') {
1620 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1621 } else {
1622 $child['eid'] = 'i'.$child['object']->id;
1623 $result[$child['object']->id] = $child;
1627 return $result;
1631 * Parses the array in search of a given eid and returns a element object with
1632 * information about the element it has found.
1634 * @param int $eid Gradetree Element ID
1636 * @return object element
1638 public function locate_element($eid) {
1639 // it is a grade - construct a new object
1640 if (strpos($eid, 'n') === 0) {
1641 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1642 return null;
1645 $itemid = $matches[1];
1646 $userid = $matches[2];
1648 //extra security check - the grade item must be in this tree
1649 if (!$item_el = $this->locate_element('i'.$itemid)) {
1650 return null;
1653 // $gradea->id may be null - means does not exist yet
1654 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1656 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1657 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1659 } else if (strpos($eid, 'g') === 0) {
1660 $id = (int) substr($eid, 1);
1661 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1662 return null;
1664 //extra security check - the grade item must be in this tree
1665 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1666 return null;
1668 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1669 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1672 // it is a category or item
1673 foreach ($this->elements as $element) {
1674 if ($element['eid'] == $eid) {
1675 return $element;
1679 return null;
1684 * This class represents a complete tree of categories, grade_items and final grades,
1685 * organises as an array primarily, but which can also be converted to other formats.
1686 * It has simple method calls with complex implementations, allowing for easy insertion,
1687 * deletion and moving of items and categories within the tree.
1689 * @uses grade_structure
1690 * @package moodlecore
1691 * @copyright 2009 Nicolas Connault
1692 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1694 class grade_tree extends grade_structure {
1697 * The basic representation of the tree as a hierarchical, 3-tiered array.
1698 * @var object $top_element
1700 public $top_element;
1703 * 2D array of grade items and categories
1704 * @var array $levels
1706 public $levels;
1709 * Grade items
1710 * @var array $items
1712 public $items;
1715 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1716 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1718 * @param int $courseid The Course ID
1719 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1720 * @param bool $category_grade_last category grade item is the last child
1721 * @param array $collapsed array of collapsed categories
1722 * @param bool $nooutcomes Whether or not outcomes should be included
1724 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1725 $collapsed=null, $nooutcomes=false) {
1726 global $USER, $CFG, $COURSE, $DB;
1728 $this->courseid = $courseid;
1729 $this->levels = array();
1730 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1732 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1733 $course = $COURSE;
1734 } else {
1735 $course = $DB->get_record('course', array('id' => $this->courseid));
1737 $this->modinfo = get_fast_modinfo($course);
1739 // get course grade tree
1740 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1742 // collapse the categories if requested
1743 if (!empty($collapsed)) {
1744 grade_tree::category_collapse($this->top_element, $collapsed);
1747 // no otucomes if requested
1748 if (!empty($nooutcomes)) {
1749 grade_tree::no_outcomes($this->top_element);
1752 // move category item to last position in category
1753 if ($category_grade_last) {
1754 grade_tree::category_grade_last($this->top_element);
1757 if ($fillers) {
1758 // inject fake categories == fillers
1759 grade_tree::inject_fillers($this->top_element, 0);
1760 // add colspans to categories and fillers
1761 grade_tree::inject_colspans($this->top_element);
1764 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1769 * Static recursive helper - removes items from collapsed categories
1771 * @param array &$element The seed of the recursion
1772 * @param array $collapsed array of collapsed categories
1774 * @return void
1776 public function category_collapse(&$element, $collapsed) {
1777 if ($element['type'] != 'category') {
1778 return;
1780 if (empty($element['children']) or count($element['children']) < 2) {
1781 return;
1784 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1785 $category_item = reset($element['children']); //keep only category item
1786 $element['children'] = array(key($element['children'])=>$category_item);
1788 } else {
1789 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1790 reset($element['children']);
1791 $first_key = key($element['children']);
1792 unset($element['children'][$first_key]);
1794 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1795 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1801 * Static recursive helper - removes all outcomes
1803 * @param array &$element The seed of the recursion
1805 * @return void
1807 public function no_outcomes(&$element) {
1808 if ($element['type'] != 'category') {
1809 return;
1811 foreach ($element['children'] as $sortorder=>$child) {
1812 if ($element['children'][$sortorder]['type'] == 'item'
1813 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1814 unset($element['children'][$sortorder]);
1816 } else if ($element['children'][$sortorder]['type'] == 'category') {
1817 grade_tree::no_outcomes($element['children'][$sortorder]);
1823 * Static recursive helper - makes the grade_item for category the last children
1825 * @param array &$element The seed of the recursion
1827 * @return void
1829 public function category_grade_last(&$element) {
1830 if (empty($element['children'])) {
1831 return;
1833 if (count($element['children']) < 2) {
1834 return;
1836 $first_item = reset($element['children']);
1837 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1838 // the category item might have been already removed
1839 $order = key($element['children']);
1840 unset($element['children'][$order]);
1841 $element['children'][$order] =& $first_item;
1843 foreach ($element['children'] as $sortorder => $child) {
1844 grade_tree::category_grade_last($element['children'][$sortorder]);
1849 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1851 * @param array &$levels The levels of the grade tree through which to recurse
1852 * @param array &$element The seed of the recursion
1853 * @param int $depth How deep are we?
1854 * @return void
1856 public function fill_levels(&$levels, &$element, $depth) {
1857 if (!array_key_exists($depth, $levels)) {
1858 $levels[$depth] = array();
1861 // prepare unique identifier
1862 if ($element['type'] == 'category') {
1863 $element['eid'] = 'c'.$element['object']->id;
1864 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1865 $element['eid'] = 'i'.$element['object']->id;
1866 $this->items[$element['object']->id] =& $element['object'];
1869 $levels[$depth][] =& $element;
1870 $depth++;
1871 if (empty($element['children'])) {
1872 return;
1874 $prev = 0;
1875 foreach ($element['children'] as $sortorder=>$child) {
1876 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1877 $element['children'][$sortorder]['prev'] = $prev;
1878 $element['children'][$sortorder]['next'] = 0;
1879 if ($prev) {
1880 $element['children'][$prev]['next'] = $sortorder;
1882 $prev = $sortorder;
1887 * Static recursive helper - makes full tree (all leafes are at the same level)
1889 * @param array &$element The seed of the recursion
1890 * @param int $depth How deep are we?
1892 * @return int
1894 public function inject_fillers(&$element, $depth) {
1895 $depth++;
1897 if (empty($element['children'])) {
1898 return $depth;
1900 $chdepths = array();
1901 $chids = array_keys($element['children']);
1902 $last_child = end($chids);
1903 $first_child = reset($chids);
1905 foreach ($chids as $chid) {
1906 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1908 arsort($chdepths);
1910 $maxdepth = reset($chdepths);
1911 foreach ($chdepths as $chid=>$chd) {
1912 if ($chd == $maxdepth) {
1913 continue;
1915 for ($i=0; $i < $maxdepth-$chd; $i++) {
1916 if ($chid == $first_child) {
1917 $type = 'fillerfirst';
1918 } else if ($chid == $last_child) {
1919 $type = 'fillerlast';
1920 } else {
1921 $type = 'filler';
1923 $oldchild =& $element['children'][$chid];
1924 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1925 'eid'=>'', 'depth'=>$element['object']->depth,
1926 'children'=>array($oldchild));
1930 return $maxdepth;
1934 * Static recursive helper - add colspan information into categories
1936 * @param array &$element The seed of the recursion
1938 * @return int
1940 public function inject_colspans(&$element) {
1941 if (empty($element['children'])) {
1942 return 1;
1944 $count = 0;
1945 foreach ($element['children'] as $key=>$child) {
1946 $count += grade_tree::inject_colspans($element['children'][$key]);
1948 $element['colspan'] = $count;
1949 return $count;
1953 * Parses the array in search of a given eid and returns a element object with
1954 * information about the element it has found.
1955 * @param int $eid Gradetree Element ID
1956 * @return object element
1958 public function locate_element($eid) {
1959 // it is a grade - construct a new object
1960 if (strpos($eid, 'n') === 0) {
1961 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1962 return null;
1965 $itemid = $matches[1];
1966 $userid = $matches[2];
1968 //extra security check - the grade item must be in this tree
1969 if (!$item_el = $this->locate_element('i'.$itemid)) {
1970 return null;
1973 // $gradea->id may be null - means does not exist yet
1974 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1976 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1977 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1979 } else if (strpos($eid, 'g') === 0) {
1980 $id = (int) substr($eid, 1);
1981 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1982 return null;
1984 //extra security check - the grade item must be in this tree
1985 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1986 return null;
1988 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1989 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1992 // it is a category or item
1993 foreach ($this->levels as $row) {
1994 foreach ($row as $element) {
1995 if ($element['type'] == 'filler') {
1996 continue;
1998 if ($element['eid'] == $eid) {
1999 return $element;
2004 return null;
2008 * Returns a well-formed XML representation of the grade-tree using recursion.
2010 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2011 * @param string $tabs The control character to use for tabs
2013 * @return string $xml
2015 public function exporttoxml($root=null, $tabs="\t") {
2016 $xml = null;
2017 $first = false;
2018 if (is_null($root)) {
2019 $root = $this->top_element;
2020 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2021 $xml .= "<gradetree>\n";
2022 $first = true;
2025 $type = 'undefined';
2026 if (strpos($root['object']->table, 'grade_categories') !== false) {
2027 $type = 'category';
2028 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2029 $type = 'item';
2030 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2031 $type = 'outcome';
2034 $xml .= "$tabs<element type=\"$type\">\n";
2035 foreach ($root['object'] as $var => $value) {
2036 if (!is_object($value) && !is_array($value) && !empty($value)) {
2037 $xml .= "$tabs\t<$var>$value</$var>\n";
2041 if (!empty($root['children'])) {
2042 $xml .= "$tabs\t<children>\n";
2043 foreach ($root['children'] as $sortorder => $child) {
2044 $xml .= $this->exportToXML($child, $tabs."\t\t");
2046 $xml .= "$tabs\t</children>\n";
2049 $xml .= "$tabs</element>\n";
2051 if ($first) {
2052 $xml .= "</gradetree>";
2055 return $xml;
2059 * Returns a JSON representation of the grade-tree using recursion.
2061 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2062 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2064 * @return string
2066 public function exporttojson($root=null, $tabs="\t") {
2067 $json = null;
2068 $first = false;
2069 if (is_null($root)) {
2070 $root = $this->top_element;
2071 $first = true;
2074 $name = '';
2077 if (strpos($root['object']->table, 'grade_categories') !== false) {
2078 $name = $root['object']->fullname;
2079 if ($name == '?') {
2080 $name = $root['object']->get_name();
2082 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2083 $name = $root['object']->itemname;
2084 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2085 $name = $root['object']->itemname;
2088 $json .= "$tabs {\n";
2089 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2090 $json .= "$tabs\t \"name\": \"$name\",\n";
2092 foreach ($root['object'] as $var => $value) {
2093 if (!is_object($value) && !is_array($value) && !empty($value)) {
2094 $json .= "$tabs\t \"$var\": \"$value\",\n";
2098 $json = substr($json, 0, strrpos($json, ','));
2100 if (!empty($root['children'])) {
2101 $json .= ",\n$tabs\t\"children\": [\n";
2102 foreach ($root['children'] as $sortorder => $child) {
2103 $json .= $this->exportToJSON($child, $tabs."\t\t");
2105 $json = substr($json, 0, strrpos($json, ','));
2106 $json .= "\n$tabs\t]\n";
2109 if ($first) {
2110 $json .= "\n}";
2111 } else {
2112 $json .= "\n$tabs},\n";
2115 return $json;
2119 * Returns the array of levels
2121 * @return array
2123 public function get_levels() {
2124 return $this->levels;
2128 * Returns the array of grade items
2130 * @return array
2132 public function get_items() {
2133 return $this->items;
2137 * Returns a specific Grade Item
2139 * @param int $itemid The ID of the grade_item object
2141 * @return grade_item
2143 public function get_item($itemid) {
2144 if (array_key_exists($itemid, $this->items)) {
2145 return $this->items[$itemid];
2146 } else {
2147 return false;
2153 * Local shortcut function for creating an edit/delete button for a grade_* object.
2154 * @param string $type 'edit' or 'delete'
2155 * @param int $courseid The Course ID
2156 * @param grade_* $object The grade_* object
2157 * @return string html
2159 function grade_button($type, $courseid, $object) {
2160 global $CFG, $OUTPUT;
2161 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2162 $objectidstring = $matches[1] . 'id';
2163 } else {
2164 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2167 $strdelete = get_string('delete');
2168 $stredit = get_string('edit');
2170 if ($type == 'delete') {
2171 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2172 } else if ($type == 'edit') {
2173 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2176 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2181 * This method adds settings to the settings block for the grade system and its
2182 * plugins
2184 * @global moodle_page $PAGE
2186 function grade_extend_settings($plugininfo, $courseid) {
2187 global $PAGE;
2189 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2191 $strings = array_shift($plugininfo);
2193 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2194 foreach ($reports as $report) {
2195 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2199 if ($imports = grade_helper::get_plugins_import($courseid)) {
2200 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2201 foreach ($imports as $import) {
2202 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2206 if ($exports = grade_helper::get_plugins_export($courseid)) {
2207 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2208 foreach ($exports as $export) {
2209 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2213 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2214 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2217 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2218 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2219 foreach ($preferences as $preference) {
2220 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2224 if ($letters = grade_helper::get_info_letters($courseid)) {
2225 $letters = array_shift($letters);
2226 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2229 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2230 $outcomes = array_shift($outcomes);
2231 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2234 if ($scales = grade_helper::get_info_scales($courseid)) {
2235 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2238 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2239 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2240 foreach ($categories as $category) {
2241 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2245 if ($gradenode->contains_active_node()) {
2246 // If the gradenode is active include the settings base node (gradeadministration) in
2247 // the navbar, typcially this is ignored.
2248 $PAGE->navbar->includesettingsbase = true;
2250 // If we can get the course admin node make sure it is closed by default
2251 // as in this case the gradenode will be opened
2252 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2253 $coursenode->make_inactive();
2254 $coursenode->forceopen = false;
2260 * Grade helper class
2262 * This class provides several helpful functions that work irrespective of any
2263 * current state.
2265 * @copyright 2010 Sam Hemelryk
2266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2268 abstract class grade_helper {
2270 * Cached manage settings info {@see get_info_settings}
2271 * @var grade_plugin_info|false
2273 protected static $managesetting = null;
2275 * Cached grade report plugins {@see get_plugins_reports}
2276 * @var array|false
2278 protected static $gradereports = null;
2280 * Cached grade report plugins preferences {@see get_info_scales}
2281 * @var array|false
2283 protected static $gradereportpreferences = null;
2285 * Cached scale info {@see get_info_scales}
2286 * @var grade_plugin_info|false
2288 protected static $scaleinfo = null;
2290 * Cached outcome info {@see get_info_outcomes}
2291 * @var grade_plugin_info|false
2293 protected static $outcomeinfo = null;
2295 * Cached info on edit structure {@see get_info_edit_structure}
2296 * @var array|false
2298 protected static $edittree = null;
2300 * Cached leftter info {@see get_info_letters}
2301 * @var grade_plugin_info|false
2303 protected static $letterinfo = null;
2305 * Cached grade import plugins {@see get_plugins_import}
2306 * @var array|false
2308 protected static $importplugins = null;
2310 * Cached grade export plugins {@see get_plugins_export}
2311 * @var array|false
2313 protected static $exportplugins = null;
2315 * Cached grade plugin strings
2316 * @var array
2318 protected static $pluginstrings = null;
2321 * Gets strings commonly used by the describe plugins
2323 * report => get_string('view'),
2324 * edittree => get_string('edittree', 'grades'),
2325 * scale => get_string('scales'),
2326 * outcome => get_string('outcomes', 'grades'),
2327 * letter => get_string('letters', 'grades'),
2328 * export => get_string('export', 'grades'),
2329 * import => get_string('import'),
2330 * preferences => get_string('mypreferences', 'grades'),
2331 * settings => get_string('settings')
2333 * @return array
2335 public static function get_plugin_strings() {
2336 if (self::$pluginstrings === null) {
2337 self::$pluginstrings = array(
2338 'report' => get_string('view'),
2339 'edittree' => get_string('edittree', 'grades'),
2340 'scale' => get_string('scales'),
2341 'outcome' => get_string('outcomes', 'grades'),
2342 'letter' => get_string('letters', 'grades'),
2343 'export' => get_string('export', 'grades'),
2344 'import' => get_string('import'),
2345 'preferences' => get_string('mypreferences', 'grades'),
2346 'settings' => get_string('settings')
2349 return self::$pluginstrings;
2352 * Get grade_plugin_info object for managing settings if the user can
2354 * @param int $courseid
2355 * @return grade_plugin_info
2357 public static function get_info_manage_settings($courseid) {
2358 if (self::$managesetting !== null) {
2359 return self::$managesetting;
2361 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2362 if (has_capability('moodle/course:update', $context)) {
2363 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2364 } else {
2365 self::$managesetting = false;
2367 return self::$managesetting;
2370 * Returns an array of plugin reports as grade_plugin_info objects
2372 * @param int $courseid
2373 * @return array
2375 public static function get_plugins_reports($courseid) {
2376 global $SITE;
2378 if (self::$gradereports !== null) {
2379 return self::$gradereports;
2381 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2382 $gradereports = array();
2383 $gradepreferences = array();
2384 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2385 //some reports make no sense if we're not within a course
2386 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2387 continue;
2390 // Remove ones we can't see
2391 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2392 continue;
2395 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2396 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2397 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2399 // Add link to preferences tab if such a page exists
2400 if (file_exists($plugindir.'/preferences.php')) {
2401 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2402 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2405 if (count($gradereports) == 0) {
2406 $gradereports = false;
2407 $gradepreferences = false;
2408 } else if (count($gradepreferences) == 0) {
2409 $gradepreferences = false;
2410 asort($gradereports);
2411 } else {
2412 asort($gradereports);
2413 asort($gradepreferences);
2415 self::$gradereports = $gradereports;
2416 self::$gradereportpreferences = $gradepreferences;
2417 return self::$gradereports;
2420 * Returns an array of grade plugin report preferences for plugin reports that
2421 * support preferences
2422 * @param int $courseid
2423 * @return array
2425 public static function get_plugins_report_preferences($courseid) {
2426 if (self::$gradereportpreferences !== null) {
2427 return self::$gradereportpreferences;
2429 self::get_plugins_reports($courseid);
2430 return self::$gradereportpreferences;
2433 * Get information on scales
2434 * @param int $courseid
2435 * @return grade_plugin_info
2437 public static function get_info_scales($courseid) {
2438 if (self::$scaleinfo !== null) {
2439 return self::$scaleinfo;
2441 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2442 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2443 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2444 } else {
2445 self::$scaleinfo = false;
2447 return self::$scaleinfo;
2450 * Get information on outcomes
2451 * @param int $courseid
2452 * @return grade_plugin_info
2454 public static function get_info_outcomes($courseid) {
2455 global $CFG, $SITE;
2457 if (self::$outcomeinfo !== null) {
2458 return self::$outcomeinfo;
2460 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2461 $canmanage = has_capability('moodle/grade:manage', $context);
2462 $canupdate = has_capability('moodle/course:update', $context);
2463 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2464 $outcomes = array();
2465 if ($canupdate) {
2466 if ($courseid!=$SITE->id) {
2467 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2468 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2470 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2471 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2472 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2473 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2474 } else {
2475 if ($courseid!=$SITE->id) {
2476 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2477 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2480 self::$outcomeinfo = $outcomes;
2481 } else {
2482 self::$outcomeinfo = false;
2484 return self::$outcomeinfo;
2487 * Get information on editing structures
2488 * @param int $courseid
2489 * @return array
2491 public static function get_info_edit_structure($courseid) {
2492 if (self::$edittree !== null) {
2493 return self::$edittree;
2495 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2496 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2497 self::$edittree = array(
2498 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2499 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2501 } else {
2502 self::$edittree = false;
2504 return self::$edittree;
2507 * Get information on letters
2508 * @param int $courseid
2509 * @return array
2511 public static function get_info_letters($courseid) {
2512 if (self::$letterinfo !== null) {
2513 return self::$letterinfo;
2515 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2516 $canmanage = has_capability('moodle/grade:manage', $context);
2517 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2518 if ($canmanage || $canmanageletters) {
2519 self::$letterinfo = array(
2520 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2521 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2523 } else {
2524 self::$letterinfo = false;
2526 return self::$letterinfo;
2529 * Get information import plugins
2530 * @param int $courseid
2531 * @return array
2533 public static function get_plugins_import($courseid) {
2534 global $CFG;
2536 if (self::$importplugins !== null) {
2537 return self::$importplugins;
2539 $importplugins = array();
2540 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2542 if (has_capability('moodle/grade:import', $context)) {
2543 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2544 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2545 continue;
2547 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2548 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2549 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2553 if ($CFG->gradepublishing) {
2554 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2555 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2559 if (count($importplugins) > 0) {
2560 asort($importplugins);
2561 self::$importplugins = $importplugins;
2562 } else {
2563 self::$importplugins = false;
2565 return self::$importplugins;
2568 * Get information export plugins
2569 * @param int $courseid
2570 * @return array
2572 public static function get_plugins_export($courseid) {
2573 global $CFG;
2575 if (self::$exportplugins !== null) {
2576 return self::$exportplugins;
2578 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2579 $exportplugins = array();
2580 if (has_capability('moodle/grade:export', $context)) {
2581 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2582 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2583 continue;
2585 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2586 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2587 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2590 if ($CFG->gradepublishing) {
2591 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2592 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2595 if (count($exportplugins) > 0) {
2596 asort($exportplugins);
2597 self::$exportplugins = $exportplugins;
2598 } else {
2599 self::$exportplugins = false;
2601 return self::$exportplugins;