Merge branch 'MDL-43773-master' of https://github.com/lucisgit/moodle
[moodle.git] / grade / lib.php
blobd3f13ac4d40dfb18b13fcfc6a21af2d371fdb946
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');
26 require_once($CFG->dirroot . '/grade/export/lib.php');
28 /**
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator {
37 /**
38 * The couse whose users we are interested in
40 protected $course;
42 /**
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
47 /**
48 * The group ID we are interested in. 0 means all groups.
50 protected $groupid;
52 /**
53 * A recordset of graded users
55 protected $users_rs;
57 /**
58 * A recordset of user grades (grade_grade instances)
60 protected $grades_rs;
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
67 /**
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
72 /**
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
77 /**
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
82 /**
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
87 /**
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
92 /**
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
97 /**
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
101 protected $suspendedusers = array();
104 * Constructor
106 * @param object $course A course object
107 * @param array $grade_items array of grade items, if not specified only user info returned
108 * @param int $groupid iterate only group users if present
109 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
110 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
111 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
112 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
114 public function __construct($course, $grade_items=null, $groupid=0,
115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
117 $this->course = $course;
118 $this->grade_items = $grade_items;
119 $this->groupid = $groupid;
120 $this->sortfield1 = $sortfield1;
121 $this->sortorder1 = $sortorder1;
122 $this->sortfield2 = $sortfield2;
123 $this->sortorder2 = $sortorder2;
125 $this->gradestack = array();
129 * Initialise the iterator
131 * @return boolean success
133 public function init() {
134 global $CFG, $DB;
136 $this->close();
138 export_verify_grades($this->course->id);
139 $course_item = grade_item::fetch_course_item($this->course->id);
140 if ($course_item->needsupdate) {
141 // Can not calculate all final grades - sorry.
142 return false;
145 $coursecontext = context_course::instance($this->course->id);
147 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
148 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
149 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
153 if ($this->groupid) {
154 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
155 $groupwheresql = "AND gm.groupid = :groupid";
156 // $params contents: gradebookroles
157 $params['groupid'] = $this->groupid;
158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
163 if (empty($this->sortfield1)) {
164 // We must do some sorting even if not specified.
165 $ofields = ", u.id AS usrt";
166 $order = "usrt ASC";
168 } else {
169 $ofields = ", u.$this->sortfield1 AS usrt1";
170 $order = "usrt1 $this->sortorder1";
171 if (!empty($this->sortfield2)) {
172 $ofields .= ", u.$this->sortfield2 AS usrt2";
173 $order .= ", usrt2 $this->sortorder2";
175 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
176 // User order MUST be the same in both queries,
177 // must include the only unique user->id if not already present.
178 $ofields .= ", u.id AS usrt";
179 $order .= ", usrt ASC";
183 $userfields = 'u.*';
184 $customfieldssql = '';
185 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
186 $customfieldscount = 0;
187 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
188 foreach ($customfieldsarray as $field) {
189 if (!empty($field->customid)) {
190 $customfieldssql .= "
191 LEFT JOIN (SELECT * FROM {user_info_data}
192 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
193 ON u.id = cf$customfieldscount.userid";
194 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->shortname}";
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
201 $users_sql = "SELECT $userfields $ofields
202 FROM {user} u
203 JOIN ($enrolledsql) je ON je.id = u.id
204 $groupsql $customfieldssql
205 JOIN (
206 SELECT DISTINCT ra.userid
207 FROM {role_assignments} ra
208 WHERE ra.roleid $gradebookroles_sql
209 AND ra.contextid $relatedctxsql
210 ) rainner ON rainner.userid = u.id
211 WHERE u.deleted = 0
212 $groupwheresql
213 ORDER BY $order";
214 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
216 if (!$this->onlyactive) {
217 $context = context_course::instance($this->course->id);
218 $this->suspendedusers = get_suspended_userids($context);
219 } else {
220 $this->suspendedusers = array();
223 if (!empty($this->grade_items)) {
224 $itemids = array_keys($this->grade_items);
225 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
226 $params = array_merge($params, $grades_params);
228 $grades_sql = "SELECT g.* $ofields
229 FROM {grade_grades} g
230 JOIN {user} u ON g.userid = u.id
231 JOIN ($enrolledsql) je ON je.id = u.id
232 $groupsql
233 JOIN (
234 SELECT DISTINCT ra.userid
235 FROM {role_assignments} ra
236 WHERE ra.roleid $gradebookroles_sql
237 AND ra.contextid $relatedctxsql
238 ) rainner ON rainner.userid = u.id
239 WHERE u.deleted = 0
240 AND g.itemid $itemidsql
241 $groupwheresql
242 ORDER BY $order, g.itemid ASC";
243 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
244 } else {
245 $this->grades_rs = false;
248 return true;
252 * Returns information about the next user
253 * @return mixed array of user info, all grades and feedback or null when no more users found
255 public function next_user() {
256 if (!$this->users_rs) {
257 return false; // no users present
260 if (!$this->users_rs->valid()) {
261 if ($current = $this->_pop()) {
262 // this is not good - user or grades updated between the two reads above :-(
265 return false; // no more users
266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
271 // find grades of this user
272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
278 if (empty($current->userid)) {
279 break;
282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
284 $this->_push($current);
285 break;
288 $grade_records[$current->itemid] = $current;
291 $grades = array();
292 $feedbacks = array();
294 if (!empty($this->grade_items)) {
295 foreach ($this->grade_items as $grade_item) {
296 if (!isset($feedbacks[$grade_item->id])) {
297 $feedbacks[$grade_item->id] = new stdClass();
299 if (array_key_exists($grade_item->id, $grade_records)) {
300 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
301 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
302 unset($grade_records[$grade_item->id]->feedback);
303 unset($grade_records[$grade_item->id]->feedbackformat);
304 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
305 } else {
306 $feedbacks[$grade_item->id]->feedback = '';
307 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
308 $grades[$grade_item->id] =
309 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
314 // Set user suspended status.
315 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
316 $result = new stdClass();
317 $result->user = $user;
318 $result->grades = $grades;
319 $result->feedbacks = $feedbacks;
320 return $result;
324 * Close the iterator, do not forget to call this function
326 public function close() {
327 if ($this->users_rs) {
328 $this->users_rs->close();
329 $this->users_rs = null;
331 if ($this->grades_rs) {
332 $this->grades_rs->close();
333 $this->grades_rs = null;
335 $this->gradestack = array();
339 * Should all enrolled users be exported or just those with an active enrolment?
341 * @param bool $onlyactive True to limit the export to users with an active enrolment
343 public function require_active_enrolment($onlyactive = true) {
344 if (!empty($this->users_rs)) {
345 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
347 $this->onlyactive = $onlyactive;
351 * Allow custom fields to be included
353 * @param bool $allow Whether to allow custom fields or not
354 * @return void
356 public function allow_user_custom_fields($allow = true) {
357 if ($allow) {
358 $this->allowusercustomfields = true;
359 } else {
360 $this->allowusercustomfields = false;
365 * Add a grade_grade instance to the grade stack
367 * @param grade_grade $grade Grade object
369 * @return void
371 private function _push($grade) {
372 array_push($this->gradestack, $grade);
377 * Remove a grade_grade instance from the grade stack
379 * @return grade_grade current grade object
381 private function _pop() {
382 global $DB;
383 if (empty($this->gradestack)) {
384 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
385 return null; // no grades present
388 $current = $this->grades_rs->current();
390 $this->grades_rs->next();
392 return $current;
393 } else {
394 return array_pop($this->gradestack);
400 * Print a selection popup form of the graded users in a course.
402 * @deprecated since 2.0
404 * @param int $course id of the course
405 * @param string $actionpage The page receiving the data from the popoup form
406 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
407 * @param int $groupid id of requested group, 0 means all
408 * @param int $includeall bool include all option
409 * @param bool $return If true, will return the HTML, otherwise, will print directly
410 * @return null
412 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
413 global $CFG, $USER, $OUTPUT;
414 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
417 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
418 global $USER, $CFG;
420 if (is_null($userid)) {
421 $userid = $USER->id;
423 $coursecontext = context_course::instance($course->id);
424 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
425 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
426 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
427 $menu = array(); // Will be a list of userid => user name
428 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
429 $gui = new graded_users_iterator($course, null, $groupid);
430 $gui->require_active_enrolment($showonlyactiveenrol);
431 $gui->init();
432 $label = get_string('selectauser', 'grades');
433 if ($includeall) {
434 $menu[0] = get_string('allusers', 'grades');
435 $label = get_string('selectalloroneuser', 'grades');
437 while ($userdata = $gui->next_user()) {
438 $user = $userdata->user;
439 $userfullname = fullname($user);
440 if ($user->suspendedenrolment) {
441 $menususpendedusers[$user->id] = $userfullname;
442 } else {
443 $menu[$user->id] = $userfullname;
446 $gui->close();
448 if ($includeall) {
449 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
452 if (!empty($menususpendedusers)) {
453 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
455 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
456 $select->label = $label;
457 $select->formid = 'choosegradeuser';
458 return $select;
462 * Print grading plugin selection popup form.
464 * @param array $plugin_info An array of plugins containing information for the selector
465 * @param boolean $return return as string
467 * @return nothing or string if $return true
469 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
470 global $CFG, $OUTPUT, $PAGE;
472 $menu = array();
473 $count = 0;
474 $active = '';
476 foreach ($plugin_info as $plugin_type => $plugins) {
477 if ($plugin_type == 'strings') {
478 continue;
481 $first_plugin = reset($plugins);
483 $sectionname = $plugin_info['strings'][$plugin_type];
484 $section = array();
486 foreach ($plugins as $plugin) {
487 $link = $plugin->link->out(false);
488 $section[$link] = $plugin->string;
489 $count++;
490 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
491 $active = $link;
495 if ($section) {
496 $menu[] = array($sectionname=>$section);
500 // finally print/return the popup form
501 if ($count > 1) {
502 $select = new url_select($menu, $active, null, 'choosepluginreport');
503 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
504 if ($return) {
505 return $OUTPUT->render($select);
506 } else {
507 echo $OUTPUT->render($select);
509 } else {
510 // only one option - no plugin selector needed
511 return '';
516 * Print grading plugin selection tab-based navigation.
518 * @param string $active_type type of plugin on current page - import, export, report or edit
519 * @param string $active_plugin active plugin type - grader, user, cvs, ...
520 * @param array $plugin_info Array of plugins
521 * @param boolean $return return as string
523 * @return nothing or string if $return true
525 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
526 global $CFG, $COURSE;
528 if (!isset($currenttab)) { //TODO: this is weird
529 $currenttab = '';
532 $tabs = array();
533 $top_row = array();
534 $bottom_row = array();
535 $inactive = array($active_plugin);
536 $activated = array();
538 $count = 0;
539 $active = '';
541 foreach ($plugin_info as $plugin_type => $plugins) {
542 if ($plugin_type == 'strings') {
543 continue;
546 // If $plugins is actually the definition of a child-less parent link:
547 if (!empty($plugins->id)) {
548 $string = $plugins->string;
549 if (!empty($plugin_info[$active_type]->parent)) {
550 $string = $plugin_info[$active_type]->parent->string;
553 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
554 continue;
557 $first_plugin = reset($plugins);
558 $url = $first_plugin->link;
560 if ($plugin_type == 'report') {
561 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
564 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
566 if ($active_type == $plugin_type) {
567 foreach ($plugins as $plugin) {
568 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
569 if ($plugin->id == $active_plugin) {
570 $inactive = array($plugin->id);
576 $tabs[] = $top_row;
577 $tabs[] = $bottom_row;
579 if ($return) {
580 return print_tabs($tabs, $active_type, $inactive, $activated, true);
581 } else {
582 print_tabs($tabs, $active_type, $inactive, $activated);
587 * grade_get_plugin_info
589 * @param int $courseid The course id
590 * @param string $active_type type of plugin on current page - import, export, report or edit
591 * @param string $active_plugin active plugin type - grader, user, cvs, ...
593 * @return array
595 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
596 global $CFG, $SITE;
598 $context = context_course::instance($courseid);
600 $plugin_info = array();
601 $count = 0;
602 $active = '';
603 $url_prefix = $CFG->wwwroot . '/grade/';
605 // Language strings
606 $plugin_info['strings'] = grade_helper::get_plugin_strings();
608 if ($reports = grade_helper::get_plugins_reports($courseid)) {
609 $plugin_info['report'] = $reports;
612 //showing grade categories and items make no sense if we're not within a course
613 if ($courseid!=$SITE->id) {
614 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
615 $plugin_info['edittree'] = $edittree;
619 if ($scale = grade_helper::get_info_scales($courseid)) {
620 $plugin_info['scale'] = array('view'=>$scale);
623 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
624 $plugin_info['outcome'] = $outcomes;
627 if ($letters = grade_helper::get_info_letters($courseid)) {
628 $plugin_info['letter'] = $letters;
631 if ($imports = grade_helper::get_plugins_import($courseid)) {
632 $plugin_info['import'] = $imports;
635 if ($exports = grade_helper::get_plugins_export($courseid)) {
636 $plugin_info['export'] = $exports;
639 foreach ($plugin_info as $plugin_type => $plugins) {
640 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
641 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
642 break;
644 foreach ($plugins as $plugin) {
645 if (is_a($plugin, 'grade_plugin_info')) {
646 if ($active_plugin == $plugin->id) {
647 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
653 //hide course settings if we're not in a course
654 if ($courseid!=$SITE->id) {
655 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
656 $plugin_info['settings'] = array('course'=>$setting);
660 // Put preferences last
661 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
662 $plugin_info['preferences'] = $preferences;
665 foreach ($plugin_info as $plugin_type => $plugins) {
666 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
667 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
668 break;
670 foreach ($plugins as $plugin) {
671 if (is_a($plugin, 'grade_plugin_info')) {
672 if ($active_plugin == $plugin->id) {
673 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
679 return $plugin_info;
683 * A simple class containing info about grade plugins.
684 * Can be subclassed for special rules
686 * @package core_grades
687 * @copyright 2009 Nicolas Connault
688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
690 class grade_plugin_info {
692 * A unique id for this plugin
694 * @var mixed
696 public $id;
698 * A URL to access this plugin
700 * @var mixed
702 public $link;
704 * The name of this plugin
706 * @var mixed
708 public $string;
710 * Another grade_plugin_info object, parent of the current one
712 * @var mixed
714 public $parent;
717 * Constructor
719 * @param int $id A unique id for this plugin
720 * @param string $link A URL to access this plugin
721 * @param string $string The name of this plugin
722 * @param object $parent Another grade_plugin_info object, parent of the current one
724 * @return void
726 public function __construct($id, $link, $string, $parent=null) {
727 $this->id = $id;
728 $this->link = $link;
729 $this->string = $string;
730 $this->parent = $parent;
735 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
736 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
737 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
738 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
739 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
741 * @param int $courseid Course id
742 * @param string $active_type The type of the current page (report, settings,
743 * import, export, scales, outcomes, letters)
744 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
745 * @param string $heading The heading of the page. Tries to guess if none is given
746 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
747 * @param string $bodytags Additional attributes that will be added to the <body> tag
748 * @param string $buttons Additional buttons to display on the page
749 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
751 * @return string HTML code or nothing if $return == false
753 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
754 $heading = false, $return=false,
755 $buttons=false, $shownavigation=true) {
756 global $CFG, $OUTPUT, $PAGE;
758 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
760 // Determine the string of the active plugin
761 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
762 $stractive_type = $plugin_info['strings'][$active_type];
764 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
765 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
766 } else {
767 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
770 if ($active_type == 'report') {
771 $PAGE->set_pagelayout('report');
772 } else {
773 $PAGE->set_pagelayout('admin');
775 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
776 $PAGE->set_heading($title);
777 if ($buttons instanceof single_button) {
778 $buttons = $OUTPUT->render($buttons);
780 $PAGE->set_button($buttons);
781 grade_extend_settings($plugin_info, $courseid);
783 $returnval = $OUTPUT->header();
784 if (!$return) {
785 echo $returnval;
788 // Guess heading if not given explicitly
789 if (!$heading) {
790 $heading = $stractive_plugin;
793 if ($shownavigation) {
794 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
795 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
798 if ($return) {
799 $returnval .= $OUTPUT->heading($heading);
800 } else {
801 echo $OUTPUT->heading($heading);
804 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
805 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
809 if ($return) {
810 return $returnval;
815 * Utility class used for return tracking when using edit and other forms in grade plugins
817 * @package core_grades
818 * @copyright 2009 Nicolas Connault
819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
821 class grade_plugin_return {
822 public $type;
823 public $plugin;
824 public $courseid;
825 public $userid;
826 public $page;
829 * Constructor
831 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
833 public function grade_plugin_return($params = null) {
834 if (empty($params)) {
835 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
836 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
837 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
838 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
839 $this->page = optional_param('gpr_page', null, PARAM_INT);
841 } else {
842 foreach ($params as $key=>$value) {
843 if (property_exists($this, $key)) {
844 $this->$key = $value;
851 * Returns return parameters as options array suitable for buttons.
852 * @return array options
854 public function get_options() {
855 if (empty($this->type)) {
856 return array();
859 $params = array();
861 if (!empty($this->plugin)) {
862 $params['plugin'] = $this->plugin;
865 if (!empty($this->courseid)) {
866 $params['id'] = $this->courseid;
869 if (!empty($this->userid)) {
870 $params['userid'] = $this->userid;
873 if (!empty($this->page)) {
874 $params['page'] = $this->page;
877 return $params;
881 * Returns return url
883 * @param string $default default url when params not set
884 * @param array $extras Extra URL parameters
886 * @return string url
888 public function get_return_url($default, $extras=null) {
889 global $CFG;
891 if (empty($this->type) or empty($this->plugin)) {
892 return $default;
895 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
896 $glue = '?';
898 if (!empty($this->courseid)) {
899 $url .= $glue.'id='.$this->courseid;
900 $glue = '&amp;';
903 if (!empty($this->userid)) {
904 $url .= $glue.'userid='.$this->userid;
905 $glue = '&amp;';
908 if (!empty($this->page)) {
909 $url .= $glue.'page='.$this->page;
910 $glue = '&amp;';
913 if (!empty($extras)) {
914 foreach ($extras as $key=>$value) {
915 $url .= $glue.$key.'='.$value;
916 $glue = '&amp;';
920 return $url;
924 * Returns string with hidden return tracking form elements.
925 * @return string
927 public function get_form_fields() {
928 if (empty($this->type)) {
929 return '';
932 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
934 if (!empty($this->plugin)) {
935 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
938 if (!empty($this->courseid)) {
939 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
942 if (!empty($this->userid)) {
943 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
946 if (!empty($this->page)) {
947 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
952 * Add hidden elements into mform
954 * @param object &$mform moodle form object
956 * @return void
958 public function add_mform_elements(&$mform) {
959 if (empty($this->type)) {
960 return;
963 $mform->addElement('hidden', 'gpr_type', $this->type);
964 $mform->setType('gpr_type', PARAM_SAFEDIR);
966 if (!empty($this->plugin)) {
967 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
968 $mform->setType('gpr_plugin', PARAM_PLUGIN);
971 if (!empty($this->courseid)) {
972 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
973 $mform->setType('gpr_courseid', PARAM_INT);
976 if (!empty($this->userid)) {
977 $mform->addElement('hidden', 'gpr_userid', $this->userid);
978 $mform->setType('gpr_userid', PARAM_INT);
981 if (!empty($this->page)) {
982 $mform->addElement('hidden', 'gpr_page', $this->page);
983 $mform->setType('gpr_page', PARAM_INT);
988 * Add return tracking params into url
990 * @param moodle_url $url A URL
992 * @return string $url with return tracking params
994 public function add_url_params(moodle_url $url) {
995 if (empty($this->type)) {
996 return $url;
999 $url->param('gpr_type', $this->type);
1001 if (!empty($this->plugin)) {
1002 $url->param('gpr_plugin', $this->plugin);
1005 if (!empty($this->courseid)) {
1006 $url->param('gpr_courseid' ,$this->courseid);
1009 if (!empty($this->userid)) {
1010 $url->param('gpr_userid', $this->userid);
1013 if (!empty($this->page)) {
1014 $url->param('gpr_page', $this->page);
1017 return $url;
1022 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1024 * @param string $path The path of the calling script (using __FILE__?)
1025 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1026 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1027 * an array of keys and values (e.g courseid => $courseid, itemid...)
1029 * @return string
1031 function grade_build_nav($path, $pagename=null, $id=null) {
1032 global $CFG, $COURSE, $PAGE;
1034 $strgrades = get_string('grades', 'grades');
1036 // Parse the path and build navlinks from its elements
1037 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1038 $path = substr($path, $dirroot_length);
1039 $path = str_replace('\\', '/', $path);
1041 $path_elements = explode('/', $path);
1043 $path_elements_count = count($path_elements);
1045 // First link is always 'grade'
1046 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1048 $link = null;
1049 $numberofelements = 3;
1051 // Prepare URL params string
1052 $linkparams = array();
1053 if (!is_null($id)) {
1054 if (is_array($id)) {
1055 foreach ($id as $idkey => $idvalue) {
1056 $linkparams[$idkey] = $idvalue;
1058 } else {
1059 $linkparams['id'] = $id;
1063 $navlink4 = null;
1065 // Remove file extensions from filenames
1066 foreach ($path_elements as $key => $filename) {
1067 $path_elements[$key] = str_replace('.php', '', $filename);
1070 // Second level links
1071 switch ($path_elements[1]) {
1072 case 'edit': // No link
1073 if ($path_elements[3] != 'index.php') {
1074 $numberofelements = 4;
1076 break;
1077 case 'import': // No link
1078 break;
1079 case 'export': // No link
1080 break;
1081 case 'report':
1082 // $id is required for this link. Do not print it if $id isn't given
1083 if (!is_null($id)) {
1084 $link = new moodle_url('/grade/report/index.php', $linkparams);
1087 if ($path_elements[2] == 'grader') {
1088 $numberofelements = 4;
1090 break;
1092 default:
1093 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1094 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1095 " as the second path element after 'grade'.");
1096 return false;
1098 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1100 // Third level links
1101 if (empty($pagename)) {
1102 $pagename = get_string($path_elements[2], 'grades');
1105 switch ($numberofelements) {
1106 case 3:
1107 $PAGE->navbar->add($pagename, $link);
1108 break;
1109 case 4:
1110 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1111 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1113 $PAGE->navbar->add($pagename);
1114 break;
1117 return '';
1121 * General structure representing grade items in course
1123 * @package core_grades
1124 * @copyright 2009 Nicolas Connault
1125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1127 class grade_structure {
1128 public $context;
1130 public $courseid;
1133 * Reference to modinfo for current course (for performance, to save
1134 * retrieving it from courseid every time). Not actually set except for
1135 * the grade_tree type.
1136 * @var course_modinfo
1138 public $modinfo;
1141 * 1D array of grade items only
1143 public $items;
1146 * Returns icon of element
1148 * @param array &$element An array representing an element in the grade_tree
1149 * @param bool $spacerifnone return spacer if no icon found
1151 * @return string icon or spacer
1153 public function get_element_icon(&$element, $spacerifnone=false) {
1154 global $CFG, $OUTPUT;
1155 require_once $CFG->libdir.'/filelib.php';
1157 switch ($element['type']) {
1158 case 'item':
1159 case 'courseitem':
1160 case 'categoryitem':
1161 $is_course = $element['object']->is_course_item();
1162 $is_category = $element['object']->is_category_item();
1163 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1164 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1165 $is_outcome = !empty($element['object']->outcomeid);
1167 if ($element['object']->is_calculated()) {
1168 $strcalc = get_string('calculatedgrade', 'grades');
1169 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1170 s($strcalc).'" alt="'.s($strcalc).'"/>';
1172 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1173 if ($category = $element['object']->get_item_category()) {
1174 switch ($category->aggregation) {
1175 case GRADE_AGGREGATE_MEAN:
1176 case GRADE_AGGREGATE_MEDIAN:
1177 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1178 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1179 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1180 $stragg = get_string('aggregation', 'grades');
1181 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1182 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1183 case GRADE_AGGREGATE_SUM:
1184 $stragg = get_string('aggregation', 'grades');
1185 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1186 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1190 } else if ($element['object']->itemtype == 'mod') {
1191 //prevent outcomes being displaying the same icon as the activity they are attached to
1192 if ($is_outcome) {
1193 $stroutcome = s(get_string('outcome', 'grades'));
1194 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1195 'class="icon itemicon" title="'.$stroutcome.
1196 '" alt="'.$stroutcome.'"/>';
1197 } else {
1198 $strmodname = get_string('modulename', $element['object']->itemmodule);
1199 return '<img src="'.$OUTPUT->pix_url('icon',
1200 $element['object']->itemmodule) . '" ' .
1201 'class="icon itemicon" title="' .s($strmodname).
1202 '" alt="' .s($strmodname).'"/>';
1204 } else if ($element['object']->itemtype == 'manual') {
1205 if ($element['object']->is_outcome_item()) {
1206 $stroutcome = get_string('outcome', 'grades');
1207 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1208 'class="icon itemicon" title="'.s($stroutcome).
1209 '" alt="'.s($stroutcome).'"/>';
1210 } else {
1211 $strmanual = get_string('manualitem', 'grades');
1212 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1213 'class="icon itemicon" title="'.s($strmanual).
1214 '" alt="'.s($strmanual).'"/>';
1217 break;
1219 case 'category':
1220 $strcat = get_string('category', 'grades');
1221 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1222 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1225 if ($spacerifnone) {
1226 return $OUTPUT->spacer().' ';
1227 } else {
1228 return '';
1233 * Returns name of element optionally with icon and link
1235 * @param array &$element An array representing an element in the grade_tree
1236 * @param bool $withlink Whether or not this header has a link
1237 * @param bool $icon Whether or not to display an icon with this header
1238 * @param bool $spacerifnone return spacer if no icon found
1240 * @return string header
1242 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1243 $header = '';
1245 if ($icon) {
1246 $header .= $this->get_element_icon($element, $spacerifnone);
1249 $header .= $element['object']->get_name();
1251 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1252 $element['type'] != 'courseitem') {
1253 return $header;
1256 if ($withlink) {
1257 $url = $this->get_activity_link($element);
1258 if ($url) {
1259 $a = new stdClass();
1260 $a->name = get_string('modulename', $element['object']->itemmodule);
1261 $title = get_string('linktoactivity', 'grades', $a);
1263 $header = html_writer::link($url, $header, array('title' => $title));
1267 return $header;
1270 private function get_activity_link($element) {
1271 global $CFG;
1272 /** @var array static cache of the grade.php file existence flags */
1273 static $hasgradephp = array();
1275 $itemtype = $element['object']->itemtype;
1276 $itemmodule = $element['object']->itemmodule;
1277 $iteminstance = $element['object']->iteminstance;
1278 $itemnumber = $element['object']->itemnumber;
1280 // Links only for module items that have valid instance, module and are
1281 // called from grade_tree with valid modinfo
1282 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1283 return null;
1286 // Get $cm efficiently and with visibility information using modinfo
1287 $instances = $this->modinfo->get_instances();
1288 if (empty($instances[$itemmodule][$iteminstance])) {
1289 return null;
1291 $cm = $instances[$itemmodule][$iteminstance];
1293 // Do not add link if activity is not visible to the current user
1294 if (!$cm->uservisible) {
1295 return null;
1298 if (!array_key_exists($itemmodule, $hasgradephp)) {
1299 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1300 $hasgradephp[$itemmodule] = true;
1301 } else {
1302 $hasgradephp[$itemmodule] = false;
1306 // If module has grade.php, link to that, otherwise view.php
1307 if ($hasgradephp[$itemmodule]) {
1308 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1309 if (isset($element['userid'])) {
1310 $args['userid'] = $element['userid'];
1312 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1313 } else {
1314 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1319 * Returns URL of a page that is supposed to contain detailed grade analysis
1321 * At the moment, only activity modules are supported. The method generates link
1322 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1323 * gradeid and userid. If the grade.php does not exist, null is returned.
1325 * @return moodle_url|null URL or null if unable to construct it
1327 public function get_grade_analysis_url(grade_grade $grade) {
1328 global $CFG;
1329 /** @var array static cache of the grade.php file existence flags */
1330 static $hasgradephp = array();
1332 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1333 throw new coding_exception('Passed grade without the associated grade item');
1335 $item = $grade->grade_item;
1337 if (!$item->is_external_item()) {
1338 // at the moment, only activity modules are supported
1339 return null;
1341 if ($item->itemtype !== 'mod') {
1342 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1344 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1345 return null;
1348 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1349 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1350 $hasgradephp[$item->itemmodule] = true;
1351 } else {
1352 $hasgradephp[$item->itemmodule] = false;
1356 if (!$hasgradephp[$item->itemmodule]) {
1357 return null;
1360 $instances = $this->modinfo->get_instances();
1361 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1362 return null;
1364 $cm = $instances[$item->itemmodule][$item->iteminstance];
1365 if (!$cm->uservisible) {
1366 return null;
1369 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1370 'id' => $cm->id,
1371 'itemid' => $item->id,
1372 'itemnumber' => $item->itemnumber,
1373 'gradeid' => $grade->id,
1374 'userid' => $grade->userid,
1377 return $url;
1381 * Returns an action icon leading to the grade analysis page
1383 * @param grade_grade $grade
1384 * @return string
1386 public function get_grade_analysis_icon(grade_grade $grade) {
1387 global $OUTPUT;
1389 $url = $this->get_grade_analysis_url($grade);
1390 if (is_null($url)) {
1391 return '';
1394 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1395 get_string('gradeanalysis', 'core_grades')));
1399 * Returns the grade eid - the grade may not exist yet.
1401 * @param grade_grade $grade_grade A grade_grade object
1403 * @return string eid
1405 public function get_grade_eid($grade_grade) {
1406 if (empty($grade_grade->id)) {
1407 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1408 } else {
1409 return 'g'.$grade_grade->id;
1414 * Returns the grade_item eid
1415 * @param grade_item $grade_item A grade_item object
1416 * @return string eid
1418 public function get_item_eid($grade_item) {
1419 return 'i'.$grade_item->id;
1423 * Given a grade_tree element, returns an array of parameters
1424 * used to build an icon for that element.
1426 * @param array $element An array representing an element in the grade_tree
1428 * @return array
1430 public function get_params_for_iconstr($element) {
1431 $strparams = new stdClass();
1432 $strparams->category = '';
1433 $strparams->itemname = '';
1434 $strparams->itemmodule = '';
1436 if (!method_exists($element['object'], 'get_name')) {
1437 return $strparams;
1440 $strparams->itemname = html_to_text($element['object']->get_name());
1442 // If element name is categorytotal, get the name of the parent category
1443 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1444 $parent = $element['object']->get_parent_category();
1445 $strparams->category = $parent->get_name() . ' ';
1446 } else {
1447 $strparams->category = '';
1450 $strparams->itemmodule = null;
1451 if (isset($element['object']->itemmodule)) {
1452 $strparams->itemmodule = $element['object']->itemmodule;
1454 return $strparams;
1458 * Return edit icon for give 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_edit_icon($element, $gpr) {
1466 global $CFG, $OUTPUT;
1468 if (!has_capability('moodle/grade:manage', $this->context)) {
1469 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1470 // oki - let them override grade
1471 } else {
1472 return '';
1476 static $strfeedback = null;
1477 static $streditgrade = null;
1478 if (is_null($streditgrade)) {
1479 $streditgrade = get_string('editgrade', 'grades');
1480 $strfeedback = get_string('feedback');
1483 $strparams = $this->get_params_for_iconstr($element);
1485 $object = $element['object'];
1487 switch ($element['type']) {
1488 case 'item':
1489 case 'categoryitem':
1490 case 'courseitem':
1491 $stredit = get_string('editverbose', 'grades', $strparams);
1492 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1493 $url = new moodle_url('/grade/edit/tree/item.php',
1494 array('courseid' => $this->courseid, 'id' => $object->id));
1495 } else {
1496 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1497 array('courseid' => $this->courseid, 'id' => $object->id));
1499 break;
1501 case 'category':
1502 $stredit = get_string('editverbose', 'grades', $strparams);
1503 $url = new moodle_url('/grade/edit/tree/category.php',
1504 array('courseid' => $this->courseid, 'id' => $object->id));
1505 break;
1507 case 'grade':
1508 $stredit = $streditgrade;
1509 if (empty($object->id)) {
1510 $url = new moodle_url('/grade/edit/tree/grade.php',
1511 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1512 } else {
1513 $url = new moodle_url('/grade/edit/tree/grade.php',
1514 array('courseid' => $this->courseid, 'id' => $object->id));
1516 if (!empty($object->feedback)) {
1517 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1519 break;
1521 default:
1522 $url = null;
1525 if ($url) {
1526 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1528 } else {
1529 return '';
1534 * Return hiding icon for give element
1536 * @param array $element An array representing an element in the grade_tree
1537 * @param object $gpr A grade_plugin_return object
1539 * @return string
1541 public function get_hiding_icon($element, $gpr) {
1542 global $CFG, $OUTPUT;
1544 if (!$element['object']->can_control_visibility()) {
1545 return '';
1548 if (!has_capability('moodle/grade:manage', $this->context) and
1549 !has_capability('moodle/grade:hide', $this->context)) {
1550 return '';
1553 $strparams = $this->get_params_for_iconstr($element);
1554 $strshow = get_string('showverbose', 'grades', $strparams);
1555 $strhide = get_string('hideverbose', 'grades', $strparams);
1557 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1558 $url = $gpr->add_url_params($url);
1560 if ($element['object']->is_hidden()) {
1561 $type = 'show';
1562 $tooltip = $strshow;
1564 // Change the icon and add a tooltip showing the date
1565 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1566 $type = 'hiddenuntil';
1567 $tooltip = get_string('hiddenuntildate', 'grades',
1568 userdate($element['object']->get_hidden()));
1571 $url->param('action', 'show');
1573 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1575 } else {
1576 $url->param('action', 'hide');
1577 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1580 return $hideicon;
1584 * Return locking icon for given element
1586 * @param array $element An array representing an element in the grade_tree
1587 * @param object $gpr A grade_plugin_return object
1589 * @return string
1591 public function get_locking_icon($element, $gpr) {
1592 global $CFG, $OUTPUT;
1594 $strparams = $this->get_params_for_iconstr($element);
1595 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1596 $strlock = get_string('lockverbose', 'grades', $strparams);
1598 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1599 $url = $gpr->add_url_params($url);
1601 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1602 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1603 $strparamobj = new stdClass();
1604 $strparamobj->itemname = $element['object']->grade_item->itemname;
1605 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1607 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1608 array('class' => 'action-icon'));
1610 } else if ($element['object']->is_locked()) {
1611 $type = 'unlock';
1612 $tooltip = $strunlock;
1614 // Change the icon and add a tooltip showing the date
1615 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1616 $type = 'locktime';
1617 $tooltip = get_string('locktimedate', 'grades',
1618 userdate($element['object']->get_locktime()));
1621 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1622 $action = '';
1623 } else {
1624 $url->param('action', 'unlock');
1625 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1628 } else {
1629 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1630 $action = '';
1631 } else {
1632 $url->param('action', 'lock');
1633 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1637 return $action;
1641 * Return calculation icon for given element
1643 * @param array $element An array representing an element in the grade_tree
1644 * @param object $gpr A grade_plugin_return object
1646 * @return string
1648 public function get_calculation_icon($element, $gpr) {
1649 global $CFG, $OUTPUT;
1650 if (!has_capability('moodle/grade:manage', $this->context)) {
1651 return '';
1654 $type = $element['type'];
1655 $object = $element['object'];
1657 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1658 $strparams = $this->get_params_for_iconstr($element);
1659 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1661 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1662 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1664 // show calculation icon only when calculation possible
1665 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1666 if ($object->is_calculated()) {
1667 $icon = 't/calc';
1668 } else {
1669 $icon = 't/calc_off';
1672 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1673 $url = $gpr->add_url_params($url);
1674 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
1678 return '';
1683 * Flat structure similar to grade tree.
1685 * @uses grade_structure
1686 * @package core_grades
1687 * @copyright 2009 Nicolas Connault
1688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1690 class grade_seq extends grade_structure {
1693 * 1D array of elements
1695 public $elements;
1698 * Constructor, retrieves and stores array of all grade_category and grade_item
1699 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1701 * @param int $courseid The course id
1702 * @param bool $category_grade_last category grade item is the last child
1703 * @param bool $nooutcomes Whether or not outcomes should be included
1705 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1706 global $USER, $CFG;
1708 $this->courseid = $courseid;
1709 $this->context = context_course::instance($courseid);
1711 // get course grade tree
1712 $top_element = grade_category::fetch_course_tree($courseid, true);
1714 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1716 foreach ($this->elements as $key=>$unused) {
1717 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1722 * Static recursive helper - makes the grade_item for category the last children
1724 * @param array &$element The seed of the recursion
1725 * @param bool $category_grade_last category grade item is the last child
1726 * @param bool $nooutcomes Whether or not outcomes should be included
1728 * @return array
1730 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1731 if (empty($element['children'])) {
1732 return array();
1734 $children = array();
1736 foreach ($element['children'] as $sortorder=>$unused) {
1737 if ($nooutcomes and $element['type'] != 'category' and
1738 $element['children'][$sortorder]['object']->is_outcome_item()) {
1739 continue;
1741 $children[] = $element['children'][$sortorder];
1743 unset($element['children']);
1745 if ($category_grade_last and count($children) > 1) {
1746 $cat_item = array_shift($children);
1747 array_push($children, $cat_item);
1750 $result = array();
1751 foreach ($children as $child) {
1752 if ($child['type'] == 'category') {
1753 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1754 } else {
1755 $child['eid'] = 'i'.$child['object']->id;
1756 $result[$child['object']->id] = $child;
1760 return $result;
1764 * Parses the array in search of a given eid and returns a element object with
1765 * information about the element it has found.
1767 * @param int $eid Gradetree Element ID
1769 * @return object element
1771 public function locate_element($eid) {
1772 // it is a grade - construct a new object
1773 if (strpos($eid, 'n') === 0) {
1774 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1775 return null;
1778 $itemid = $matches[1];
1779 $userid = $matches[2];
1781 //extra security check - the grade item must be in this tree
1782 if (!$item_el = $this->locate_element('i'.$itemid)) {
1783 return null;
1786 // $gradea->id may be null - means does not exist yet
1787 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1789 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1790 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1792 } else if (strpos($eid, 'g') === 0) {
1793 $id = (int) substr($eid, 1);
1794 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1795 return null;
1797 //extra security check - the grade item must be in this tree
1798 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1799 return null;
1801 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1802 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1805 // it is a category or item
1806 foreach ($this->elements as $element) {
1807 if ($element['eid'] == $eid) {
1808 return $element;
1812 return null;
1817 * This class represents a complete tree of categories, grade_items and final grades,
1818 * organises as an array primarily, but which can also be converted to other formats.
1819 * It has simple method calls with complex implementations, allowing for easy insertion,
1820 * deletion and moving of items and categories within the tree.
1822 * @uses grade_structure
1823 * @package core_grades
1824 * @copyright 2009 Nicolas Connault
1825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1827 class grade_tree extends grade_structure {
1830 * The basic representation of the tree as a hierarchical, 3-tiered array.
1831 * @var object $top_element
1833 public $top_element;
1836 * 2D array of grade items and categories
1837 * @var array $levels
1839 public $levels;
1842 * Grade items
1843 * @var array $items
1845 public $items;
1848 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1849 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1851 * @param int $courseid The Course ID
1852 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1853 * @param bool $category_grade_last category grade item is the last child
1854 * @param array $collapsed array of collapsed categories
1855 * @param bool $nooutcomes Whether or not outcomes should be included
1857 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1858 $collapsed=null, $nooutcomes=false) {
1859 global $USER, $CFG, $COURSE, $DB;
1861 $this->courseid = $courseid;
1862 $this->levels = array();
1863 $this->context = context_course::instance($courseid);
1865 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1866 $course = $COURSE;
1867 } else {
1868 $course = $DB->get_record('course', array('id' => $this->courseid));
1870 $this->modinfo = get_fast_modinfo($course);
1872 // get course grade tree
1873 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1875 // collapse the categories if requested
1876 if (!empty($collapsed)) {
1877 grade_tree::category_collapse($this->top_element, $collapsed);
1880 // no otucomes if requested
1881 if (!empty($nooutcomes)) {
1882 grade_tree::no_outcomes($this->top_element);
1885 // move category item to last position in category
1886 if ($category_grade_last) {
1887 grade_tree::category_grade_last($this->top_element);
1890 if ($fillers) {
1891 // inject fake categories == fillers
1892 grade_tree::inject_fillers($this->top_element, 0);
1893 // add colspans to categories and fillers
1894 grade_tree::inject_colspans($this->top_element);
1897 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1902 * Static recursive helper - removes items from collapsed categories
1904 * @param array &$element The seed of the recursion
1905 * @param array $collapsed array of collapsed categories
1907 * @return void
1909 public function category_collapse(&$element, $collapsed) {
1910 if ($element['type'] != 'category') {
1911 return;
1913 if (empty($element['children']) or count($element['children']) < 2) {
1914 return;
1917 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1918 $category_item = reset($element['children']); //keep only category item
1919 $element['children'] = array(key($element['children'])=>$category_item);
1921 } else {
1922 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1923 reset($element['children']);
1924 $first_key = key($element['children']);
1925 unset($element['children'][$first_key]);
1927 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1928 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1934 * Static recursive helper - removes all outcomes
1936 * @param array &$element The seed of the recursion
1938 * @return void
1940 public function no_outcomes(&$element) {
1941 if ($element['type'] != 'category') {
1942 return;
1944 foreach ($element['children'] as $sortorder=>$child) {
1945 if ($element['children'][$sortorder]['type'] == 'item'
1946 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1947 unset($element['children'][$sortorder]);
1949 } else if ($element['children'][$sortorder]['type'] == 'category') {
1950 grade_tree::no_outcomes($element['children'][$sortorder]);
1956 * Static recursive helper - makes the grade_item for category the last children
1958 * @param array &$element The seed of the recursion
1960 * @return void
1962 public function category_grade_last(&$element) {
1963 if (empty($element['children'])) {
1964 return;
1966 if (count($element['children']) < 2) {
1967 return;
1969 $first_item = reset($element['children']);
1970 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1971 // the category item might have been already removed
1972 $order = key($element['children']);
1973 unset($element['children'][$order]);
1974 $element['children'][$order] =& $first_item;
1976 foreach ($element['children'] as $sortorder => $child) {
1977 grade_tree::category_grade_last($element['children'][$sortorder]);
1982 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1984 * @param array &$levels The levels of the grade tree through which to recurse
1985 * @param array &$element The seed of the recursion
1986 * @param int $depth How deep are we?
1987 * @return void
1989 public function fill_levels(&$levels, &$element, $depth) {
1990 if (!array_key_exists($depth, $levels)) {
1991 $levels[$depth] = array();
1994 // prepare unique identifier
1995 if ($element['type'] == 'category') {
1996 $element['eid'] = 'c'.$element['object']->id;
1997 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1998 $element['eid'] = 'i'.$element['object']->id;
1999 $this->items[$element['object']->id] =& $element['object'];
2002 $levels[$depth][] =& $element;
2003 $depth++;
2004 if (empty($element['children'])) {
2005 return;
2007 $prev = 0;
2008 foreach ($element['children'] as $sortorder=>$child) {
2009 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2010 $element['children'][$sortorder]['prev'] = $prev;
2011 $element['children'][$sortorder]['next'] = 0;
2012 if ($prev) {
2013 $element['children'][$prev]['next'] = $sortorder;
2015 $prev = $sortorder;
2020 * Static recursive helper - makes full tree (all leafes are at the same level)
2022 * @param array &$element The seed of the recursion
2023 * @param int $depth How deep are we?
2025 * @return int
2027 public function inject_fillers(&$element, $depth) {
2028 $depth++;
2030 if (empty($element['children'])) {
2031 return $depth;
2033 $chdepths = array();
2034 $chids = array_keys($element['children']);
2035 $last_child = end($chids);
2036 $first_child = reset($chids);
2038 foreach ($chids as $chid) {
2039 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2041 arsort($chdepths);
2043 $maxdepth = reset($chdepths);
2044 foreach ($chdepths as $chid=>$chd) {
2045 if ($chd == $maxdepth) {
2046 continue;
2048 for ($i=0; $i < $maxdepth-$chd; $i++) {
2049 if ($chid == $first_child) {
2050 $type = 'fillerfirst';
2051 } else if ($chid == $last_child) {
2052 $type = 'fillerlast';
2053 } else {
2054 $type = 'filler';
2056 $oldchild =& $element['children'][$chid];
2057 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2058 'eid'=>'', 'depth'=>$element['object']->depth,
2059 'children'=>array($oldchild));
2063 return $maxdepth;
2067 * Static recursive helper - add colspan information into categories
2069 * @param array &$element The seed of the recursion
2071 * @return int
2073 public function inject_colspans(&$element) {
2074 if (empty($element['children'])) {
2075 return 1;
2077 $count = 0;
2078 foreach ($element['children'] as $key=>$child) {
2079 $count += grade_tree::inject_colspans($element['children'][$key]);
2081 $element['colspan'] = $count;
2082 return $count;
2086 * Parses the array in search of a given eid and returns a element object with
2087 * information about the element it has found.
2088 * @param int $eid Gradetree Element ID
2089 * @return object element
2091 public function locate_element($eid) {
2092 // it is a grade - construct a new object
2093 if (strpos($eid, 'n') === 0) {
2094 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2095 return null;
2098 $itemid = $matches[1];
2099 $userid = $matches[2];
2101 //extra security check - the grade item must be in this tree
2102 if (!$item_el = $this->locate_element('i'.$itemid)) {
2103 return null;
2106 // $gradea->id may be null - means does not exist yet
2107 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2109 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2110 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2112 } else if (strpos($eid, 'g') === 0) {
2113 $id = (int) substr($eid, 1);
2114 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2115 return null;
2117 //extra security check - the grade item must be in this tree
2118 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2119 return null;
2121 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2122 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2125 // it is a category or item
2126 foreach ($this->levels as $row) {
2127 foreach ($row as $element) {
2128 if ($element['type'] == 'filler') {
2129 continue;
2131 if ($element['eid'] == $eid) {
2132 return $element;
2137 return null;
2141 * Returns a well-formed XML representation of the grade-tree using recursion.
2143 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2144 * @param string $tabs The control character to use for tabs
2146 * @return string $xml
2148 public function exporttoxml($root=null, $tabs="\t") {
2149 $xml = null;
2150 $first = false;
2151 if (is_null($root)) {
2152 $root = $this->top_element;
2153 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2154 $xml .= "<gradetree>\n";
2155 $first = true;
2158 $type = 'undefined';
2159 if (strpos($root['object']->table, 'grade_categories') !== false) {
2160 $type = 'category';
2161 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2162 $type = 'item';
2163 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2164 $type = 'outcome';
2167 $xml .= "$tabs<element type=\"$type\">\n";
2168 foreach ($root['object'] as $var => $value) {
2169 if (!is_object($value) && !is_array($value) && !empty($value)) {
2170 $xml .= "$tabs\t<$var>$value</$var>\n";
2174 if (!empty($root['children'])) {
2175 $xml .= "$tabs\t<children>\n";
2176 foreach ($root['children'] as $sortorder => $child) {
2177 $xml .= $this->exportToXML($child, $tabs."\t\t");
2179 $xml .= "$tabs\t</children>\n";
2182 $xml .= "$tabs</element>\n";
2184 if ($first) {
2185 $xml .= "</gradetree>";
2188 return $xml;
2192 * Returns a JSON representation of the grade-tree using recursion.
2194 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2195 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2197 * @return string
2199 public function exporttojson($root=null, $tabs="\t") {
2200 $json = null;
2201 $first = false;
2202 if (is_null($root)) {
2203 $root = $this->top_element;
2204 $first = true;
2207 $name = '';
2210 if (strpos($root['object']->table, 'grade_categories') !== false) {
2211 $name = $root['object']->fullname;
2212 if ($name == '?') {
2213 $name = $root['object']->get_name();
2215 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2216 $name = $root['object']->itemname;
2217 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2218 $name = $root['object']->itemname;
2221 $json .= "$tabs {\n";
2222 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2223 $json .= "$tabs\t \"name\": \"$name\",\n";
2225 foreach ($root['object'] as $var => $value) {
2226 if (!is_object($value) && !is_array($value) && !empty($value)) {
2227 $json .= "$tabs\t \"$var\": \"$value\",\n";
2231 $json = substr($json, 0, strrpos($json, ','));
2233 if (!empty($root['children'])) {
2234 $json .= ",\n$tabs\t\"children\": [\n";
2235 foreach ($root['children'] as $sortorder => $child) {
2236 $json .= $this->exportToJSON($child, $tabs."\t\t");
2238 $json = substr($json, 0, strrpos($json, ','));
2239 $json .= "\n$tabs\t]\n";
2242 if ($first) {
2243 $json .= "\n}";
2244 } else {
2245 $json .= "\n$tabs},\n";
2248 return $json;
2252 * Returns the array of levels
2254 * @return array
2256 public function get_levels() {
2257 return $this->levels;
2261 * Returns the array of grade items
2263 * @return array
2265 public function get_items() {
2266 return $this->items;
2270 * Returns a specific Grade Item
2272 * @param int $itemid The ID of the grade_item object
2274 * @return grade_item
2276 public function get_item($itemid) {
2277 if (array_key_exists($itemid, $this->items)) {
2278 return $this->items[$itemid];
2279 } else {
2280 return false;
2286 * Local shortcut function for creating an edit/delete button for a grade_* object.
2287 * @param string $type 'edit' or 'delete'
2288 * @param int $courseid The Course ID
2289 * @param grade_* $object The grade_* object
2290 * @return string html
2292 function grade_button($type, $courseid, $object) {
2293 global $CFG, $OUTPUT;
2294 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2295 $objectidstring = $matches[1] . 'id';
2296 } else {
2297 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2300 $strdelete = get_string('delete');
2301 $stredit = get_string('edit');
2303 if ($type == 'delete') {
2304 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2305 } else if ($type == 'edit') {
2306 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2309 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2314 * This method adds settings to the settings block for the grade system and its
2315 * plugins
2317 * @global moodle_page $PAGE
2319 function grade_extend_settings($plugininfo, $courseid) {
2320 global $PAGE;
2322 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2324 $strings = array_shift($plugininfo);
2326 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2327 foreach ($reports as $report) {
2328 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2332 if ($imports = grade_helper::get_plugins_import($courseid)) {
2333 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2334 foreach ($imports as $import) {
2335 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2339 if ($exports = grade_helper::get_plugins_export($courseid)) {
2340 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2341 foreach ($exports as $export) {
2342 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2346 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2347 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2350 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2351 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2352 foreach ($preferences as $preference) {
2353 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2357 if ($letters = grade_helper::get_info_letters($courseid)) {
2358 $letters = array_shift($letters);
2359 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2362 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2363 $outcomes = array_shift($outcomes);
2364 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2367 if ($scales = grade_helper::get_info_scales($courseid)) {
2368 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2371 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2372 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2373 foreach ($categories as $category) {
2374 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2378 if ($gradenode->contains_active_node()) {
2379 // If the gradenode is active include the settings base node (gradeadministration) in
2380 // the navbar, typcially this is ignored.
2381 $PAGE->navbar->includesettingsbase = true;
2383 // If we can get the course admin node make sure it is closed by default
2384 // as in this case the gradenode will be opened
2385 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2386 $coursenode->make_inactive();
2387 $coursenode->forceopen = false;
2393 * Grade helper class
2395 * This class provides several helpful functions that work irrespective of any
2396 * current state.
2398 * @copyright 2010 Sam Hemelryk
2399 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2401 abstract class grade_helper {
2403 * Cached manage settings info {@see get_info_settings}
2404 * @var grade_plugin_info|false
2406 protected static $managesetting = null;
2408 * Cached grade report plugins {@see get_plugins_reports}
2409 * @var array|false
2411 protected static $gradereports = null;
2413 * Cached grade report plugins preferences {@see get_info_scales}
2414 * @var array|false
2416 protected static $gradereportpreferences = null;
2418 * Cached scale info {@see get_info_scales}
2419 * @var grade_plugin_info|false
2421 protected static $scaleinfo = null;
2423 * Cached outcome info {@see get_info_outcomes}
2424 * @var grade_plugin_info|false
2426 protected static $outcomeinfo = null;
2428 * Cached info on edit structure {@see get_info_edit_structure}
2429 * @var array|false
2431 protected static $edittree = null;
2433 * Cached leftter info {@see get_info_letters}
2434 * @var grade_plugin_info|false
2436 protected static $letterinfo = null;
2438 * Cached grade import plugins {@see get_plugins_import}
2439 * @var array|false
2441 protected static $importplugins = null;
2443 * Cached grade export plugins {@see get_plugins_export}
2444 * @var array|false
2446 protected static $exportplugins = null;
2448 * Cached grade plugin strings
2449 * @var array
2451 protected static $pluginstrings = null;
2454 * Gets strings commonly used by the describe plugins
2456 * report => get_string('view'),
2457 * edittree => get_string('edittree', 'grades'),
2458 * scale => get_string('scales'),
2459 * outcome => get_string('outcomes', 'grades'),
2460 * letter => get_string('letters', 'grades'),
2461 * export => get_string('export', 'grades'),
2462 * import => get_string('import'),
2463 * preferences => get_string('mypreferences', 'grades'),
2464 * settings => get_string('settings')
2466 * @return array
2468 public static function get_plugin_strings() {
2469 if (self::$pluginstrings === null) {
2470 self::$pluginstrings = array(
2471 'report' => get_string('view'),
2472 'edittree' => get_string('edittree', 'grades'),
2473 'scale' => get_string('scales'),
2474 'outcome' => get_string('outcomes', 'grades'),
2475 'letter' => get_string('letters', 'grades'),
2476 'export' => get_string('export', 'grades'),
2477 'import' => get_string('import'),
2478 'preferences' => get_string('mypreferences', 'grades'),
2479 'settings' => get_string('settings')
2482 return self::$pluginstrings;
2485 * Get grade_plugin_info object for managing settings if the user can
2487 * @param int $courseid
2488 * @return grade_plugin_info
2490 public static function get_info_manage_settings($courseid) {
2491 if (self::$managesetting !== null) {
2492 return self::$managesetting;
2494 $context = context_course::instance($courseid);
2495 if (has_capability('moodle/grade:manage', $context)) {
2496 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2497 } else {
2498 self::$managesetting = false;
2500 return self::$managesetting;
2503 * Returns an array of plugin reports as grade_plugin_info objects
2505 * @param int $courseid
2506 * @return array
2508 public static function get_plugins_reports($courseid) {
2509 global $SITE;
2511 if (self::$gradereports !== null) {
2512 return self::$gradereports;
2514 $context = context_course::instance($courseid);
2515 $gradereports = array();
2516 $gradepreferences = array();
2517 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2518 //some reports make no sense if we're not within a course
2519 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2520 continue;
2523 // Remove ones we can't see
2524 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2525 continue;
2528 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2529 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2530 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2532 // Add link to preferences tab if such a page exists
2533 if (file_exists($plugindir.'/preferences.php')) {
2534 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2535 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2538 if (count($gradereports) == 0) {
2539 $gradereports = false;
2540 $gradepreferences = false;
2541 } else if (count($gradepreferences) == 0) {
2542 $gradepreferences = false;
2543 asort($gradereports);
2544 } else {
2545 asort($gradereports);
2546 asort($gradepreferences);
2548 self::$gradereports = $gradereports;
2549 self::$gradereportpreferences = $gradepreferences;
2550 return self::$gradereports;
2553 * Returns an array of grade plugin report preferences for plugin reports that
2554 * support preferences
2555 * @param int $courseid
2556 * @return array
2558 public static function get_plugins_report_preferences($courseid) {
2559 if (self::$gradereportpreferences !== null) {
2560 return self::$gradereportpreferences;
2562 self::get_plugins_reports($courseid);
2563 return self::$gradereportpreferences;
2566 * Get information on scales
2567 * @param int $courseid
2568 * @return grade_plugin_info
2570 public static function get_info_scales($courseid) {
2571 if (self::$scaleinfo !== null) {
2572 return self::$scaleinfo;
2574 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2575 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2576 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2577 } else {
2578 self::$scaleinfo = false;
2580 return self::$scaleinfo;
2583 * Get information on outcomes
2584 * @param int $courseid
2585 * @return grade_plugin_info
2587 public static function get_info_outcomes($courseid) {
2588 global $CFG, $SITE;
2590 if (self::$outcomeinfo !== null) {
2591 return self::$outcomeinfo;
2593 $context = context_course::instance($courseid);
2594 $canmanage = has_capability('moodle/grade:manage', $context);
2595 $canupdate = has_capability('moodle/course:update', $context);
2596 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2597 $outcomes = array();
2598 if ($canupdate) {
2599 if ($courseid!=$SITE->id) {
2600 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2601 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2603 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2604 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2605 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2606 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2607 } else {
2608 if ($courseid!=$SITE->id) {
2609 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2610 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2613 self::$outcomeinfo = $outcomes;
2614 } else {
2615 self::$outcomeinfo = false;
2617 return self::$outcomeinfo;
2620 * Get information on editing structures
2621 * @param int $courseid
2622 * @return array
2624 public static function get_info_edit_structure($courseid) {
2625 if (self::$edittree !== null) {
2626 return self::$edittree;
2628 if (has_capability('moodle/grade:manage', context_course::instance($courseid))) {
2629 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2630 self::$edittree = array(
2631 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2632 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2634 } else {
2635 self::$edittree = false;
2637 return self::$edittree;
2640 * Get information on letters
2641 * @param int $courseid
2642 * @return array
2644 public static function get_info_letters($courseid) {
2645 global $SITE;
2646 if (self::$letterinfo !== null) {
2647 return self::$letterinfo;
2649 $context = context_course::instance($courseid);
2650 $canmanage = has_capability('moodle/grade:manage', $context);
2651 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2652 if ($canmanage || $canmanageletters) {
2653 // Redirect to system context when report is accessed from admin settings MDL-31633
2654 if ($context->instanceid == $SITE->id) {
2655 $param = array('edit' => 1);
2656 } else {
2657 $param = array('edit' => 1,'id' => $context->id);
2659 self::$letterinfo = array(
2660 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2661 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2663 } else {
2664 self::$letterinfo = false;
2666 return self::$letterinfo;
2669 * Get information import plugins
2670 * @param int $courseid
2671 * @return array
2673 public static function get_plugins_import($courseid) {
2674 global $CFG;
2676 if (self::$importplugins !== null) {
2677 return self::$importplugins;
2679 $importplugins = array();
2680 $context = context_course::instance($courseid);
2682 if (has_capability('moodle/grade:import', $context)) {
2683 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
2684 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2685 continue;
2687 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2688 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2689 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2693 if ($CFG->gradepublishing) {
2694 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2695 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2699 if (count($importplugins) > 0) {
2700 asort($importplugins);
2701 self::$importplugins = $importplugins;
2702 } else {
2703 self::$importplugins = false;
2705 return self::$importplugins;
2708 * Get information export plugins
2709 * @param int $courseid
2710 * @return array
2712 public static function get_plugins_export($courseid) {
2713 global $CFG;
2715 if (self::$exportplugins !== null) {
2716 return self::$exportplugins;
2718 $context = context_course::instance($courseid);
2719 $exportplugins = array();
2720 if (has_capability('moodle/grade:export', $context)) {
2721 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
2722 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2723 continue;
2725 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2726 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2727 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2730 if ($CFG->gradepublishing) {
2731 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2732 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2735 if (count($exportplugins) > 0) {
2736 asort($exportplugins);
2737 self::$exportplugins = $exportplugins;
2738 } else {
2739 self::$exportplugins = false;
2741 return self::$exportplugins;
2745 * Returns the value of a field from a user record
2747 * @param stdClass $user object
2748 * @param stdClass $field object
2749 * @return string value of the field
2751 public static function get_user_field_value($user, $field) {
2752 if (!empty($field->customid)) {
2753 $fieldname = 'customfield_' . $field->shortname;
2754 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
2755 $fieldvalue = $user->{$fieldname};
2756 } else {
2757 $fieldvalue = $field->default;
2759 } else {
2760 $fieldvalue = $user->{$field->shortname};
2762 return $fieldvalue;
2766 * Returns an array of user profile fields to be included in export
2768 * @param int $courseid
2769 * @param bool $includecustomfields
2770 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2772 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2773 global $CFG, $DB;
2775 // Gets the fields that have to be hidden
2776 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
2777 $context = context_course::instance($courseid);
2778 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2779 if ($canseehiddenfields) {
2780 $hiddenfields = array();
2783 $fields = array();
2784 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
2785 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2786 $userdefaultfields = user_get_default_fields();
2788 // Sets the list of profile fields
2789 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
2790 if (!empty($userprofilefields)) {
2791 foreach ($userprofilefields as $field) {
2792 $field = trim($field);
2793 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
2794 continue;
2796 $obj = new stdClass();
2797 $obj->customid = 0;
2798 $obj->shortname = $field;
2799 $obj->fullname = get_string($field);
2800 $fields[] = $obj;
2804 // Sets the list of custom profile fields
2805 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
2806 if ($includecustomfields && !empty($customprofilefields)) {
2807 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2808 $customfields = $DB->get_records_sql("SELECT f.*
2809 FROM {user_info_field} f
2810 JOIN {user_info_category} c ON f.categoryid=c.id
2811 WHERE f.shortname $wherefields
2812 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2813 if (!is_array($customfields)) {
2814 continue;
2817 foreach ($customfields as $field) {
2818 // Make sure we can display this custom field
2819 if (!in_array($field->shortname, $customprofilefields)) {
2820 continue;
2821 } else if (in_array($field->shortname, $hiddenfields)) {
2822 continue;
2823 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
2824 continue;
2827 $obj = new stdClass();
2828 $obj->customid = $field->id;
2829 $obj->shortname = $field->shortname;
2830 $obj->fullname = format_string($field->name);
2831 $obj->datatype = $field->datatype;
2832 $obj->default = $field->defaultdata;
2833 $fields[] = $obj;
2837 return $fields;