Moodle release 2.1.6
[moodle.git] / grade / lib.php
blob80b8ba125b45c87dcc2a9f0757fcb1c3efc4405c
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
629 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
631 * @return string HTML code or nothing if $return == false
633 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
634 $heading = false, $return=false,
635 $buttons=false, $shownavigation=true) {
636 global $CFG, $OUTPUT, $PAGE;
638 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
640 // Determine the string of the active plugin
641 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
642 $stractive_type = $plugin_info['strings'][$active_type];
644 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
645 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
646 } else {
647 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
650 if ($active_type == 'report') {
651 $PAGE->set_pagelayout('report');
652 } else {
653 $PAGE->set_pagelayout('admin');
655 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
656 $PAGE->set_heading($title);
657 if ($buttons instanceof single_button) {
658 $buttons = $OUTPUT->render($buttons);
660 $PAGE->set_button($buttons);
661 grade_extend_settings($plugin_info, $courseid);
663 $returnval = $OUTPUT->header();
664 if (!$return) {
665 echo $returnval;
668 // Guess heading if not given explicitly
669 if (!$heading) {
670 $heading = $stractive_plugin;
673 if ($shownavigation) {
674 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
675 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
678 if ($return) {
679 $returnval .= $OUTPUT->heading($heading);
680 } else {
681 echo $OUTPUT->heading($heading);
684 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
685 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
689 if ($return) {
690 return $returnval;
695 * Utility class used for return tracking when using edit and other forms in grade plugins
697 * @package moodlecore
698 * @copyright 2009 Nicolas Connault
699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
701 class grade_plugin_return {
702 public $type;
703 public $plugin;
704 public $courseid;
705 public $userid;
706 public $page;
709 * Constructor
711 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
713 public function grade_plugin_return($params = null) {
714 if (empty($params)) {
715 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
716 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
717 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
718 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
719 $this->page = optional_param('gpr_page', null, PARAM_INT);
721 } else {
722 foreach ($params as $key=>$value) {
723 if (property_exists($this, $key)) {
724 $this->$key = $value;
731 * Returns return parameters as options array suitable for buttons.
732 * @return array options
734 public function get_options() {
735 if (empty($this->type)) {
736 return array();
739 $params = array();
741 if (!empty($this->plugin)) {
742 $params['plugin'] = $this->plugin;
745 if (!empty($this->courseid)) {
746 $params['id'] = $this->courseid;
749 if (!empty($this->userid)) {
750 $params['userid'] = $this->userid;
753 if (!empty($this->page)) {
754 $params['page'] = $this->page;
757 return $params;
761 * Returns return url
763 * @param string $default default url when params not set
764 * @param array $extras Extra URL parameters
766 * @return string url
768 public function get_return_url($default, $extras=null) {
769 global $CFG;
771 if (empty($this->type) or empty($this->plugin)) {
772 return $default;
775 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
776 $glue = '?';
778 if (!empty($this->courseid)) {
779 $url .= $glue.'id='.$this->courseid;
780 $glue = '&amp;';
783 if (!empty($this->userid)) {
784 $url .= $glue.'userid='.$this->userid;
785 $glue = '&amp;';
788 if (!empty($this->page)) {
789 $url .= $glue.'page='.$this->page;
790 $glue = '&amp;';
793 if (!empty($extras)) {
794 foreach ($extras as $key=>$value) {
795 $url .= $glue.$key.'='.$value;
796 $glue = '&amp;';
800 return $url;
804 * Returns string with hidden return tracking form elements.
805 * @return string
807 public function get_form_fields() {
808 if (empty($this->type)) {
809 return '';
812 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
814 if (!empty($this->plugin)) {
815 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
818 if (!empty($this->courseid)) {
819 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
822 if (!empty($this->userid)) {
823 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
826 if (!empty($this->page)) {
827 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
832 * Add hidden elements into mform
834 * @param object &$mform moodle form object
836 * @return void
838 public function add_mform_elements(&$mform) {
839 if (empty($this->type)) {
840 return;
843 $mform->addElement('hidden', 'gpr_type', $this->type);
844 $mform->setType('gpr_type', PARAM_SAFEDIR);
846 if (!empty($this->plugin)) {
847 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
848 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
851 if (!empty($this->courseid)) {
852 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
853 $mform->setType('gpr_courseid', PARAM_INT);
856 if (!empty($this->userid)) {
857 $mform->addElement('hidden', 'gpr_userid', $this->userid);
858 $mform->setType('gpr_userid', PARAM_INT);
861 if (!empty($this->page)) {
862 $mform->addElement('hidden', 'gpr_page', $this->page);
863 $mform->setType('gpr_page', PARAM_INT);
868 * Add return tracking params into url
870 * @param moodle_url $url A URL
872 * @return string $url with return tracking params
874 public function add_url_params(moodle_url $url) {
875 if (empty($this->type)) {
876 return $url;
879 $url->param('gpr_type', $this->type);
881 if (!empty($this->plugin)) {
882 $url->param('gpr_plugin', $this->plugin);
885 if (!empty($this->courseid)) {
886 $url->param('gpr_courseid' ,$this->courseid);
889 if (!empty($this->userid)) {
890 $url->param('gpr_userid', $this->userid);
893 if (!empty($this->page)) {
894 $url->param('gpr_page', $this->page);
897 return $url;
902 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
904 * @param string $path The path of the calling script (using __FILE__?)
905 * @param string $pagename The language string to use as the last part of the navigation (non-link)
906 * @param mixed $id Either a plain integer (assuming the key is 'id') or
907 * an array of keys and values (e.g courseid => $courseid, itemid...)
909 * @return string
911 function grade_build_nav($path, $pagename=null, $id=null) {
912 global $CFG, $COURSE, $PAGE;
914 $strgrades = get_string('grades', 'grades');
916 // Parse the path and build navlinks from its elements
917 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
918 $path = substr($path, $dirroot_length);
919 $path = str_replace('\\', '/', $path);
921 $path_elements = explode('/', $path);
923 $path_elements_count = count($path_elements);
925 // First link is always 'grade'
926 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
928 $link = null;
929 $numberofelements = 3;
931 // Prepare URL params string
932 $linkparams = array();
933 if (!is_null($id)) {
934 if (is_array($id)) {
935 foreach ($id as $idkey => $idvalue) {
936 $linkparams[$idkey] = $idvalue;
938 } else {
939 $linkparams['id'] = $id;
943 $navlink4 = null;
945 // Remove file extensions from filenames
946 foreach ($path_elements as $key => $filename) {
947 $path_elements[$key] = str_replace('.php', '', $filename);
950 // Second level links
951 switch ($path_elements[1]) {
952 case 'edit': // No link
953 if ($path_elements[3] != 'index.php') {
954 $numberofelements = 4;
956 break;
957 case 'import': // No link
958 break;
959 case 'export': // No link
960 break;
961 case 'report':
962 // $id is required for this link. Do not print it if $id isn't given
963 if (!is_null($id)) {
964 $link = new moodle_url('/grade/report/index.php', $linkparams);
967 if ($path_elements[2] == 'grader') {
968 $numberofelements = 4;
970 break;
972 default:
973 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
974 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
975 " as the second path element after 'grade'.");
976 return false;
978 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
980 // Third level links
981 if (empty($pagename)) {
982 $pagename = get_string($path_elements[2], 'grades');
985 switch ($numberofelements) {
986 case 3:
987 $PAGE->navbar->add($pagename, $link);
988 break;
989 case 4:
990 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
991 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
993 $PAGE->navbar->add($pagename);
994 break;
997 return '';
1001 * General structure representing grade items in course
1003 * @package moodlecore
1004 * @copyright 2009 Nicolas Connault
1005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1007 class grade_structure {
1008 public $context;
1010 public $courseid;
1013 * Reference to modinfo for current course (for performance, to save
1014 * retrieving it from courseid every time). Not actually set except for
1015 * the grade_tree type.
1016 * @var course_modinfo
1018 public $modinfo;
1021 * 1D array of grade items only
1023 public $items;
1026 * Returns icon of element
1028 * @param array &$element An array representing an element in the grade_tree
1029 * @param bool $spacerifnone return spacer if no icon found
1031 * @return string icon or spacer
1033 public function get_element_icon(&$element, $spacerifnone=false) {
1034 global $CFG, $OUTPUT;
1036 switch ($element['type']) {
1037 case 'item':
1038 case 'courseitem':
1039 case 'categoryitem':
1040 $is_course = $element['object']->is_course_item();
1041 $is_category = $element['object']->is_category_item();
1042 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1043 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1044 $is_outcome = !empty($element['object']->outcomeid);
1046 if ($element['object']->is_calculated()) {
1047 $strcalc = get_string('calculatedgrade', 'grades');
1048 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1049 s($strcalc).'" alt="'.s($strcalc).'"/>';
1051 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1052 if ($category = $element['object']->get_item_category()) {
1053 switch ($category->aggregation) {
1054 case GRADE_AGGREGATE_MEAN:
1055 case GRADE_AGGREGATE_MEDIAN:
1056 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1057 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1058 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1059 $stragg = get_string('aggregation', 'grades');
1060 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1061 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1062 case GRADE_AGGREGATE_SUM:
1063 $stragg = get_string('aggregation', 'grades');
1064 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1065 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1069 } else if ($element['object']->itemtype == 'mod') {
1070 //prevent outcomes being displaying the same icon as the activity they are attached to
1071 if ($is_outcome) {
1072 $stroutcome = s(get_string('outcome', 'grades'));
1073 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1074 'class="icon itemicon" title="'.$stroutcome.
1075 '" alt="'.$stroutcome.'"/>';
1076 } else {
1077 $strmodname = get_string('modulename', $element['object']->itemmodule);
1078 return '<img src="'.$OUTPUT->pix_url('icon',
1079 $element['object']->itemmodule) . '" ' .
1080 'class="icon itemicon" title="' .s($strmodname).
1081 '" alt="' .s($strmodname).'"/>';
1083 } else if ($element['object']->itemtype == 'manual') {
1084 if ($element['object']->is_outcome_item()) {
1085 $stroutcome = get_string('outcome', 'grades');
1086 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1087 'class="icon itemicon" title="'.s($stroutcome).
1088 '" alt="'.s($stroutcome).'"/>';
1089 } else {
1090 $strmanual = get_string('manualitem', 'grades');
1091 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1092 'class="icon itemicon" title="'.s($strmanual).
1093 '" alt="'.s($strmanual).'"/>';
1096 break;
1098 case 'category':
1099 $strcat = get_string('category', 'grades');
1100 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1101 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1104 if ($spacerifnone) {
1105 return $OUTPUT->spacer().' ';
1106 } else {
1107 return '';
1112 * Returns name of element optionally with icon and link
1114 * @param array &$element An array representing an element in the grade_tree
1115 * @param bool $withlink Whether or not this header has a link
1116 * @param bool $icon Whether or not to display an icon with this header
1117 * @param bool $spacerifnone return spacer if no icon found
1119 * @return string header
1121 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1122 $header = '';
1124 if ($icon) {
1125 $header .= $this->get_element_icon($element, $spacerifnone);
1128 $header .= $element['object']->get_name();
1130 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1131 $element['type'] != 'courseitem') {
1132 return $header;
1135 if ($withlink) {
1136 $url = $this->get_activity_link($element);
1137 if ($url) {
1138 $a = new stdClass();
1139 $a->name = get_string('modulename', $element['object']->itemmodule);
1140 $title = get_string('linktoactivity', 'grades', $a);
1142 $header = html_writer::link($url, $header, array('title' => $title));
1146 return $header;
1149 private function get_activity_link($element) {
1150 global $CFG;
1152 $itemtype = $element['object']->itemtype;
1153 $itemmodule = $element['object']->itemmodule;
1154 $iteminstance = $element['object']->iteminstance;
1156 // Links only for module items that have valid instance, module and are
1157 // called from grade_tree with valid modinfo
1158 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1159 return null;
1162 // Get $cm efficiently and with visibility information using modinfo
1163 $instances = $this->modinfo->get_instances();
1164 if (empty($instances[$itemmodule][$iteminstance])) {
1165 return null;
1167 $cm = $instances[$itemmodule][$iteminstance];
1169 // Do not add link if activity is not visible to the current user
1170 if (!$cm->uservisible) {
1171 return null;
1174 // If module has grade.php, link to that, otherwise view.php
1175 $dir = $CFG->dirroot . '/mod/' . $itemmodule;
1176 if (file_exists($dir.'/grade.php')) {
1177 return new moodle_url('/mod/' . $itemmodule . '/grade.php', array('id' => $cm->id));
1178 } else {
1179 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1184 * Returns the grade eid - the grade may not exist yet.
1186 * @param grade_grade $grade_grade A grade_grade object
1188 * @return string eid
1190 public function get_grade_eid($grade_grade) {
1191 if (empty($grade_grade->id)) {
1192 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1193 } else {
1194 return 'g'.$grade_grade->id;
1199 * Returns the grade_item eid
1200 * @param grade_item $grade_item A grade_item object
1201 * @return string eid
1203 public function get_item_eid($grade_item) {
1204 return 'i'.$grade_item->id;
1208 * Given a grade_tree element, returns an array of parameters
1209 * used to build an icon for that element.
1211 * @param array $element An array representing an element in the grade_tree
1213 * @return array
1215 public function get_params_for_iconstr($element) {
1216 $strparams = new stdClass();
1217 $strparams->category = '';
1218 $strparams->itemname = '';
1219 $strparams->itemmodule = '';
1221 if (!method_exists($element['object'], 'get_name')) {
1222 return $strparams;
1225 $strparams->itemname = html_to_text($element['object']->get_name());
1227 // If element name is categorytotal, get the name of the parent category
1228 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1229 $parent = $element['object']->get_parent_category();
1230 $strparams->category = $parent->get_name() . ' ';
1231 } else {
1232 $strparams->category = '';
1235 $strparams->itemmodule = null;
1236 if (isset($element['object']->itemmodule)) {
1237 $strparams->itemmodule = $element['object']->itemmodule;
1239 return $strparams;
1243 * Return edit icon for give element
1245 * @param array $element An array representing an element in the grade_tree
1246 * @param object $gpr A grade_plugin_return object
1248 * @return string
1250 public function get_edit_icon($element, $gpr) {
1251 global $CFG, $OUTPUT;
1253 if (!has_capability('moodle/grade:manage', $this->context)) {
1254 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1255 // oki - let them override grade
1256 } else {
1257 return '';
1261 static $strfeedback = null;
1262 static $streditgrade = null;
1263 if (is_null($streditgrade)) {
1264 $streditgrade = get_string('editgrade', 'grades');
1265 $strfeedback = get_string('feedback');
1268 $strparams = $this->get_params_for_iconstr($element);
1270 $object = $element['object'];
1272 switch ($element['type']) {
1273 case 'item':
1274 case 'categoryitem':
1275 case 'courseitem':
1276 $stredit = get_string('editverbose', 'grades', $strparams);
1277 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1278 $url = new moodle_url('/grade/edit/tree/item.php',
1279 array('courseid' => $this->courseid, 'id' => $object->id));
1280 } else {
1281 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1282 array('courseid' => $this->courseid, 'id' => $object->id));
1284 break;
1286 case 'category':
1287 $stredit = get_string('editverbose', 'grades', $strparams);
1288 $url = new moodle_url('/grade/edit/tree/category.php',
1289 array('courseid' => $this->courseid, 'id' => $object->id));
1290 break;
1292 case 'grade':
1293 $stredit = $streditgrade;
1294 if (empty($object->id)) {
1295 $url = new moodle_url('/grade/edit/tree/grade.php',
1296 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1297 } else {
1298 $url = new moodle_url('/grade/edit/tree/grade.php',
1299 array('courseid' => $this->courseid, 'id' => $object->id));
1301 if (!empty($object->feedback)) {
1302 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1304 break;
1306 default:
1307 $url = null;
1310 if ($url) {
1311 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1313 } else {
1314 return '';
1319 * Return hiding icon for give element
1321 * @param array $element An array representing an element in the grade_tree
1322 * @param object $gpr A grade_plugin_return object
1324 * @return string
1326 public function get_hiding_icon($element, $gpr) {
1327 global $CFG, $OUTPUT;
1329 if (!has_capability('moodle/grade:manage', $this->context) and
1330 !has_capability('moodle/grade:hide', $this->context)) {
1331 return '';
1334 $strparams = $this->get_params_for_iconstr($element);
1335 $strshow = get_string('showverbose', 'grades', $strparams);
1336 $strhide = get_string('hideverbose', 'grades', $strparams);
1338 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1339 $url = $gpr->add_url_params($url);
1341 if ($element['object']->is_hidden()) {
1342 $type = 'show';
1343 $tooltip = $strshow;
1345 // Change the icon and add a tooltip showing the date
1346 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1347 $type = 'hiddenuntil';
1348 $tooltip = get_string('hiddenuntildate', 'grades',
1349 userdate($element['object']->get_hidden()));
1352 $url->param('action', 'show');
1354 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1356 } else {
1357 $url->param('action', 'hide');
1358 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1361 return $hideicon;
1365 * Return locking icon for given element
1367 * @param array $element An array representing an element in the grade_tree
1368 * @param object $gpr A grade_plugin_return object
1370 * @return string
1372 public function get_locking_icon($element, $gpr) {
1373 global $CFG, $OUTPUT;
1375 $strparams = $this->get_params_for_iconstr($element);
1376 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1377 $strlock = get_string('lockverbose', 'grades', $strparams);
1379 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1380 $url = $gpr->add_url_params($url);
1382 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1383 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1384 $strparamobj = new stdClass();
1385 $strparamobj->itemname = $element['object']->grade_item->itemname;
1386 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1388 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1390 } else if ($element['object']->is_locked()) {
1391 $type = 'unlock';
1392 $tooltip = $strunlock;
1394 // Change the icon and add a tooltip showing the date
1395 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1396 $type = 'locktime';
1397 $tooltip = get_string('locktimedate', 'grades',
1398 userdate($element['object']->get_locktime()));
1401 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1402 $action = '';
1403 } else {
1404 $url->param('action', 'unlock');
1405 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1408 } else {
1409 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1410 $action = '';
1411 } else {
1412 $url->param('action', 'lock');
1413 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1417 return $action;
1421 * Return calculation icon for given element
1423 * @param array $element An array representing an element in the grade_tree
1424 * @param object $gpr A grade_plugin_return object
1426 * @return string
1428 public function get_calculation_icon($element, $gpr) {
1429 global $CFG, $OUTPUT;
1430 if (!has_capability('moodle/grade:manage', $this->context)) {
1431 return '';
1434 $type = $element['type'];
1435 $object = $element['object'];
1437 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1438 $strparams = $this->get_params_for_iconstr($element);
1439 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1441 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1442 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1444 // show calculation icon only when calculation possible
1445 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1446 if ($object->is_calculated()) {
1447 $icon = 't/calc';
1448 } else {
1449 $icon = 't/calc_off';
1452 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1453 $url = $gpr->add_url_params($url);
1454 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1458 return '';
1463 * Flat structure similar to grade tree.
1465 * @uses grade_structure
1466 * @package moodlecore
1467 * @copyright 2009 Nicolas Connault
1468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1470 class grade_seq extends grade_structure {
1473 * 1D array of elements
1475 public $elements;
1478 * Constructor, retrieves and stores array of all grade_category and grade_item
1479 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1481 * @param int $courseid The course id
1482 * @param bool $category_grade_last category grade item is the last child
1483 * @param bool $nooutcomes Whether or not outcomes should be included
1485 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1486 global $USER, $CFG;
1488 $this->courseid = $courseid;
1489 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1491 // get course grade tree
1492 $top_element = grade_category::fetch_course_tree($courseid, true);
1494 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1496 foreach ($this->elements as $key=>$unused) {
1497 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1502 * Static recursive helper - makes the grade_item for category the last children
1504 * @param array &$element The seed of the recursion
1505 * @param bool $category_grade_last category grade item is the last child
1506 * @param bool $nooutcomes Whether or not outcomes should be included
1508 * @return array
1510 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1511 if (empty($element['children'])) {
1512 return array();
1514 $children = array();
1516 foreach ($element['children'] as $sortorder=>$unused) {
1517 if ($nooutcomes and $element['type'] != 'category' and
1518 $element['children'][$sortorder]['object']->is_outcome_item()) {
1519 continue;
1521 $children[] = $element['children'][$sortorder];
1523 unset($element['children']);
1525 if ($category_grade_last and count($children) > 1) {
1526 $cat_item = array_shift($children);
1527 array_push($children, $cat_item);
1530 $result = array();
1531 foreach ($children as $child) {
1532 if ($child['type'] == 'category') {
1533 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1534 } else {
1535 $child['eid'] = 'i'.$child['object']->id;
1536 $result[$child['object']->id] = $child;
1540 return $result;
1544 * Parses the array in search of a given eid and returns a element object with
1545 * information about the element it has found.
1547 * @param int $eid Gradetree Element ID
1549 * @return object element
1551 public function locate_element($eid) {
1552 // it is a grade - construct a new object
1553 if (strpos($eid, 'n') === 0) {
1554 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1555 return null;
1558 $itemid = $matches[1];
1559 $userid = $matches[2];
1561 //extra security check - the grade item must be in this tree
1562 if (!$item_el = $this->locate_element('i'.$itemid)) {
1563 return null;
1566 // $gradea->id may be null - means does not exist yet
1567 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1569 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1570 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1572 } else if (strpos($eid, 'g') === 0) {
1573 $id = (int) substr($eid, 1);
1574 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1575 return null;
1577 //extra security check - the grade item must be in this tree
1578 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1579 return null;
1581 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1582 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1585 // it is a category or item
1586 foreach ($this->elements as $element) {
1587 if ($element['eid'] == $eid) {
1588 return $element;
1592 return null;
1597 * This class represents a complete tree of categories, grade_items and final grades,
1598 * organises as an array primarily, but which can also be converted to other formats.
1599 * It has simple method calls with complex implementations, allowing for easy insertion,
1600 * deletion and moving of items and categories within the tree.
1602 * @uses grade_structure
1603 * @package moodlecore
1604 * @copyright 2009 Nicolas Connault
1605 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1607 class grade_tree extends grade_structure {
1610 * The basic representation of the tree as a hierarchical, 3-tiered array.
1611 * @var object $top_element
1613 public $top_element;
1616 * 2D array of grade items and categories
1617 * @var array $levels
1619 public $levels;
1622 * Grade items
1623 * @var array $items
1625 public $items;
1628 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1629 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1631 * @param int $courseid The Course ID
1632 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1633 * @param bool $category_grade_last category grade item is the last child
1634 * @param array $collapsed array of collapsed categories
1635 * @param bool $nooutcomes Whether or not outcomes should be included
1637 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1638 $collapsed=null, $nooutcomes=false) {
1639 global $USER, $CFG, $COURSE, $DB;
1641 $this->courseid = $courseid;
1642 $this->levels = array();
1643 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1645 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1646 $course = $COURSE;
1647 } else {
1648 $course = $DB->get_record('course', array('id' => $this->courseid));
1650 $this->modinfo = get_fast_modinfo($course);
1652 // get course grade tree
1653 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1655 // collapse the categories if requested
1656 if (!empty($collapsed)) {
1657 grade_tree::category_collapse($this->top_element, $collapsed);
1660 // no otucomes if requested
1661 if (!empty($nooutcomes)) {
1662 grade_tree::no_outcomes($this->top_element);
1665 // move category item to last position in category
1666 if ($category_grade_last) {
1667 grade_tree::category_grade_last($this->top_element);
1670 if ($fillers) {
1671 // inject fake categories == fillers
1672 grade_tree::inject_fillers($this->top_element, 0);
1673 // add colspans to categories and fillers
1674 grade_tree::inject_colspans($this->top_element);
1677 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1682 * Static recursive helper - removes items from collapsed categories
1684 * @param array &$element The seed of the recursion
1685 * @param array $collapsed array of collapsed categories
1687 * @return void
1689 public function category_collapse(&$element, $collapsed) {
1690 if ($element['type'] != 'category') {
1691 return;
1693 if (empty($element['children']) or count($element['children']) < 2) {
1694 return;
1697 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1698 $category_item = reset($element['children']); //keep only category item
1699 $element['children'] = array(key($element['children'])=>$category_item);
1701 } else {
1702 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1703 reset($element['children']);
1704 $first_key = key($element['children']);
1705 unset($element['children'][$first_key]);
1707 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1708 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1714 * Static recursive helper - removes all outcomes
1716 * @param array &$element The seed of the recursion
1718 * @return void
1720 public function no_outcomes(&$element) {
1721 if ($element['type'] != 'category') {
1722 return;
1724 foreach ($element['children'] as $sortorder=>$child) {
1725 if ($element['children'][$sortorder]['type'] == 'item'
1726 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1727 unset($element['children'][$sortorder]);
1729 } else if ($element['children'][$sortorder]['type'] == 'category') {
1730 grade_tree::no_outcomes($element['children'][$sortorder]);
1736 * Static recursive helper - makes the grade_item for category the last children
1738 * @param array &$element The seed of the recursion
1740 * @return void
1742 public function category_grade_last(&$element) {
1743 if (empty($element['children'])) {
1744 return;
1746 if (count($element['children']) < 2) {
1747 return;
1749 $first_item = reset($element['children']);
1750 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1751 // the category item might have been already removed
1752 $order = key($element['children']);
1753 unset($element['children'][$order]);
1754 $element['children'][$order] =& $first_item;
1756 foreach ($element['children'] as $sortorder => $child) {
1757 grade_tree::category_grade_last($element['children'][$sortorder]);
1762 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1764 * @param array &$levels The levels of the grade tree through which to recurse
1765 * @param array &$element The seed of the recursion
1766 * @param int $depth How deep are we?
1767 * @return void
1769 public function fill_levels(&$levels, &$element, $depth) {
1770 if (!array_key_exists($depth, $levels)) {
1771 $levels[$depth] = array();
1774 // prepare unique identifier
1775 if ($element['type'] == 'category') {
1776 $element['eid'] = 'c'.$element['object']->id;
1777 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1778 $element['eid'] = 'i'.$element['object']->id;
1779 $this->items[$element['object']->id] =& $element['object'];
1782 $levels[$depth][] =& $element;
1783 $depth++;
1784 if (empty($element['children'])) {
1785 return;
1787 $prev = 0;
1788 foreach ($element['children'] as $sortorder=>$child) {
1789 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1790 $element['children'][$sortorder]['prev'] = $prev;
1791 $element['children'][$sortorder]['next'] = 0;
1792 if ($prev) {
1793 $element['children'][$prev]['next'] = $sortorder;
1795 $prev = $sortorder;
1800 * Static recursive helper - makes full tree (all leafes are at the same level)
1802 * @param array &$element The seed of the recursion
1803 * @param int $depth How deep are we?
1805 * @return int
1807 public function inject_fillers(&$element, $depth) {
1808 $depth++;
1810 if (empty($element['children'])) {
1811 return $depth;
1813 $chdepths = array();
1814 $chids = array_keys($element['children']);
1815 $last_child = end($chids);
1816 $first_child = reset($chids);
1818 foreach ($chids as $chid) {
1819 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1821 arsort($chdepths);
1823 $maxdepth = reset($chdepths);
1824 foreach ($chdepths as $chid=>$chd) {
1825 if ($chd == $maxdepth) {
1826 continue;
1828 for ($i=0; $i < $maxdepth-$chd; $i++) {
1829 if ($chid == $first_child) {
1830 $type = 'fillerfirst';
1831 } else if ($chid == $last_child) {
1832 $type = 'fillerlast';
1833 } else {
1834 $type = 'filler';
1836 $oldchild =& $element['children'][$chid];
1837 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1838 'eid'=>'', 'depth'=>$element['object']->depth,
1839 'children'=>array($oldchild));
1843 return $maxdepth;
1847 * Static recursive helper - add colspan information into categories
1849 * @param array &$element The seed of the recursion
1851 * @return int
1853 public function inject_colspans(&$element) {
1854 if (empty($element['children'])) {
1855 return 1;
1857 $count = 0;
1858 foreach ($element['children'] as $key=>$child) {
1859 $count += grade_tree::inject_colspans($element['children'][$key]);
1861 $element['colspan'] = $count;
1862 return $count;
1866 * Parses the array in search of a given eid and returns a element object with
1867 * information about the element it has found.
1868 * @param int $eid Gradetree Element ID
1869 * @return object element
1871 public function locate_element($eid) {
1872 // it is a grade - construct a new object
1873 if (strpos($eid, 'n') === 0) {
1874 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1875 return null;
1878 $itemid = $matches[1];
1879 $userid = $matches[2];
1881 //extra security check - the grade item must be in this tree
1882 if (!$item_el = $this->locate_element('i'.$itemid)) {
1883 return null;
1886 // $gradea->id may be null - means does not exist yet
1887 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1889 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1890 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1892 } else if (strpos($eid, 'g') === 0) {
1893 $id = (int) substr($eid, 1);
1894 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1895 return null;
1897 //extra security check - the grade item must be in this tree
1898 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1899 return null;
1901 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1902 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1905 // it is a category or item
1906 foreach ($this->levels as $row) {
1907 foreach ($row as $element) {
1908 if ($element['type'] == 'filler') {
1909 continue;
1911 if ($element['eid'] == $eid) {
1912 return $element;
1917 return null;
1921 * Returns a well-formed XML representation of the grade-tree using recursion.
1923 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1924 * @param string $tabs The control character to use for tabs
1926 * @return string $xml
1928 public function exporttoxml($root=null, $tabs="\t") {
1929 $xml = null;
1930 $first = false;
1931 if (is_null($root)) {
1932 $root = $this->top_element;
1933 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
1934 $xml .= "<gradetree>\n";
1935 $first = true;
1938 $type = 'undefined';
1939 if (strpos($root['object']->table, 'grade_categories') !== false) {
1940 $type = 'category';
1941 } else if (strpos($root['object']->table, 'grade_items') !== false) {
1942 $type = 'item';
1943 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
1944 $type = 'outcome';
1947 $xml .= "$tabs<element type=\"$type\">\n";
1948 foreach ($root['object'] as $var => $value) {
1949 if (!is_object($value) && !is_array($value) && !empty($value)) {
1950 $xml .= "$tabs\t<$var>$value</$var>\n";
1954 if (!empty($root['children'])) {
1955 $xml .= "$tabs\t<children>\n";
1956 foreach ($root['children'] as $sortorder => $child) {
1957 $xml .= $this->exportToXML($child, $tabs."\t\t");
1959 $xml .= "$tabs\t</children>\n";
1962 $xml .= "$tabs</element>\n";
1964 if ($first) {
1965 $xml .= "</gradetree>";
1968 return $xml;
1972 * Returns a JSON representation of the grade-tree using recursion.
1974 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1975 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
1977 * @return string
1979 public function exporttojson($root=null, $tabs="\t") {
1980 $json = null;
1981 $first = false;
1982 if (is_null($root)) {
1983 $root = $this->top_element;
1984 $first = true;
1987 $name = '';
1990 if (strpos($root['object']->table, 'grade_categories') !== false) {
1991 $name = $root['object']->fullname;
1992 if ($name == '?') {
1993 $name = $root['object']->get_name();
1995 } else if (strpos($root['object']->table, 'grade_items') !== false) {
1996 $name = $root['object']->itemname;
1997 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
1998 $name = $root['object']->itemname;
2001 $json .= "$tabs {\n";
2002 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2003 $json .= "$tabs\t \"name\": \"$name\",\n";
2005 foreach ($root['object'] as $var => $value) {
2006 if (!is_object($value) && !is_array($value) && !empty($value)) {
2007 $json .= "$tabs\t \"$var\": \"$value\",\n";
2011 $json = substr($json, 0, strrpos($json, ','));
2013 if (!empty($root['children'])) {
2014 $json .= ",\n$tabs\t\"children\": [\n";
2015 foreach ($root['children'] as $sortorder => $child) {
2016 $json .= $this->exportToJSON($child, $tabs."\t\t");
2018 $json = substr($json, 0, strrpos($json, ','));
2019 $json .= "\n$tabs\t]\n";
2022 if ($first) {
2023 $json .= "\n}";
2024 } else {
2025 $json .= "\n$tabs},\n";
2028 return $json;
2032 * Returns the array of levels
2034 * @return array
2036 public function get_levels() {
2037 return $this->levels;
2041 * Returns the array of grade items
2043 * @return array
2045 public function get_items() {
2046 return $this->items;
2050 * Returns a specific Grade Item
2052 * @param int $itemid The ID of the grade_item object
2054 * @return grade_item
2056 public function get_item($itemid) {
2057 if (array_key_exists($itemid, $this->items)) {
2058 return $this->items[$itemid];
2059 } else {
2060 return false;
2066 * Local shortcut function for creating an edit/delete button for a grade_* object.
2067 * @param string $type 'edit' or 'delete'
2068 * @param int $courseid The Course ID
2069 * @param grade_* $object The grade_* object
2070 * @return string html
2072 function grade_button($type, $courseid, $object) {
2073 global $CFG, $OUTPUT;
2074 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2075 $objectidstring = $matches[1] . 'id';
2076 } else {
2077 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2080 $strdelete = get_string('delete');
2081 $stredit = get_string('edit');
2083 if ($type == 'delete') {
2084 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2085 } else if ($type == 'edit') {
2086 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2089 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2094 * This method adds settings to the settings block for the grade system and its
2095 * plugins
2097 * @global moodle_page $PAGE
2099 function grade_extend_settings($plugininfo, $courseid) {
2100 global $PAGE;
2102 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2104 $strings = array_shift($plugininfo);
2106 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2107 foreach ($reports as $report) {
2108 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2112 if ($imports = grade_helper::get_plugins_import($courseid)) {
2113 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2114 foreach ($imports as $import) {
2115 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2119 if ($exports = grade_helper::get_plugins_export($courseid)) {
2120 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2121 foreach ($exports as $export) {
2122 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2126 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2127 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2130 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2131 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2132 foreach ($preferences as $preference) {
2133 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2137 if ($letters = grade_helper::get_info_letters($courseid)) {
2138 $letters = array_shift($letters);
2139 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2142 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2143 $outcomes = array_shift($outcomes);
2144 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2147 if ($scales = grade_helper::get_info_scales($courseid)) {
2148 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2151 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2152 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2153 foreach ($categories as $category) {
2154 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2158 if ($gradenode->contains_active_node()) {
2159 // If the gradenode is active include the settings base node (gradeadministration) in
2160 // the navbar, typcially this is ignored.
2161 $PAGE->navbar->includesettingsbase = true;
2163 // If we can get the course admin node make sure it is closed by default
2164 // as in this case the gradenode will be opened
2165 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2166 $coursenode->make_inactive();
2167 $coursenode->forceopen = false;
2173 * Grade helper class
2175 * This class provides several helpful functions that work irrespective of any
2176 * current state.
2178 * @copyright 2010 Sam Hemelryk
2179 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2181 abstract class grade_helper {
2183 * Cached manage settings info {@see get_info_settings}
2184 * @var grade_plugin_info|false
2186 protected static $managesetting = null;
2188 * Cached grade report plugins {@see get_plugins_reports}
2189 * @var array|false
2191 protected static $gradereports = null;
2193 * Cached grade report plugins preferences {@see get_info_scales}
2194 * @var array|false
2196 protected static $gradereportpreferences = null;
2198 * Cached scale info {@see get_info_scales}
2199 * @var grade_plugin_info|false
2201 protected static $scaleinfo = null;
2203 * Cached outcome info {@see get_info_outcomes}
2204 * @var grade_plugin_info|false
2206 protected static $outcomeinfo = null;
2208 * Cached info on edit structure {@see get_info_edit_structure}
2209 * @var array|false
2211 protected static $edittree = null;
2213 * Cached leftter info {@see get_info_letters}
2214 * @var grade_plugin_info|false
2216 protected static $letterinfo = null;
2218 * Cached grade import plugins {@see get_plugins_import}
2219 * @var array|false
2221 protected static $importplugins = null;
2223 * Cached grade export plugins {@see get_plugins_export}
2224 * @var array|false
2226 protected static $exportplugins = null;
2228 * Cached grade plugin strings
2229 * @var array
2231 protected static $pluginstrings = null;
2234 * Gets strings commonly used by the describe plugins
2236 * report => get_string('view'),
2237 * edittree => get_string('edittree', 'grades'),
2238 * scale => get_string('scales'),
2239 * outcome => get_string('outcomes', 'grades'),
2240 * letter => get_string('letters', 'grades'),
2241 * export => get_string('export', 'grades'),
2242 * import => get_string('import'),
2243 * preferences => get_string('mypreferences', 'grades'),
2244 * settings => get_string('settings')
2246 * @return array
2248 public static function get_plugin_strings() {
2249 if (self::$pluginstrings === null) {
2250 self::$pluginstrings = array(
2251 'report' => get_string('view'),
2252 'edittree' => get_string('edittree', 'grades'),
2253 'scale' => get_string('scales'),
2254 'outcome' => get_string('outcomes', 'grades'),
2255 'letter' => get_string('letters', 'grades'),
2256 'export' => get_string('export', 'grades'),
2257 'import' => get_string('import'),
2258 'preferences' => get_string('mypreferences', 'grades'),
2259 'settings' => get_string('settings')
2262 return self::$pluginstrings;
2265 * Get grade_plugin_info object for managing settings if the user can
2267 * @param int $courseid
2268 * @return grade_plugin_info
2270 public static function get_info_manage_settings($courseid) {
2271 if (self::$managesetting !== null) {
2272 return self::$managesetting;
2274 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2275 if (has_capability('moodle/course:update', $context)) {
2276 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2277 } else {
2278 self::$managesetting = false;
2280 return self::$managesetting;
2283 * Returns an array of plugin reports as grade_plugin_info objects
2285 * @param int $courseid
2286 * @return array
2288 public static function get_plugins_reports($courseid) {
2289 global $SITE;
2291 if (self::$gradereports !== null) {
2292 return self::$gradereports;
2294 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2295 $gradereports = array();
2296 $gradepreferences = array();
2297 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2298 //some reports make no sense if we're not within a course
2299 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2300 continue;
2303 // Remove ones we can't see
2304 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2305 continue;
2308 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2309 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2310 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2312 // Add link to preferences tab if such a page exists
2313 if (file_exists($plugindir.'/preferences.php')) {
2314 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2315 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2318 if (count($gradereports) == 0) {
2319 $gradereports = false;
2320 $gradepreferences = false;
2321 } else if (count($gradepreferences) == 0) {
2322 $gradepreferences = false;
2323 asort($gradereports);
2324 } else {
2325 asort($gradereports);
2326 asort($gradepreferences);
2328 self::$gradereports = $gradereports;
2329 self::$gradereportpreferences = $gradepreferences;
2330 return self::$gradereports;
2333 * Returns an array of grade plugin report preferences for plugin reports that
2334 * support preferences
2335 * @param int $courseid
2336 * @return array
2338 public static function get_plugins_report_preferences($courseid) {
2339 if (self::$gradereportpreferences !== null) {
2340 return self::$gradereportpreferences;
2342 self::get_plugins_reports($courseid);
2343 return self::$gradereportpreferences;
2346 * Get information on scales
2347 * @param int $courseid
2348 * @return grade_plugin_info
2350 public static function get_info_scales($courseid) {
2351 if (self::$scaleinfo !== null) {
2352 return self::$scaleinfo;
2354 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2355 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2356 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2357 } else {
2358 self::$scaleinfo = false;
2360 return self::$scaleinfo;
2363 * Get information on outcomes
2364 * @param int $courseid
2365 * @return grade_plugin_info
2367 public static function get_info_outcomes($courseid) {
2368 global $CFG, $SITE;
2370 if (self::$outcomeinfo !== null) {
2371 return self::$outcomeinfo;
2373 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2374 $canmanage = has_capability('moodle/grade:manage', $context);
2375 $canupdate = has_capability('moodle/course:update', $context);
2376 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2377 $outcomes = array();
2378 if ($canupdate) {
2379 if ($courseid!=$SITE->id) {
2380 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2381 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2383 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2384 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2385 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2386 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2387 } else {
2388 if ($courseid!=$SITE->id) {
2389 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2390 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2393 self::$outcomeinfo = $outcomes;
2394 } else {
2395 self::$outcomeinfo = false;
2397 return self::$outcomeinfo;
2400 * Get information on editing structures
2401 * @param int $courseid
2402 * @return array
2404 public static function get_info_edit_structure($courseid) {
2405 if (self::$edittree !== null) {
2406 return self::$edittree;
2408 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2409 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2410 self::$edittree = array(
2411 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2412 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2414 } else {
2415 self::$edittree = false;
2417 return self::$edittree;
2420 * Get information on letters
2421 * @param int $courseid
2422 * @return array
2424 public static function get_info_letters($courseid) {
2425 if (self::$letterinfo !== null) {
2426 return self::$letterinfo;
2428 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2429 $canmanage = has_capability('moodle/grade:manage', $context);
2430 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2431 if ($canmanage || $canmanageletters) {
2432 self::$letterinfo = array(
2433 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2434 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2436 } else {
2437 self::$letterinfo = false;
2439 return self::$letterinfo;
2442 * Get information import plugins
2443 * @param int $courseid
2444 * @return array
2446 public static function get_plugins_import($courseid) {
2447 global $CFG;
2449 if (self::$importplugins !== null) {
2450 return self::$importplugins;
2452 $importplugins = array();
2453 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2455 if (has_capability('moodle/grade:import', $context)) {
2456 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2457 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2458 continue;
2460 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2461 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2462 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2466 if ($CFG->gradepublishing) {
2467 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2468 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2472 if (count($importplugins) > 0) {
2473 asort($importplugins);
2474 self::$importplugins = $importplugins;
2475 } else {
2476 self::$importplugins = false;
2478 return self::$importplugins;
2481 * Get information export plugins
2482 * @param int $courseid
2483 * @return array
2485 public static function get_plugins_export($courseid) {
2486 global $CFG;
2488 if (self::$exportplugins !== null) {
2489 return self::$exportplugins;
2491 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2492 $exportplugins = array();
2493 if (has_capability('moodle/grade:export', $context)) {
2494 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2495 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2496 continue;
2498 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2499 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2500 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2503 if ($CFG->gradepublishing) {
2504 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2505 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2508 if (count($exportplugins) > 0) {
2509 asort($exportplugins);
2510 self::$exportplugins = $exportplugins;
2511 } else {
2512 self::$exportplugins = false;
2514 return self::$exportplugins;