Merge branch 'MDL-40264-m25-essay-zero' of git://github.com/ktemkin/moodle into MOODL...
[moodle.git] / grade / lib.php
blob7f67b190b04ab892467fa9fb378891e0283ed421
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);
146 $relatedcontexts = get_related_contexts_string($coursecontext);
148 list($gradebookroles_sql, $params) =
149 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
150 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
152 $params = array_merge($params, $enrolledparams);
154 if ($this->groupid) {
155 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
156 $groupwheresql = "AND gm.groupid = :groupid";
157 // $params contents: gradebookroles
158 $params['groupid'] = $this->groupid;
159 } else {
160 $groupsql = "";
161 $groupwheresql = "";
164 if (empty($this->sortfield1)) {
165 // we must do some sorting even if not specified
166 $ofields = ", u.id AS usrt";
167 $order = "usrt ASC";
169 } else {
170 $ofields = ", u.$this->sortfield1 AS usrt1";
171 $order = "usrt1 $this->sortorder1";
172 if (!empty($this->sortfield2)) {
173 $ofields .= ", u.$this->sortfield2 AS usrt2";
174 $order .= ", usrt2 $this->sortorder2";
176 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
177 // user order MUST be the same in both queries,
178 // must include the only unique user->id if not already present
179 $ofields .= ", u.id AS usrt";
180 $order .= ", usrt ASC";
184 $userfields = 'u.*';
185 $customfieldssql = '';
186 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
187 $customfieldscount = 0;
188 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
189 foreach ($customfieldsarray as $field) {
190 if (!empty($field->customid)) {
191 $customfieldssql .= "
192 LEFT JOIN (SELECT * FROM {user_info_data}
193 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
194 ON u.id = cf$customfieldscount.userid";
195 $userfields .= ", cf$customfieldscount.data AS 'customfield_{$field->shortname}'";
196 $params['cf'.$customfieldscount] = $field->customid;
197 $customfieldscount++;
202 // $params contents: gradebookroles and groupid (for $groupwheresql)
203 $users_sql = "SELECT $userfields $ofields
204 FROM {user} u
205 JOIN ($enrolledsql) je ON je.id = u.id
206 $groupsql $customfieldssql
207 JOIN (
208 SELECT DISTINCT ra.userid
209 FROM {role_assignments} ra
210 WHERE ra.roleid $gradebookroles_sql
211 AND ra.contextid $relatedcontexts
212 ) rainner ON rainner.userid = u.id
213 WHERE u.deleted = 0
214 $groupwheresql
215 ORDER BY $order";
216 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
218 if (!$this->onlyactive) {
219 $context = context_course::instance($this->course->id);
220 $this->suspendedusers = get_suspended_userids($context);
221 } else {
222 $this->suspendedusers = array();
225 if (!empty($this->grade_items)) {
226 $itemids = array_keys($this->grade_items);
227 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
228 $params = array_merge($params, $grades_params);
229 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
231 $grades_sql = "SELECT g.* $ofields
232 FROM {grade_grades} g
233 JOIN {user} u ON g.userid = u.id
234 JOIN ($enrolledsql) je ON je.id = u.id
235 $groupsql
236 JOIN (
237 SELECT DISTINCT ra.userid
238 FROM {role_assignments} ra
239 WHERE ra.roleid $gradebookroles_sql
240 AND ra.contextid $relatedcontexts
241 ) rainner ON rainner.userid = u.id
242 WHERE u.deleted = 0
243 AND g.itemid $itemidsql
244 $groupwheresql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
247 } else {
248 $this->grades_rs = false;
251 return true;
255 * Returns information about the next user
256 * @return mixed array of user info, all grades and feedback or null when no more users found
258 public function next_user() {
259 if (!$this->users_rs) {
260 return false; // no users present
263 if (!$this->users_rs->valid()) {
264 if ($current = $this->_pop()) {
265 // this is not good - user or grades updated between the two reads above :-(
268 return false; // no more users
269 } else {
270 $user = $this->users_rs->current();
271 $this->users_rs->next();
274 // find grades of this user
275 $grade_records = array();
276 while (true) {
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid)) {
282 break;
285 if ($current->userid != $user->id) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
288 break;
291 $grade_records[$current->itemid] = $current;
294 $grades = array();
295 $feedbacks = array();
297 if (!empty($this->grade_items)) {
298 foreach ($this->grade_items as $grade_item) {
299 if (!isset($feedbacks[$grade_item->id])) {
300 $feedbacks[$grade_item->id] = new stdClass();
302 if (array_key_exists($grade_item->id, $grade_records)) {
303 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
304 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
305 unset($grade_records[$grade_item->id]->feedback);
306 unset($grade_records[$grade_item->id]->feedbackformat);
307 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
308 } else {
309 $feedbacks[$grade_item->id]->feedback = '';
310 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
311 $grades[$grade_item->id] =
312 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
317 // Set user suspended status.
318 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
319 $result = new stdClass();
320 $result->user = $user;
321 $result->grades = $grades;
322 $result->feedbacks = $feedbacks;
323 return $result;
327 * Close the iterator, do not forget to call this function
329 public function close() {
330 if ($this->users_rs) {
331 $this->users_rs->close();
332 $this->users_rs = null;
334 if ($this->grades_rs) {
335 $this->grades_rs->close();
336 $this->grades_rs = null;
338 $this->gradestack = array();
342 * Should all enrolled users be exported or just those with an active enrolment?
344 * @param bool $onlyactive True to limit the export to users with an active enrolment
346 public function require_active_enrolment($onlyactive = true) {
347 if (!empty($this->users_rs)) {
348 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
350 $this->onlyactive = $onlyactive;
354 * Allow custom fields to be included
356 * @param bool $allow Whether to allow custom fields or not
357 * @return void
359 public function allow_user_custom_fields($allow = true) {
360 if ($allow) {
361 $this->allowusercustomfields = true;
362 } else {
363 $this->allowusercustomfields = false;
368 * Add a grade_grade instance to the grade stack
370 * @param grade_grade $grade Grade object
372 * @return void
374 private function _push($grade) {
375 array_push($this->gradestack, $grade);
380 * Remove a grade_grade instance from the grade stack
382 * @return grade_grade current grade object
384 private function _pop() {
385 global $DB;
386 if (empty($this->gradestack)) {
387 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
388 return null; // no grades present
391 $current = $this->grades_rs->current();
393 $this->grades_rs->next();
395 return $current;
396 } else {
397 return array_pop($this->gradestack);
403 * Print a selection popup form of the graded users in a course.
405 * @deprecated since 2.0
407 * @param int $course id of the course
408 * @param string $actionpage The page receiving the data from the popoup form
409 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
410 * @param int $groupid id of requested group, 0 means all
411 * @param int $includeall bool include all option
412 * @param bool $return If true, will return the HTML, otherwise, will print directly
413 * @return null
415 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
416 global $CFG, $USER, $OUTPUT;
417 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
420 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
421 global $USER;
423 if (is_null($userid)) {
424 $userid = $USER->id;
426 $coursecontext = context_course::instance($course->id);
427 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
428 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
429 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
430 $menu = array(); // Will be a list of userid => user name
431 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
432 $gui = new graded_users_iterator($course, null, $groupid);
433 $gui->require_active_enrolment($showonlyactiveenrol);
434 $gui->init();
435 $label = get_string('selectauser', 'grades');
436 if ($includeall) {
437 $menu[0] = get_string('allusers', 'grades');
438 $label = get_string('selectalloroneuser', 'grades');
440 while ($userdata = $gui->next_user()) {
441 $user = $userdata->user;
442 $userfullname = fullname($user);
443 if ($user->suspendedenrolment) {
444 $menususpendedusers[$user->id] = $userfullname;
445 } else {
446 $menu[$user->id] = $userfullname;
449 $gui->close();
451 if ($includeall) {
452 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
455 if (!empty($menususpendedusers)) {
456 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
458 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
459 $select->label = $label;
460 $select->formid = 'choosegradeuser';
461 return $select;
465 * Print grading plugin selection popup form.
467 * @param array $plugin_info An array of plugins containing information for the selector
468 * @param boolean $return return as string
470 * @return nothing or string if $return true
472 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
473 global $CFG, $OUTPUT, $PAGE;
475 $menu = array();
476 $count = 0;
477 $active = '';
479 foreach ($plugin_info as $plugin_type => $plugins) {
480 if ($plugin_type == 'strings') {
481 continue;
484 $first_plugin = reset($plugins);
486 $sectionname = $plugin_info['strings'][$plugin_type];
487 $section = array();
489 foreach ($plugins as $plugin) {
490 $link = $plugin->link->out(false);
491 $section[$link] = $plugin->string;
492 $count++;
493 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
494 $active = $link;
498 if ($section) {
499 $menu[] = array($sectionname=>$section);
503 // finally print/return the popup form
504 if ($count > 1) {
505 $select = new url_select($menu, $active, null, 'choosepluginreport');
506 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
507 if ($return) {
508 return $OUTPUT->render($select);
509 } else {
510 echo $OUTPUT->render($select);
512 } else {
513 // only one option - no plugin selector needed
514 return '';
519 * Print grading plugin selection tab-based navigation.
521 * @param string $active_type type of plugin on current page - import, export, report or edit
522 * @param string $active_plugin active plugin type - grader, user, cvs, ...
523 * @param array $plugin_info Array of plugins
524 * @param boolean $return return as string
526 * @return nothing or string if $return true
528 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
529 global $CFG, $COURSE;
531 if (!isset($currenttab)) { //TODO: this is weird
532 $currenttab = '';
535 $tabs = array();
536 $top_row = array();
537 $bottom_row = array();
538 $inactive = array($active_plugin);
539 $activated = array();
541 $count = 0;
542 $active = '';
544 foreach ($plugin_info as $plugin_type => $plugins) {
545 if ($plugin_type == 'strings') {
546 continue;
549 // If $plugins is actually the definition of a child-less parent link:
550 if (!empty($plugins->id)) {
551 $string = $plugins->string;
552 if (!empty($plugin_info[$active_type]->parent)) {
553 $string = $plugin_info[$active_type]->parent->string;
556 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
557 continue;
560 $first_plugin = reset($plugins);
561 $url = $first_plugin->link;
563 if ($plugin_type == 'report') {
564 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
567 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
569 if ($active_type == $plugin_type) {
570 foreach ($plugins as $plugin) {
571 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
572 if ($plugin->id == $active_plugin) {
573 $inactive = array($plugin->id);
579 $tabs[] = $top_row;
580 $tabs[] = $bottom_row;
582 if ($return) {
583 return print_tabs($tabs, $active_type, $inactive, $activated, true);
584 } else {
585 print_tabs($tabs, $active_type, $inactive, $activated);
590 * grade_get_plugin_info
592 * @param int $courseid The course id
593 * @param string $active_type type of plugin on current page - import, export, report or edit
594 * @param string $active_plugin active plugin type - grader, user, cvs, ...
596 * @return array
598 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
599 global $CFG, $SITE;
601 $context = context_course::instance($courseid);
603 $plugin_info = array();
604 $count = 0;
605 $active = '';
606 $url_prefix = $CFG->wwwroot . '/grade/';
608 // Language strings
609 $plugin_info['strings'] = grade_helper::get_plugin_strings();
611 if ($reports = grade_helper::get_plugins_reports($courseid)) {
612 $plugin_info['report'] = $reports;
615 //showing grade categories and items make no sense if we're not within a course
616 if ($courseid!=$SITE->id) {
617 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
618 $plugin_info['edittree'] = $edittree;
622 if ($scale = grade_helper::get_info_scales($courseid)) {
623 $plugin_info['scale'] = array('view'=>$scale);
626 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
627 $plugin_info['outcome'] = $outcomes;
630 if ($letters = grade_helper::get_info_letters($courseid)) {
631 $plugin_info['letter'] = $letters;
634 if ($imports = grade_helper::get_plugins_import($courseid)) {
635 $plugin_info['import'] = $imports;
638 if ($exports = grade_helper::get_plugins_export($courseid)) {
639 $plugin_info['export'] = $exports;
642 foreach ($plugin_info as $plugin_type => $plugins) {
643 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
644 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
645 break;
647 foreach ($plugins as $plugin) {
648 if (is_a($plugin, 'grade_plugin_info')) {
649 if ($active_plugin == $plugin->id) {
650 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
656 //hide course settings if we're not in a course
657 if ($courseid!=$SITE->id) {
658 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
659 $plugin_info['settings'] = array('course'=>$setting);
663 // Put preferences last
664 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
665 $plugin_info['preferences'] = $preferences;
668 foreach ($plugin_info as $plugin_type => $plugins) {
669 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
670 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
671 break;
673 foreach ($plugins as $plugin) {
674 if (is_a($plugin, 'grade_plugin_info')) {
675 if ($active_plugin == $plugin->id) {
676 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
682 return $plugin_info;
686 * A simple class containing info about grade plugins.
687 * Can be subclassed for special rules
689 * @package core_grades
690 * @copyright 2009 Nicolas Connault
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 class grade_plugin_info {
695 * A unique id for this plugin
697 * @var mixed
699 public $id;
701 * A URL to access this plugin
703 * @var mixed
705 public $link;
707 * The name of this plugin
709 * @var mixed
711 public $string;
713 * Another grade_plugin_info object, parent of the current one
715 * @var mixed
717 public $parent;
720 * Constructor
722 * @param int $id A unique id for this plugin
723 * @param string $link A URL to access this plugin
724 * @param string $string The name of this plugin
725 * @param object $parent Another grade_plugin_info object, parent of the current one
727 * @return void
729 public function __construct($id, $link, $string, $parent=null) {
730 $this->id = $id;
731 $this->link = $link;
732 $this->string = $string;
733 $this->parent = $parent;
738 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
739 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
740 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
741 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
742 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
744 * @param int $courseid Course id
745 * @param string $active_type The type of the current page (report, settings,
746 * import, export, scales, outcomes, letters)
747 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
748 * @param string $heading The heading of the page. Tries to guess if none is given
749 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
750 * @param string $bodytags Additional attributes that will be added to the <body> tag
751 * @param string $buttons Additional buttons to display on the page
752 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
754 * @return string HTML code or nothing if $return == false
756 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
757 $heading = false, $return=false,
758 $buttons=false, $shownavigation=true) {
759 global $CFG, $OUTPUT, $PAGE;
761 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
763 // Determine the string of the active plugin
764 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
765 $stractive_type = $plugin_info['strings'][$active_type];
767 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
768 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
769 } else {
770 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
773 if ($active_type == 'report') {
774 $PAGE->set_pagelayout('report');
775 } else {
776 $PAGE->set_pagelayout('admin');
778 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
779 $PAGE->set_heading($title);
780 if ($buttons instanceof single_button) {
781 $buttons = $OUTPUT->render($buttons);
783 $PAGE->set_button($buttons);
784 grade_extend_settings($plugin_info, $courseid);
786 $returnval = $OUTPUT->header();
787 if (!$return) {
788 echo $returnval;
791 // Guess heading if not given explicitly
792 if (!$heading) {
793 $heading = $stractive_plugin;
796 if ($shownavigation) {
797 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
798 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
801 if ($return) {
802 $returnval .= $OUTPUT->heading($heading);
803 } else {
804 echo $OUTPUT->heading($heading);
807 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
808 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
812 if ($return) {
813 return $returnval;
818 * Utility class used for return tracking when using edit and other forms in grade plugins
820 * @package core_grades
821 * @copyright 2009 Nicolas Connault
822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
824 class grade_plugin_return {
825 public $type;
826 public $plugin;
827 public $courseid;
828 public $userid;
829 public $page;
832 * Constructor
834 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
836 public function grade_plugin_return($params = null) {
837 if (empty($params)) {
838 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
839 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
840 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
841 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
842 $this->page = optional_param('gpr_page', null, PARAM_INT);
844 } else {
845 foreach ($params as $key=>$value) {
846 if (property_exists($this, $key)) {
847 $this->$key = $value;
854 * Returns return parameters as options array suitable for buttons.
855 * @return array options
857 public function get_options() {
858 if (empty($this->type)) {
859 return array();
862 $params = array();
864 if (!empty($this->plugin)) {
865 $params['plugin'] = $this->plugin;
868 if (!empty($this->courseid)) {
869 $params['id'] = $this->courseid;
872 if (!empty($this->userid)) {
873 $params['userid'] = $this->userid;
876 if (!empty($this->page)) {
877 $params['page'] = $this->page;
880 return $params;
884 * Returns return url
886 * @param string $default default url when params not set
887 * @param array $extras Extra URL parameters
889 * @return string url
891 public function get_return_url($default, $extras=null) {
892 global $CFG;
894 if (empty($this->type) or empty($this->plugin)) {
895 return $default;
898 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
899 $glue = '?';
901 if (!empty($this->courseid)) {
902 $url .= $glue.'id='.$this->courseid;
903 $glue = '&amp;';
906 if (!empty($this->userid)) {
907 $url .= $glue.'userid='.$this->userid;
908 $glue = '&amp;';
911 if (!empty($this->page)) {
912 $url .= $glue.'page='.$this->page;
913 $glue = '&amp;';
916 if (!empty($extras)) {
917 foreach ($extras as $key=>$value) {
918 $url .= $glue.$key.'='.$value;
919 $glue = '&amp;';
923 return $url;
927 * Returns string with hidden return tracking form elements.
928 * @return string
930 public function get_form_fields() {
931 if (empty($this->type)) {
932 return '';
935 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
937 if (!empty($this->plugin)) {
938 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
941 if (!empty($this->courseid)) {
942 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
945 if (!empty($this->userid)) {
946 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
949 if (!empty($this->page)) {
950 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
955 * Add hidden elements into mform
957 * @param object &$mform moodle form object
959 * @return void
961 public function add_mform_elements(&$mform) {
962 if (empty($this->type)) {
963 return;
966 $mform->addElement('hidden', 'gpr_type', $this->type);
967 $mform->setType('gpr_type', PARAM_SAFEDIR);
969 if (!empty($this->plugin)) {
970 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
971 $mform->setType('gpr_plugin', PARAM_PLUGIN);
974 if (!empty($this->courseid)) {
975 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
976 $mform->setType('gpr_courseid', PARAM_INT);
979 if (!empty($this->userid)) {
980 $mform->addElement('hidden', 'gpr_userid', $this->userid);
981 $mform->setType('gpr_userid', PARAM_INT);
984 if (!empty($this->page)) {
985 $mform->addElement('hidden', 'gpr_page', $this->page);
986 $mform->setType('gpr_page', PARAM_INT);
991 * Add return tracking params into url
993 * @param moodle_url $url A URL
995 * @return string $url with return tracking params
997 public function add_url_params(moodle_url $url) {
998 if (empty($this->type)) {
999 return $url;
1002 $url->param('gpr_type', $this->type);
1004 if (!empty($this->plugin)) {
1005 $url->param('gpr_plugin', $this->plugin);
1008 if (!empty($this->courseid)) {
1009 $url->param('gpr_courseid' ,$this->courseid);
1012 if (!empty($this->userid)) {
1013 $url->param('gpr_userid', $this->userid);
1016 if (!empty($this->page)) {
1017 $url->param('gpr_page', $this->page);
1020 return $url;
1025 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1027 * @param string $path The path of the calling script (using __FILE__?)
1028 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1029 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1030 * an array of keys and values (e.g courseid => $courseid, itemid...)
1032 * @return string
1034 function grade_build_nav($path, $pagename=null, $id=null) {
1035 global $CFG, $COURSE, $PAGE;
1037 $strgrades = get_string('grades', 'grades');
1039 // Parse the path and build navlinks from its elements
1040 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1041 $path = substr($path, $dirroot_length);
1042 $path = str_replace('\\', '/', $path);
1044 $path_elements = explode('/', $path);
1046 $path_elements_count = count($path_elements);
1048 // First link is always 'grade'
1049 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1051 $link = null;
1052 $numberofelements = 3;
1054 // Prepare URL params string
1055 $linkparams = array();
1056 if (!is_null($id)) {
1057 if (is_array($id)) {
1058 foreach ($id as $idkey => $idvalue) {
1059 $linkparams[$idkey] = $idvalue;
1061 } else {
1062 $linkparams['id'] = $id;
1066 $navlink4 = null;
1068 // Remove file extensions from filenames
1069 foreach ($path_elements as $key => $filename) {
1070 $path_elements[$key] = str_replace('.php', '', $filename);
1073 // Second level links
1074 switch ($path_elements[1]) {
1075 case 'edit': // No link
1076 if ($path_elements[3] != 'index.php') {
1077 $numberofelements = 4;
1079 break;
1080 case 'import': // No link
1081 break;
1082 case 'export': // No link
1083 break;
1084 case 'report':
1085 // $id is required for this link. Do not print it if $id isn't given
1086 if (!is_null($id)) {
1087 $link = new moodle_url('/grade/report/index.php', $linkparams);
1090 if ($path_elements[2] == 'grader') {
1091 $numberofelements = 4;
1093 break;
1095 default:
1096 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1097 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1098 " as the second path element after 'grade'.");
1099 return false;
1101 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1103 // Third level links
1104 if (empty($pagename)) {
1105 $pagename = get_string($path_elements[2], 'grades');
1108 switch ($numberofelements) {
1109 case 3:
1110 $PAGE->navbar->add($pagename, $link);
1111 break;
1112 case 4:
1113 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1114 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1116 $PAGE->navbar->add($pagename);
1117 break;
1120 return '';
1124 * General structure representing grade items in course
1126 * @package core_grades
1127 * @copyright 2009 Nicolas Connault
1128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1130 class grade_structure {
1131 public $context;
1133 public $courseid;
1136 * Reference to modinfo for current course (for performance, to save
1137 * retrieving it from courseid every time). Not actually set except for
1138 * the grade_tree type.
1139 * @var course_modinfo
1141 public $modinfo;
1144 * 1D array of grade items only
1146 public $items;
1149 * Returns icon of element
1151 * @param array &$element An array representing an element in the grade_tree
1152 * @param bool $spacerifnone return spacer if no icon found
1154 * @return string icon or spacer
1156 public function get_element_icon(&$element, $spacerifnone=false) {
1157 global $CFG, $OUTPUT;
1158 require_once $CFG->libdir.'/filelib.php';
1160 switch ($element['type']) {
1161 case 'item':
1162 case 'courseitem':
1163 case 'categoryitem':
1164 $is_course = $element['object']->is_course_item();
1165 $is_category = $element['object']->is_category_item();
1166 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1167 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1168 $is_outcome = !empty($element['object']->outcomeid);
1170 if ($element['object']->is_calculated()) {
1171 $strcalc = get_string('calculatedgrade', 'grades');
1172 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1173 s($strcalc).'" alt="'.s($strcalc).'"/>';
1175 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1176 if ($category = $element['object']->get_item_category()) {
1177 switch ($category->aggregation) {
1178 case GRADE_AGGREGATE_MEAN:
1179 case GRADE_AGGREGATE_MEDIAN:
1180 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1181 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1182 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1183 $stragg = get_string('aggregation', 'grades');
1184 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1185 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1186 case GRADE_AGGREGATE_SUM:
1187 $stragg = get_string('aggregation', 'grades');
1188 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1189 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1193 } else if ($element['object']->itemtype == 'mod') {
1194 //prevent outcomes being displaying the same icon as the activity they are attached to
1195 if ($is_outcome) {
1196 $stroutcome = s(get_string('outcome', 'grades'));
1197 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1198 'class="icon itemicon" title="'.$stroutcome.
1199 '" alt="'.$stroutcome.'"/>';
1200 } else {
1201 $strmodname = get_string('modulename', $element['object']->itemmodule);
1202 return '<img src="'.$OUTPUT->pix_url('icon',
1203 $element['object']->itemmodule) . '" ' .
1204 'class="icon itemicon" title="' .s($strmodname).
1205 '" alt="' .s($strmodname).'"/>';
1207 } else if ($element['object']->itemtype == 'manual') {
1208 if ($element['object']->is_outcome_item()) {
1209 $stroutcome = get_string('outcome', 'grades');
1210 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1211 'class="icon itemicon" title="'.s($stroutcome).
1212 '" alt="'.s($stroutcome).'"/>';
1213 } else {
1214 $strmanual = get_string('manualitem', 'grades');
1215 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1216 'class="icon itemicon" title="'.s($strmanual).
1217 '" alt="'.s($strmanual).'"/>';
1220 break;
1222 case 'category':
1223 $strcat = get_string('category', 'grades');
1224 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1225 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1228 if ($spacerifnone) {
1229 return $OUTPUT->spacer().' ';
1230 } else {
1231 return '';
1236 * Returns name of element optionally with icon and link
1238 * @param array &$element An array representing an element in the grade_tree
1239 * @param bool $withlink Whether or not this header has a link
1240 * @param bool $icon Whether or not to display an icon with this header
1241 * @param bool $spacerifnone return spacer if no icon found
1243 * @return string header
1245 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1246 $header = '';
1248 if ($icon) {
1249 $header .= $this->get_element_icon($element, $spacerifnone);
1252 $header .= $element['object']->get_name();
1254 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1255 $element['type'] != 'courseitem') {
1256 return $header;
1259 if ($withlink) {
1260 $url = $this->get_activity_link($element);
1261 if ($url) {
1262 $a = new stdClass();
1263 $a->name = get_string('modulename', $element['object']->itemmodule);
1264 $title = get_string('linktoactivity', 'grades', $a);
1266 $header = html_writer::link($url, $header, array('title' => $title));
1270 return $header;
1273 private function get_activity_link($element) {
1274 global $CFG;
1275 /** @var array static cache of the grade.php file existence flags */
1276 static $hasgradephp = array();
1278 $itemtype = $element['object']->itemtype;
1279 $itemmodule = $element['object']->itemmodule;
1280 $iteminstance = $element['object']->iteminstance;
1281 $itemnumber = $element['object']->itemnumber;
1283 // Links only for module items that have valid instance, module and are
1284 // called from grade_tree with valid modinfo
1285 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1286 return null;
1289 // Get $cm efficiently and with visibility information using modinfo
1290 $instances = $this->modinfo->get_instances();
1291 if (empty($instances[$itemmodule][$iteminstance])) {
1292 return null;
1294 $cm = $instances[$itemmodule][$iteminstance];
1296 // Do not add link if activity is not visible to the current user
1297 if (!$cm->uservisible) {
1298 return null;
1301 if (!array_key_exists($itemmodule, $hasgradephp)) {
1302 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1303 $hasgradephp[$itemmodule] = true;
1304 } else {
1305 $hasgradephp[$itemmodule] = false;
1309 // If module has grade.php, link to that, otherwise view.php
1310 if ($hasgradephp[$itemmodule]) {
1311 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1312 if (isset($element['userid'])) {
1313 $args['userid'] = $element['userid'];
1315 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1316 } else {
1317 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1322 * Returns URL of a page that is supposed to contain detailed grade analysis
1324 * At the moment, only activity modules are supported. The method generates link
1325 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1326 * gradeid and userid. If the grade.php does not exist, null is returned.
1328 * @return moodle_url|null URL or null if unable to construct it
1330 public function get_grade_analysis_url(grade_grade $grade) {
1331 global $CFG;
1332 /** @var array static cache of the grade.php file existence flags */
1333 static $hasgradephp = array();
1335 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1336 throw new coding_exception('Passed grade without the associated grade item');
1338 $item = $grade->grade_item;
1340 if (!$item->is_external_item()) {
1341 // at the moment, only activity modules are supported
1342 return null;
1344 if ($item->itemtype !== 'mod') {
1345 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1347 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1348 return null;
1351 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1352 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1353 $hasgradephp[$item->itemmodule] = true;
1354 } else {
1355 $hasgradephp[$item->itemmodule] = false;
1359 if (!$hasgradephp[$item->itemmodule]) {
1360 return null;
1363 $instances = $this->modinfo->get_instances();
1364 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1365 return null;
1367 $cm = $instances[$item->itemmodule][$item->iteminstance];
1368 if (!$cm->uservisible) {
1369 return null;
1372 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1373 'id' => $cm->id,
1374 'itemid' => $item->id,
1375 'itemnumber' => $item->itemnumber,
1376 'gradeid' => $grade->id,
1377 'userid' => $grade->userid,
1380 return $url;
1384 * Returns an action icon leading to the grade analysis page
1386 * @param grade_grade $grade
1387 * @return string
1389 public function get_grade_analysis_icon(grade_grade $grade) {
1390 global $OUTPUT;
1392 $url = $this->get_grade_analysis_url($grade);
1393 if (is_null($url)) {
1394 return '';
1397 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1398 get_string('gradeanalysis', 'core_grades')));
1402 * Returns the grade eid - the grade may not exist yet.
1404 * @param grade_grade $grade_grade A grade_grade object
1406 * @return string eid
1408 public function get_grade_eid($grade_grade) {
1409 if (empty($grade_grade->id)) {
1410 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1411 } else {
1412 return 'g'.$grade_grade->id;
1417 * Returns the grade_item eid
1418 * @param grade_item $grade_item A grade_item object
1419 * @return string eid
1421 public function get_item_eid($grade_item) {
1422 return 'i'.$grade_item->id;
1426 * Given a grade_tree element, returns an array of parameters
1427 * used to build an icon for that element.
1429 * @param array $element An array representing an element in the grade_tree
1431 * @return array
1433 public function get_params_for_iconstr($element) {
1434 $strparams = new stdClass();
1435 $strparams->category = '';
1436 $strparams->itemname = '';
1437 $strparams->itemmodule = '';
1439 if (!method_exists($element['object'], 'get_name')) {
1440 return $strparams;
1443 $strparams->itemname = html_to_text($element['object']->get_name());
1445 // If element name is categorytotal, get the name of the parent category
1446 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1447 $parent = $element['object']->get_parent_category();
1448 $strparams->category = $parent->get_name() . ' ';
1449 } else {
1450 $strparams->category = '';
1453 $strparams->itemmodule = null;
1454 if (isset($element['object']->itemmodule)) {
1455 $strparams->itemmodule = $element['object']->itemmodule;
1457 return $strparams;
1461 * Return edit icon for give element
1463 * @param array $element An array representing an element in the grade_tree
1464 * @param object $gpr A grade_plugin_return object
1466 * @return string
1468 public function get_edit_icon($element, $gpr) {
1469 global $CFG, $OUTPUT;
1471 if (!has_capability('moodle/grade:manage', $this->context)) {
1472 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1473 // oki - let them override grade
1474 } else {
1475 return '';
1479 static $strfeedback = null;
1480 static $streditgrade = null;
1481 if (is_null($streditgrade)) {
1482 $streditgrade = get_string('editgrade', 'grades');
1483 $strfeedback = get_string('feedback');
1486 $strparams = $this->get_params_for_iconstr($element);
1488 $object = $element['object'];
1490 switch ($element['type']) {
1491 case 'item':
1492 case 'categoryitem':
1493 case 'courseitem':
1494 $stredit = get_string('editverbose', 'grades', $strparams);
1495 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1496 $url = new moodle_url('/grade/edit/tree/item.php',
1497 array('courseid' => $this->courseid, 'id' => $object->id));
1498 } else {
1499 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1500 array('courseid' => $this->courseid, 'id' => $object->id));
1502 break;
1504 case 'category':
1505 $stredit = get_string('editverbose', 'grades', $strparams);
1506 $url = new moodle_url('/grade/edit/tree/category.php',
1507 array('courseid' => $this->courseid, 'id' => $object->id));
1508 break;
1510 case 'grade':
1511 $stredit = $streditgrade;
1512 if (empty($object->id)) {
1513 $url = new moodle_url('/grade/edit/tree/grade.php',
1514 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1515 } else {
1516 $url = new moodle_url('/grade/edit/tree/grade.php',
1517 array('courseid' => $this->courseid, 'id' => $object->id));
1519 if (!empty($object->feedback)) {
1520 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1522 break;
1524 default:
1525 $url = null;
1528 if ($url) {
1529 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1531 } else {
1532 return '';
1537 * Return hiding icon for give element
1539 * @param array $element An array representing an element in the grade_tree
1540 * @param object $gpr A grade_plugin_return object
1542 * @return string
1544 public function get_hiding_icon($element, $gpr) {
1545 global $CFG, $OUTPUT;
1547 if (!has_capability('moodle/grade:manage', $this->context) and
1548 !has_capability('moodle/grade:hide', $this->context)) {
1549 return '';
1552 $strparams = $this->get_params_for_iconstr($element);
1553 $strshow = get_string('showverbose', 'grades', $strparams);
1554 $strhide = get_string('hideverbose', 'grades', $strparams);
1556 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1557 $url = $gpr->add_url_params($url);
1559 if ($element['object']->is_hidden()) {
1560 $type = 'show';
1561 $tooltip = $strshow;
1563 // Change the icon and add a tooltip showing the date
1564 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1565 $type = 'hiddenuntil';
1566 $tooltip = get_string('hiddenuntildate', 'grades',
1567 userdate($element['object']->get_hidden()));
1570 $url->param('action', 'show');
1572 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1574 } else {
1575 $url->param('action', 'hide');
1576 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1579 return $hideicon;
1583 * Return locking icon for given element
1585 * @param array $element An array representing an element in the grade_tree
1586 * @param object $gpr A grade_plugin_return object
1588 * @return string
1590 public function get_locking_icon($element, $gpr) {
1591 global $CFG, $OUTPUT;
1593 $strparams = $this->get_params_for_iconstr($element);
1594 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1595 $strlock = get_string('lockverbose', 'grades', $strparams);
1597 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1598 $url = $gpr->add_url_params($url);
1600 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1601 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1602 $strparamobj = new stdClass();
1603 $strparamobj->itemname = $element['object']->grade_item->itemname;
1604 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1606 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1607 array('class' => 'action-icon'));
1609 } else if ($element['object']->is_locked()) {
1610 $type = 'unlock';
1611 $tooltip = $strunlock;
1613 // Change the icon and add a tooltip showing the date
1614 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1615 $type = 'locktime';
1616 $tooltip = get_string('locktimedate', 'grades',
1617 userdate($element['object']->get_locktime()));
1620 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1621 $action = '';
1622 } else {
1623 $url->param('action', 'unlock');
1624 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1627 } else {
1628 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1629 $action = '';
1630 } else {
1631 $url->param('action', 'lock');
1632 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1636 return $action;
1640 * Return calculation icon for given element
1642 * @param array $element An array representing an element in the grade_tree
1643 * @param object $gpr A grade_plugin_return object
1645 * @return string
1647 public function get_calculation_icon($element, $gpr) {
1648 global $CFG, $OUTPUT;
1649 if (!has_capability('moodle/grade:manage', $this->context)) {
1650 return '';
1653 $type = $element['type'];
1654 $object = $element['object'];
1656 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1657 $strparams = $this->get_params_for_iconstr($element);
1658 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1660 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1661 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1663 // show calculation icon only when calculation possible
1664 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1665 if ($object->is_calculated()) {
1666 $icon = 't/calc';
1667 } else {
1668 $icon = 't/calc_off';
1671 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1672 $url = $gpr->add_url_params($url);
1673 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
1677 return '';
1682 * Flat structure similar to grade tree.
1684 * @uses grade_structure
1685 * @package core_grades
1686 * @copyright 2009 Nicolas Connault
1687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1689 class grade_seq extends grade_structure {
1692 * 1D array of elements
1694 public $elements;
1697 * Constructor, retrieves and stores array of all grade_category and grade_item
1698 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1700 * @param int $courseid The course id
1701 * @param bool $category_grade_last category grade item is the last child
1702 * @param bool $nooutcomes Whether or not outcomes should be included
1704 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1705 global $USER, $CFG;
1707 $this->courseid = $courseid;
1708 $this->context = context_course::instance($courseid);
1710 // get course grade tree
1711 $top_element = grade_category::fetch_course_tree($courseid, true);
1713 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1715 foreach ($this->elements as $key=>$unused) {
1716 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1721 * Static recursive helper - makes the grade_item for category the last children
1723 * @param array &$element The seed of the recursion
1724 * @param bool $category_grade_last category grade item is the last child
1725 * @param bool $nooutcomes Whether or not outcomes should be included
1727 * @return array
1729 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1730 if (empty($element['children'])) {
1731 return array();
1733 $children = array();
1735 foreach ($element['children'] as $sortorder=>$unused) {
1736 if ($nooutcomes and $element['type'] != 'category' and
1737 $element['children'][$sortorder]['object']->is_outcome_item()) {
1738 continue;
1740 $children[] = $element['children'][$sortorder];
1742 unset($element['children']);
1744 if ($category_grade_last and count($children) > 1) {
1745 $cat_item = array_shift($children);
1746 array_push($children, $cat_item);
1749 $result = array();
1750 foreach ($children as $child) {
1751 if ($child['type'] == 'category') {
1752 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1753 } else {
1754 $child['eid'] = 'i'.$child['object']->id;
1755 $result[$child['object']->id] = $child;
1759 return $result;
1763 * Parses the array in search of a given eid and returns a element object with
1764 * information about the element it has found.
1766 * @param int $eid Gradetree Element ID
1768 * @return object element
1770 public function locate_element($eid) {
1771 // it is a grade - construct a new object
1772 if (strpos($eid, 'n') === 0) {
1773 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1774 return null;
1777 $itemid = $matches[1];
1778 $userid = $matches[2];
1780 //extra security check - the grade item must be in this tree
1781 if (!$item_el = $this->locate_element('i'.$itemid)) {
1782 return null;
1785 // $gradea->id may be null - means does not exist yet
1786 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1788 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1789 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1791 } else if (strpos($eid, 'g') === 0) {
1792 $id = (int) substr($eid, 1);
1793 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1794 return null;
1796 //extra security check - the grade item must be in this tree
1797 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1798 return null;
1800 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1801 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1804 // it is a category or item
1805 foreach ($this->elements as $element) {
1806 if ($element['eid'] == $eid) {
1807 return $element;
1811 return null;
1816 * This class represents a complete tree of categories, grade_items and final grades,
1817 * organises as an array primarily, but which can also be converted to other formats.
1818 * It has simple method calls with complex implementations, allowing for easy insertion,
1819 * deletion and moving of items and categories within the tree.
1821 * @uses grade_structure
1822 * @package core_grades
1823 * @copyright 2009 Nicolas Connault
1824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1826 class grade_tree extends grade_structure {
1829 * The basic representation of the tree as a hierarchical, 3-tiered array.
1830 * @var object $top_element
1832 public $top_element;
1835 * 2D array of grade items and categories
1836 * @var array $levels
1838 public $levels;
1841 * Grade items
1842 * @var array $items
1844 public $items;
1847 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1848 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1850 * @param int $courseid The Course ID
1851 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1852 * @param bool $category_grade_last category grade item is the last child
1853 * @param array $collapsed array of collapsed categories
1854 * @param bool $nooutcomes Whether or not outcomes should be included
1856 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1857 $collapsed=null, $nooutcomes=false) {
1858 global $USER, $CFG, $COURSE, $DB;
1860 $this->courseid = $courseid;
1861 $this->levels = array();
1862 $this->context = context_course::instance($courseid);
1864 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1865 $course = $COURSE;
1866 } else {
1867 $course = $DB->get_record('course', array('id' => $this->courseid));
1869 $this->modinfo = get_fast_modinfo($course);
1871 // get course grade tree
1872 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1874 // collapse the categories if requested
1875 if (!empty($collapsed)) {
1876 grade_tree::category_collapse($this->top_element, $collapsed);
1879 // no otucomes if requested
1880 if (!empty($nooutcomes)) {
1881 grade_tree::no_outcomes($this->top_element);
1884 // move category item to last position in category
1885 if ($category_grade_last) {
1886 grade_tree::category_grade_last($this->top_element);
1889 if ($fillers) {
1890 // inject fake categories == fillers
1891 grade_tree::inject_fillers($this->top_element, 0);
1892 // add colspans to categories and fillers
1893 grade_tree::inject_colspans($this->top_element);
1896 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1901 * Static recursive helper - removes items from collapsed categories
1903 * @param array &$element The seed of the recursion
1904 * @param array $collapsed array of collapsed categories
1906 * @return void
1908 public function category_collapse(&$element, $collapsed) {
1909 if ($element['type'] != 'category') {
1910 return;
1912 if (empty($element['children']) or count($element['children']) < 2) {
1913 return;
1916 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1917 $category_item = reset($element['children']); //keep only category item
1918 $element['children'] = array(key($element['children'])=>$category_item);
1920 } else {
1921 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1922 reset($element['children']);
1923 $first_key = key($element['children']);
1924 unset($element['children'][$first_key]);
1926 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1927 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1933 * Static recursive helper - removes all outcomes
1935 * @param array &$element The seed of the recursion
1937 * @return void
1939 public function no_outcomes(&$element) {
1940 if ($element['type'] != 'category') {
1941 return;
1943 foreach ($element['children'] as $sortorder=>$child) {
1944 if ($element['children'][$sortorder]['type'] == 'item'
1945 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1946 unset($element['children'][$sortorder]);
1948 } else if ($element['children'][$sortorder]['type'] == 'category') {
1949 grade_tree::no_outcomes($element['children'][$sortorder]);
1955 * Static recursive helper - makes the grade_item for category the last children
1957 * @param array &$element The seed of the recursion
1959 * @return void
1961 public function category_grade_last(&$element) {
1962 if (empty($element['children'])) {
1963 return;
1965 if (count($element['children']) < 2) {
1966 return;
1968 $first_item = reset($element['children']);
1969 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1970 // the category item might have been already removed
1971 $order = key($element['children']);
1972 unset($element['children'][$order]);
1973 $element['children'][$order] =& $first_item;
1975 foreach ($element['children'] as $sortorder => $child) {
1976 grade_tree::category_grade_last($element['children'][$sortorder]);
1981 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1983 * @param array &$levels The levels of the grade tree through which to recurse
1984 * @param array &$element The seed of the recursion
1985 * @param int $depth How deep are we?
1986 * @return void
1988 public function fill_levels(&$levels, &$element, $depth) {
1989 if (!array_key_exists($depth, $levels)) {
1990 $levels[$depth] = array();
1993 // prepare unique identifier
1994 if ($element['type'] == 'category') {
1995 $element['eid'] = 'c'.$element['object']->id;
1996 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1997 $element['eid'] = 'i'.$element['object']->id;
1998 $this->items[$element['object']->id] =& $element['object'];
2001 $levels[$depth][] =& $element;
2002 $depth++;
2003 if (empty($element['children'])) {
2004 return;
2006 $prev = 0;
2007 foreach ($element['children'] as $sortorder=>$child) {
2008 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2009 $element['children'][$sortorder]['prev'] = $prev;
2010 $element['children'][$sortorder]['next'] = 0;
2011 if ($prev) {
2012 $element['children'][$prev]['next'] = $sortorder;
2014 $prev = $sortorder;
2019 * Static recursive helper - makes full tree (all leafes are at the same level)
2021 * @param array &$element The seed of the recursion
2022 * @param int $depth How deep are we?
2024 * @return int
2026 public function inject_fillers(&$element, $depth) {
2027 $depth++;
2029 if (empty($element['children'])) {
2030 return $depth;
2032 $chdepths = array();
2033 $chids = array_keys($element['children']);
2034 $last_child = end($chids);
2035 $first_child = reset($chids);
2037 foreach ($chids as $chid) {
2038 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2040 arsort($chdepths);
2042 $maxdepth = reset($chdepths);
2043 foreach ($chdepths as $chid=>$chd) {
2044 if ($chd == $maxdepth) {
2045 continue;
2047 for ($i=0; $i < $maxdepth-$chd; $i++) {
2048 if ($chid == $first_child) {
2049 $type = 'fillerfirst';
2050 } else if ($chid == $last_child) {
2051 $type = 'fillerlast';
2052 } else {
2053 $type = 'filler';
2055 $oldchild =& $element['children'][$chid];
2056 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2057 'eid'=>'', 'depth'=>$element['object']->depth,
2058 'children'=>array($oldchild));
2062 return $maxdepth;
2066 * Static recursive helper - add colspan information into categories
2068 * @param array &$element The seed of the recursion
2070 * @return int
2072 public function inject_colspans(&$element) {
2073 if (empty($element['children'])) {
2074 return 1;
2076 $count = 0;
2077 foreach ($element['children'] as $key=>$child) {
2078 $count += grade_tree::inject_colspans($element['children'][$key]);
2080 $element['colspan'] = $count;
2081 return $count;
2085 * Parses the array in search of a given eid and returns a element object with
2086 * information about the element it has found.
2087 * @param int $eid Gradetree Element ID
2088 * @return object element
2090 public function locate_element($eid) {
2091 // it is a grade - construct a new object
2092 if (strpos($eid, 'n') === 0) {
2093 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2094 return null;
2097 $itemid = $matches[1];
2098 $userid = $matches[2];
2100 //extra security check - the grade item must be in this tree
2101 if (!$item_el = $this->locate_element('i'.$itemid)) {
2102 return null;
2105 // $gradea->id may be null - means does not exist yet
2106 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2108 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2109 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2111 } else if (strpos($eid, 'g') === 0) {
2112 $id = (int) substr($eid, 1);
2113 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2114 return null;
2116 //extra security check - the grade item must be in this tree
2117 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2118 return null;
2120 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2121 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2124 // it is a category or item
2125 foreach ($this->levels as $row) {
2126 foreach ($row as $element) {
2127 if ($element['type'] == 'filler') {
2128 continue;
2130 if ($element['eid'] == $eid) {
2131 return $element;
2136 return null;
2140 * Returns a well-formed XML representation of the grade-tree using recursion.
2142 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2143 * @param string $tabs The control character to use for tabs
2145 * @return string $xml
2147 public function exporttoxml($root=null, $tabs="\t") {
2148 $xml = null;
2149 $first = false;
2150 if (is_null($root)) {
2151 $root = $this->top_element;
2152 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2153 $xml .= "<gradetree>\n";
2154 $first = true;
2157 $type = 'undefined';
2158 if (strpos($root['object']->table, 'grade_categories') !== false) {
2159 $type = 'category';
2160 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2161 $type = 'item';
2162 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2163 $type = 'outcome';
2166 $xml .= "$tabs<element type=\"$type\">\n";
2167 foreach ($root['object'] as $var => $value) {
2168 if (!is_object($value) && !is_array($value) && !empty($value)) {
2169 $xml .= "$tabs\t<$var>$value</$var>\n";
2173 if (!empty($root['children'])) {
2174 $xml .= "$tabs\t<children>\n";
2175 foreach ($root['children'] as $sortorder => $child) {
2176 $xml .= $this->exportToXML($child, $tabs."\t\t");
2178 $xml .= "$tabs\t</children>\n";
2181 $xml .= "$tabs</element>\n";
2183 if ($first) {
2184 $xml .= "</gradetree>";
2187 return $xml;
2191 * Returns a JSON representation of the grade-tree using recursion.
2193 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2194 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2196 * @return string
2198 public function exporttojson($root=null, $tabs="\t") {
2199 $json = null;
2200 $first = false;
2201 if (is_null($root)) {
2202 $root = $this->top_element;
2203 $first = true;
2206 $name = '';
2209 if (strpos($root['object']->table, 'grade_categories') !== false) {
2210 $name = $root['object']->fullname;
2211 if ($name == '?') {
2212 $name = $root['object']->get_name();
2214 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2215 $name = $root['object']->itemname;
2216 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2217 $name = $root['object']->itemname;
2220 $json .= "$tabs {\n";
2221 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2222 $json .= "$tabs\t \"name\": \"$name\",\n";
2224 foreach ($root['object'] as $var => $value) {
2225 if (!is_object($value) && !is_array($value) && !empty($value)) {
2226 $json .= "$tabs\t \"$var\": \"$value\",\n";
2230 $json = substr($json, 0, strrpos($json, ','));
2232 if (!empty($root['children'])) {
2233 $json .= ",\n$tabs\t\"children\": [\n";
2234 foreach ($root['children'] as $sortorder => $child) {
2235 $json .= $this->exportToJSON($child, $tabs."\t\t");
2237 $json = substr($json, 0, strrpos($json, ','));
2238 $json .= "\n$tabs\t]\n";
2241 if ($first) {
2242 $json .= "\n}";
2243 } else {
2244 $json .= "\n$tabs},\n";
2247 return $json;
2251 * Returns the array of levels
2253 * @return array
2255 public function get_levels() {
2256 return $this->levels;
2260 * Returns the array of grade items
2262 * @return array
2264 public function get_items() {
2265 return $this->items;
2269 * Returns a specific Grade Item
2271 * @param int $itemid The ID of the grade_item object
2273 * @return grade_item
2275 public function get_item($itemid) {
2276 if (array_key_exists($itemid, $this->items)) {
2277 return $this->items[$itemid];
2278 } else {
2279 return false;
2285 * Local shortcut function for creating an edit/delete button for a grade_* object.
2286 * @param string $type 'edit' or 'delete'
2287 * @param int $courseid The Course ID
2288 * @param grade_* $object The grade_* object
2289 * @return string html
2291 function grade_button($type, $courseid, $object) {
2292 global $CFG, $OUTPUT;
2293 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2294 $objectidstring = $matches[1] . 'id';
2295 } else {
2296 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2299 $strdelete = get_string('delete');
2300 $stredit = get_string('edit');
2302 if ($type == 'delete') {
2303 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2304 } else if ($type == 'edit') {
2305 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2308 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2313 * This method adds settings to the settings block for the grade system and its
2314 * plugins
2316 * @global moodle_page $PAGE
2318 function grade_extend_settings($plugininfo, $courseid) {
2319 global $PAGE;
2321 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2323 $strings = array_shift($plugininfo);
2325 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2326 foreach ($reports as $report) {
2327 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2331 if ($imports = grade_helper::get_plugins_import($courseid)) {
2332 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2333 foreach ($imports as $import) {
2334 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2338 if ($exports = grade_helper::get_plugins_export($courseid)) {
2339 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2340 foreach ($exports as $export) {
2341 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2345 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2346 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2349 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2350 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2351 foreach ($preferences as $preference) {
2352 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2356 if ($letters = grade_helper::get_info_letters($courseid)) {
2357 $letters = array_shift($letters);
2358 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2361 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2362 $outcomes = array_shift($outcomes);
2363 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2366 if ($scales = grade_helper::get_info_scales($courseid)) {
2367 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2370 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2371 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2372 foreach ($categories as $category) {
2373 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2377 if ($gradenode->contains_active_node()) {
2378 // If the gradenode is active include the settings base node (gradeadministration) in
2379 // the navbar, typcially this is ignored.
2380 $PAGE->navbar->includesettingsbase = true;
2382 // If we can get the course admin node make sure it is closed by default
2383 // as in this case the gradenode will be opened
2384 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2385 $coursenode->make_inactive();
2386 $coursenode->forceopen = false;
2392 * Grade helper class
2394 * This class provides several helpful functions that work irrespective of any
2395 * current state.
2397 * @copyright 2010 Sam Hemelryk
2398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2400 abstract class grade_helper {
2402 * Cached manage settings info {@see get_info_settings}
2403 * @var grade_plugin_info|false
2405 protected static $managesetting = null;
2407 * Cached grade report plugins {@see get_plugins_reports}
2408 * @var array|false
2410 protected static $gradereports = null;
2412 * Cached grade report plugins preferences {@see get_info_scales}
2413 * @var array|false
2415 protected static $gradereportpreferences = null;
2417 * Cached scale info {@see get_info_scales}
2418 * @var grade_plugin_info|false
2420 protected static $scaleinfo = null;
2422 * Cached outcome info {@see get_info_outcomes}
2423 * @var grade_plugin_info|false
2425 protected static $outcomeinfo = null;
2427 * Cached info on edit structure {@see get_info_edit_structure}
2428 * @var array|false
2430 protected static $edittree = null;
2432 * Cached leftter info {@see get_info_letters}
2433 * @var grade_plugin_info|false
2435 protected static $letterinfo = null;
2437 * Cached grade import plugins {@see get_plugins_import}
2438 * @var array|false
2440 protected static $importplugins = null;
2442 * Cached grade export plugins {@see get_plugins_export}
2443 * @var array|false
2445 protected static $exportplugins = null;
2447 * Cached grade plugin strings
2448 * @var array
2450 protected static $pluginstrings = null;
2453 * Gets strings commonly used by the describe plugins
2455 * report => get_string('view'),
2456 * edittree => get_string('edittree', 'grades'),
2457 * scale => get_string('scales'),
2458 * outcome => get_string('outcomes', 'grades'),
2459 * letter => get_string('letters', 'grades'),
2460 * export => get_string('export', 'grades'),
2461 * import => get_string('import'),
2462 * preferences => get_string('mypreferences', 'grades'),
2463 * settings => get_string('settings')
2465 * @return array
2467 public static function get_plugin_strings() {
2468 if (self::$pluginstrings === null) {
2469 self::$pluginstrings = array(
2470 'report' => get_string('view'),
2471 'edittree' => get_string('edittree', 'grades'),
2472 'scale' => get_string('scales'),
2473 'outcome' => get_string('outcomes', 'grades'),
2474 'letter' => get_string('letters', 'grades'),
2475 'export' => get_string('export', 'grades'),
2476 'import' => get_string('import'),
2477 'preferences' => get_string('mypreferences', 'grades'),
2478 'settings' => get_string('settings')
2481 return self::$pluginstrings;
2484 * Get grade_plugin_info object for managing settings if the user can
2486 * @param int $courseid
2487 * @return grade_plugin_info
2489 public static function get_info_manage_settings($courseid) {
2490 if (self::$managesetting !== null) {
2491 return self::$managesetting;
2493 $context = context_course::instance($courseid);
2494 if (has_capability('moodle/grade:manage', $context)) {
2495 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2496 } else {
2497 self::$managesetting = false;
2499 return self::$managesetting;
2502 * Returns an array of plugin reports as grade_plugin_info objects
2504 * @param int $courseid
2505 * @return array
2507 public static function get_plugins_reports($courseid) {
2508 global $SITE;
2510 if (self::$gradereports !== null) {
2511 return self::$gradereports;
2513 $context = context_course::instance($courseid);
2514 $gradereports = array();
2515 $gradepreferences = array();
2516 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2517 //some reports make no sense if we're not within a course
2518 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2519 continue;
2522 // Remove ones we can't see
2523 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2524 continue;
2527 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2528 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2529 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2531 // Add link to preferences tab if such a page exists
2532 if (file_exists($plugindir.'/preferences.php')) {
2533 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2534 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2537 if (count($gradereports) == 0) {
2538 $gradereports = false;
2539 $gradepreferences = false;
2540 } else if (count($gradepreferences) == 0) {
2541 $gradepreferences = false;
2542 asort($gradereports);
2543 } else {
2544 asort($gradereports);
2545 asort($gradepreferences);
2547 self::$gradereports = $gradereports;
2548 self::$gradereportpreferences = $gradepreferences;
2549 return self::$gradereports;
2552 * Returns an array of grade plugin report preferences for plugin reports that
2553 * support preferences
2554 * @param int $courseid
2555 * @return array
2557 public static function get_plugins_report_preferences($courseid) {
2558 if (self::$gradereportpreferences !== null) {
2559 return self::$gradereportpreferences;
2561 self::get_plugins_reports($courseid);
2562 return self::$gradereportpreferences;
2565 * Get information on scales
2566 * @param int $courseid
2567 * @return grade_plugin_info
2569 public static function get_info_scales($courseid) {
2570 if (self::$scaleinfo !== null) {
2571 return self::$scaleinfo;
2573 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2574 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2575 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2576 } else {
2577 self::$scaleinfo = false;
2579 return self::$scaleinfo;
2582 * Get information on outcomes
2583 * @param int $courseid
2584 * @return grade_plugin_info
2586 public static function get_info_outcomes($courseid) {
2587 global $CFG, $SITE;
2589 if (self::$outcomeinfo !== null) {
2590 return self::$outcomeinfo;
2592 $context = context_course::instance($courseid);
2593 $canmanage = has_capability('moodle/grade:manage', $context);
2594 $canupdate = has_capability('moodle/course:update', $context);
2595 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2596 $outcomes = array();
2597 if ($canupdate) {
2598 if ($courseid!=$SITE->id) {
2599 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2600 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2602 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2603 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2604 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2605 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2606 } else {
2607 if ($courseid!=$SITE->id) {
2608 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2609 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2612 self::$outcomeinfo = $outcomes;
2613 } else {
2614 self::$outcomeinfo = false;
2616 return self::$outcomeinfo;
2619 * Get information on editing structures
2620 * @param int $courseid
2621 * @return array
2623 public static function get_info_edit_structure($courseid) {
2624 if (self::$edittree !== null) {
2625 return self::$edittree;
2627 if (has_capability('moodle/grade:manage', context_course::instance($courseid))) {
2628 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2629 self::$edittree = array(
2630 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2631 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2633 } else {
2634 self::$edittree = false;
2636 return self::$edittree;
2639 * Get information on letters
2640 * @param int $courseid
2641 * @return array
2643 public static function get_info_letters($courseid) {
2644 global $SITE;
2645 if (self::$letterinfo !== null) {
2646 return self::$letterinfo;
2648 $context = context_course::instance($courseid);
2649 $canmanage = has_capability('moodle/grade:manage', $context);
2650 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2651 if ($canmanage || $canmanageletters) {
2652 // Redirect to system context when report is accessed from admin settings MDL-31633
2653 if ($context->instanceid == $SITE->id) {
2654 $param = array('edit' => 1);
2655 } else {
2656 $param = array('edit' => 1,'id' => $context->id);
2658 self::$letterinfo = array(
2659 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2660 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2662 } else {
2663 self::$letterinfo = false;
2665 return self::$letterinfo;
2668 * Get information import plugins
2669 * @param int $courseid
2670 * @return array
2672 public static function get_plugins_import($courseid) {
2673 global $CFG;
2675 if (self::$importplugins !== null) {
2676 return self::$importplugins;
2678 $importplugins = array();
2679 $context = context_course::instance($courseid);
2681 if (has_capability('moodle/grade:import', $context)) {
2682 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2683 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2684 continue;
2686 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2687 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2688 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2692 if ($CFG->gradepublishing) {
2693 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2694 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2698 if (count($importplugins) > 0) {
2699 asort($importplugins);
2700 self::$importplugins = $importplugins;
2701 } else {
2702 self::$importplugins = false;
2704 return self::$importplugins;
2707 * Get information export plugins
2708 * @param int $courseid
2709 * @return array
2711 public static function get_plugins_export($courseid) {
2712 global $CFG;
2714 if (self::$exportplugins !== null) {
2715 return self::$exportplugins;
2717 $context = context_course::instance($courseid);
2718 $exportplugins = array();
2719 if (has_capability('moodle/grade:export', $context)) {
2720 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2721 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2722 continue;
2724 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2725 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2726 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2729 if ($CFG->gradepublishing) {
2730 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2731 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2734 if (count($exportplugins) > 0) {
2735 asort($exportplugins);
2736 self::$exportplugins = $exportplugins;
2737 } else {
2738 self::$exportplugins = false;
2740 return self::$exportplugins;
2744 * Returns the value of a field from a user record
2746 * @param stdClass $user object
2747 * @param stdClass $field object
2748 * @return string value of the field
2750 public static function get_user_field_value($user, $field) {
2751 if (!empty($field->customid)) {
2752 $fieldname = 'customfield_' . $field->shortname;
2753 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
2754 $fieldvalue = $user->{$fieldname};
2755 } else {
2756 $fieldvalue = $field->default;
2758 } else {
2759 $fieldvalue = $user->{$field->shortname};
2761 return $fieldvalue;
2765 * Returns an array of user profile fields to be included in export
2767 * @param int $courseid
2768 * @param bool $includecustomfields
2769 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2771 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2772 global $CFG, $DB;
2774 // Gets the fields that have to be hidden
2775 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
2776 $context = context_course::instance($courseid);
2777 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2778 if ($canseehiddenfields) {
2779 $hiddenfields = array();
2782 $fields = array();
2783 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
2784 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2785 $userdefaultfields = user_get_default_fields();
2787 // Sets the list of profile fields
2788 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
2789 if (!empty($userprofilefields)) {
2790 foreach ($userprofilefields as $field) {
2791 $field = trim($field);
2792 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
2793 continue;
2795 $obj = new stdClass();
2796 $obj->customid = 0;
2797 $obj->shortname = $field;
2798 $obj->fullname = get_string($field);
2799 $fields[] = $obj;
2803 // Sets the list of custom profile fields
2804 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
2805 if ($includecustomfields && !empty($customprofilefields)) {
2806 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2807 $customfields = $DB->get_records_sql("SELECT f.*
2808 FROM {user_info_field} f
2809 JOIN {user_info_category} c ON f.categoryid=c.id
2810 WHERE f.shortname $wherefields
2811 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2812 if (!is_array($customfields)) {
2813 continue;
2816 foreach ($customfields as $field) {
2817 // Make sure we can display this custom field
2818 if (!in_array($field->shortname, $customprofilefields)) {
2819 continue;
2820 } else if (in_array($field->shortname, $hiddenfields)) {
2821 continue;
2822 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
2823 continue;
2826 $obj = new stdClass();
2827 $obj->customid = $field->id;
2828 $obj->shortname = $field->shortname;
2829 $obj->fullname = format_string($field->name);
2830 $obj->datatype = $field->datatype;
2831 $obj->default = $field->defaultdata;
2832 $fields[] = $obj;
2836 return $fields;