MDL-11276, average calculations are inaccurate in percentage form due to double rounding
[moodle-pu.git] / lib / gradelib.php
blob16ac00de70423b75ce7fa097655a5965d5db5b13
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // NOTICE OF COPYRIGHT //
5 // //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
8 // //
9 // Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
10 // //
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. //
15 // //
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: //
20 // //
21 // http://www.gnu.org/copyleft/gpl.html //
22 // //
23 ///////////////////////////////////////////////////////////////////////////
25 /**
26 * Library of functions for gradebook
28 * @author Moodle HQ developers
29 * @version $Id$
30 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
31 * @package moodlecore
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 - only these functions should be used in modules *****/
45 /**
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) {
63 global $USER;
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)) {
77 // create a new one
78 $grade_item = false;
80 } else if (count($grade_items) == 1){
81 $grade_item = reset($grade_items);
82 unset($grade_items); //release memory
84 } else {
85 debugging('Found more than one grade item');
86 return GRADE_UPDATE_MULTIPLE;
89 if (!empty($itemdetails['deleted'])) {
90 if ($grade_item) {
91 if ($grade_item->delete($source)) {
92 return GRADE_UPDATE_OK;
93 } else {
94 return GRADE_UPDATE_FAILED;
97 return GRADE_UPDATE_OK;
100 /// Create or update the grade_item if needed
102 if (!$grade_item) {
103 if ($itemdetails) {
104 $itemdetails = (array)$itemdetails;
106 // grademin and grademax ignored when scale specified
107 if (array_key_exists('scaleid', $itemdetails)) {
108 if ($itemdetails['scaleid']) {
109 unset($itemdetails['grademin']);
110 unset($itemdetails['grademax']);
114 foreach ($itemdetails as $k=>$v) {
115 if (!in_array($k, $allowed)) {
116 // ignore it
117 continue;
119 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
120 // no grade item needed!
121 return GRADE_UPDATE_OK;
123 $params[$k] = $v;
126 $grade_item = new grade_item($params);
127 $grade_item->insert();
129 } else {
130 if ($grade_item->is_locked()) {
131 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
132 if (!$confirm_regrade) {
133 $message = get_string('gradeitemislocked', 'grades', $grade_item->itemname);
134 $back_link = '';
135 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
136 notice_yesno($message, $regrade_link, $back_link);
137 return GRADE_UPDATE_ITEM_LOCKED;
141 if ($itemdetails) {
142 $itemdetails = (array)$itemdetails;
143 $update = false;
144 foreach ($itemdetails as $k=>$v) {
145 if (!in_array($k, $allowed)) {
146 // ignore it
147 continue;
149 if ($grade_item->{$k} != $v) {
150 $grade_item->{$k} = $v;
151 $update = true;
154 if ($update) {
155 $grade_item->update();
160 /// Some extra checks
161 // do we use grading?
162 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
163 return GRADE_UPDATE_OK;
166 // no grade submitted
167 if (empty($grades)) {
168 return GRADE_UPDATE_OK;
171 /// Finally start processing of grades
172 if (is_object($grades)) {
173 $grades = array($grades);
174 } else {
175 if (array_key_exists('userid', $grades)) {
176 $grades = array($grades);
180 $failed = false;
181 foreach ($grades as $grade) {
182 $grade = (array)$grade;
183 if (empty($grade['userid'])) {
184 $failed = true;
185 debugging('Invalid userid in grade submitted');
186 continue;
187 } else {
188 $userid = $grade['userid'];
191 $rawgrade = false;
192 $feedback = false;
193 $feedbackformat = FORMAT_MOODLE;
195 if (array_key_exists('rawgrade', $grade)) {
196 $rawgrade = $grade['rawgrade'];
199 if (array_key_exists('feedback', $grade)) {
200 $feedback = $grade['feedback'];
203 if (array_key_exists('feedbackformat', $grade)) {
204 $feedbackformat = $grade['feedbackformat'];
207 if (array_key_exists('usermodified', $grade)) {
208 $usermodified = $grade['usermodified'];
209 } else {
210 $usermodified = $USER->id;
213 // update or insert the grade
214 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
215 $failed = true;
219 if (!$failed) {
220 return GRADE_UPDATE_OK;
221 } else {
222 return GRADE_UPDATE_FAILED;
228 * Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
229 * If it's locked to the current user then the module can print a nice message or prevent editing in the module.
230 * If no $userid is given, the method will always return the grade_item's locked state.
231 * If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
232 * the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
233 * return the locked state of the specific grade.
235 * @param int $courseid id of course
236 * @param string $itemtype 'mod', 'block'
237 * @param string $itemmodule 'forum, 'quiz', etc.
238 * @param int $iteminstance id of the item module
239 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
240 * @param int $userid ID of the graded user
241 * @return boolean Whether the grade is locked or not
243 function grade_is_locked($courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $userid=NULL) {
245 if (!$grade_items = grade_item::fetch_all(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber'))) {
246 return false;
248 } else if (count($grade_items) == 1){
249 $grade_item = reset($grade_items);
250 return $grade_item->is_locked($userid);
252 } else {
253 debugging('Found more than one grade item');
254 foreach ($grade_items as $grade_item) {
255 if ($grade_item->is_locked($userid)) {
256 return true;
259 return false;
264 * Returns list of outcomes used in activity together with current outcomes for user
265 * @param int $courseid id of course
266 * @param string $itemtype 'mod', 'block'
267 * @param string $itemmodule 'forum, 'quiz', etc.
268 * @param int $iteminstance id of the item module
269 * @param int $userid optional id of the graded user
270 * @return array of outcome information objects (scaleid, name, grade and locked status) indexed with itemnumbers
272 function grade_get_outcomes($courseid, $itemtype, $itemmodule, $iteminstance, $userid=0) {
273 $result = array();
274 $course_item = grade_item::fetch_course_item($courseid);
275 $needsupdate = $course_item->needsupdate;
277 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
278 foreach ($items as $item) {
279 if (empty($item->outcomeid)) {
280 continue;
282 if (!$outcome = grade_outcome::fetch(array('id'=>$item->outcomeid))) {
283 debugging('Incorect outcomeid found');
284 continue;
286 // prepare outcome info with user grade
287 $o = new object();
288 $o->scaleid = $outcome->scaleid;
289 $o->name = $outcome->get_name();
291 if (empty($userid)) {
292 //no user info
293 } if ($grade = $item->get_grade($userid,false)) {
294 $o->grade = $grade->finalgrade;
295 $o->locked = $grade->is_locked();
296 $o->hidden = $grade->is_hidden();
298 } else {
299 $o->grade = null;
300 $o->locked = $item->is_locked();
301 $o->hidden = $grade->is_hidden();
304 if ($needsupdate) {
305 $o->grade = false;
306 } else {
307 $o->grade = intval($o->grade); // 0 means no grade, int for scales
310 $result[$item->itemnumber] = $o;
314 return $result;
318 * Updates outcomes of user
319 * @param int $courseid id of course
320 * @param string $itemtype 'mod', 'block'
321 * @param string $itemmodule 'forum, 'quiz', etc.
322 * @param int $iteminstance id of the item module
323 * @param int $userid ID of the graded user
325 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
326 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
327 foreach ($items as $item) {
328 if (!array_key_exists($item->itemnumber, $data)) {
329 continue;
331 $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
332 $item->update_final_grade($userid, $grade, $source);
338 * Returns list of grades used in activity optionally with current grades of one user
339 * @param int $courseid id of course
340 * @param string $itemtype 'mod', 'block'
341 * @param string $itemmodule 'forum, 'quiz', etc.
342 * @param int $iteminstance id of the item module
343 * @param int $userid optional id of the graded user; if userid not used, returns only information about grade_item
344 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
346 function grade_get_final_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid=0) {
347 $result = array();
348 $course_item = grade_item::fetch_course_item($courseid);
349 $needsupdate = $course_item->needsupdate;
351 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
352 foreach ($items as $item) {
353 if (!empty($item->outcomeid)) {
354 continue;
356 // prepare grade info with user grade
357 $o = new object();
358 $o->scaleid = $item->scaleid;
359 $o->name = $item->get_name();
360 $o->grademin = $item->grademin;
361 $o->grademax = $item->grademax;
362 $o->gradepass = $item->gadepass;
364 if (empty($userid)) {
365 //no user info
367 } if ($grade = $item->get_grade($userid, false)) {
368 $o->grade = $grade->finalgrade;
369 $o->locked = $grade->is_locked();
370 $o->hidden = $grade->is_hidden();
371 $o->overridden = $grade->overridden;
373 if ($text = $grade->load_text()) {
374 $o->feedback = $text->feedback;
375 $o->feedbackformat = $text->feedbackformat;
376 } else {
377 $o->feedback = null;
378 $o->feedbackformat = FORMAT_MOODLE;
381 } else {
382 $o->grade = null;
383 $o->locked = $item->is_locked();
384 $o->hidden = $grade->is_hidden();
385 $o->overridden = 0;
386 $o->feedback = null;
387 $o->feedbackformat = FORMAT_MOODLE;
390 // create text representation of grade
391 if ($needsupdate) {
392 $o->grade = false;
393 $o->str_grade = get_string('error');
395 } else if (is_null($o->grade)) {
396 $o->str_grade = get_string('nograde');
398 } else {
399 switch ($item->gradetype) {
400 case GRADE_TYPE_VALUE:
401 $o->str_grade = $o->grade;
402 break;
404 case GRADE_TYPE_SCALE:
405 $scale = $item->load_scale();
406 $o->str_grade = format_string($scale[$o->grade-1]);
407 break;
409 case GRADE_TYPE_NONE:
410 case GRADE_TYPE_TEXT:
411 default:
412 $o->str_grade = '';
416 // create html representation of feedback
417 if (is_null($o->feedback)) {
418 $o->str_feedback = '';
419 } else {
420 $o->str_feedback = format_text($o->feedback, $o->feedbackformat);
423 $result[$item->itemnumber] = $o;
427 return $result;
430 /***** END OF PUBLIC API *****/
434 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
435 * @param string idnumber string (with magic quotes)
436 * @param object $cm used for course module idnumbers and items attached to modules
437 * @param object $gradeitem is item idnumber
438 * @return boolean true means idnumber ok
440 function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
441 if ($idnumber == '') {
442 //we allow empty idnumbers
443 return true;
446 // keep existing even when not unique
447 if ($cm and $cm->idnumber == $idnumber) {
448 return true;
449 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
450 return true;
453 if (get_records('course_modules', 'idnumber', $idnumber)) {
454 return false;
457 if (get_records('grade_items', 'idnumber', $idnumber)) {
458 return false;
461 return true;
465 * Force final grade recalculation in all course items
466 * @param int $courseid
468 function grade_force_full_regrading($courseid) {
469 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
473 * Updates all final grades in course.
475 * @param int $courseid
476 * @param int $userid if specified, try to do a quick regrading of grades of this user only
477 * @param object $updated_item the item in which
478 * @return boolean true if ok, array of errors if problems found (item id is used as key)
480 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
482 $course_item = grade_item::fetch_course_item($courseid);
484 if ($userid) {
485 // one raw grade updated for one user
486 if (empty($updated_item)) {
487 error("updated_item_id can not be null!");
489 if ($course_item->needsupdate) {
490 $updated_item->force_regrading();
491 return 'Can not do fast regrading after updating of raw grades';
494 } else {
495 if (!$course_item->needsupdate) {
496 // nothing to do :-)
497 return true;
501 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
502 $depends_on = array();
504 // first mark all category and calculated items as needing regrading
505 // this is slower, but 100% accurate
506 foreach ($grade_items as $gid=>$gitem) {
507 if (!empty($updated_item) and $updated_item->id == $gid) {
508 $grade_items[$gid]->needsupdate = 1;
510 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
511 $grade_items[$gid]->needsupdate = 1;
514 // construct depends_on lookup array
515 $depends_on[$gid] = $grade_items[$gid]->depends_on();
518 $errors = array();
519 $finalids = array();
520 $gids = array_keys($grade_items);
521 $failed = 0;
523 while (count($finalids) < count($gids)) { // work until all grades are final or error found
524 $count = 0;
525 foreach ($gids as $gid) {
526 if (in_array($gid, $finalids)) {
527 continue; // already final
530 if (!$grade_items[$gid]->needsupdate) {
531 $finalids[] = $gid; // we can make it final - does not need update
532 continue;
535 $doupdate = true;
536 foreach ($depends_on[$gid] as $did) {
537 if (!in_array($did, $finalids)) {
538 $doupdate = false;
539 continue; // this item depends on something that is not yet in finals array
543 //oki - let's update, calculate or aggregate :-)
544 if ($doupdate) {
545 $result = $grade_items[$gid]->regrade_final_grades($userid);
547 if ($result === true) {
548 $grade_items[$gid]->regrading_finished();
549 $grade_items[$gid]->check_locktime(); // do the locktime item locking
550 $count++;
551 $finalids[] = $gid;
553 } else {
554 $grade_items[$gid]->force_regrading();
555 $errors[$gid] = $result;
560 if ($count == 0) {
561 $failed++;
562 } else {
563 $failed = 0;
566 if ($failed > 1) {
567 foreach($gids as $gid) {
568 if (in_array($gid, $finalids)) {
569 continue; // this one is ok
571 $grade_items[$gid]->force_regrading();
572 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
574 break; // oki, found error
578 if (count($errors) == 0) {
579 if (empty($userid)) {
580 // do the locktime locking of grades, but only when doing full regrading
581 grade_grade::check_locktime_all($gids);
583 return true;
584 } else {
585 return $errors;
590 * For backwards compatibility with old third-party modules, this function can
591 * be used to import all grades from activities with legacy grading.
592 * @param int $courseid or null if all courses
594 function grade_grab_legacy_grades($courseid=null) {
596 global $CFG;
598 if (!$mods = get_list_of_plugins('mod') ) {
599 error('No modules installed!');
602 if ($courseid) {
603 $course_sql = " AND cm.course=$courseid";
604 } else {
605 $course_sql = "";
608 foreach ($mods as $mod) {
610 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
611 continue;
614 if (!$module = get_record('modules', 'name', $mod)) {
615 //not installed
616 continue;
619 if (!$module->visible) {
620 //disabled module
621 continue;
624 $fullmod = $CFG->dirroot.'/mod/'.$mod;
626 // include the module lib once
627 if (file_exists($fullmod.'/lib.php')) {
628 include_once($fullmod.'/lib.php');
629 // look for modname_grades() function - old gradebook pulling function
630 // if present sync the grades with new grading system
631 $gradefunc = $mod.'_grades';
632 if (function_exists($gradefunc)) {
634 // get all instance of the activity
635 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
636 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
637 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
639 if ($modinstances = get_records_sql($sql)) {
640 foreach ($modinstances as $modinstance) {
641 grade_update_mod_grades($modinstance);
650 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
652 function grade_grab_grades() {
654 global $CFG;
656 if (!$mods = get_list_of_plugins('mod') ) {
657 error('No modules installed!');
660 foreach ($mods as $mod) {
662 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
663 continue;
666 if (!$module = get_record('modules', 'name', $mod)) {
667 //not installed
668 continue;
671 if (!$module->visible) {
672 //disabled module
673 continue;
676 $fullmod = $CFG->dirroot.'/mod/'.$mod;
678 // include the module lib once
679 if (file_exists($fullmod.'/lib.php')) {
680 include_once($fullmod.'/lib.php');
681 // look for modname_grades() function - old gradebook pulling function
682 // if present sync the grades with new grading system
683 $gradefunc = $mod.'_update_grades';
684 if (function_exists($gradefunc)) {
685 $gradefunc();
692 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
693 * @param object $modinstance object with extra cmidnumber and modname property
694 * @return boolean success
696 function grade_update_mod_grades($modinstance, $userid=0) {
697 global $CFG;
699 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
700 if (!file_exists($fullmod.'/lib.php')) {
701 debugging('missing lib.php file in module');
702 return false;
704 include_once($fullmod.'/lib.php');
706 // does it use legacy grading?
707 $gradefunc = $modinstance->modname.'_grades';
708 $updategradesfunc = $modinstance->modname.'_update_grades';
709 $updateitemfunc = $modinstance->modname.'_grade_item_update';
711 if (function_exists($gradefunc)) {
713 // legacy module - not yet converted
714 if ($oldgrades = $gradefunc($modinstance->id)) {
716 $grademax = $oldgrades->maxgrade;
717 $scaleid = NULL;
718 if (!is_numeric($grademax)) {
719 // scale name is provided as a string, try to find it
720 if (!$scale = get_record('scale', 'name', $grademax)) {
721 debugging('Incorrect scale name! name:'.$grademax);
722 return false;
724 $scaleid = $scale->id;
727 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
728 debugging('Can not get/create legacy grade item!');
729 return false;
732 $grades = array();
733 foreach ($oldgrades->grades as $uid=>$usergrade) {
734 if ($userid and $uid != $userid) {
735 continue;
737 $grade = new object();
738 $grade->userid = $uid;
740 if ($usergrade == '-') {
741 // no grade
742 $grade->rawgrade = null;
744 } else if ($scaleid) {
745 // scale in use, words used
746 $gradescale = explode(",", $scale->scale);
747 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
749 } else {
750 // good old numeric value
751 $grade->rawgrade = $usergrade;
753 $grades[] = $grade;
756 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
757 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
760 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
761 //new grading supported, force updating of grades
762 $updateitemfunc($modinstance);
763 $updategradesfunc($modinstance, $userid);
765 } else {
766 // mudule does not support grading??
769 return true;
773 * Get and update/create grade item for legacy modules.
775 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
777 // does it already exist?
778 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
779 if (count($grade_items) > 1) {
780 debugging('Multiple legacy grade_items found.');
781 return false;
784 $grade_item = reset($grade_items);
786 if (is_null($grademax) and is_null($scaleid)) {
787 $grade_item->gradetype = GRADE_TYPE_NONE;
789 } else if ($scaleid) {
790 $grade_item->gradetype = GRADE_TYPE_SCALE;
791 $grade_item->scaleid = $scaleid;
792 $grade_item->grademin = 1;
794 } else {
795 $grade_item->gradetype = GRADE_TYPE_VALUE;
796 $grade_item->grademax = $grademax;
797 $grade_item->grademin = 0;
800 $grade_item->itemname = $modinstance->name;
801 $grade_item->idnumber = $modinstance->cmidnumber;
803 $grade_item->update();
805 return $grade_item;
808 // create new one
809 $params = array('courseid' =>$modinstance->course,
810 'itemtype' =>'mod',
811 'itemmodule' =>$modinstance->modname,
812 'iteminstance'=>$modinstance->id,
813 'itemnumber' =>0,
814 'itemname' =>$modinstance->name,
815 'idnumber' =>$modinstance->cmidnumber);
817 if (is_null($grademax) and is_null($scaleid)) {
818 $params['gradetype'] = GRADE_TYPE_NONE;
820 } else if ($scaleid) {
821 $params['gradetype'] = GRADE_TYPE_SCALE;
822 $params['scaleid'] = $scaleid;
823 $grade_item->grademin = 1;
824 } else {
825 $params['gradetype'] = GRADE_TYPE_VALUE;
826 $params['grademax'] = $grademax;
827 $params['grademin'] = 0;
830 $grade_item = new grade_item($params);
831 $grade_item->insert();
833 return $grade_item;
837 * Remove all grade related course data - history is kept
838 * @param int $courseid
839 * @param bool @showfeedback print feedback
841 function remove_course_grades($courseid, $showfeedback) {
842 $strdeleted = get_string('deleted');
844 $course_category = grade_category::fetch_course_category($courseid);
845 $course_category->delete('coursedelete');
846 if ($showfeedback) {
847 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
850 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
851 foreach ($outcomes as $outcome) {
852 $outcome->delete('coursedelete');
855 delete_records('grade_outcomes_courses', 'courseid', $courseid);
856 if ($showfeedback) {
857 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
860 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
861 foreach ($scales as $scale) {
862 $scale->delete('coursedelete');
865 if ($showfeedback) {
866 notify($strdeleted.' - '.get_string('scales'));
871 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
872 * @param int $steps The value between each level.
873 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
874 * @param int $lowest The lowest value to include
875 * @param int $highest The highest value to include
877 function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
878 // TODO reject or implement
882 * Grading cron job
884 function grade_cron() {
885 global $CFG;
887 $now = time();
889 $sql = "SELECT i.*
890 FROM {$CFG->prefix}grade_items i
891 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
892 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
894 // go through all courses that have proper final grades and lock them if needed
895 if ($rs = get_recordset_sql($sql)) {
896 if ($rs->RecordCount() > 0) {
897 while ($item = rs_fetch_next_record($rs)) {
898 $grade_item = new grade_item($item, false);
899 $grade_item->locked = $now;
900 $grade_item->update('locktime');
903 rs_close($rs);
906 $sql = "SELECT g.*
907 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
908 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
909 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
911 // go through all courses that have proper final grades and lock them if needed
912 if ($rs = get_recordset_sql($sql)) {
913 if ($rs->RecordCount() > 0) {
914 while ($grade = rs_fetch_next_record($rs)) {
915 $grade_grade = new grade_grade($grade, false);
916 $grade_grade->locked = $now;
917 $grade_grade->update('locktime');
920 rs_close($rs);