MDL-29592 weblib: prevent warnings when $USER not set
[moodle.git] / grade / lib.php
blob8c969f289946460b50ba5fa0215b5f395c64edbe
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once $CFG->libdir.'/gradelib.php';
27 /**
28 * This class iterates over all users that are graded in a course.
29 * Returns detailed info about users and their grades.
31 * @author Petr Skoda <skodak@moodle.org>
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 class graded_users_iterator {
35 public $course;
36 public $grade_items;
37 public $groupid;
38 public $users_rs;
39 public $grades_rs;
40 public $gradestack;
41 public $sortfield1;
42 public $sortorder1;
43 public $sortfield2;
44 public $sortorder2;
46 /**
47 * Constructor
49 * @param object $course A course object
50 * @param array $grade_items array of grade items, if not specified only user info returned
51 * @param int $groupid iterate only group users if present
52 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
53 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
54 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
55 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
57 public function graded_users_iterator($course, $grade_items=null, $groupid=0,
58 $sortfield1='lastname', $sortorder1='ASC',
59 $sortfield2='firstname', $sortorder2='ASC') {
60 $this->course = $course;
61 $this->grade_items = $grade_items;
62 $this->groupid = $groupid;
63 $this->sortfield1 = $sortfield1;
64 $this->sortorder1 = $sortorder1;
65 $this->sortfield2 = $sortfield2;
66 $this->sortorder2 = $sortorder2;
68 $this->gradestack = array();
71 /**
72 * Initialise the iterator
73 * @return boolean success
75 public function init() {
76 global $CFG, $DB;
78 $this->close();
80 grade_regrade_final_grades($this->course->id);
81 $course_item = grade_item::fetch_course_item($this->course->id);
82 if ($course_item->needsupdate) {
83 // can not calculate all final grades - sorry
84 return false;
87 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
88 $relatedcontexts = get_related_contexts_string($coursecontext);
90 list($gradebookroles_sql, $params) =
91 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
93 //limit to users with an active enrolment
94 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext);
96 $params = array_merge($params, $enrolledparams);
98 if ($this->groupid) {
99 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
100 $groupwheresql = "AND gm.groupid = :groupid";
101 // $params contents: gradebookroles
102 $params['groupid'] = $this->groupid;
103 } else {
104 $groupsql = "";
105 $groupwheresql = "";
108 if (empty($this->sortfield1)) {
109 // we must do some sorting even if not specified
110 $ofields = ", u.id AS usrt";
111 $order = "usrt ASC";
113 } else {
114 $ofields = ", u.$this->sortfield1 AS usrt1";
115 $order = "usrt1 $this->sortorder1";
116 if (!empty($this->sortfield2)) {
117 $ofields .= ", u.$this->sortfield2 AS usrt2";
118 $order .= ", usrt2 $this->sortorder2";
120 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
121 // user order MUST be the same in both queries,
122 // must include the only unique user->id if not already present
123 $ofields .= ", u.id AS usrt";
124 $order .= ", usrt ASC";
128 // $params contents: gradebookroles and groupid (for $groupwheresql)
129 $users_sql = "SELECT u.* $ofields
130 FROM {user} u
131 JOIN ($enrolledsql) je ON je.id = u.id
132 $groupsql
133 JOIN (
134 SELECT DISTINCT ra.userid
135 FROM {role_assignments} ra
136 WHERE ra.roleid $gradebookroles_sql
137 AND ra.contextid $relatedcontexts
138 ) rainner ON rainner.userid = u.id
139 WHERE u.deleted = 0
140 $groupwheresql
141 ORDER BY $order";
142 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
144 if (!empty($this->grade_items)) {
145 $itemids = array_keys($this->grade_items);
146 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
147 $params = array_merge($params, $grades_params);
148 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
150 $grades_sql = "SELECT g.* $ofields
151 FROM {grade_grades} g
152 JOIN {user} u ON g.userid = u.id
153 JOIN ($enrolledsql) je ON je.id = u.id
154 $groupsql
155 JOIN (
156 SELECT DISTINCT ra.userid
157 FROM {role_assignments} ra
158 WHERE ra.roleid $gradebookroles_sql
159 AND ra.contextid $relatedcontexts
160 ) rainner ON rainner.userid = u.id
161 WHERE u.deleted = 0
162 AND g.itemid $itemidsql
163 $groupwheresql
164 ORDER BY $order, g.itemid ASC";
165 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
166 } else {
167 $this->grades_rs = false;
170 return true;
174 * Returns information about the next user
175 * @return mixed array of user info, all grades and feedback or null when no more users found
177 function next_user() {
178 if (!$this->users_rs) {
179 return false; // no users present
182 if (!$this->users_rs->valid()) {
183 if ($current = $this->_pop()) {
184 // this is not good - user or grades updated between the two reads above :-(
187 return false; // no more users
188 } else {
189 $user = $this->users_rs->current();
190 $this->users_rs->next();
193 // find grades of this user
194 $grade_records = array();
195 while (true) {
196 if (!$current = $this->_pop()) {
197 break; // no more grades
200 if (empty($current->userid)) {
201 break;
204 if ($current->userid != $user->id) {
205 // grade of the next user, we have all for this user
206 $this->_push($current);
207 break;
210 $grade_records[$current->itemid] = $current;
213 $grades = array();
214 $feedbacks = array();
216 if (!empty($this->grade_items)) {
217 foreach ($this->grade_items as $grade_item) {
218 if (array_key_exists($grade_item->id, $grade_records)) {
219 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
220 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
221 unset($grade_records[$grade_item->id]->feedback);
222 unset($grade_records[$grade_item->id]->feedbackformat);
223 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
224 } else {
225 $feedbacks[$grade_item->id]->feedback = '';
226 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
227 $grades[$grade_item->id] =
228 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
233 $result = new stdClass();
234 $result->user = $user;
235 $result->grades = $grades;
236 $result->feedbacks = $feedbacks;
237 return $result;
241 * Close the iterator, do not forget to call this function.
242 * @return void
244 function close() {
245 if ($this->users_rs) {
246 $this->users_rs->close();
247 $this->users_rs = null;
249 if ($this->grades_rs) {
250 $this->grades_rs->close();
251 $this->grades_rs = null;
253 $this->gradestack = array();
258 * _push
260 * @param grade_grade $grade Grade object
262 * @return void
264 function _push($grade) {
265 array_push($this->gradestack, $grade);
270 * _pop
272 * @return object current grade object
274 function _pop() {
275 global $DB;
276 if (empty($this->gradestack)) {
277 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
278 return null; // no grades present
281 $current = $this->grades_rs->current();
283 $this->grades_rs->next();
285 return $current;
286 } else {
287 return array_pop($this->gradestack);
293 * Print a selection popup form of the graded users in a course.
295 * @deprecated since 2.0
297 * @param int $course id of the course
298 * @param string $actionpage The page receiving the data from the popoup form
299 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
300 * @param int $groupid id of requested group, 0 means all
301 * @param int $includeall bool include all option
302 * @param bool $return If true, will return the HTML, otherwise, will print directly
303 * @return null
305 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
306 global $CFG, $USER, $OUTPUT;
307 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
310 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
311 global $USER;
313 if (is_null($userid)) {
314 $userid = $USER->id;
317 $menu = array(); // Will be a list of userid => user name
318 $gui = new graded_users_iterator($course, null, $groupid);
319 $gui->init();
320 $label = get_string('selectauser', 'grades');
321 if ($includeall) {
322 $menu[0] = get_string('allusers', 'grades');
323 $label = get_string('selectalloroneuser', 'grades');
325 while ($userdata = $gui->next_user()) {
326 $user = $userdata->user;
327 $menu[$user->id] = fullname($user);
329 $gui->close();
331 if ($includeall) {
332 $menu[0] .= " (" . (count($menu) - 1) . ")";
334 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
335 $select->label = $label;
336 $select->formid = 'choosegradeuser';
337 return $select;
341 * Print grading plugin selection popup form.
343 * @param array $plugin_info An array of plugins containing information for the selector
344 * @param boolean $return return as string
346 * @return nothing or string if $return true
348 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
349 global $CFG, $OUTPUT, $PAGE;
351 $menu = array();
352 $count = 0;
353 $active = '';
355 foreach ($plugin_info as $plugin_type => $plugins) {
356 if ($plugin_type == 'strings') {
357 continue;
360 $first_plugin = reset($plugins);
362 $sectionname = $plugin_info['strings'][$plugin_type];
363 $section = array();
365 foreach ($plugins as $plugin) {
366 $link = $plugin->link->out(false);
367 $section[$link] = $plugin->string;
368 $count++;
369 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
370 $active = $link;
374 if ($section) {
375 $menu[] = array($sectionname=>$section);
379 // finally print/return the popup form
380 if ($count > 1) {
381 $select = new url_select($menu, $active, null, 'choosepluginreport');
383 if ($return) {
384 return $OUTPUT->render($select);
385 } else {
386 echo $OUTPUT->render($select);
388 } else {
389 // only one option - no plugin selector needed
390 return '';
395 * Print grading plugin selection tab-based navigation.
397 * @param string $active_type type of plugin on current page - import, export, report or edit
398 * @param string $active_plugin active plugin type - grader, user, cvs, ...
399 * @param array $plugin_info Array of plugins
400 * @param boolean $return return as string
402 * @return nothing or string if $return true
404 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
405 global $CFG, $COURSE;
407 if (!isset($currenttab)) { //TODO: this is weird
408 $currenttab = '';
411 $tabs = array();
412 $top_row = array();
413 $bottom_row = array();
414 $inactive = array($active_plugin);
415 $activated = array();
417 $count = 0;
418 $active = '';
420 foreach ($plugin_info as $plugin_type => $plugins) {
421 if ($plugin_type == 'strings') {
422 continue;
425 // If $plugins is actually the definition of a child-less parent link:
426 if (!empty($plugins->id)) {
427 $string = $plugins->string;
428 if (!empty($plugin_info[$active_type]->parent)) {
429 $string = $plugin_info[$active_type]->parent->string;
432 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
433 continue;
436 $first_plugin = reset($plugins);
437 $url = $first_plugin->link;
439 if ($plugin_type == 'report') {
440 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
443 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
445 if ($active_type == $plugin_type) {
446 foreach ($plugins as $plugin) {
447 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
448 if ($plugin->id == $active_plugin) {
449 $inactive = array($plugin->id);
455 $tabs[] = $top_row;
456 $tabs[] = $bottom_row;
458 if ($return) {
459 return print_tabs($tabs, $active_type, $inactive, $activated, true);
460 } else {
461 print_tabs($tabs, $active_type, $inactive, $activated);
466 * grade_get_plugin_info
468 * @param int $courseid The course id
469 * @param string $active_type type of plugin on current page - import, export, report or edit
470 * @param string $active_plugin active plugin type - grader, user, cvs, ...
472 * @return array
474 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
475 global $CFG, $SITE;
477 $context = get_context_instance(CONTEXT_COURSE, $courseid);
479 $plugin_info = array();
480 $count = 0;
481 $active = '';
482 $url_prefix = $CFG->wwwroot . '/grade/';
484 // Language strings
485 $plugin_info['strings'] = grade_helper::get_plugin_strings();
487 if ($reports = grade_helper::get_plugins_reports($courseid)) {
488 $plugin_info['report'] = $reports;
491 //showing grade categories and items make no sense if we're not within a course
492 if ($courseid!=$SITE->id) {
493 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
494 $plugin_info['edittree'] = $edittree;
498 if ($scale = grade_helper::get_info_scales($courseid)) {
499 $plugin_info['scale'] = array('view'=>$scale);
502 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
503 $plugin_info['outcome'] = $outcomes;
506 if ($letters = grade_helper::get_info_letters($courseid)) {
507 $plugin_info['letter'] = $letters;
510 if ($imports = grade_helper::get_plugins_import($courseid)) {
511 $plugin_info['import'] = $imports;
514 if ($exports = grade_helper::get_plugins_export($courseid)) {
515 $plugin_info['export'] = $exports;
518 foreach ($plugin_info as $plugin_type => $plugins) {
519 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
520 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
521 break;
523 foreach ($plugins as $plugin) {
524 if (is_a($plugin, 'grade_plugin_info')) {
525 if ($active_plugin == $plugin->id) {
526 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
532 //hide course settings if we're not in a course
533 if ($courseid!=$SITE->id) {
534 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
535 $plugin_info['settings'] = array('course'=>$setting);
539 // Put preferences last
540 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
541 $plugin_info['preferences'] = $preferences;
544 foreach ($plugin_info as $plugin_type => $plugins) {
545 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
546 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
547 break;
549 foreach ($plugins as $plugin) {
550 if (is_a($plugin, 'grade_plugin_info')) {
551 if ($active_plugin == $plugin->id) {
552 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
558 return $plugin_info;
562 * A simple class containing info about grade plugins.
563 * Can be subclassed for special rules
565 * @package core_grades
566 * @copyright 2009 Nicolas Connault
567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
569 class grade_plugin_info {
571 * A unique id for this plugin
573 * @var mixed
575 public $id;
577 * A URL to access this plugin
579 * @var mixed
581 public $link;
583 * The name of this plugin
585 * @var mixed
587 public $string;
589 * Another grade_plugin_info object, parent of the current one
591 * @var mixed
593 public $parent;
596 * Constructor
598 * @param int $id A unique id for this plugin
599 * @param string $link A URL to access this plugin
600 * @param string $string The name of this plugin
601 * @param object $parent Another grade_plugin_info object, parent of the current one
603 * @return void
605 public function __construct($id, $link, $string, $parent=null) {
606 $this->id = $id;
607 $this->link = $link;
608 $this->string = $string;
609 $this->parent = $parent;
614 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
615 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
616 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
617 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
618 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
620 * @param int $courseid Course id
621 * @param string $active_type The type of the current page (report, settings,
622 * import, export, scales, outcomes, letters)
623 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
624 * @param string $heading The heading of the page. Tries to guess if none is given
625 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
626 * @param string $bodytags Additional attributes that will be added to the <body> tag
627 * @param string $buttons Additional buttons to display on the page
628 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
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);
677 if ($return) {
678 $returnval .= $OUTPUT->heading($heading);
679 } else {
680 echo $OUTPUT->heading($heading);
683 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
684 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
688 if ($return) {
689 return $returnval;
694 * Utility class used for return tracking when using edit and other forms in grade plugins
696 * @package core_grades
697 * @copyright 2009 Nicolas Connault
698 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
700 class grade_plugin_return {
701 public $type;
702 public $plugin;
703 public $courseid;
704 public $userid;
705 public $page;
708 * Constructor
710 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
712 public function grade_plugin_return($params = null) {
713 if (empty($params)) {
714 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
715 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
716 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
717 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
718 $this->page = optional_param('gpr_page', null, PARAM_INT);
720 } else {
721 foreach ($params as $key=>$value) {
722 if (property_exists($this, $key)) {
723 $this->$key = $value;
730 * Returns return parameters as options array suitable for buttons.
731 * @return array options
733 public function get_options() {
734 if (empty($this->type)) {
735 return array();
738 $params = array();
740 if (!empty($this->plugin)) {
741 $params['plugin'] = $this->plugin;
744 if (!empty($this->courseid)) {
745 $params['id'] = $this->courseid;
748 if (!empty($this->userid)) {
749 $params['userid'] = $this->userid;
752 if (!empty($this->page)) {
753 $params['page'] = $this->page;
756 return $params;
760 * Returns return url
762 * @param string $default default url when params not set
763 * @param array $extras Extra URL parameters
765 * @return string url
767 public function get_return_url($default, $extras=null) {
768 global $CFG;
770 if (empty($this->type) or empty($this->plugin)) {
771 return $default;
774 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
775 $glue = '?';
777 if (!empty($this->courseid)) {
778 $url .= $glue.'id='.$this->courseid;
779 $glue = '&amp;';
782 if (!empty($this->userid)) {
783 $url .= $glue.'userid='.$this->userid;
784 $glue = '&amp;';
787 if (!empty($this->page)) {
788 $url .= $glue.'page='.$this->page;
789 $glue = '&amp;';
792 if (!empty($extras)) {
793 foreach ($extras as $key=>$value) {
794 $url .= $glue.$key.'='.$value;
795 $glue = '&amp;';
799 return $url;
803 * Returns string with hidden return tracking form elements.
804 * @return string
806 public function get_form_fields() {
807 if (empty($this->type)) {
808 return '';
811 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
813 if (!empty($this->plugin)) {
814 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
817 if (!empty($this->courseid)) {
818 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
821 if (!empty($this->userid)) {
822 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
825 if (!empty($this->page)) {
826 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
831 * Add hidden elements into mform
833 * @param object &$mform moodle form object
835 * @return void
837 public function add_mform_elements(&$mform) {
838 if (empty($this->type)) {
839 return;
842 $mform->addElement('hidden', 'gpr_type', $this->type);
843 $mform->setType('gpr_type', PARAM_SAFEDIR);
845 if (!empty($this->plugin)) {
846 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
847 $mform->setType('gpr_plugin', PARAM_PLUGIN);
850 if (!empty($this->courseid)) {
851 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
852 $mform->setType('gpr_courseid', PARAM_INT);
855 if (!empty($this->userid)) {
856 $mform->addElement('hidden', 'gpr_userid', $this->userid);
857 $mform->setType('gpr_userid', PARAM_INT);
860 if (!empty($this->page)) {
861 $mform->addElement('hidden', 'gpr_page', $this->page);
862 $mform->setType('gpr_page', PARAM_INT);
867 * Add return tracking params into url
869 * @param moodle_url $url A URL
871 * @return string $url with return tracking params
873 public function add_url_params(moodle_url $url) {
874 if (empty($this->type)) {
875 return $url;
878 $url->param('gpr_type', $this->type);
880 if (!empty($this->plugin)) {
881 $url->param('gpr_plugin', $this->plugin);
884 if (!empty($this->courseid)) {
885 $url->param('gpr_courseid' ,$this->courseid);
888 if (!empty($this->userid)) {
889 $url->param('gpr_userid', $this->userid);
892 if (!empty($this->page)) {
893 $url->param('gpr_page', $this->page);
896 return $url;
901 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
903 * @param string $path The path of the calling script (using __FILE__?)
904 * @param string $pagename The language string to use as the last part of the navigation (non-link)
905 * @param mixed $id Either a plain integer (assuming the key is 'id') or
906 * an array of keys and values (e.g courseid => $courseid, itemid...)
908 * @return string
910 function grade_build_nav($path, $pagename=null, $id=null) {
911 global $CFG, $COURSE, $PAGE;
913 $strgrades = get_string('grades', 'grades');
915 // Parse the path and build navlinks from its elements
916 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
917 $path = substr($path, $dirroot_length);
918 $path = str_replace('\\', '/', $path);
920 $path_elements = explode('/', $path);
922 $path_elements_count = count($path_elements);
924 // First link is always 'grade'
925 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
927 $link = null;
928 $numberofelements = 3;
930 // Prepare URL params string
931 $linkparams = array();
932 if (!is_null($id)) {
933 if (is_array($id)) {
934 foreach ($id as $idkey => $idvalue) {
935 $linkparams[$idkey] = $idvalue;
937 } else {
938 $linkparams['id'] = $id;
942 $navlink4 = null;
944 // Remove file extensions from filenames
945 foreach ($path_elements as $key => $filename) {
946 $path_elements[$key] = str_replace('.php', '', $filename);
949 // Second level links
950 switch ($path_elements[1]) {
951 case 'edit': // No link
952 if ($path_elements[3] != 'index.php') {
953 $numberofelements = 4;
955 break;
956 case 'import': // No link
957 break;
958 case 'export': // No link
959 break;
960 case 'report':
961 // $id is required for this link. Do not print it if $id isn't given
962 if (!is_null($id)) {
963 $link = new moodle_url('/grade/report/index.php', $linkparams);
966 if ($path_elements[2] == 'grader') {
967 $numberofelements = 4;
969 break;
971 default:
972 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
973 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
974 " as the second path element after 'grade'.");
975 return false;
977 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
979 // Third level links
980 if (empty($pagename)) {
981 $pagename = get_string($path_elements[2], 'grades');
984 switch ($numberofelements) {
985 case 3:
986 $PAGE->navbar->add($pagename, $link);
987 break;
988 case 4:
989 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
990 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
992 $PAGE->navbar->add($pagename);
993 break;
996 return '';
1000 * General structure representing grade items in course
1002 * @package core_grades
1003 * @copyright 2009 Nicolas Connault
1004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1006 class grade_structure {
1007 public $context;
1009 public $courseid;
1012 * Reference to modinfo for current course (for performance, to save
1013 * retrieving it from courseid every time). Not actually set except for
1014 * the grade_tree type.
1015 * @var course_modinfo
1017 public $modinfo;
1020 * 1D array of grade items only
1022 public $items;
1025 * Returns icon of element
1027 * @param array &$element An array representing an element in the grade_tree
1028 * @param bool $spacerifnone return spacer if no icon found
1030 * @return string icon or spacer
1032 public function get_element_icon(&$element, $spacerifnone=false) {
1033 global $CFG, $OUTPUT;
1035 switch ($element['type']) {
1036 case 'item':
1037 case 'courseitem':
1038 case 'categoryitem':
1039 $is_course = $element['object']->is_course_item();
1040 $is_category = $element['object']->is_category_item();
1041 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1042 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1043 $is_outcome = !empty($element['object']->outcomeid);
1045 if ($element['object']->is_calculated()) {
1046 $strcalc = get_string('calculatedgrade', 'grades');
1047 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1048 s($strcalc).'" alt="'.s($strcalc).'"/>';
1050 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1051 if ($category = $element['object']->get_item_category()) {
1052 switch ($category->aggregation) {
1053 case GRADE_AGGREGATE_MEAN:
1054 case GRADE_AGGREGATE_MEDIAN:
1055 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1056 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1057 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1058 $stragg = get_string('aggregation', 'grades');
1059 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1060 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1061 case GRADE_AGGREGATE_SUM:
1062 $stragg = get_string('aggregation', 'grades');
1063 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1064 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1068 } else if ($element['object']->itemtype == 'mod') {
1069 //prevent outcomes being displaying the same icon as the activity they are attached to
1070 if ($is_outcome) {
1071 $stroutcome = s(get_string('outcome', 'grades'));
1072 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1073 'class="icon itemicon" title="'.$stroutcome.
1074 '" alt="'.$stroutcome.'"/>';
1075 } else {
1076 $strmodname = get_string('modulename', $element['object']->itemmodule);
1077 return '<img src="'.$OUTPUT->pix_url('icon',
1078 $element['object']->itemmodule) . '" ' .
1079 'class="icon itemicon" title="' .s($strmodname).
1080 '" alt="' .s($strmodname).'"/>';
1082 } else if ($element['object']->itemtype == 'manual') {
1083 if ($element['object']->is_outcome_item()) {
1084 $stroutcome = get_string('outcome', 'grades');
1085 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1086 'class="icon itemicon" title="'.s($stroutcome).
1087 '" alt="'.s($stroutcome).'"/>';
1088 } else {
1089 $strmanual = get_string('manualitem', 'grades');
1090 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1091 'class="icon itemicon" title="'.s($strmanual).
1092 '" alt="'.s($strmanual).'"/>';
1095 break;
1097 case 'category':
1098 $strcat = get_string('category', 'grades');
1099 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1100 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1103 if ($spacerifnone) {
1104 return $OUTPUT->spacer().' ';
1105 } else {
1106 return '';
1111 * Returns name of element optionally with icon and link
1113 * @param array &$element An array representing an element in the grade_tree
1114 * @param bool $withlink Whether or not this header has a link
1115 * @param bool $icon Whether or not to display an icon with this header
1116 * @param bool $spacerifnone return spacer if no icon found
1118 * @return string header
1120 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1121 $header = '';
1123 if ($icon) {
1124 $header .= $this->get_element_icon($element, $spacerifnone);
1127 $header .= $element['object']->get_name();
1129 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1130 $element['type'] != 'courseitem') {
1131 return $header;
1134 if ($withlink) {
1135 $url = $this->get_activity_link($element);
1136 if ($url) {
1137 $a = new stdClass();
1138 $a->name = get_string('modulename', $element['object']->itemmodule);
1139 $title = get_string('linktoactivity', 'grades', $a);
1141 $header = html_writer::link($url, $header, array('title' => $title));
1145 return $header;
1148 private function get_activity_link($element) {
1149 global $CFG;
1150 /** @var array static cache of the grade.php file existence flags */
1151 static $hasgradephp = array();
1153 $itemtype = $element['object']->itemtype;
1154 $itemmodule = $element['object']->itemmodule;
1155 $iteminstance = $element['object']->iteminstance;
1156 $itemnumber = $element['object']->itemnumber;
1158 // Links only for module items that have valid instance, module and are
1159 // called from grade_tree with valid modinfo
1160 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1161 return null;
1164 // Get $cm efficiently and with visibility information using modinfo
1165 $instances = $this->modinfo->get_instances();
1166 if (empty($instances[$itemmodule][$iteminstance])) {
1167 return null;
1169 $cm = $instances[$itemmodule][$iteminstance];
1171 // Do not add link if activity is not visible to the current user
1172 if (!$cm->uservisible) {
1173 return null;
1176 if (!array_key_exists($itemmodule, $hasgradephp)) {
1177 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1178 $hasgradephp[$itemmodule] = true;
1179 } else {
1180 $hasgradephp[$itemmodule] = false;
1184 // If module has grade.php, link to that, otherwise view.php
1185 if ($hasgradephp[$itemmodule]) {
1186 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1187 if (isset($element['userid'])) {
1188 $args['userid'] = $element['userid'];
1190 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1191 } else {
1192 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1197 * Returns URL of a page that is supposed to contain detailed grade analysis
1199 * At the moment, only activity modules are supported. The method generates link
1200 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1201 * gradeid and userid. If the grade.php does not exist, null is returned.
1203 * @return moodle_url|null URL or null if unable to construct it
1205 public function get_grade_analysis_url(grade_grade $grade) {
1206 global $CFG;
1207 /** @var array static cache of the grade.php file existence flags */
1208 static $hasgradephp = array();
1210 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1211 throw new coding_exception('Passed grade without the associated grade item');
1213 $item = $grade->grade_item;
1215 if (!$item->is_external_item()) {
1216 // at the moment, only activity modules are supported
1217 return null;
1219 if ($item->itemtype !== 'mod') {
1220 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1222 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1223 return null;
1226 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1227 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1228 $hasgradephp[$item->itemmodule] = true;
1229 } else {
1230 $hasgradephp[$item->itemmodule] = false;
1234 if (!$hasgradephp[$item->itemmodule]) {
1235 return null;
1238 $instances = $this->modinfo->get_instances();
1239 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1240 return null;
1242 $cm = $instances[$item->itemmodule][$item->iteminstance];
1243 if (!$cm->uservisible) {
1244 return null;
1247 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1248 'id' => $cm->id,
1249 'itemid' => $item->id,
1250 'itemnumber' => $item->itemnumber,
1251 'gradeid' => $grade->id,
1252 'userid' => $grade->userid,
1255 return $url;
1259 * Returns an action icon leading to the grade analysis page
1261 * @param grade_grade $grade
1262 * @return string
1264 public function get_grade_analysis_icon(grade_grade $grade) {
1265 global $OUTPUT;
1267 $url = $this->get_grade_analysis_url($grade);
1268 if (is_null($url)) {
1269 return '';
1272 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1273 get_string('gradeanalysis', 'core_grades')));
1277 * Returns the grade eid - the grade may not exist yet.
1279 * @param grade_grade $grade_grade A grade_grade object
1281 * @return string eid
1283 public function get_grade_eid($grade_grade) {
1284 if (empty($grade_grade->id)) {
1285 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1286 } else {
1287 return 'g'.$grade_grade->id;
1292 * Returns the grade_item eid
1293 * @param grade_item $grade_item A grade_item object
1294 * @return string eid
1296 public function get_item_eid($grade_item) {
1297 return 'i'.$grade_item->id;
1301 * Given a grade_tree element, returns an array of parameters
1302 * used to build an icon for that element.
1304 * @param array $element An array representing an element in the grade_tree
1306 * @return array
1308 public function get_params_for_iconstr($element) {
1309 $strparams = new stdClass();
1310 $strparams->category = '';
1311 $strparams->itemname = '';
1312 $strparams->itemmodule = '';
1314 if (!method_exists($element['object'], 'get_name')) {
1315 return $strparams;
1318 $strparams->itemname = html_to_text($element['object']->get_name());
1320 // If element name is categorytotal, get the name of the parent category
1321 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1322 $parent = $element['object']->get_parent_category();
1323 $strparams->category = $parent->get_name() . ' ';
1324 } else {
1325 $strparams->category = '';
1328 $strparams->itemmodule = null;
1329 if (isset($element['object']->itemmodule)) {
1330 $strparams->itemmodule = $element['object']->itemmodule;
1332 return $strparams;
1336 * Return edit icon for give element
1338 * @param array $element An array representing an element in the grade_tree
1339 * @param object $gpr A grade_plugin_return object
1341 * @return string
1343 public function get_edit_icon($element, $gpr) {
1344 global $CFG, $OUTPUT;
1346 if (!has_capability('moodle/grade:manage', $this->context)) {
1347 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1348 // oki - let them override grade
1349 } else {
1350 return '';
1354 static $strfeedback = null;
1355 static $streditgrade = null;
1356 if (is_null($streditgrade)) {
1357 $streditgrade = get_string('editgrade', 'grades');
1358 $strfeedback = get_string('feedback');
1361 $strparams = $this->get_params_for_iconstr($element);
1363 $object = $element['object'];
1365 switch ($element['type']) {
1366 case 'item':
1367 case 'categoryitem':
1368 case 'courseitem':
1369 $stredit = get_string('editverbose', 'grades', $strparams);
1370 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1371 $url = new moodle_url('/grade/edit/tree/item.php',
1372 array('courseid' => $this->courseid, 'id' => $object->id));
1373 } else {
1374 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1375 array('courseid' => $this->courseid, 'id' => $object->id));
1377 break;
1379 case 'category':
1380 $stredit = get_string('editverbose', 'grades', $strparams);
1381 $url = new moodle_url('/grade/edit/tree/category.php',
1382 array('courseid' => $this->courseid, 'id' => $object->id));
1383 break;
1385 case 'grade':
1386 $stredit = $streditgrade;
1387 if (empty($object->id)) {
1388 $url = new moodle_url('/grade/edit/tree/grade.php',
1389 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1390 } else {
1391 $url = new moodle_url('/grade/edit/tree/grade.php',
1392 array('courseid' => $this->courseid, 'id' => $object->id));
1394 if (!empty($object->feedback)) {
1395 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1397 break;
1399 default:
1400 $url = null;
1403 if ($url) {
1404 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1406 } else {
1407 return '';
1412 * Return hiding icon for give element
1414 * @param array $element An array representing an element in the grade_tree
1415 * @param object $gpr A grade_plugin_return object
1417 * @return string
1419 public function get_hiding_icon($element, $gpr) {
1420 global $CFG, $OUTPUT;
1422 if (!has_capability('moodle/grade:manage', $this->context) and
1423 !has_capability('moodle/grade:hide', $this->context)) {
1424 return '';
1427 $strparams = $this->get_params_for_iconstr($element);
1428 $strshow = get_string('showverbose', 'grades', $strparams);
1429 $strhide = get_string('hideverbose', 'grades', $strparams);
1431 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1432 $url = $gpr->add_url_params($url);
1434 if ($element['object']->is_hidden()) {
1435 $type = 'show';
1436 $tooltip = $strshow;
1438 // Change the icon and add a tooltip showing the date
1439 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1440 $type = 'hiddenuntil';
1441 $tooltip = get_string('hiddenuntildate', 'grades',
1442 userdate($element['object']->get_hidden()));
1445 $url->param('action', 'show');
1447 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1449 } else {
1450 $url->param('action', 'hide');
1451 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1454 return $hideicon;
1458 * Return locking icon for given element
1460 * @param array $element An array representing an element in the grade_tree
1461 * @param object $gpr A grade_plugin_return object
1463 * @return string
1465 public function get_locking_icon($element, $gpr) {
1466 global $CFG, $OUTPUT;
1468 $strparams = $this->get_params_for_iconstr($element);
1469 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1470 $strlock = get_string('lockverbose', 'grades', $strparams);
1472 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1473 $url = $gpr->add_url_params($url);
1475 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1476 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1477 $strparamobj = new stdClass();
1478 $strparamobj->itemname = $element['object']->grade_item->itemname;
1479 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1481 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1483 } else if ($element['object']->is_locked()) {
1484 $type = 'unlock';
1485 $tooltip = $strunlock;
1487 // Change the icon and add a tooltip showing the date
1488 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1489 $type = 'locktime';
1490 $tooltip = get_string('locktimedate', 'grades',
1491 userdate($element['object']->get_locktime()));
1494 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1495 $action = '';
1496 } else {
1497 $url->param('action', 'unlock');
1498 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1501 } else {
1502 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1503 $action = '';
1504 } else {
1505 $url->param('action', 'lock');
1506 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1510 return $action;
1514 * Return calculation icon for given element
1516 * @param array $element An array representing an element in the grade_tree
1517 * @param object $gpr A grade_plugin_return object
1519 * @return string
1521 public function get_calculation_icon($element, $gpr) {
1522 global $CFG, $OUTPUT;
1523 if (!has_capability('moodle/grade:manage', $this->context)) {
1524 return '';
1527 $type = $element['type'];
1528 $object = $element['object'];
1530 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1531 $strparams = $this->get_params_for_iconstr($element);
1532 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1534 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1535 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1537 // show calculation icon only when calculation possible
1538 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1539 if ($object->is_calculated()) {
1540 $icon = 't/calc';
1541 } else {
1542 $icon = 't/calc_off';
1545 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1546 $url = $gpr->add_url_params($url);
1547 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1551 return '';
1556 * Flat structure similar to grade tree.
1558 * @uses grade_structure
1559 * @package core_grades
1560 * @copyright 2009 Nicolas Connault
1561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1563 class grade_seq extends grade_structure {
1566 * 1D array of elements
1568 public $elements;
1571 * Constructor, retrieves and stores array of all grade_category and grade_item
1572 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1574 * @param int $courseid The course id
1575 * @param bool $category_grade_last category grade item is the last child
1576 * @param bool $nooutcomes Whether or not outcomes should be included
1578 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1579 global $USER, $CFG;
1581 $this->courseid = $courseid;
1582 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1584 // get course grade tree
1585 $top_element = grade_category::fetch_course_tree($courseid, true);
1587 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1589 foreach ($this->elements as $key=>$unused) {
1590 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1595 * Static recursive helper - makes the grade_item for category the last children
1597 * @param array &$element The seed of the recursion
1598 * @param bool $category_grade_last category grade item is the last child
1599 * @param bool $nooutcomes Whether or not outcomes should be included
1601 * @return array
1603 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1604 if (empty($element['children'])) {
1605 return array();
1607 $children = array();
1609 foreach ($element['children'] as $sortorder=>$unused) {
1610 if ($nooutcomes and $element['type'] != 'category' and
1611 $element['children'][$sortorder]['object']->is_outcome_item()) {
1612 continue;
1614 $children[] = $element['children'][$sortorder];
1616 unset($element['children']);
1618 if ($category_grade_last and count($children) > 1) {
1619 $cat_item = array_shift($children);
1620 array_push($children, $cat_item);
1623 $result = array();
1624 foreach ($children as $child) {
1625 if ($child['type'] == 'category') {
1626 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1627 } else {
1628 $child['eid'] = 'i'.$child['object']->id;
1629 $result[$child['object']->id] = $child;
1633 return $result;
1637 * Parses the array in search of a given eid and returns a element object with
1638 * information about the element it has found.
1640 * @param int $eid Gradetree Element ID
1642 * @return object element
1644 public function locate_element($eid) {
1645 // it is a grade - construct a new object
1646 if (strpos($eid, 'n') === 0) {
1647 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1648 return null;
1651 $itemid = $matches[1];
1652 $userid = $matches[2];
1654 //extra security check - the grade item must be in this tree
1655 if (!$item_el = $this->locate_element('i'.$itemid)) {
1656 return null;
1659 // $gradea->id may be null - means does not exist yet
1660 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1662 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1663 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1665 } else if (strpos($eid, 'g') === 0) {
1666 $id = (int) substr($eid, 1);
1667 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1668 return null;
1670 //extra security check - the grade item must be in this tree
1671 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1672 return null;
1674 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1675 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1678 // it is a category or item
1679 foreach ($this->elements as $element) {
1680 if ($element['eid'] == $eid) {
1681 return $element;
1685 return null;
1690 * This class represents a complete tree of categories, grade_items and final grades,
1691 * organises as an array primarily, but which can also be converted to other formats.
1692 * It has simple method calls with complex implementations, allowing for easy insertion,
1693 * deletion and moving of items and categories within the tree.
1695 * @uses grade_structure
1696 * @package core_grades
1697 * @copyright 2009 Nicolas Connault
1698 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1700 class grade_tree extends grade_structure {
1703 * The basic representation of the tree as a hierarchical, 3-tiered array.
1704 * @var object $top_element
1706 public $top_element;
1709 * 2D array of grade items and categories
1710 * @var array $levels
1712 public $levels;
1715 * Grade items
1716 * @var array $items
1718 public $items;
1721 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1722 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1724 * @param int $courseid The Course ID
1725 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1726 * @param bool $category_grade_last category grade item is the last child
1727 * @param array $collapsed array of collapsed categories
1728 * @param bool $nooutcomes Whether or not outcomes should be included
1730 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1731 $collapsed=null, $nooutcomes=false) {
1732 global $USER, $CFG, $COURSE, $DB;
1734 $this->courseid = $courseid;
1735 $this->levels = array();
1736 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1738 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1739 $course = $COURSE;
1740 } else {
1741 $course = $DB->get_record('course', array('id' => $this->courseid));
1743 $this->modinfo = get_fast_modinfo($course);
1745 // get course grade tree
1746 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1748 // collapse the categories if requested
1749 if (!empty($collapsed)) {
1750 grade_tree::category_collapse($this->top_element, $collapsed);
1753 // no otucomes if requested
1754 if (!empty($nooutcomes)) {
1755 grade_tree::no_outcomes($this->top_element);
1758 // move category item to last position in category
1759 if ($category_grade_last) {
1760 grade_tree::category_grade_last($this->top_element);
1763 if ($fillers) {
1764 // inject fake categories == fillers
1765 grade_tree::inject_fillers($this->top_element, 0);
1766 // add colspans to categories and fillers
1767 grade_tree::inject_colspans($this->top_element);
1770 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1775 * Static recursive helper - removes items from collapsed categories
1777 * @param array &$element The seed of the recursion
1778 * @param array $collapsed array of collapsed categories
1780 * @return void
1782 public function category_collapse(&$element, $collapsed) {
1783 if ($element['type'] != 'category') {
1784 return;
1786 if (empty($element['children']) or count($element['children']) < 2) {
1787 return;
1790 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1791 $category_item = reset($element['children']); //keep only category item
1792 $element['children'] = array(key($element['children'])=>$category_item);
1794 } else {
1795 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1796 reset($element['children']);
1797 $first_key = key($element['children']);
1798 unset($element['children'][$first_key]);
1800 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1801 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1807 * Static recursive helper - removes all outcomes
1809 * @param array &$element The seed of the recursion
1811 * @return void
1813 public function no_outcomes(&$element) {
1814 if ($element['type'] != 'category') {
1815 return;
1817 foreach ($element['children'] as $sortorder=>$child) {
1818 if ($element['children'][$sortorder]['type'] == 'item'
1819 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1820 unset($element['children'][$sortorder]);
1822 } else if ($element['children'][$sortorder]['type'] == 'category') {
1823 grade_tree::no_outcomes($element['children'][$sortorder]);
1829 * Static recursive helper - makes the grade_item for category the last children
1831 * @param array &$element The seed of the recursion
1833 * @return void
1835 public function category_grade_last(&$element) {
1836 if (empty($element['children'])) {
1837 return;
1839 if (count($element['children']) < 2) {
1840 return;
1842 $first_item = reset($element['children']);
1843 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1844 // the category item might have been already removed
1845 $order = key($element['children']);
1846 unset($element['children'][$order]);
1847 $element['children'][$order] =& $first_item;
1849 foreach ($element['children'] as $sortorder => $child) {
1850 grade_tree::category_grade_last($element['children'][$sortorder]);
1855 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1857 * @param array &$levels The levels of the grade tree through which to recurse
1858 * @param array &$element The seed of the recursion
1859 * @param int $depth How deep are we?
1860 * @return void
1862 public function fill_levels(&$levels, &$element, $depth) {
1863 if (!array_key_exists($depth, $levels)) {
1864 $levels[$depth] = array();
1867 // prepare unique identifier
1868 if ($element['type'] == 'category') {
1869 $element['eid'] = 'c'.$element['object']->id;
1870 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1871 $element['eid'] = 'i'.$element['object']->id;
1872 $this->items[$element['object']->id] =& $element['object'];
1875 $levels[$depth][] =& $element;
1876 $depth++;
1877 if (empty($element['children'])) {
1878 return;
1880 $prev = 0;
1881 foreach ($element['children'] as $sortorder=>$child) {
1882 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1883 $element['children'][$sortorder]['prev'] = $prev;
1884 $element['children'][$sortorder]['next'] = 0;
1885 if ($prev) {
1886 $element['children'][$prev]['next'] = $sortorder;
1888 $prev = $sortorder;
1893 * Static recursive helper - makes full tree (all leafes are at the same level)
1895 * @param array &$element The seed of the recursion
1896 * @param int $depth How deep are we?
1898 * @return int
1900 public function inject_fillers(&$element, $depth) {
1901 $depth++;
1903 if (empty($element['children'])) {
1904 return $depth;
1906 $chdepths = array();
1907 $chids = array_keys($element['children']);
1908 $last_child = end($chids);
1909 $first_child = reset($chids);
1911 foreach ($chids as $chid) {
1912 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1914 arsort($chdepths);
1916 $maxdepth = reset($chdepths);
1917 foreach ($chdepths as $chid=>$chd) {
1918 if ($chd == $maxdepth) {
1919 continue;
1921 for ($i=0; $i < $maxdepth-$chd; $i++) {
1922 if ($chid == $first_child) {
1923 $type = 'fillerfirst';
1924 } else if ($chid == $last_child) {
1925 $type = 'fillerlast';
1926 } else {
1927 $type = 'filler';
1929 $oldchild =& $element['children'][$chid];
1930 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1931 'eid'=>'', 'depth'=>$element['object']->depth,
1932 'children'=>array($oldchild));
1936 return $maxdepth;
1940 * Static recursive helper - add colspan information into categories
1942 * @param array &$element The seed of the recursion
1944 * @return int
1946 public function inject_colspans(&$element) {
1947 if (empty($element['children'])) {
1948 return 1;
1950 $count = 0;
1951 foreach ($element['children'] as $key=>$child) {
1952 $count += grade_tree::inject_colspans($element['children'][$key]);
1954 $element['colspan'] = $count;
1955 return $count;
1959 * Parses the array in search of a given eid and returns a element object with
1960 * information about the element it has found.
1961 * @param int $eid Gradetree Element ID
1962 * @return object element
1964 public function locate_element($eid) {
1965 // it is a grade - construct a new object
1966 if (strpos($eid, 'n') === 0) {
1967 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1968 return null;
1971 $itemid = $matches[1];
1972 $userid = $matches[2];
1974 //extra security check - the grade item must be in this tree
1975 if (!$item_el = $this->locate_element('i'.$itemid)) {
1976 return null;
1979 // $gradea->id may be null - means does not exist yet
1980 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1982 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1983 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1985 } else if (strpos($eid, 'g') === 0) {
1986 $id = (int) substr($eid, 1);
1987 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1988 return null;
1990 //extra security check - the grade item must be in this tree
1991 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1992 return null;
1994 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1995 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1998 // it is a category or item
1999 foreach ($this->levels as $row) {
2000 foreach ($row as $element) {
2001 if ($element['type'] == 'filler') {
2002 continue;
2004 if ($element['eid'] == $eid) {
2005 return $element;
2010 return null;
2014 * Returns a well-formed XML representation of the grade-tree using recursion.
2016 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2017 * @param string $tabs The control character to use for tabs
2019 * @return string $xml
2021 public function exporttoxml($root=null, $tabs="\t") {
2022 $xml = null;
2023 $first = false;
2024 if (is_null($root)) {
2025 $root = $this->top_element;
2026 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2027 $xml .= "<gradetree>\n";
2028 $first = true;
2031 $type = 'undefined';
2032 if (strpos($root['object']->table, 'grade_categories') !== false) {
2033 $type = 'category';
2034 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2035 $type = 'item';
2036 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2037 $type = 'outcome';
2040 $xml .= "$tabs<element type=\"$type\">\n";
2041 foreach ($root['object'] as $var => $value) {
2042 if (!is_object($value) && !is_array($value) && !empty($value)) {
2043 $xml .= "$tabs\t<$var>$value</$var>\n";
2047 if (!empty($root['children'])) {
2048 $xml .= "$tabs\t<children>\n";
2049 foreach ($root['children'] as $sortorder => $child) {
2050 $xml .= $this->exportToXML($child, $tabs."\t\t");
2052 $xml .= "$tabs\t</children>\n";
2055 $xml .= "$tabs</element>\n";
2057 if ($first) {
2058 $xml .= "</gradetree>";
2061 return $xml;
2065 * Returns a JSON representation of the grade-tree using recursion.
2067 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2068 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2070 * @return string
2072 public function exporttojson($root=null, $tabs="\t") {
2073 $json = null;
2074 $first = false;
2075 if (is_null($root)) {
2076 $root = $this->top_element;
2077 $first = true;
2080 $name = '';
2083 if (strpos($root['object']->table, 'grade_categories') !== false) {
2084 $name = $root['object']->fullname;
2085 if ($name == '?') {
2086 $name = $root['object']->get_name();
2088 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2089 $name = $root['object']->itemname;
2090 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2091 $name = $root['object']->itemname;
2094 $json .= "$tabs {\n";
2095 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2096 $json .= "$tabs\t \"name\": \"$name\",\n";
2098 foreach ($root['object'] as $var => $value) {
2099 if (!is_object($value) && !is_array($value) && !empty($value)) {
2100 $json .= "$tabs\t \"$var\": \"$value\",\n";
2104 $json = substr($json, 0, strrpos($json, ','));
2106 if (!empty($root['children'])) {
2107 $json .= ",\n$tabs\t\"children\": [\n";
2108 foreach ($root['children'] as $sortorder => $child) {
2109 $json .= $this->exportToJSON($child, $tabs."\t\t");
2111 $json = substr($json, 0, strrpos($json, ','));
2112 $json .= "\n$tabs\t]\n";
2115 if ($first) {
2116 $json .= "\n}";
2117 } else {
2118 $json .= "\n$tabs},\n";
2121 return $json;
2125 * Returns the array of levels
2127 * @return array
2129 public function get_levels() {
2130 return $this->levels;
2134 * Returns the array of grade items
2136 * @return array
2138 public function get_items() {
2139 return $this->items;
2143 * Returns a specific Grade Item
2145 * @param int $itemid The ID of the grade_item object
2147 * @return grade_item
2149 public function get_item($itemid) {
2150 if (array_key_exists($itemid, $this->items)) {
2151 return $this->items[$itemid];
2152 } else {
2153 return false;
2159 * Local shortcut function for creating an edit/delete button for a grade_* object.
2160 * @param string $type 'edit' or 'delete'
2161 * @param int $courseid The Course ID
2162 * @param grade_* $object The grade_* object
2163 * @return string html
2165 function grade_button($type, $courseid, $object) {
2166 global $CFG, $OUTPUT;
2167 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2168 $objectidstring = $matches[1] . 'id';
2169 } else {
2170 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2173 $strdelete = get_string('delete');
2174 $stredit = get_string('edit');
2176 if ($type == 'delete') {
2177 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2178 } else if ($type == 'edit') {
2179 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2182 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2187 * This method adds settings to the settings block for the grade system and its
2188 * plugins
2190 * @global moodle_page $PAGE
2192 function grade_extend_settings($plugininfo, $courseid) {
2193 global $PAGE;
2195 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2197 $strings = array_shift($plugininfo);
2199 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2200 foreach ($reports as $report) {
2201 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2205 if ($imports = grade_helper::get_plugins_import($courseid)) {
2206 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2207 foreach ($imports as $import) {
2208 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2212 if ($exports = grade_helper::get_plugins_export($courseid)) {
2213 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2214 foreach ($exports as $export) {
2215 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2219 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2220 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2223 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2224 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2225 foreach ($preferences as $preference) {
2226 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2230 if ($letters = grade_helper::get_info_letters($courseid)) {
2231 $letters = array_shift($letters);
2232 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2235 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2236 $outcomes = array_shift($outcomes);
2237 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2240 if ($scales = grade_helper::get_info_scales($courseid)) {
2241 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2244 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2245 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2246 foreach ($categories as $category) {
2247 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2251 if ($gradenode->contains_active_node()) {
2252 // If the gradenode is active include the settings base node (gradeadministration) in
2253 // the navbar, typcially this is ignored.
2254 $PAGE->navbar->includesettingsbase = true;
2256 // If we can get the course admin node make sure it is closed by default
2257 // as in this case the gradenode will be opened
2258 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2259 $coursenode->make_inactive();
2260 $coursenode->forceopen = false;
2266 * Grade helper class
2268 * This class provides several helpful functions that work irrespective of any
2269 * current state.
2271 * @copyright 2010 Sam Hemelryk
2272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2274 abstract class grade_helper {
2276 * Cached manage settings info {@see get_info_settings}
2277 * @var grade_plugin_info|false
2279 protected static $managesetting = null;
2281 * Cached grade report plugins {@see get_plugins_reports}
2282 * @var array|false
2284 protected static $gradereports = null;
2286 * Cached grade report plugins preferences {@see get_info_scales}
2287 * @var array|false
2289 protected static $gradereportpreferences = null;
2291 * Cached scale info {@see get_info_scales}
2292 * @var grade_plugin_info|false
2294 protected static $scaleinfo = null;
2296 * Cached outcome info {@see get_info_outcomes}
2297 * @var grade_plugin_info|false
2299 protected static $outcomeinfo = null;
2301 * Cached info on edit structure {@see get_info_edit_structure}
2302 * @var array|false
2304 protected static $edittree = null;
2306 * Cached leftter info {@see get_info_letters}
2307 * @var grade_plugin_info|false
2309 protected static $letterinfo = null;
2311 * Cached grade import plugins {@see get_plugins_import}
2312 * @var array|false
2314 protected static $importplugins = null;
2316 * Cached grade export plugins {@see get_plugins_export}
2317 * @var array|false
2319 protected static $exportplugins = null;
2321 * Cached grade plugin strings
2322 * @var array
2324 protected static $pluginstrings = null;
2327 * Gets strings commonly used by the describe plugins
2329 * report => get_string('view'),
2330 * edittree => get_string('edittree', 'grades'),
2331 * scale => get_string('scales'),
2332 * outcome => get_string('outcomes', 'grades'),
2333 * letter => get_string('letters', 'grades'),
2334 * export => get_string('export', 'grades'),
2335 * import => get_string('import'),
2336 * preferences => get_string('mypreferences', 'grades'),
2337 * settings => get_string('settings')
2339 * @return array
2341 public static function get_plugin_strings() {
2342 if (self::$pluginstrings === null) {
2343 self::$pluginstrings = array(
2344 'report' => get_string('view'),
2345 'edittree' => get_string('edittree', 'grades'),
2346 'scale' => get_string('scales'),
2347 'outcome' => get_string('outcomes', 'grades'),
2348 'letter' => get_string('letters', 'grades'),
2349 'export' => get_string('export', 'grades'),
2350 'import' => get_string('import'),
2351 'preferences' => get_string('mypreferences', 'grades'),
2352 'settings' => get_string('settings')
2355 return self::$pluginstrings;
2358 * Get grade_plugin_info object for managing settings if the user can
2360 * @param int $courseid
2361 * @return grade_plugin_info
2363 public static function get_info_manage_settings($courseid) {
2364 if (self::$managesetting !== null) {
2365 return self::$managesetting;
2367 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2368 if (has_capability('moodle/course:update', $context)) {
2369 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2370 } else {
2371 self::$managesetting = false;
2373 return self::$managesetting;
2376 * Returns an array of plugin reports as grade_plugin_info objects
2378 * @param int $courseid
2379 * @return array
2381 public static function get_plugins_reports($courseid) {
2382 global $SITE;
2384 if (self::$gradereports !== null) {
2385 return self::$gradereports;
2387 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2388 $gradereports = array();
2389 $gradepreferences = array();
2390 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2391 //some reports make no sense if we're not within a course
2392 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2393 continue;
2396 // Remove ones we can't see
2397 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2398 continue;
2401 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2402 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2403 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2405 // Add link to preferences tab if such a page exists
2406 if (file_exists($plugindir.'/preferences.php')) {
2407 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2408 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2411 if (count($gradereports) == 0) {
2412 $gradereports = false;
2413 $gradepreferences = false;
2414 } else if (count($gradepreferences) == 0) {
2415 $gradepreferences = false;
2416 asort($gradereports);
2417 } else {
2418 asort($gradereports);
2419 asort($gradepreferences);
2421 self::$gradereports = $gradereports;
2422 self::$gradereportpreferences = $gradepreferences;
2423 return self::$gradereports;
2426 * Returns an array of grade plugin report preferences for plugin reports that
2427 * support preferences
2428 * @param int $courseid
2429 * @return array
2431 public static function get_plugins_report_preferences($courseid) {
2432 if (self::$gradereportpreferences !== null) {
2433 return self::$gradereportpreferences;
2435 self::get_plugins_reports($courseid);
2436 return self::$gradereportpreferences;
2439 * Get information on scales
2440 * @param int $courseid
2441 * @return grade_plugin_info
2443 public static function get_info_scales($courseid) {
2444 if (self::$scaleinfo !== null) {
2445 return self::$scaleinfo;
2447 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2448 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2449 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2450 } else {
2451 self::$scaleinfo = false;
2453 return self::$scaleinfo;
2456 * Get information on outcomes
2457 * @param int $courseid
2458 * @return grade_plugin_info
2460 public static function get_info_outcomes($courseid) {
2461 global $CFG, $SITE;
2463 if (self::$outcomeinfo !== null) {
2464 return self::$outcomeinfo;
2466 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2467 $canmanage = has_capability('moodle/grade:manage', $context);
2468 $canupdate = has_capability('moodle/course:update', $context);
2469 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2470 $outcomes = array();
2471 if ($canupdate) {
2472 if ($courseid!=$SITE->id) {
2473 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2474 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2476 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2477 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2478 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2479 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2480 } else {
2481 if ($courseid!=$SITE->id) {
2482 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2483 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2486 self::$outcomeinfo = $outcomes;
2487 } else {
2488 self::$outcomeinfo = false;
2490 return self::$outcomeinfo;
2493 * Get information on editing structures
2494 * @param int $courseid
2495 * @return array
2497 public static function get_info_edit_structure($courseid) {
2498 if (self::$edittree !== null) {
2499 return self::$edittree;
2501 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2502 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2503 self::$edittree = array(
2504 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2505 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2507 } else {
2508 self::$edittree = false;
2510 return self::$edittree;
2513 * Get information on letters
2514 * @param int $courseid
2515 * @return array
2517 public static function get_info_letters($courseid) {
2518 if (self::$letterinfo !== null) {
2519 return self::$letterinfo;
2521 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2522 $canmanage = has_capability('moodle/grade:manage', $context);
2523 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2524 if ($canmanage || $canmanageletters) {
2525 self::$letterinfo = array(
2526 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2527 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2529 } else {
2530 self::$letterinfo = false;
2532 return self::$letterinfo;
2535 * Get information import plugins
2536 * @param int $courseid
2537 * @return array
2539 public static function get_plugins_import($courseid) {
2540 global $CFG;
2542 if (self::$importplugins !== null) {
2543 return self::$importplugins;
2545 $importplugins = array();
2546 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2548 if (has_capability('moodle/grade:import', $context)) {
2549 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2550 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2551 continue;
2553 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2554 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2555 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2559 if ($CFG->gradepublishing) {
2560 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2561 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2565 if (count($importplugins) > 0) {
2566 asort($importplugins);
2567 self::$importplugins = $importplugins;
2568 } else {
2569 self::$importplugins = false;
2571 return self::$importplugins;
2574 * Get information export plugins
2575 * @param int $courseid
2576 * @return array
2578 public static function get_plugins_export($courseid) {
2579 global $CFG;
2581 if (self::$exportplugins !== null) {
2582 return self::$exportplugins;
2584 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2585 $exportplugins = array();
2586 if (has_capability('moodle/grade:export', $context)) {
2587 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2588 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2589 continue;
2591 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2592 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2593 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2596 if ($CFG->gradepublishing) {
2597 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2598 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2601 if (count($exportplugins) > 0) {
2602 asort($exportplugins);
2603 self::$exportplugins = $exportplugins;
2604 } else {
2605 self::$exportplugins = false;
2607 return self::$exportplugins;