3 ///////////////////////////////////////////////////////////////////////////
4 // NOTICE OF COPYRIGHT //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
9 // Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
11 // This program is free software; you can redistribute it and/or modify //
12 // it under the terms of the GNU General Public License as published by //
13 // the Free Software Foundation; either version 2 of the License, or //
14 // (at your option) any later version. //
16 // This program is distributed in the hope that it will be useful, //
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
19 // GNU General Public License for more details: //
21 // http://www.gnu.org/copyleft/gpl.html //
23 ///////////////////////////////////////////////////////////////////////////
26 * Library of functions for gradebook
28 * @author Moodle HQ developers
30 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
34 require_once($CFG->libdir
. '/grade/constants.php');
36 require_once($CFG->libdir
. '/grade/grade_category.php');
37 require_once($CFG->libdir
. '/grade/grade_item.php');
38 require_once($CFG->libdir
. '/grade/grade_grade.php');
39 require_once($CFG->libdir
. '/grade/grade_scale.php');
40 require_once($CFG->libdir
. '/grade/grade_outcome.php');
41 require_once($CFG->libdir
. '/grade/grade_grade_text.php');
43 /***** PUBLIC GRADE API *****/
46 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
47 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
48 * or key means do not change existing.
50 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
51 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted'.
53 * @param string $source source of the grade such as 'mod/assignment'
54 * @param int $courseid id of course
55 * @param string $itemtype type of grade item - mod, block
56 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
57 * @param int $iteminstance instance it of graded subject
58 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
59 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
60 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
62 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
65 // only following grade_item properties can be changed in this function
66 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted');
68 // grade item identification
69 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
71 if (is_null($courseid) or is_null($itemtype)) {
72 debugging('Missing courseid or itemtype');
73 return GRADE_UPDATE_FAILED
;
76 if (!$grade_items = grade_item
::fetch_all($params)) {
80 } else if (count($grade_items) == 1){
81 $grade_item = reset($grade_items);
82 unset($grade_items); //release memory
85 debugging('Found more than one grade item');
86 return GRADE_UPDATE_MULTIPLE
;
89 if (!empty($itemdetails['deleted'])) {
91 if ($grade_item->delete($source)) {
92 return GRADE_UPDATE_OK
;
94 return GRADE_UPDATE_FAILED
;
97 return GRADE_UPDATE_OK
;
100 /// Create or update the grade_item if needed
103 $itemdetails = (array)$itemdetails;
105 // grademin and grademax ignored when scale specified
106 if (array_key_exists('scaleid', $itemdetails)) {
107 if ($itemdetails['scaleid']) {
108 unset($itemdetails['grademin']);
109 unset($itemdetails['grademax']);
113 foreach ($itemdetails as $k=>$v) {
114 if (!in_array($k, $allowed)) {
118 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE
) {
119 // no grade item needed!
120 return GRADE_UPDATE_OK
;
125 $grade_item = new grade_item($params);
126 $grade_item->insert();
129 if ($grade_item->is_locked()) {
130 debugging('Grading item is locked!');
131 return GRADE_UPDATE_ITEM_LOCKED
;
135 $itemdetails = (array)$itemdetails;
137 foreach ($itemdetails as $k=>$v) {
138 if (!in_array($k, $allowed)) {
142 if ($grade_item->{$k} != $v) {
143 $grade_item->{$k} = $v;
148 $grade_item->update();
153 /// Some extra checks
154 // do we use grading?
155 if ($grade_item->gradetype
== GRADE_TYPE_NONE
) {
156 return GRADE_UPDATE_OK
;
159 // no grade submitted
160 if (empty($grades)) {
161 return GRADE_UPDATE_OK
;
164 /// Finally start processing of grades
165 if (is_object($grades)) {
166 $grades = array($grades);
168 if (array_key_exists('userid', $grades)) {
169 $grades = array($grades);
174 foreach ($grades as $grade) {
175 $grade = (array)$grade;
176 if (empty($grade['userid'])) {
178 debugging('Invalid userid in grade submitted');
181 $userid = $grade['userid'];
186 $feedbackformat = FORMAT_MOODLE
;
188 if (array_key_exists('rawgrade', $grade)) {
189 $rawgrade = $grade['rawgrade'];
192 if (array_key_exists('feedback', $grade)) {
193 $feedback = $grade['feedback'];
196 if (array_key_exists('feedbackformat', $grade)) {
197 $feedbackformat = $grade['feedbackformat'];
200 if (array_key_exists('usermodified', $grade)) {
201 $usermodified = $grade['usermodified'];
203 $usermodified = $USER->id
;
206 // update or insert the grade
207 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
213 return GRADE_UPDATE_OK
;
215 return GRADE_UPDATE_FAILED
;
221 * Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
222 * If it's locked to the current user then the module can print a nice message or prevent editing in the module.
223 * If no $userid is given, the method will always return the grade_item's locked state.
224 * If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
225 * the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
226 * return the locked state of the specific grade.
228 * @param int $courseid id of course
229 * @param string $itemtype 'mod', 'block'
230 * @param string $itemmodule 'forum, 'quiz', etc.
231 * @param int $iteminstance id of the item module
232 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
233 * @param int $userid ID of the graded user
234 * @return boolean Whether the grade is locked or not
236 function grade_is_locked($courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $userid=NULL) {
238 if (!$grade_items = grade_item
::fetch_all(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber'))) {
241 } else if (count($grade_items) == 1){
242 $grade_item = reset($grade_items);
243 return $grade_item->is_locked($userid);
246 debugging('Found more than one grade item');
247 foreach ($grade_items as $grade_item) {
248 if ($grade_item->is_locked($userid)) {
257 * Returns list of outcomes used in course together with current outcomes for this user
258 * @param int $courseid id of course
259 * @param string $itemtype 'mod', 'block'
260 * @param string $itemmodule 'forum, 'quiz', etc.
261 * @param int $iteminstance id of the item module
262 * @param int $userid ID of the graded user
263 * @return array of outcome information objects (scaleid, name, grade and locked status) indexed with itemnumbers
265 function grade_get_outcomes($courseid, $itemtype, $itemmodule, $iteminstance, $userid=0) {
267 if ($items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
268 foreach ($items as $item) {
269 if (empty($item->outcomeid
)) {
272 if (!$outcome = grade_outcome
::fetch(array('id'=>$item->outcomeid
))) {
273 debugging('Incorect outcomeid found');
276 // prepare outcome info with user grade
278 $o->scaleid
= $outcome->scaleid
;
279 $o->name
= $outcome->fullname
;
281 if (empty($userid)) {
283 } if ($grade = $item->get_grade($userid,false)) {
284 $o->grade
= $grade->finalgrade
;
285 $o->locked
= $grade->is_locked();
288 $o->locked
= $item->is_locked();
290 $o->grade
= intval($o->grade
); // 0 means no grade, int for scales
292 $result[$item->itemnumber
] = $o;
300 * Updates outcomes of user
301 * @param int $courseid id of course
302 * @param string $itemtype 'mod', 'block'
303 * @param string $itemmodule 'forum, 'quiz', etc.
304 * @param int $iteminstance id of the item module
305 * @param int $userid ID of the graded user
307 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
308 if ($items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
309 foreach ($items as $item) {
310 if (!array_key_exists($item->itemnumber
, $data)) {
313 $grade = $data[$item->itemnumber
] < 1 ?
null : $data[$item->itemnumber
];
314 $item->update_final_grade($userid, $grade, $source);
319 /***** END OF PUBLIC API *****/
323 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
324 * @param string idnumber string (with magic quotes)
325 * @param object $cm used for course module idnumbers and items attached to modules
326 * @param object $gradeitem is item idnumber
327 * @return boolean true means idnumber ok
329 function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
330 if ($idnumber == '') {
331 //we allow empty idnumbers
335 // keep existing even when not unique
336 if ($cm and $cm->idnumber
== $idnumber) {
338 } else if ($grade_item and $grade_item->idnumber
== $idnumber) {
342 if (get_records('course_modules', 'idnumber', $idnumber)) {
346 if (get_records('grade_items', 'idnumber', $idnumber)) {
354 * Force final grade recalculation in all course items
355 * @param int $courseid
357 function grade_force_full_regrading($courseid) {
358 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
362 * Updates all final grades in course.
364 * @param int $courseid
365 * @param int $userid if specified, try to do a quick regrading of grades of this user only
366 * @param object $updated_item the item in which
367 * @return boolean true if ok, array of errors if problems found (item id is used as key)
369 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
371 $course_item = grade_item
::fetch_course_item($courseid);
374 // one raw grade updated for one user
375 if (empty($updated_item)) {
376 error("updated_item_id can not be null!");
378 if ($course_item->needsupdate
) {
379 $updated_item->force_regrading();
380 return 'Can not do fast regrading after updating of raw grades';
384 if (!$course_item->needsupdate
) {
390 $grade_items = grade_item
::fetch_all(array('courseid'=>$courseid));
391 $depends_on = array();
393 // first mark all category and calculated items as needing regrading
394 // this is slower, but 100% accurate
395 foreach ($grade_items as $gid=>$gitem) {
396 if (!empty($updated_item) and $updated_item->id
== $gid) {
397 $grade_items[$gid]->needsupdate
= 1;
399 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
400 $grade_items[$gid]->needsupdate
= 1;
403 // construct depends_on lookup array
404 $depends_on[$gid] = $grade_items[$gid]->depends_on();
409 $gids = array_keys($grade_items);
412 while (count($finalids) < count($gids)) { // work until all grades are final or error found
414 foreach ($gids as $gid) {
415 if (in_array($gid, $finalids)) {
416 continue; // already final
419 if (!$grade_items[$gid]->needsupdate
) {
420 $finalids[] = $gid; // we can make it final - does not need update
425 foreach ($depends_on[$gid] as $did) {
426 if (!in_array($did, $finalids)) {
428 continue; // this item depends on something that is not yet in finals array
432 //oki - let's update, calculate or aggregate :-)
434 $result = $grade_items[$gid]->regrade_final_grades($userid);
436 if ($result === true) {
437 $grade_items[$gid]->regrading_finished();
438 $grade_items[$gid]->check_locktime(); // do the locktime item locking
443 $grade_items[$gid]->force_regrading();
444 $errors[$gid] = $result;
456 foreach($gids as $gid) {
457 if (in_array($gid, $finalids)) {
458 continue; // this one is ok
460 $grade_items[$gid]->force_regrading();
461 $errors[$grade_items[$gid]->id
] = 'Probably circular reference or broken calculation formula'; // TODO: localize
463 break; // oki, found error
467 if (count($errors) == 0) {
468 if (empty($userid)) {
469 // do the locktime locking of grades, but only when doing full regrading
470 grade_grade
::check_locktime_all($gids);
479 * For backwards compatibility with old third-party modules, this function can
480 * be used to import all grades from activities with legacy grading.
481 * @param int $courseid or null if all courses
483 function grade_grab_legacy_grades($courseid=null) {
487 if (!$mods = get_list_of_plugins('mod') ) {
488 error('No modules installed!');
492 $course_sql = " AND cm.course=$courseid";
497 foreach ($mods as $mod) {
499 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
503 if (!$module = get_record('modules', 'name', $mod)) {
508 if (!$module->visible
) {
513 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
515 // include the module lib once
516 if (file_exists($fullmod.'/lib.php')) {
517 include_once($fullmod.'/lib.php');
518 // look for modname_grades() function - old gradebook pulling function
519 // if present sync the grades with new grading system
520 $gradefunc = $mod.'_grades';
521 if (function_exists($gradefunc)) {
523 // get all instance of the activity
524 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
525 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
526 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
528 if ($modinstances = get_records_sql($sql)) {
529 foreach ($modinstances as $modinstance) {
530 grade_update_mod_grades($modinstance);
539 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
541 function grade_grab_grades() {
545 if (!$mods = get_list_of_plugins('mod') ) {
546 error('No modules installed!');
549 foreach ($mods as $mod) {
551 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
555 if (!$module = get_record('modules', 'name', $mod)) {
560 if (!$module->visible
) {
565 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
567 // include the module lib once
568 if (file_exists($fullmod.'/lib.php')) {
569 include_once($fullmod.'/lib.php');
570 // look for modname_grades() function - old gradebook pulling function
571 // if present sync the grades with new grading system
572 $gradefunc = $mod.'_update_grades';
573 if (function_exists($gradefunc)) {
581 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
582 * @param object $modinstance object with extra cmidnumber and modname property
583 * @return boolean success
585 function grade_update_mod_grades($modinstance, $userid=0) {
588 $fullmod = $CFG->dirroot
.'/mod/'.$modinstance->modname
;
589 if (!file_exists($fullmod.'/lib.php')) {
590 debugging('missing lib.php file in module');
593 include_once($fullmod.'/lib.php');
595 // does it use legacy grading?
596 $gradefunc = $modinstance->modname
.'_grades';
597 $updategradesfunc = $modinstance->modname
.'_update_grades';
598 $updateitemfunc = $modinstance->modname
.'_grade_item_update';
600 if (function_exists($gradefunc)) {
602 // legacy module - not yet converted
603 if ($oldgrades = $gradefunc($modinstance->id
)) {
605 $grademax = $oldgrades->maxgrade
;
607 if (!is_numeric($grademax)) {
608 // scale name is provided as a string, try to find it
609 if (!$scale = get_record('scale', 'name', $grademax)) {
610 debugging('Incorrect scale name! name:'.$grademax);
613 $scaleid = $scale->id
;
616 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
617 debugging('Can not get/create legacy grade item!');
622 foreach ($oldgrades->grades
as $uid=>$usergrade) {
623 if ($userid and $uid != $userid) {
626 $grade = new object();
627 $grade->userid
= $uid;
629 if ($usergrade == '-') {
631 $grade->rawgrade
= null;
633 } else if ($scaleid) {
634 // scale in use, words used
635 $gradescale = explode(",", $scale->scale
);
636 $grade->rawgrade
= array_search($usergrade, $gradescale) +
1;
639 // good old numeric value
640 $grade->rawgrade
= $usergrade;
645 grade_update('legacygrab', $grade_item->courseid
, $grade_item->itemtype
, $grade_item->itemmodule
,
646 $grade_item->iteminstance
, $grade_item->itemnumber
, $grades);
649 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
650 //new grading supported, force updating of grades
651 $updateitemfunc($modinstance);
652 $updategradesfunc($modinstance, $userid);
655 // mudule does not support grading??
662 * Get and update/create grade item for legacy modules.
664 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
666 // does it already exist?
667 if ($grade_items = grade_item
::fetch_all(array('courseid'=>$modinstance->course
, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname
, 'iteminstance'=>$modinstance->id
, 'itemnumber'=>0))) {
668 if (count($grade_items) > 1) {
669 debugging('Multiple legacy grade_items found.');
673 $grade_item = reset($grade_items);
675 if (is_null($grademax) and is_null($scaleid)) {
676 $grade_item->gradetype
= GRADE_TYPE_NONE
;
678 } else if ($scaleid) {
679 $grade_item->gradetype
= GRADE_TYPE_SCALE
;
680 $grade_item->scaleid
= $scaleid;
681 $grade_item->grademin
= 1;
684 $grade_item->gradetype
= GRADE_TYPE_VALUE
;
685 $grade_item->grademax
= $grademax;
686 $grade_item->grademin
= 0;
689 $grade_item->itemname
= $modinstance->name
;
690 $grade_item->idnumber
= $modinstance->cmidnumber
;
692 $grade_item->update();
698 $params = array('courseid' =>$modinstance->course
,
700 'itemmodule' =>$modinstance->modname
,
701 'iteminstance'=>$modinstance->id
,
703 'itemname' =>$modinstance->name
,
704 'idnumber' =>$modinstance->cmidnumber
);
706 if (is_null($grademax) and is_null($scaleid)) {
707 $params['gradetype'] = GRADE_TYPE_NONE
;
709 } else if ($scaleid) {
710 $params['gradetype'] = GRADE_TYPE_SCALE
;
711 $params['scaleid'] = $scaleid;
712 $grade_item->grademin
= 1;
714 $params['gradetype'] = GRADE_TYPE_VALUE
;
715 $params['grademax'] = $grademax;
716 $params['grademin'] = 0;
719 $grade_item = new grade_item($params);
720 $grade_item->insert();
726 * Remove all grade related course data - history is kept
727 * @param int $courseid
728 * @showfeedback boolean print feedback
730 function remove_course_grades($courseid, $showfeedback) {
731 $strdeleted = get_string('deleted');
733 $course_category = grade_category
::fetch_course_category($courseid);
734 $course_category->delete('coursedelete');
736 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
739 if ($outcomes = grade_outcome
::fetch_all(array('courseid'=>$courseid))) {
740 foreach ($outcomes as $outcome) {
741 $outcome->delete('coursedelete');
744 delete_records('grade_outcomes_courses', 'courseid', $courseid);
746 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
749 if ($scales = grade_scale
::fetch_all(array('courseid'=>$courseid))) {
750 foreach ($scales as $scale) {
751 $scale->delete('coursedelete');
755 notify($strdeleted.' - '.get_string('scales'));
760 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
761 * @param int $steps The value between each level.
762 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
763 * @param int $lowest The lowest value to include
764 * @param int $highest The highest value to include
766 function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
767 // TODO reject or implement
773 function grade_cron() {
779 FROM {$CFG->prefix}grade_items i
780 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
781 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
783 // go through all courses that have proper final grades and lock them if needed
784 if ($rs = get_recordset_sql($sql)) {
785 if ($rs->RecordCount() > 0) {
786 while ($item = rs_fetch_next_record($rs)) {
787 $grade_item = new grade_item($item, false);
788 $grade_item->locked
= $now;
789 $grade_item->update('locktime');
796 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
797 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
798 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
800 // go through all courses that have proper final grades and lock them if needed
801 if ($rs = get_recordset_sql($sql)) {
802 if ($rs->RecordCount() > 0) {
803 while ($grade = rs_fetch_next_record($rs)) {
804 $grade_grade = new grade_grade($grade, false);
805 $grade_grade->locked
= $now;
806 $grade_grade->update('locktime');