MDL-32867 filemanager and repository
[moodle.git] / grade / lib.php
blob185fed52039e00a722260e08d962bc13d39feb47
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 * Should users whose enrolment has been suspended be ignored?
49 protected $onlyactive = false;
51 /**
52 * Constructor
54 * @param object $course A course object
55 * @param array $grade_items array of grade items, if not specified only user info returned
56 * @param int $groupid iterate only group users if present
57 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
58 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
59 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
60 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
62 public function graded_users_iterator($course, $grade_items=null, $groupid=0,
63 $sortfield1='lastname', $sortorder1='ASC',
64 $sortfield2='firstname', $sortorder2='ASC') {
65 $this->course = $course;
66 $this->grade_items = $grade_items;
67 $this->groupid = $groupid;
68 $this->sortfield1 = $sortfield1;
69 $this->sortorder1 = $sortorder1;
70 $this->sortfield2 = $sortfield2;
71 $this->sortorder2 = $sortorder2;
73 $this->gradestack = array();
76 /**
77 * Initialise the iterator
78 * @return boolean success
80 public function init() {
81 global $CFG, $DB;
83 $this->close();
85 grade_regrade_final_grades($this->course->id);
86 $course_item = grade_item::fetch_course_item($this->course->id);
87 if ($course_item->needsupdate) {
88 // can not calculate all final grades - sorry
89 return false;
92 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
93 $relatedcontexts = get_related_contexts_string($coursecontext);
95 list($gradebookroles_sql, $params) =
96 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
97 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
99 $params = array_merge($params, $enrolledparams);
101 if ($this->groupid) {
102 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
103 $groupwheresql = "AND gm.groupid = :groupid";
104 // $params contents: gradebookroles
105 $params['groupid'] = $this->groupid;
106 } else {
107 $groupsql = "";
108 $groupwheresql = "";
111 if (empty($this->sortfield1)) {
112 // we must do some sorting even if not specified
113 $ofields = ", u.id AS usrt";
114 $order = "usrt ASC";
116 } else {
117 $ofields = ", u.$this->sortfield1 AS usrt1";
118 $order = "usrt1 $this->sortorder1";
119 if (!empty($this->sortfield2)) {
120 $ofields .= ", u.$this->sortfield2 AS usrt2";
121 $order .= ", usrt2 $this->sortorder2";
123 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
124 // user order MUST be the same in both queries,
125 // must include the only unique user->id if not already present
126 $ofields .= ", u.id AS usrt";
127 $order .= ", usrt ASC";
131 // $params contents: gradebookroles and groupid (for $groupwheresql)
132 $users_sql = "SELECT u.* $ofields
133 FROM {user} u
134 JOIN ($enrolledsql) je ON je.id = u.id
135 $groupsql
136 JOIN (
137 SELECT DISTINCT ra.userid
138 FROM {role_assignments} ra
139 WHERE ra.roleid $gradebookroles_sql
140 AND ra.contextid $relatedcontexts
141 ) rainner ON rainner.userid = u.id
142 WHERE u.deleted = 0
143 $groupwheresql
144 ORDER BY $order";
145 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
147 if (!empty($this->grade_items)) {
148 $itemids = array_keys($this->grade_items);
149 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
150 $params = array_merge($params, $grades_params);
151 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
153 $grades_sql = "SELECT g.* $ofields
154 FROM {grade_grades} g
155 JOIN {user} u ON g.userid = u.id
156 JOIN ($enrolledsql) je ON je.id = u.id
157 $groupsql
158 JOIN (
159 SELECT DISTINCT ra.userid
160 FROM {role_assignments} ra
161 WHERE ra.roleid $gradebookroles_sql
162 AND ra.contextid $relatedcontexts
163 ) rainner ON rainner.userid = u.id
164 WHERE u.deleted = 0
165 AND g.itemid $itemidsql
166 $groupwheresql
167 ORDER BY $order, g.itemid ASC";
168 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
169 } else {
170 $this->grades_rs = false;
173 return true;
177 * Returns information about the next user
178 * @return mixed array of user info, all grades and feedback or null when no more users found
180 function next_user() {
181 if (!$this->users_rs) {
182 return false; // no users present
185 if (!$this->users_rs->valid()) {
186 if ($current = $this->_pop()) {
187 // this is not good - user or grades updated between the two reads above :-(
190 return false; // no more users
191 } else {
192 $user = $this->users_rs->current();
193 $this->users_rs->next();
196 // find grades of this user
197 $grade_records = array();
198 while (true) {
199 if (!$current = $this->_pop()) {
200 break; // no more grades
203 if (empty($current->userid)) {
204 break;
207 if ($current->userid != $user->id) {
208 // grade of the next user, we have all for this user
209 $this->_push($current);
210 break;
213 $grade_records[$current->itemid] = $current;
216 $grades = array();
217 $feedbacks = array();
219 if (!empty($this->grade_items)) {
220 foreach ($this->grade_items as $grade_item) {
221 if (!isset($feedbacks[$grade_item->id])) {
222 $feedbacks[$grade_item->id] = new stdClass();
224 if (array_key_exists($grade_item->id, $grade_records)) {
225 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
226 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
227 unset($grade_records[$grade_item->id]->feedback);
228 unset($grade_records[$grade_item->id]->feedbackformat);
229 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
230 } else {
231 $feedbacks[$grade_item->id]->feedback = '';
232 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
233 $grades[$grade_item->id] =
234 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
239 $result = new stdClass();
240 $result->user = $user;
241 $result->grades = $grades;
242 $result->feedbacks = $feedbacks;
243 return $result;
247 * Close the iterator, do not forget to call this function.
248 * @return void
250 function close() {
251 if ($this->users_rs) {
252 $this->users_rs->close();
253 $this->users_rs = null;
255 if ($this->grades_rs) {
256 $this->grades_rs->close();
257 $this->grades_rs = null;
259 $this->gradestack = array();
263 * Should all enrolled users be exported or just those with an active enrolment?
265 * @param bool $onlyactive True to limit the export to users with an active enrolment
267 public function require_active_enrolment($onlyactive = true) {
268 if (!empty($this->users_rs)) {
269 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
271 $this->onlyactive = $onlyactive;
276 * _push
278 * @param grade_grade $grade Grade object
280 * @return void
282 function _push($grade) {
283 array_push($this->gradestack, $grade);
288 * _pop
290 * @return object current grade object
292 function _pop() {
293 global $DB;
294 if (empty($this->gradestack)) {
295 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
296 return null; // no grades present
299 $current = $this->grades_rs->current();
301 $this->grades_rs->next();
303 return $current;
304 } else {
305 return array_pop($this->gradestack);
311 * Print a selection popup form of the graded users in a course.
313 * @deprecated since 2.0
315 * @param int $course id of the course
316 * @param string $actionpage The page receiving the data from the popoup form
317 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
318 * @param int $groupid id of requested group, 0 means all
319 * @param int $includeall bool include all option
320 * @param bool $return If true, will return the HTML, otherwise, will print directly
321 * @return null
323 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
324 global $CFG, $USER, $OUTPUT;
325 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
328 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
329 global $USER;
331 if (is_null($userid)) {
332 $userid = $USER->id;
335 $menu = array(); // Will be a list of userid => user name
336 $gui = new graded_users_iterator($course, null, $groupid);
337 $gui->init();
338 $label = get_string('selectauser', 'grades');
339 if ($includeall) {
340 $menu[0] = get_string('allusers', 'grades');
341 $label = get_string('selectalloroneuser', 'grades');
343 while ($userdata = $gui->next_user()) {
344 $user = $userdata->user;
345 $menu[$user->id] = fullname($user);
347 $gui->close();
349 if ($includeall) {
350 $menu[0] .= " (" . (count($menu) - 1) . ")";
352 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
353 $select->label = $label;
354 $select->formid = 'choosegradeuser';
355 return $select;
359 * Print grading plugin selection popup form.
361 * @param array $plugin_info An array of plugins containing information for the selector
362 * @param boolean $return return as string
364 * @return nothing or string if $return true
366 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
367 global $CFG, $OUTPUT, $PAGE;
369 $menu = array();
370 $count = 0;
371 $active = '';
373 foreach ($plugin_info as $plugin_type => $plugins) {
374 if ($plugin_type == 'strings') {
375 continue;
378 $first_plugin = reset($plugins);
380 $sectionname = $plugin_info['strings'][$plugin_type];
381 $section = array();
383 foreach ($plugins as $plugin) {
384 $link = $plugin->link->out(false);
385 $section[$link] = $plugin->string;
386 $count++;
387 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
388 $active = $link;
392 if ($section) {
393 $menu[] = array($sectionname=>$section);
397 // finally print/return the popup form
398 if ($count > 1) {
399 $select = new url_select($menu, $active, null, 'choosepluginreport');
401 if ($return) {
402 return $OUTPUT->render($select);
403 } else {
404 echo $OUTPUT->render($select);
406 } else {
407 // only one option - no plugin selector needed
408 return '';
413 * Print grading plugin selection tab-based navigation.
415 * @param string $active_type type of plugin on current page - import, export, report or edit
416 * @param string $active_plugin active plugin type - grader, user, cvs, ...
417 * @param array $plugin_info Array of plugins
418 * @param boolean $return return as string
420 * @return nothing or string if $return true
422 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
423 global $CFG, $COURSE;
425 if (!isset($currenttab)) { //TODO: this is weird
426 $currenttab = '';
429 $tabs = array();
430 $top_row = array();
431 $bottom_row = array();
432 $inactive = array($active_plugin);
433 $activated = array();
435 $count = 0;
436 $active = '';
438 foreach ($plugin_info as $plugin_type => $plugins) {
439 if ($plugin_type == 'strings') {
440 continue;
443 // If $plugins is actually the definition of a child-less parent link:
444 if (!empty($plugins->id)) {
445 $string = $plugins->string;
446 if (!empty($plugin_info[$active_type]->parent)) {
447 $string = $plugin_info[$active_type]->parent->string;
450 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
451 continue;
454 $first_plugin = reset($plugins);
455 $url = $first_plugin->link;
457 if ($plugin_type == 'report') {
458 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
461 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
463 if ($active_type == $plugin_type) {
464 foreach ($plugins as $plugin) {
465 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
466 if ($plugin->id == $active_plugin) {
467 $inactive = array($plugin->id);
473 $tabs[] = $top_row;
474 $tabs[] = $bottom_row;
476 if ($return) {
477 return print_tabs($tabs, $active_type, $inactive, $activated, true);
478 } else {
479 print_tabs($tabs, $active_type, $inactive, $activated);
484 * grade_get_plugin_info
486 * @param int $courseid The course id
487 * @param string $active_type type of plugin on current page - import, export, report or edit
488 * @param string $active_plugin active plugin type - grader, user, cvs, ...
490 * @return array
492 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
493 global $CFG, $SITE;
495 $context = get_context_instance(CONTEXT_COURSE, $courseid);
497 $plugin_info = array();
498 $count = 0;
499 $active = '';
500 $url_prefix = $CFG->wwwroot . '/grade/';
502 // Language strings
503 $plugin_info['strings'] = grade_helper::get_plugin_strings();
505 if ($reports = grade_helper::get_plugins_reports($courseid)) {
506 $plugin_info['report'] = $reports;
509 //showing grade categories and items make no sense if we're not within a course
510 if ($courseid!=$SITE->id) {
511 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
512 $plugin_info['edittree'] = $edittree;
516 if ($scale = grade_helper::get_info_scales($courseid)) {
517 $plugin_info['scale'] = array('view'=>$scale);
520 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
521 $plugin_info['outcome'] = $outcomes;
524 if ($letters = grade_helper::get_info_letters($courseid)) {
525 $plugin_info['letter'] = $letters;
528 if ($imports = grade_helper::get_plugins_import($courseid)) {
529 $plugin_info['import'] = $imports;
532 if ($exports = grade_helper::get_plugins_export($courseid)) {
533 $plugin_info['export'] = $exports;
536 foreach ($plugin_info as $plugin_type => $plugins) {
537 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
538 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
539 break;
541 foreach ($plugins as $plugin) {
542 if (is_a($plugin, 'grade_plugin_info')) {
543 if ($active_plugin == $plugin->id) {
544 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
550 //hide course settings if we're not in a course
551 if ($courseid!=$SITE->id) {
552 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
553 $plugin_info['settings'] = array('course'=>$setting);
557 // Put preferences last
558 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
559 $plugin_info['preferences'] = $preferences;
562 foreach ($plugin_info as $plugin_type => $plugins) {
563 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
564 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
565 break;
567 foreach ($plugins as $plugin) {
568 if (is_a($plugin, 'grade_plugin_info')) {
569 if ($active_plugin == $plugin->id) {
570 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
576 return $plugin_info;
580 * A simple class containing info about grade plugins.
581 * Can be subclassed for special rules
583 * @package core_grades
584 * @copyright 2009 Nicolas Connault
585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
587 class grade_plugin_info {
589 * A unique id for this plugin
591 * @var mixed
593 public $id;
595 * A URL to access this plugin
597 * @var mixed
599 public $link;
601 * The name of this plugin
603 * @var mixed
605 public $string;
607 * Another grade_plugin_info object, parent of the current one
609 * @var mixed
611 public $parent;
614 * Constructor
616 * @param int $id A unique id for this plugin
617 * @param string $link A URL to access this plugin
618 * @param string $string The name of this plugin
619 * @param object $parent Another grade_plugin_info object, parent of the current one
621 * @return void
623 public function __construct($id, $link, $string, $parent=null) {
624 $this->id = $id;
625 $this->link = $link;
626 $this->string = $string;
627 $this->parent = $parent;
632 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
633 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
634 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
635 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
636 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
638 * @param int $courseid Course id
639 * @param string $active_type The type of the current page (report, settings,
640 * import, export, scales, outcomes, letters)
641 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
642 * @param string $heading The heading of the page. Tries to guess if none is given
643 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
644 * @param string $bodytags Additional attributes that will be added to the <body> tag
645 * @param string $buttons Additional buttons to display on the page
646 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
648 * @return string HTML code or nothing if $return == false
650 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
651 $heading = false, $return=false,
652 $buttons=false, $shownavigation=true) {
653 global $CFG, $OUTPUT, $PAGE;
655 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
657 // Determine the string of the active plugin
658 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
659 $stractive_type = $plugin_info['strings'][$active_type];
661 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
662 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
663 } else {
664 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
667 if ($active_type == 'report') {
668 $PAGE->set_pagelayout('report');
669 } else {
670 $PAGE->set_pagelayout('admin');
672 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
673 $PAGE->set_heading($title);
674 if ($buttons instanceof single_button) {
675 $buttons = $OUTPUT->render($buttons);
677 $PAGE->set_button($buttons);
678 grade_extend_settings($plugin_info, $courseid);
680 $returnval = $OUTPUT->header();
681 if (!$return) {
682 echo $returnval;
685 // Guess heading if not given explicitly
686 if (!$heading) {
687 $heading = $stractive_plugin;
690 if ($shownavigation) {
691 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
692 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
695 if ($return) {
696 $returnval .= $OUTPUT->heading($heading);
697 } else {
698 echo $OUTPUT->heading($heading);
701 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
702 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
706 if ($return) {
707 return $returnval;
712 * Utility class used for return tracking when using edit and other forms in grade plugins
714 * @package core_grades
715 * @copyright 2009 Nicolas Connault
716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
718 class grade_plugin_return {
719 public $type;
720 public $plugin;
721 public $courseid;
722 public $userid;
723 public $page;
726 * Constructor
728 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
730 public function grade_plugin_return($params = null) {
731 if (empty($params)) {
732 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
733 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
734 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
735 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
736 $this->page = optional_param('gpr_page', null, PARAM_INT);
738 } else {
739 foreach ($params as $key=>$value) {
740 if (property_exists($this, $key)) {
741 $this->$key = $value;
748 * Returns return parameters as options array suitable for buttons.
749 * @return array options
751 public function get_options() {
752 if (empty($this->type)) {
753 return array();
756 $params = array();
758 if (!empty($this->plugin)) {
759 $params['plugin'] = $this->plugin;
762 if (!empty($this->courseid)) {
763 $params['id'] = $this->courseid;
766 if (!empty($this->userid)) {
767 $params['userid'] = $this->userid;
770 if (!empty($this->page)) {
771 $params['page'] = $this->page;
774 return $params;
778 * Returns return url
780 * @param string $default default url when params not set
781 * @param array $extras Extra URL parameters
783 * @return string url
785 public function get_return_url($default, $extras=null) {
786 global $CFG;
788 if (empty($this->type) or empty($this->plugin)) {
789 return $default;
792 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
793 $glue = '?';
795 if (!empty($this->courseid)) {
796 $url .= $glue.'id='.$this->courseid;
797 $glue = '&amp;';
800 if (!empty($this->userid)) {
801 $url .= $glue.'userid='.$this->userid;
802 $glue = '&amp;';
805 if (!empty($this->page)) {
806 $url .= $glue.'page='.$this->page;
807 $glue = '&amp;';
810 if (!empty($extras)) {
811 foreach ($extras as $key=>$value) {
812 $url .= $glue.$key.'='.$value;
813 $glue = '&amp;';
817 return $url;
821 * Returns string with hidden return tracking form elements.
822 * @return string
824 public function get_form_fields() {
825 if (empty($this->type)) {
826 return '';
829 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
831 if (!empty($this->plugin)) {
832 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
835 if (!empty($this->courseid)) {
836 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
839 if (!empty($this->userid)) {
840 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
843 if (!empty($this->page)) {
844 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
849 * Add hidden elements into mform
851 * @param object &$mform moodle form object
853 * @return void
855 public function add_mform_elements(&$mform) {
856 if (empty($this->type)) {
857 return;
860 $mform->addElement('hidden', 'gpr_type', $this->type);
861 $mform->setType('gpr_type', PARAM_SAFEDIR);
863 if (!empty($this->plugin)) {
864 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
865 $mform->setType('gpr_plugin', PARAM_PLUGIN);
868 if (!empty($this->courseid)) {
869 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
870 $mform->setType('gpr_courseid', PARAM_INT);
873 if (!empty($this->userid)) {
874 $mform->addElement('hidden', 'gpr_userid', $this->userid);
875 $mform->setType('gpr_userid', PARAM_INT);
878 if (!empty($this->page)) {
879 $mform->addElement('hidden', 'gpr_page', $this->page);
880 $mform->setType('gpr_page', PARAM_INT);
885 * Add return tracking params into url
887 * @param moodle_url $url A URL
889 * @return string $url with return tracking params
891 public function add_url_params(moodle_url $url) {
892 if (empty($this->type)) {
893 return $url;
896 $url->param('gpr_type', $this->type);
898 if (!empty($this->plugin)) {
899 $url->param('gpr_plugin', $this->plugin);
902 if (!empty($this->courseid)) {
903 $url->param('gpr_courseid' ,$this->courseid);
906 if (!empty($this->userid)) {
907 $url->param('gpr_userid', $this->userid);
910 if (!empty($this->page)) {
911 $url->param('gpr_page', $this->page);
914 return $url;
919 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
921 * @param string $path The path of the calling script (using __FILE__?)
922 * @param string $pagename The language string to use as the last part of the navigation (non-link)
923 * @param mixed $id Either a plain integer (assuming the key is 'id') or
924 * an array of keys and values (e.g courseid => $courseid, itemid...)
926 * @return string
928 function grade_build_nav($path, $pagename=null, $id=null) {
929 global $CFG, $COURSE, $PAGE;
931 $strgrades = get_string('grades', 'grades');
933 // Parse the path and build navlinks from its elements
934 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
935 $path = substr($path, $dirroot_length);
936 $path = str_replace('\\', '/', $path);
938 $path_elements = explode('/', $path);
940 $path_elements_count = count($path_elements);
942 // First link is always 'grade'
943 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
945 $link = null;
946 $numberofelements = 3;
948 // Prepare URL params string
949 $linkparams = array();
950 if (!is_null($id)) {
951 if (is_array($id)) {
952 foreach ($id as $idkey => $idvalue) {
953 $linkparams[$idkey] = $idvalue;
955 } else {
956 $linkparams['id'] = $id;
960 $navlink4 = null;
962 // Remove file extensions from filenames
963 foreach ($path_elements as $key => $filename) {
964 $path_elements[$key] = str_replace('.php', '', $filename);
967 // Second level links
968 switch ($path_elements[1]) {
969 case 'edit': // No link
970 if ($path_elements[3] != 'index.php') {
971 $numberofelements = 4;
973 break;
974 case 'import': // No link
975 break;
976 case 'export': // No link
977 break;
978 case 'report':
979 // $id is required for this link. Do not print it if $id isn't given
980 if (!is_null($id)) {
981 $link = new moodle_url('/grade/report/index.php', $linkparams);
984 if ($path_elements[2] == 'grader') {
985 $numberofelements = 4;
987 break;
989 default:
990 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
991 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
992 " as the second path element after 'grade'.");
993 return false;
995 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
997 // Third level links
998 if (empty($pagename)) {
999 $pagename = get_string($path_elements[2], 'grades');
1002 switch ($numberofelements) {
1003 case 3:
1004 $PAGE->navbar->add($pagename, $link);
1005 break;
1006 case 4:
1007 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1008 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1010 $PAGE->navbar->add($pagename);
1011 break;
1014 return '';
1018 * General structure representing grade items in course
1020 * @package core_grades
1021 * @copyright 2009 Nicolas Connault
1022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1024 class grade_structure {
1025 public $context;
1027 public $courseid;
1030 * Reference to modinfo for current course (for performance, to save
1031 * retrieving it from courseid every time). Not actually set except for
1032 * the grade_tree type.
1033 * @var course_modinfo
1035 public $modinfo;
1038 * 1D array of grade items only
1040 public $items;
1043 * Returns icon of element
1045 * @param array &$element An array representing an element in the grade_tree
1046 * @param bool $spacerifnone return spacer if no icon found
1048 * @return string icon or spacer
1050 public function get_element_icon(&$element, $spacerifnone=false) {
1051 global $CFG, $OUTPUT;
1053 switch ($element['type']) {
1054 case 'item':
1055 case 'courseitem':
1056 case 'categoryitem':
1057 $is_course = $element['object']->is_course_item();
1058 $is_category = $element['object']->is_category_item();
1059 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1060 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1061 $is_outcome = !empty($element['object']->outcomeid);
1063 if ($element['object']->is_calculated()) {
1064 $strcalc = get_string('calculatedgrade', 'grades');
1065 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1066 s($strcalc).'" alt="'.s($strcalc).'"/>';
1068 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1069 if ($category = $element['object']->get_item_category()) {
1070 switch ($category->aggregation) {
1071 case GRADE_AGGREGATE_MEAN:
1072 case GRADE_AGGREGATE_MEDIAN:
1073 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1074 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1075 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1076 $stragg = get_string('aggregation', 'grades');
1077 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1078 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1079 case GRADE_AGGREGATE_SUM:
1080 $stragg = get_string('aggregation', 'grades');
1081 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1082 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1086 } else if ($element['object']->itemtype == 'mod') {
1087 //prevent outcomes being displaying the same icon as the activity they are attached to
1088 if ($is_outcome) {
1089 $stroutcome = s(get_string('outcome', 'grades'));
1090 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1091 'class="icon itemicon" title="'.$stroutcome.
1092 '" alt="'.$stroutcome.'"/>';
1093 } else {
1094 $strmodname = get_string('modulename', $element['object']->itemmodule);
1095 return '<img src="'.$OUTPUT->pix_url('icon',
1096 $element['object']->itemmodule) . '" ' .
1097 'class="icon itemicon" title="' .s($strmodname).
1098 '" alt="' .s($strmodname).'"/>';
1100 } else if ($element['object']->itemtype == 'manual') {
1101 if ($element['object']->is_outcome_item()) {
1102 $stroutcome = get_string('outcome', 'grades');
1103 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1104 'class="icon itemicon" title="'.s($stroutcome).
1105 '" alt="'.s($stroutcome).'"/>';
1106 } else {
1107 $strmanual = get_string('manualitem', 'grades');
1108 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
1109 'class="icon itemicon" title="'.s($strmanual).
1110 '" alt="'.s($strmanual).'"/>';
1113 break;
1115 case 'category':
1116 $strcat = get_string('category', 'grades');
1117 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
1118 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1121 if ($spacerifnone) {
1122 return $OUTPUT->spacer().' ';
1123 } else {
1124 return '';
1129 * Returns name of element optionally with icon and link
1131 * @param array &$element An array representing an element in the grade_tree
1132 * @param bool $withlink Whether or not this header has a link
1133 * @param bool $icon Whether or not to display an icon with this header
1134 * @param bool $spacerifnone return spacer if no icon found
1136 * @return string header
1138 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1139 $header = '';
1141 if ($icon) {
1142 $header .= $this->get_element_icon($element, $spacerifnone);
1145 $header .= $element['object']->get_name();
1147 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1148 $element['type'] != 'courseitem') {
1149 return $header;
1152 if ($withlink) {
1153 $url = $this->get_activity_link($element);
1154 if ($url) {
1155 $a = new stdClass();
1156 $a->name = get_string('modulename', $element['object']->itemmodule);
1157 $title = get_string('linktoactivity', 'grades', $a);
1159 $header = html_writer::link($url, $header, array('title' => $title));
1163 return $header;
1166 private function get_activity_link($element) {
1167 global $CFG;
1168 /** @var array static cache of the grade.php file existence flags */
1169 static $hasgradephp = array();
1171 $itemtype = $element['object']->itemtype;
1172 $itemmodule = $element['object']->itemmodule;
1173 $iteminstance = $element['object']->iteminstance;
1174 $itemnumber = $element['object']->itemnumber;
1176 // Links only for module items that have valid instance, module and are
1177 // called from grade_tree with valid modinfo
1178 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1179 return null;
1182 // Get $cm efficiently and with visibility information using modinfo
1183 $instances = $this->modinfo->get_instances();
1184 if (empty($instances[$itemmodule][$iteminstance])) {
1185 return null;
1187 $cm = $instances[$itemmodule][$iteminstance];
1189 // Do not add link if activity is not visible to the current user
1190 if (!$cm->uservisible) {
1191 return null;
1194 if (!array_key_exists($itemmodule, $hasgradephp)) {
1195 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1196 $hasgradephp[$itemmodule] = true;
1197 } else {
1198 $hasgradephp[$itemmodule] = false;
1202 // If module has grade.php, link to that, otherwise view.php
1203 if ($hasgradephp[$itemmodule]) {
1204 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1205 if (isset($element['userid'])) {
1206 $args['userid'] = $element['userid'];
1208 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1209 } else {
1210 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1215 * Returns URL of a page that is supposed to contain detailed grade analysis
1217 * At the moment, only activity modules are supported. The method generates link
1218 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1219 * gradeid and userid. If the grade.php does not exist, null is returned.
1221 * @return moodle_url|null URL or null if unable to construct it
1223 public function get_grade_analysis_url(grade_grade $grade) {
1224 global $CFG;
1225 /** @var array static cache of the grade.php file existence flags */
1226 static $hasgradephp = array();
1228 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1229 throw new coding_exception('Passed grade without the associated grade item');
1231 $item = $grade->grade_item;
1233 if (!$item->is_external_item()) {
1234 // at the moment, only activity modules are supported
1235 return null;
1237 if ($item->itemtype !== 'mod') {
1238 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1240 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1241 return null;
1244 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1245 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1246 $hasgradephp[$item->itemmodule] = true;
1247 } else {
1248 $hasgradephp[$item->itemmodule] = false;
1252 if (!$hasgradephp[$item->itemmodule]) {
1253 return null;
1256 $instances = $this->modinfo->get_instances();
1257 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1258 return null;
1260 $cm = $instances[$item->itemmodule][$item->iteminstance];
1261 if (!$cm->uservisible) {
1262 return null;
1265 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1266 'id' => $cm->id,
1267 'itemid' => $item->id,
1268 'itemnumber' => $item->itemnumber,
1269 'gradeid' => $grade->id,
1270 'userid' => $grade->userid,
1273 return $url;
1277 * Returns an action icon leading to the grade analysis page
1279 * @param grade_grade $grade
1280 * @return string
1282 public function get_grade_analysis_icon(grade_grade $grade) {
1283 global $OUTPUT;
1285 $url = $this->get_grade_analysis_url($grade);
1286 if (is_null($url)) {
1287 return '';
1290 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1291 get_string('gradeanalysis', 'core_grades')));
1295 * Returns the grade eid - the grade may not exist yet.
1297 * @param grade_grade $grade_grade A grade_grade object
1299 * @return string eid
1301 public function get_grade_eid($grade_grade) {
1302 if (empty($grade_grade->id)) {
1303 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1304 } else {
1305 return 'g'.$grade_grade->id;
1310 * Returns the grade_item eid
1311 * @param grade_item $grade_item A grade_item object
1312 * @return string eid
1314 public function get_item_eid($grade_item) {
1315 return 'i'.$grade_item->id;
1319 * Given a grade_tree element, returns an array of parameters
1320 * used to build an icon for that element.
1322 * @param array $element An array representing an element in the grade_tree
1324 * @return array
1326 public function get_params_for_iconstr($element) {
1327 $strparams = new stdClass();
1328 $strparams->category = '';
1329 $strparams->itemname = '';
1330 $strparams->itemmodule = '';
1332 if (!method_exists($element['object'], 'get_name')) {
1333 return $strparams;
1336 $strparams->itemname = html_to_text($element['object']->get_name());
1338 // If element name is categorytotal, get the name of the parent category
1339 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1340 $parent = $element['object']->get_parent_category();
1341 $strparams->category = $parent->get_name() . ' ';
1342 } else {
1343 $strparams->category = '';
1346 $strparams->itemmodule = null;
1347 if (isset($element['object']->itemmodule)) {
1348 $strparams->itemmodule = $element['object']->itemmodule;
1350 return $strparams;
1354 * Return edit icon for give element
1356 * @param array $element An array representing an element in the grade_tree
1357 * @param object $gpr A grade_plugin_return object
1359 * @return string
1361 public function get_edit_icon($element, $gpr) {
1362 global $CFG, $OUTPUT;
1364 if (!has_capability('moodle/grade:manage', $this->context)) {
1365 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1366 // oki - let them override grade
1367 } else {
1368 return '';
1372 static $strfeedback = null;
1373 static $streditgrade = null;
1374 if (is_null($streditgrade)) {
1375 $streditgrade = get_string('editgrade', 'grades');
1376 $strfeedback = get_string('feedback');
1379 $strparams = $this->get_params_for_iconstr($element);
1381 $object = $element['object'];
1383 switch ($element['type']) {
1384 case 'item':
1385 case 'categoryitem':
1386 case 'courseitem':
1387 $stredit = get_string('editverbose', 'grades', $strparams);
1388 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1389 $url = new moodle_url('/grade/edit/tree/item.php',
1390 array('courseid' => $this->courseid, 'id' => $object->id));
1391 } else {
1392 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1393 array('courseid' => $this->courseid, 'id' => $object->id));
1395 break;
1397 case 'category':
1398 $stredit = get_string('editverbose', 'grades', $strparams);
1399 $url = new moodle_url('/grade/edit/tree/category.php',
1400 array('courseid' => $this->courseid, 'id' => $object->id));
1401 break;
1403 case 'grade':
1404 $stredit = $streditgrade;
1405 if (empty($object->id)) {
1406 $url = new moodle_url('/grade/edit/tree/grade.php',
1407 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1408 } else {
1409 $url = new moodle_url('/grade/edit/tree/grade.php',
1410 array('courseid' => $this->courseid, 'id' => $object->id));
1412 if (!empty($object->feedback)) {
1413 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1415 break;
1417 default:
1418 $url = null;
1421 if ($url) {
1422 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1424 } else {
1425 return '';
1430 * Return hiding icon for give element
1432 * @param array $element An array representing an element in the grade_tree
1433 * @param object $gpr A grade_plugin_return object
1435 * @return string
1437 public function get_hiding_icon($element, $gpr) {
1438 global $CFG, $OUTPUT;
1440 if (!has_capability('moodle/grade:manage', $this->context) and
1441 !has_capability('moodle/grade:hide', $this->context)) {
1442 return '';
1445 $strparams = $this->get_params_for_iconstr($element);
1446 $strshow = get_string('showverbose', 'grades', $strparams);
1447 $strhide = get_string('hideverbose', 'grades', $strparams);
1449 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1450 $url = $gpr->add_url_params($url);
1452 if ($element['object']->is_hidden()) {
1453 $type = 'show';
1454 $tooltip = $strshow;
1456 // Change the icon and add a tooltip showing the date
1457 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1458 $type = 'hiddenuntil';
1459 $tooltip = get_string('hiddenuntildate', 'grades',
1460 userdate($element['object']->get_hidden()));
1463 $url->param('action', 'show');
1465 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
1467 } else {
1468 $url->param('action', 'hide');
1469 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1472 return $hideicon;
1476 * Return locking icon for given element
1478 * @param array $element An array representing an element in the grade_tree
1479 * @param object $gpr A grade_plugin_return object
1481 * @return string
1483 public function get_locking_icon($element, $gpr) {
1484 global $CFG, $OUTPUT;
1486 $strparams = $this->get_params_for_iconstr($element);
1487 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1488 $strlock = get_string('lockverbose', 'grades', $strparams);
1490 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1491 $url = $gpr->add_url_params($url);
1493 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1494 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1495 $strparamobj = new stdClass();
1496 $strparamobj->itemname = $element['object']->grade_item->itemname;
1497 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1499 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
1501 } else if ($element['object']->is_locked()) {
1502 $type = 'unlock';
1503 $tooltip = $strunlock;
1505 // Change the icon and add a tooltip showing the date
1506 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1507 $type = 'locktime';
1508 $tooltip = get_string('locktimedate', 'grades',
1509 userdate($element['object']->get_locktime()));
1512 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1513 $action = '';
1514 } else {
1515 $url->param('action', 'unlock');
1516 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1519 } else {
1520 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1521 $action = '';
1522 } else {
1523 $url->param('action', 'lock');
1524 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1528 return $action;
1532 * Return calculation icon for given element
1534 * @param array $element An array representing an element in the grade_tree
1535 * @param object $gpr A grade_plugin_return object
1537 * @return string
1539 public function get_calculation_icon($element, $gpr) {
1540 global $CFG, $OUTPUT;
1541 if (!has_capability('moodle/grade:manage', $this->context)) {
1542 return '';
1545 $type = $element['type'];
1546 $object = $element['object'];
1548 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1549 $strparams = $this->get_params_for_iconstr($element);
1550 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1552 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1553 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1555 // show calculation icon only when calculation possible
1556 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1557 if ($object->is_calculated()) {
1558 $icon = 't/calc';
1559 } else {
1560 $icon = 't/calc_off';
1563 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1564 $url = $gpr->add_url_params($url);
1565 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
1569 return '';
1574 * Flat structure similar to grade tree.
1576 * @uses grade_structure
1577 * @package core_grades
1578 * @copyright 2009 Nicolas Connault
1579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1581 class grade_seq extends grade_structure {
1584 * 1D array of elements
1586 public $elements;
1589 * Constructor, retrieves and stores array of all grade_category and grade_item
1590 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1592 * @param int $courseid The course id
1593 * @param bool $category_grade_last category grade item is the last child
1594 * @param bool $nooutcomes Whether or not outcomes should be included
1596 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1597 global $USER, $CFG;
1599 $this->courseid = $courseid;
1600 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1602 // get course grade tree
1603 $top_element = grade_category::fetch_course_tree($courseid, true);
1605 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1607 foreach ($this->elements as $key=>$unused) {
1608 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1613 * Static recursive helper - makes the grade_item for category the last children
1615 * @param array &$element The seed of the recursion
1616 * @param bool $category_grade_last category grade item is the last child
1617 * @param bool $nooutcomes Whether or not outcomes should be included
1619 * @return array
1621 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1622 if (empty($element['children'])) {
1623 return array();
1625 $children = array();
1627 foreach ($element['children'] as $sortorder=>$unused) {
1628 if ($nooutcomes and $element['type'] != 'category' and
1629 $element['children'][$sortorder]['object']->is_outcome_item()) {
1630 continue;
1632 $children[] = $element['children'][$sortorder];
1634 unset($element['children']);
1636 if ($category_grade_last and count($children) > 1) {
1637 $cat_item = array_shift($children);
1638 array_push($children, $cat_item);
1641 $result = array();
1642 foreach ($children as $child) {
1643 if ($child['type'] == 'category') {
1644 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1645 } else {
1646 $child['eid'] = 'i'.$child['object']->id;
1647 $result[$child['object']->id] = $child;
1651 return $result;
1655 * Parses the array in search of a given eid and returns a element object with
1656 * information about the element it has found.
1658 * @param int $eid Gradetree Element ID
1660 * @return object element
1662 public function locate_element($eid) {
1663 // it is a grade - construct a new object
1664 if (strpos($eid, 'n') === 0) {
1665 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1666 return null;
1669 $itemid = $matches[1];
1670 $userid = $matches[2];
1672 //extra security check - the grade item must be in this tree
1673 if (!$item_el = $this->locate_element('i'.$itemid)) {
1674 return null;
1677 // $gradea->id may be null - means does not exist yet
1678 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1680 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1681 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1683 } else if (strpos($eid, 'g') === 0) {
1684 $id = (int) substr($eid, 1);
1685 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1686 return null;
1688 //extra security check - the grade item must be in this tree
1689 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1690 return null;
1692 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1693 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1696 // it is a category or item
1697 foreach ($this->elements as $element) {
1698 if ($element['eid'] == $eid) {
1699 return $element;
1703 return null;
1708 * This class represents a complete tree of categories, grade_items and final grades,
1709 * organises as an array primarily, but which can also be converted to other formats.
1710 * It has simple method calls with complex implementations, allowing for easy insertion,
1711 * deletion and moving of items and categories within the tree.
1713 * @uses grade_structure
1714 * @package core_grades
1715 * @copyright 2009 Nicolas Connault
1716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1718 class grade_tree extends grade_structure {
1721 * The basic representation of the tree as a hierarchical, 3-tiered array.
1722 * @var object $top_element
1724 public $top_element;
1727 * 2D array of grade items and categories
1728 * @var array $levels
1730 public $levels;
1733 * Grade items
1734 * @var array $items
1736 public $items;
1739 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1740 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1742 * @param int $courseid The Course ID
1743 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1744 * @param bool $category_grade_last category grade item is the last child
1745 * @param array $collapsed array of collapsed categories
1746 * @param bool $nooutcomes Whether or not outcomes should be included
1748 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1749 $collapsed=null, $nooutcomes=false) {
1750 global $USER, $CFG, $COURSE, $DB;
1752 $this->courseid = $courseid;
1753 $this->levels = array();
1754 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1756 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1757 $course = $COURSE;
1758 } else {
1759 $course = $DB->get_record('course', array('id' => $this->courseid));
1761 $this->modinfo = get_fast_modinfo($course);
1763 // get course grade tree
1764 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1766 // collapse the categories if requested
1767 if (!empty($collapsed)) {
1768 grade_tree::category_collapse($this->top_element, $collapsed);
1771 // no otucomes if requested
1772 if (!empty($nooutcomes)) {
1773 grade_tree::no_outcomes($this->top_element);
1776 // move category item to last position in category
1777 if ($category_grade_last) {
1778 grade_tree::category_grade_last($this->top_element);
1781 if ($fillers) {
1782 // inject fake categories == fillers
1783 grade_tree::inject_fillers($this->top_element, 0);
1784 // add colspans to categories and fillers
1785 grade_tree::inject_colspans($this->top_element);
1788 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1793 * Static recursive helper - removes items from collapsed categories
1795 * @param array &$element The seed of the recursion
1796 * @param array $collapsed array of collapsed categories
1798 * @return void
1800 public function category_collapse(&$element, $collapsed) {
1801 if ($element['type'] != 'category') {
1802 return;
1804 if (empty($element['children']) or count($element['children']) < 2) {
1805 return;
1808 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1809 $category_item = reset($element['children']); //keep only category item
1810 $element['children'] = array(key($element['children'])=>$category_item);
1812 } else {
1813 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1814 reset($element['children']);
1815 $first_key = key($element['children']);
1816 unset($element['children'][$first_key]);
1818 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1819 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1825 * Static recursive helper - removes all outcomes
1827 * @param array &$element The seed of the recursion
1829 * @return void
1831 public function no_outcomes(&$element) {
1832 if ($element['type'] != 'category') {
1833 return;
1835 foreach ($element['children'] as $sortorder=>$child) {
1836 if ($element['children'][$sortorder]['type'] == 'item'
1837 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1838 unset($element['children'][$sortorder]);
1840 } else if ($element['children'][$sortorder]['type'] == 'category') {
1841 grade_tree::no_outcomes($element['children'][$sortorder]);
1847 * Static recursive helper - makes the grade_item for category the last children
1849 * @param array &$element The seed of the recursion
1851 * @return void
1853 public function category_grade_last(&$element) {
1854 if (empty($element['children'])) {
1855 return;
1857 if (count($element['children']) < 2) {
1858 return;
1860 $first_item = reset($element['children']);
1861 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1862 // the category item might have been already removed
1863 $order = key($element['children']);
1864 unset($element['children'][$order]);
1865 $element['children'][$order] =& $first_item;
1867 foreach ($element['children'] as $sortorder => $child) {
1868 grade_tree::category_grade_last($element['children'][$sortorder]);
1873 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1875 * @param array &$levels The levels of the grade tree through which to recurse
1876 * @param array &$element The seed of the recursion
1877 * @param int $depth How deep are we?
1878 * @return void
1880 public function fill_levels(&$levels, &$element, $depth) {
1881 if (!array_key_exists($depth, $levels)) {
1882 $levels[$depth] = array();
1885 // prepare unique identifier
1886 if ($element['type'] == 'category') {
1887 $element['eid'] = 'c'.$element['object']->id;
1888 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1889 $element['eid'] = 'i'.$element['object']->id;
1890 $this->items[$element['object']->id] =& $element['object'];
1893 $levels[$depth][] =& $element;
1894 $depth++;
1895 if (empty($element['children'])) {
1896 return;
1898 $prev = 0;
1899 foreach ($element['children'] as $sortorder=>$child) {
1900 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1901 $element['children'][$sortorder]['prev'] = $prev;
1902 $element['children'][$sortorder]['next'] = 0;
1903 if ($prev) {
1904 $element['children'][$prev]['next'] = $sortorder;
1906 $prev = $sortorder;
1911 * Static recursive helper - makes full tree (all leafes are at the same level)
1913 * @param array &$element The seed of the recursion
1914 * @param int $depth How deep are we?
1916 * @return int
1918 public function inject_fillers(&$element, $depth) {
1919 $depth++;
1921 if (empty($element['children'])) {
1922 return $depth;
1924 $chdepths = array();
1925 $chids = array_keys($element['children']);
1926 $last_child = end($chids);
1927 $first_child = reset($chids);
1929 foreach ($chids as $chid) {
1930 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1932 arsort($chdepths);
1934 $maxdepth = reset($chdepths);
1935 foreach ($chdepths as $chid=>$chd) {
1936 if ($chd == $maxdepth) {
1937 continue;
1939 for ($i=0; $i < $maxdepth-$chd; $i++) {
1940 if ($chid == $first_child) {
1941 $type = 'fillerfirst';
1942 } else if ($chid == $last_child) {
1943 $type = 'fillerlast';
1944 } else {
1945 $type = 'filler';
1947 $oldchild =& $element['children'][$chid];
1948 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1949 'eid'=>'', 'depth'=>$element['object']->depth,
1950 'children'=>array($oldchild));
1954 return $maxdepth;
1958 * Static recursive helper - add colspan information into categories
1960 * @param array &$element The seed of the recursion
1962 * @return int
1964 public function inject_colspans(&$element) {
1965 if (empty($element['children'])) {
1966 return 1;
1968 $count = 0;
1969 foreach ($element['children'] as $key=>$child) {
1970 $count += grade_tree::inject_colspans($element['children'][$key]);
1972 $element['colspan'] = $count;
1973 return $count;
1977 * Parses the array in search of a given eid and returns a element object with
1978 * information about the element it has found.
1979 * @param int $eid Gradetree Element ID
1980 * @return object element
1982 public function locate_element($eid) {
1983 // it is a grade - construct a new object
1984 if (strpos($eid, 'n') === 0) {
1985 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1986 return null;
1989 $itemid = $matches[1];
1990 $userid = $matches[2];
1992 //extra security check - the grade item must be in this tree
1993 if (!$item_el = $this->locate_element('i'.$itemid)) {
1994 return null;
1997 // $gradea->id may be null - means does not exist yet
1998 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2000 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2001 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2003 } else if (strpos($eid, 'g') === 0) {
2004 $id = (int) substr($eid, 1);
2005 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2006 return null;
2008 //extra security check - the grade item must be in this tree
2009 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2010 return null;
2012 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2013 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2016 // it is a category or item
2017 foreach ($this->levels as $row) {
2018 foreach ($row as $element) {
2019 if ($element['type'] == 'filler') {
2020 continue;
2022 if ($element['eid'] == $eid) {
2023 return $element;
2028 return null;
2032 * Returns a well-formed XML representation of the grade-tree using recursion.
2034 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2035 * @param string $tabs The control character to use for tabs
2037 * @return string $xml
2039 public function exporttoxml($root=null, $tabs="\t") {
2040 $xml = null;
2041 $first = false;
2042 if (is_null($root)) {
2043 $root = $this->top_element;
2044 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2045 $xml .= "<gradetree>\n";
2046 $first = true;
2049 $type = 'undefined';
2050 if (strpos($root['object']->table, 'grade_categories') !== false) {
2051 $type = 'category';
2052 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2053 $type = 'item';
2054 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2055 $type = 'outcome';
2058 $xml .= "$tabs<element type=\"$type\">\n";
2059 foreach ($root['object'] as $var => $value) {
2060 if (!is_object($value) && !is_array($value) && !empty($value)) {
2061 $xml .= "$tabs\t<$var>$value</$var>\n";
2065 if (!empty($root['children'])) {
2066 $xml .= "$tabs\t<children>\n";
2067 foreach ($root['children'] as $sortorder => $child) {
2068 $xml .= $this->exportToXML($child, $tabs."\t\t");
2070 $xml .= "$tabs\t</children>\n";
2073 $xml .= "$tabs</element>\n";
2075 if ($first) {
2076 $xml .= "</gradetree>";
2079 return $xml;
2083 * Returns a JSON representation of the grade-tree using recursion.
2085 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2086 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2088 * @return string
2090 public function exporttojson($root=null, $tabs="\t") {
2091 $json = null;
2092 $first = false;
2093 if (is_null($root)) {
2094 $root = $this->top_element;
2095 $first = true;
2098 $name = '';
2101 if (strpos($root['object']->table, 'grade_categories') !== false) {
2102 $name = $root['object']->fullname;
2103 if ($name == '?') {
2104 $name = $root['object']->get_name();
2106 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2107 $name = $root['object']->itemname;
2108 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2109 $name = $root['object']->itemname;
2112 $json .= "$tabs {\n";
2113 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2114 $json .= "$tabs\t \"name\": \"$name\",\n";
2116 foreach ($root['object'] as $var => $value) {
2117 if (!is_object($value) && !is_array($value) && !empty($value)) {
2118 $json .= "$tabs\t \"$var\": \"$value\",\n";
2122 $json = substr($json, 0, strrpos($json, ','));
2124 if (!empty($root['children'])) {
2125 $json .= ",\n$tabs\t\"children\": [\n";
2126 foreach ($root['children'] as $sortorder => $child) {
2127 $json .= $this->exportToJSON($child, $tabs."\t\t");
2129 $json = substr($json, 0, strrpos($json, ','));
2130 $json .= "\n$tabs\t]\n";
2133 if ($first) {
2134 $json .= "\n}";
2135 } else {
2136 $json .= "\n$tabs},\n";
2139 return $json;
2143 * Returns the array of levels
2145 * @return array
2147 public function get_levels() {
2148 return $this->levels;
2152 * Returns the array of grade items
2154 * @return array
2156 public function get_items() {
2157 return $this->items;
2161 * Returns a specific Grade Item
2163 * @param int $itemid The ID of the grade_item object
2165 * @return grade_item
2167 public function get_item($itemid) {
2168 if (array_key_exists($itemid, $this->items)) {
2169 return $this->items[$itemid];
2170 } else {
2171 return false;
2177 * Local shortcut function for creating an edit/delete button for a grade_* object.
2178 * @param string $type 'edit' or 'delete'
2179 * @param int $courseid The Course ID
2180 * @param grade_* $object The grade_* object
2181 * @return string html
2183 function grade_button($type, $courseid, $object) {
2184 global $CFG, $OUTPUT;
2185 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2186 $objectidstring = $matches[1] . 'id';
2187 } else {
2188 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2191 $strdelete = get_string('delete');
2192 $stredit = get_string('edit');
2194 if ($type == 'delete') {
2195 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2196 } else if ($type == 'edit') {
2197 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2200 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
2205 * This method adds settings to the settings block for the grade system and its
2206 * plugins
2208 * @global moodle_page $PAGE
2210 function grade_extend_settings($plugininfo, $courseid) {
2211 global $PAGE;
2213 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2215 $strings = array_shift($plugininfo);
2217 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2218 foreach ($reports as $report) {
2219 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2223 if ($imports = grade_helper::get_plugins_import($courseid)) {
2224 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2225 foreach ($imports as $import) {
2226 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2230 if ($exports = grade_helper::get_plugins_export($courseid)) {
2231 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2232 foreach ($exports as $export) {
2233 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2237 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2238 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2241 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2242 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2243 foreach ($preferences as $preference) {
2244 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2248 if ($letters = grade_helper::get_info_letters($courseid)) {
2249 $letters = array_shift($letters);
2250 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2253 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2254 $outcomes = array_shift($outcomes);
2255 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2258 if ($scales = grade_helper::get_info_scales($courseid)) {
2259 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2262 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2263 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2264 foreach ($categories as $category) {
2265 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2269 if ($gradenode->contains_active_node()) {
2270 // If the gradenode is active include the settings base node (gradeadministration) in
2271 // the navbar, typcially this is ignored.
2272 $PAGE->navbar->includesettingsbase = true;
2274 // If we can get the course admin node make sure it is closed by default
2275 // as in this case the gradenode will be opened
2276 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2277 $coursenode->make_inactive();
2278 $coursenode->forceopen = false;
2284 * Grade helper class
2286 * This class provides several helpful functions that work irrespective of any
2287 * current state.
2289 * @copyright 2010 Sam Hemelryk
2290 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2292 abstract class grade_helper {
2294 * Cached manage settings info {@see get_info_settings}
2295 * @var grade_plugin_info|false
2297 protected static $managesetting = null;
2299 * Cached grade report plugins {@see get_plugins_reports}
2300 * @var array|false
2302 protected static $gradereports = null;
2304 * Cached grade report plugins preferences {@see get_info_scales}
2305 * @var array|false
2307 protected static $gradereportpreferences = null;
2309 * Cached scale info {@see get_info_scales}
2310 * @var grade_plugin_info|false
2312 protected static $scaleinfo = null;
2314 * Cached outcome info {@see get_info_outcomes}
2315 * @var grade_plugin_info|false
2317 protected static $outcomeinfo = null;
2319 * Cached info on edit structure {@see get_info_edit_structure}
2320 * @var array|false
2322 protected static $edittree = null;
2324 * Cached leftter info {@see get_info_letters}
2325 * @var grade_plugin_info|false
2327 protected static $letterinfo = null;
2329 * Cached grade import plugins {@see get_plugins_import}
2330 * @var array|false
2332 protected static $importplugins = null;
2334 * Cached grade export plugins {@see get_plugins_export}
2335 * @var array|false
2337 protected static $exportplugins = null;
2339 * Cached grade plugin strings
2340 * @var array
2342 protected static $pluginstrings = null;
2345 * Gets strings commonly used by the describe plugins
2347 * report => get_string('view'),
2348 * edittree => get_string('edittree', 'grades'),
2349 * scale => get_string('scales'),
2350 * outcome => get_string('outcomes', 'grades'),
2351 * letter => get_string('letters', 'grades'),
2352 * export => get_string('export', 'grades'),
2353 * import => get_string('import'),
2354 * preferences => get_string('mypreferences', 'grades'),
2355 * settings => get_string('settings')
2357 * @return array
2359 public static function get_plugin_strings() {
2360 if (self::$pluginstrings === null) {
2361 self::$pluginstrings = array(
2362 'report' => get_string('view'),
2363 'edittree' => get_string('edittree', 'grades'),
2364 'scale' => get_string('scales'),
2365 'outcome' => get_string('outcomes', 'grades'),
2366 'letter' => get_string('letters', 'grades'),
2367 'export' => get_string('export', 'grades'),
2368 'import' => get_string('import'),
2369 'preferences' => get_string('mypreferences', 'grades'),
2370 'settings' => get_string('settings')
2373 return self::$pluginstrings;
2376 * Get grade_plugin_info object for managing settings if the user can
2378 * @param int $courseid
2379 * @return grade_plugin_info
2381 public static function get_info_manage_settings($courseid) {
2382 if (self::$managesetting !== null) {
2383 return self::$managesetting;
2385 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2386 if (has_capability('moodle/course:update', $context)) {
2387 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2388 } else {
2389 self::$managesetting = false;
2391 return self::$managesetting;
2394 * Returns an array of plugin reports as grade_plugin_info objects
2396 * @param int $courseid
2397 * @return array
2399 public static function get_plugins_reports($courseid) {
2400 global $SITE;
2402 if (self::$gradereports !== null) {
2403 return self::$gradereports;
2405 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2406 $gradereports = array();
2407 $gradepreferences = array();
2408 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2409 //some reports make no sense if we're not within a course
2410 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2411 continue;
2414 // Remove ones we can't see
2415 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2416 continue;
2419 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2420 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2421 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2423 // Add link to preferences tab if such a page exists
2424 if (file_exists($plugindir.'/preferences.php')) {
2425 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2426 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2429 if (count($gradereports) == 0) {
2430 $gradereports = false;
2431 $gradepreferences = false;
2432 } else if (count($gradepreferences) == 0) {
2433 $gradepreferences = false;
2434 asort($gradereports);
2435 } else {
2436 asort($gradereports);
2437 asort($gradepreferences);
2439 self::$gradereports = $gradereports;
2440 self::$gradereportpreferences = $gradepreferences;
2441 return self::$gradereports;
2444 * Returns an array of grade plugin report preferences for plugin reports that
2445 * support preferences
2446 * @param int $courseid
2447 * @return array
2449 public static function get_plugins_report_preferences($courseid) {
2450 if (self::$gradereportpreferences !== null) {
2451 return self::$gradereportpreferences;
2453 self::get_plugins_reports($courseid);
2454 return self::$gradereportpreferences;
2457 * Get information on scales
2458 * @param int $courseid
2459 * @return grade_plugin_info
2461 public static function get_info_scales($courseid) {
2462 if (self::$scaleinfo !== null) {
2463 return self::$scaleinfo;
2465 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2466 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2467 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2468 } else {
2469 self::$scaleinfo = false;
2471 return self::$scaleinfo;
2474 * Get information on outcomes
2475 * @param int $courseid
2476 * @return grade_plugin_info
2478 public static function get_info_outcomes($courseid) {
2479 global $CFG, $SITE;
2481 if (self::$outcomeinfo !== null) {
2482 return self::$outcomeinfo;
2484 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2485 $canmanage = has_capability('moodle/grade:manage', $context);
2486 $canupdate = has_capability('moodle/course:update', $context);
2487 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2488 $outcomes = array();
2489 if ($canupdate) {
2490 if ($courseid!=$SITE->id) {
2491 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2492 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2494 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2495 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2496 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2497 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2498 } else {
2499 if ($courseid!=$SITE->id) {
2500 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2501 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2504 self::$outcomeinfo = $outcomes;
2505 } else {
2506 self::$outcomeinfo = false;
2508 return self::$outcomeinfo;
2511 * Get information on editing structures
2512 * @param int $courseid
2513 * @return array
2515 public static function get_info_edit_structure($courseid) {
2516 if (self::$edittree !== null) {
2517 return self::$edittree;
2519 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2520 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2521 self::$edittree = array(
2522 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2523 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2525 } else {
2526 self::$edittree = false;
2528 return self::$edittree;
2531 * Get information on letters
2532 * @param int $courseid
2533 * @return array
2535 public static function get_info_letters($courseid) {
2536 if (self::$letterinfo !== null) {
2537 return self::$letterinfo;
2539 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2540 $canmanage = has_capability('moodle/grade:manage', $context);
2541 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2542 if ($canmanage || $canmanageletters) {
2543 self::$letterinfo = array(
2544 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2545 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
2547 } else {
2548 self::$letterinfo = false;
2550 return self::$letterinfo;
2553 * Get information import plugins
2554 * @param int $courseid
2555 * @return array
2557 public static function get_plugins_import($courseid) {
2558 global $CFG;
2560 if (self::$importplugins !== null) {
2561 return self::$importplugins;
2563 $importplugins = array();
2564 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2566 if (has_capability('moodle/grade:import', $context)) {
2567 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2568 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2569 continue;
2571 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2572 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2573 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2577 if ($CFG->gradepublishing) {
2578 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2579 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2583 if (count($importplugins) > 0) {
2584 asort($importplugins);
2585 self::$importplugins = $importplugins;
2586 } else {
2587 self::$importplugins = false;
2589 return self::$importplugins;
2592 * Get information export plugins
2593 * @param int $courseid
2594 * @return array
2596 public static function get_plugins_export($courseid) {
2597 global $CFG;
2599 if (self::$exportplugins !== null) {
2600 return self::$exportplugins;
2602 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2603 $exportplugins = array();
2604 if (has_capability('moodle/grade:export', $context)) {
2605 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2606 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2607 continue;
2609 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2610 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2611 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2614 if ($CFG->gradepublishing) {
2615 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2616 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2619 if (count($exportplugins) > 0) {
2620 asort($exportplugins);
2621 self::$exportplugins = $exportplugins;
2622 } else {
2623 self::$exportplugins = false;
2625 return self::$exportplugins;