MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / lib / gradelib.php
blob096ee4f500d824a32421e6f5c9931f7cd5f41558
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');
42 /***** PUBLIC GRADE API - only these functions should be used in modules *****/
44 /**
45 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
46 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
47 * or key means do not change existing.
49 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
50 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted'.
52 * Manual, course or category items can not be updated by this function.
54 * @param string $source source of the grade such as 'mod/assignment'
55 * @param int $courseid id of course
56 * @param string $itemtype type of grade item - mod, block
57 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
58 * @param int $iteminstance instance it of graded subject
59 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
60 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
61 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
63 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
64 global $USER;
66 // only following grade_item properties can be changed in this function
67 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted');
69 // grade item identification
70 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
72 if (is_null($courseid) or is_null($itemtype)) {
73 debugging('Missing courseid or itemtype');
74 return GRADE_UPDATE_FAILED;
77 if (!$grade_items = grade_item::fetch_all($params)) {
78 // create a new one
79 $grade_item = false;
81 } else if (count($grade_items) == 1){
82 $grade_item = reset($grade_items);
83 unset($grade_items); //release memory
85 } else {
86 debugging('Found more than one grade item');
87 return GRADE_UPDATE_MULTIPLE;
90 if (!empty($itemdetails['deleted'])) {
91 if ($grade_item) {
92 if ($grade_item->delete($source)) {
93 return GRADE_UPDATE_OK;
94 } else {
95 return GRADE_UPDATE_FAILED;
98 return GRADE_UPDATE_OK;
101 /// Create or update the grade_item if needed
103 if (!$grade_item) {
104 if ($itemdetails) {
105 $itemdetails = (array)$itemdetails;
107 // grademin and grademax ignored when scale specified
108 if (array_key_exists('scaleid', $itemdetails)) {
109 if ($itemdetails['scaleid']) {
110 unset($itemdetails['grademin']);
111 unset($itemdetails['grademax']);
115 foreach ($itemdetails as $k=>$v) {
116 if (!in_array($k, $allowed)) {
117 // ignore it
118 continue;
120 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
121 // no grade item needed!
122 return GRADE_UPDATE_OK;
124 $params[$k] = $v;
127 $grade_item = new grade_item($params);
128 $grade_item->insert();
130 } else {
131 if ($grade_item->is_locked()) {
132 $message = get_string('gradeitemislocked', 'grades', $grade_item->itemname);
133 notice($message);
134 return GRADE_UPDATE_ITEM_LOCKED;
137 if ($itemdetails) {
138 $itemdetails = (array)$itemdetails;
139 $update = false;
140 foreach ($itemdetails as $k=>$v) {
141 if (!in_array($k, $allowed)) {
142 // ignore it
143 continue;
145 if ($grade_item->{$k} != $v) {
146 $grade_item->{$k} = $v;
147 $update = true;
150 if ($update) {
151 $grade_item->update();
156 /// Some extra checks
157 // do we use grading?
158 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
159 return GRADE_UPDATE_OK;
162 // no grade submitted
163 if (empty($grades)) {
164 return GRADE_UPDATE_OK;
167 /// Finally start processing of grades
168 if (is_object($grades)) {
169 $grades = array($grades);
170 } else {
171 if (array_key_exists('userid', $grades)) {
172 $grades = array($grades);
176 $failed = false;
177 foreach ($grades as $grade) {
178 $grade = (array)$grade;
179 if (empty($grade['userid'])) {
180 $failed = true;
181 debugging('Invalid userid in grade submitted');
182 continue;
183 } else {
184 $userid = $grade['userid'];
187 $rawgrade = false;
188 $feedback = false;
189 $feedbackformat = FORMAT_MOODLE;
191 if (array_key_exists('rawgrade', $grade)) {
192 $rawgrade = $grade['rawgrade'];
195 if (array_key_exists('feedback', $grade)) {
196 $feedback = $grade['feedback'];
199 if (array_key_exists('feedbackformat', $grade)) {
200 $feedbackformat = $grade['feedbackformat'];
203 if (array_key_exists('usermodified', $grade)) {
204 $usermodified = $grade['usermodified'];
205 } else {
206 $usermodified = $USER->id;
209 // update or insert the grade
210 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
211 $failed = true;
215 if (!$failed) {
216 return GRADE_UPDATE_OK;
217 } else {
218 return GRADE_UPDATE_FAILED;
223 * Updates outcomes of user
224 * Manual outcomes can not be updated.
225 * @param string $source source of the grade such as 'mod/assignment'
226 * @param int $courseid id of course
227 * @param string $itemtype 'mod', 'block'
228 * @param string $itemmodule 'forum, 'quiz', etc.
229 * @param int $iteminstance id of the item module
230 * @param int $userid ID of the graded user
231 * @param array $data array itemnumber=>outcomegrade
233 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
234 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
235 foreach ($items as $item) {
236 if (!array_key_exists($item->itemnumber, $data)) {
237 continue;
239 $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
240 $item->update_final_grade($userid, $grade, $source);
246 * Returns grading information for given activity - optionally with users grades
247 * Manual, course or category items can not be queried.
248 * @param int $courseid id of course
249 * @param string $itemtype 'mod', 'block'
250 * @param string $itemmodule 'forum, 'quiz', etc.
251 * @param int $iteminstance id of the item module
252 * @param int $userid optional id of the graded user; if userid not used, returns only information about grade_item
253 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
255 function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=0) {
256 global $CFG;
258 $return = new object();
259 $return->items = array();
260 $return->outcomes = array();
262 $course_item = grade_item::fetch_course_item($courseid);
263 $needsupdate = array();
264 if ($course_item->needsupdate) {
265 $result = grade_regrade_final_grades($courseid);
266 if ($result !== true) {
267 $needsupdate = array_keys($result);
271 if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
272 foreach ($grade_items as $grade_item) {
273 $decimalpoints = null;
275 if (empty($grade_item->outcomeid)) {
276 // prepare information about grade item
277 $item = new object();
278 $item->itemnumber = $grade_item->itemnumber;
279 $item->scaleid = $grade_item->scaleid;
280 $item->name = $grade_item->get_name();
281 $item->grademin = $grade_item->grademin;
282 $item->grademax = $grade_item->grademax;
283 $item->gradepass = $grade_item->gradepass;
284 $item->locked = $grade_item->is_locked();
285 $item->hidden = $grade_item->is_hidden();
286 $item->grades = array();
288 switch ($grade_item->gradetype) {
289 case GRADE_TYPE_NONE:
290 continue;
292 case GRADE_TYPE_VALUE:
293 $item->scaleid = 0;
294 break;
296 case GRADE_TYPE_TEXT:
297 $item->scaleid = 0;
298 $item->grademin = 0;
299 $item->grademax = 0;
300 $item->gradepass = 0;
301 break;
304 if (empty($userid_or_ids)) {
305 $userids = array();
307 } else if (is_array($userid_or_ids)) {
308 $userids = $userid_or_ids;
310 } else {
311 $userids = array($userid_or_ids);
314 if ($userids) {
315 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
316 foreach ($userids as $userid) {
317 $grade_grades[$userid]->grade_item =& $grade_item;
319 $grade = new object();
320 $grade->grade = $grade_grades[$userid]->finalgrade;
321 $grade->locked = $grade_grades[$userid]->is_locked();
322 $grade->hidden = $grade_grades[$userid]->is_hidden();
323 $grade->overridden = $grade_grades[$userid]->overridden;
324 $grade->feedback = $grade_grades[$userid]->feedback;
325 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
326 $grade->usermodified = $grade_grades[$userid]->usermodified;
328 // create text representation of grade
329 if (in_array($grade_item->id, $needsupdate)) {
330 $grade->grade = false;
331 $grade->str_grade = get_string('error');
333 } else if (is_null($grade->grade)) {
334 $grade->str_grade = '-';
336 } else {
337 $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
340 // create html representation of feedback
341 if (is_null($grade->feedback)) {
342 $grade->str_feedback = '';
343 } else {
344 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
347 $item->grades[$userid] = $grade;
350 $return->items[$grade_item->itemnumber] = $item;
352 } else {
353 if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
354 debugging('Incorect outcomeid found');
355 continue;
358 // outcome info
359 $outcome = new object();
360 $outcome->itemnumber = $grade_item->itemnumber;
361 $outcome->scaleid = $grade_outcome->scaleid;
362 $outcome->name = $grade_outcome->get_name();
363 $outcome->locked = $grade_item->is_locked();
364 $outcome->hidden = $grade_item->is_hidden();
366 if (empty($userid_or_ids)) {
367 $userids = array();
368 } else if (is_array($userid_or_ids)) {
369 $userids = $userid_or_ids;
370 } else {
371 $userids = array($userid_or_ids);
374 if ($userids) {
375 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
376 foreach ($userids as $userid) {
377 $grade_grades[$userid]->grade_item =& $grade_item;
379 $grade = new object();
380 $grade->grade = $grade_grades[$userid]->finalgrade;
381 $grade->locked = $grade_grades[$userid]->is_locked();
382 $grade->hidden = $grade_grades[$userid]->is_hidden();
383 $grade->feedback = $grade_grades[$userid]->feedback;
384 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
385 $grade->usermodified = $grade_grades[$userid]->usermodified;
387 // create text representation of grade
388 if (in_array($grade_item->id, $needsupdate)) {
389 $grade->grade = false;
390 $grade->str_grade = get_string('error');
392 } else if (is_null($grade->grade)) {
393 $grade->grade = 0;
394 $grade->str_grade = get_string('nooutcome', 'grades');
396 } else {
397 $grade->grade = (int)$grade->grade;
398 $scale = $grade_item->load_scale();
399 $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
402 // create html representation of feedback
403 if (is_null($grade->feedback)) {
404 $grade->str_feedback = '';
405 } else {
406 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
409 $outcome->grades[$userid] = $grade;
412 $return->outcomes[$grade_item->itemnumber] = $outcome;
418 // sort results using itemnumbers
419 ksort($return->items, SORT_NUMERIC);
420 ksort($return->outcomes, SORT_NUMERIC);
422 return $return;
425 /***** END OF PUBLIC API *****/
428 * Returns string representation of grade value
429 * @param float $value grade value
430 * @param object $grade_item - by reference to prevent scale reloading
431 * @param bool $localized use localised decimal separator
432 * @param int $display type of display - raw, letter, percentage
433 * @param int $decimalplaces number of decimal places when displaying float values
434 * @return string
436 function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
437 if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
438 return '';
441 // no grade yet?
442 if (is_null($value)) {
443 return '-';
446 if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
447 //unknown type??
448 return '';
451 if (is_null($displaytype)) {
452 $displaytype = $grade_item->get_displaytype();
455 if (is_null($decimals)) {
456 $decimals = $grade_item->get_decimals();
459 switch ($displaytype) {
460 case GRADE_DISPLAY_TYPE_REAL:
461 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
462 $scale = $grade_item->load_scale();
463 $value = (int)bounded_number($grade_item->grademin, $value, $grade_item->grademax);
464 return format_string($scale->scale_items[$value-1]);
466 } else {
467 return format_float($value, $decimals, $localized);
470 case GRADE_DISPLAY_TYPE_PERCENTAGE:
471 $min = $grade_item->grademin;
472 $max = $grade_item->grademax;
473 if ($min == $max) {
474 return '';
476 $value = bounded_number($min, $value, $max);
477 $percentage = (($value-$min)*100)/($max-$min);
478 return format_float($percentage, $decimals, $localized).' %';
480 case GRADE_DISPLAY_TYPE_LETTER:
481 $context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid);
482 if (!$letters = grade_get_letters($context)) {
483 return ''; // no letters??
486 $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
487 $value = bounded_number(0, $value, 100); // just in case
488 foreach ($letters as $boundary => $letter) {
489 if ($value >= $boundary) {
490 return format_string($letter);
493 return '-'; // no match? maybe '' would be more correct
495 default:
496 return '';
501 * Returns grade letters array used in context
502 * @param object $context object or null for defaults
503 * @return array of grade_boundary=>letter_string
505 function grade_get_letters($context=null) {
506 if (empty($context)) {
507 //default grading letters
508 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
511 static $cache = array();
513 if (array_key_exists($context->id, $cache)) {
514 return $cache[$context->id];
517 if (count($cache) > 100) {
518 $cache = array(); // cache size limit
521 $letters = array();
523 $contexts = get_parent_contexts($context);
524 array_unshift($contexts, $context->id);
526 foreach ($contexts as $ctxid) {
527 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
528 foreach ($records as $record) {
529 $letters[$record->lowerboundary] = $record->letter;
533 if (!empty($letters)) {
534 $cache[$context->id] = $letters;
535 return $letters;
539 $letters = grade_get_letters(null);
540 $cache[$context->id] = $letters;
541 return $letters;
546 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
547 * @param string idnumber string (with magic quotes)
548 * @param object $cm used for course module idnumbers and items attached to modules
549 * @param object $gradeitem is item idnumber
550 * @return boolean true means idnumber ok
552 function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
553 if ($idnumber == '') {
554 //we allow empty idnumbers
555 return true;
558 // keep existing even when not unique
559 if ($cm and $cm->idnumber == $idnumber) {
560 return true;
561 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
562 return true;
565 if (get_records('course_modules', 'idnumber', $idnumber)) {
566 return false;
569 if (get_records('grade_items', 'idnumber', $idnumber)) {
570 return false;
573 return true;
577 * Force final grade recalculation in all course items
578 * @param int $courseid
580 function grade_force_full_regrading($courseid) {
581 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
585 * Updates all final grades in course.
587 * @param int $courseid
588 * @param int $userid if specified, try to do a quick regrading of grades of this user only
589 * @param object $updated_item the item in which
590 * @return boolean true if ok, array of errors if problems found (item id is used as key)
592 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
594 $course_item = grade_item::fetch_course_item($courseid);
596 if ($userid) {
597 // one raw grade updated for one user
598 if (empty($updated_item)) {
599 error("updated_item_id can not be null!");
601 if ($course_item->needsupdate) {
602 $updated_item->force_regrading();
603 return 'Can not do fast regrading after updating of raw grades';
606 } else {
607 if (!$course_item->needsupdate) {
608 // nothing to do :-)
609 return true;
613 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
614 $depends_on = array();
616 // first mark all category and calculated items as needing regrading
617 // this is slower, but 100% accurate
618 foreach ($grade_items as $gid=>$gitem) {
619 if (!empty($updated_item) and $updated_item->id == $gid) {
620 $grade_items[$gid]->needsupdate = 1;
622 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
623 $grade_items[$gid]->needsupdate = 1;
626 // construct depends_on lookup array
627 $depends_on[$gid] = $grade_items[$gid]->depends_on();
630 $errors = array();
631 $finalids = array();
632 $gids = array_keys($grade_items);
633 $failed = 0;
635 while (count($finalids) < count($gids)) { // work until all grades are final or error found
636 $count = 0;
637 foreach ($gids as $gid) {
638 if (in_array($gid, $finalids)) {
639 continue; // already final
642 if (!$grade_items[$gid]->needsupdate) {
643 $finalids[] = $gid; // we can make it final - does not need update
644 continue;
647 $doupdate = true;
648 foreach ($depends_on[$gid] as $did) {
649 if (!in_array($did, $finalids)) {
650 $doupdate = false;
651 continue; // this item depends on something that is not yet in finals array
655 //oki - let's update, calculate or aggregate :-)
656 if ($doupdate) {
657 $result = $grade_items[$gid]->regrade_final_grades($userid);
659 if ($result === true) {
660 $grade_items[$gid]->regrading_finished();
661 $grade_items[$gid]->check_locktime(); // do the locktime item locking
662 $count++;
663 $finalids[] = $gid;
665 } else {
666 $grade_items[$gid]->force_regrading();
667 $errors[$gid] = $result;
672 if ($count == 0) {
673 $failed++;
674 } else {
675 $failed = 0;
678 if ($failed > 1) {
679 foreach($gids as $gid) {
680 if (in_array($gid, $finalids)) {
681 continue; // this one is ok
683 $grade_items[$gid]->force_regrading();
684 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
686 break; // oki, found error
690 if (count($errors) == 0) {
691 if (empty($userid)) {
692 // do the locktime locking of grades, but only when doing full regrading
693 grade_grade::check_locktime_all($gids);
695 return true;
696 } else {
697 return $errors;
702 * For backwards compatibility with old third-party modules, this function can
703 * be used to import all grades from activities with legacy grading.
704 * @param int $courseid or null if all courses
706 function grade_grab_legacy_grades($courseid=null) {
708 global $CFG;
710 if (!$mods = get_list_of_plugins('mod') ) {
711 error('No modules installed!');
714 if ($courseid) {
715 $course_sql = " AND cm.course=$courseid";
716 } else {
717 $course_sql = "";
720 foreach ($mods as $mod) {
722 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
723 continue;
726 if (!$module = get_record('modules', 'name', $mod)) {
727 //not installed
728 continue;
731 if (!$module->visible) {
732 //disabled module
733 continue;
736 $fullmod = $CFG->dirroot.'/mod/'.$mod;
738 // include the module lib once
739 if (file_exists($fullmod.'/lib.php')) {
740 include_once($fullmod.'/lib.php');
741 // look for modname_grades() function - old gradebook pulling function
742 // if present sync the grades with new grading system
743 $gradefunc = $mod.'_grades';
744 if (function_exists($gradefunc)) {
746 // get all instance of the activity
747 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
748 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
749 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
751 if ($modinstances = get_records_sql($sql)) {
752 foreach ($modinstances as $modinstance) {
753 grade_update_mod_grades($modinstance);
762 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
764 function grade_grab_grades() {
766 global $CFG;
768 if (!$mods = get_list_of_plugins('mod') ) {
769 error('No modules installed!');
772 foreach ($mods as $mod) {
774 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
775 continue;
778 if (!$module = get_record('modules', 'name', $mod)) {
779 //not installed
780 continue;
783 if (!$module->visible) {
784 //disabled module
785 continue;
788 $fullmod = $CFG->dirroot.'/mod/'.$mod;
790 // include the module lib once
791 if (file_exists($fullmod.'/lib.php')) {
792 include_once($fullmod.'/lib.php');
793 // look for modname_grades() function - old gradebook pulling function
794 // if present sync the grades with new grading system
795 $gradefunc = $mod.'_update_grades';
796 if (function_exists($gradefunc)) {
797 $gradefunc();
804 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
805 * @param object $modinstance object with extra cmidnumber and modname property
806 * @return boolean success
808 function grade_update_mod_grades($modinstance, $userid=0) {
809 global $CFG;
811 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
812 if (!file_exists($fullmod.'/lib.php')) {
813 debugging('missing lib.php file in module');
814 return false;
816 include_once($fullmod.'/lib.php');
818 // does it use legacy grading?
819 $gradefunc = $modinstance->modname.'_grades';
820 $updategradesfunc = $modinstance->modname.'_update_grades';
821 $updateitemfunc = $modinstance->modname.'_grade_item_update';
823 if (function_exists($gradefunc)) {
825 // legacy module - not yet converted
826 if ($oldgrades = $gradefunc($modinstance->id)) {
828 $grademax = $oldgrades->maxgrade;
829 $scaleid = NULL;
830 if (!is_numeric($grademax)) {
831 // scale name is provided as a string, try to find it
832 if (!$scale = get_record('scale', 'name', $grademax)) {
833 debugging('Incorrect scale name! name:'.$grademax);
834 return false;
836 $scaleid = $scale->id;
839 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
840 debugging('Can not get/create legacy grade item!');
841 return false;
844 $grades = array();
845 foreach ($oldgrades->grades as $uid=>$usergrade) {
846 if ($userid and $uid != $userid) {
847 continue;
849 $grade = new object();
850 $grade->userid = $uid;
852 if ($usergrade == '-') {
853 // no grade
854 $grade->rawgrade = null;
856 } else if ($scaleid) {
857 // scale in use, words used
858 $gradescale = explode(",", $scale->scale);
859 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
861 } else {
862 // good old numeric value
863 $grade->rawgrade = $usergrade;
865 $grades[] = $grade;
868 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
869 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
872 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
873 //new grading supported, force updating of grades
874 $updateitemfunc($modinstance);
875 $updategradesfunc($modinstance, $userid);
877 } else {
878 // mudule does not support grading??
881 return true;
885 * Get and update/create grade item for legacy modules.
887 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
889 // does it already exist?
890 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
891 if (count($grade_items) > 1) {
892 debugging('Multiple legacy grade_items found.');
893 return false;
896 $grade_item = reset($grade_items);
898 if (is_null($grademax) and is_null($scaleid)) {
899 $grade_item->gradetype = GRADE_TYPE_NONE;
901 } else if ($scaleid) {
902 $grade_item->gradetype = GRADE_TYPE_SCALE;
903 $grade_item->scaleid = $scaleid;
904 $grade_item->grademin = 1;
906 } else {
907 $grade_item->gradetype = GRADE_TYPE_VALUE;
908 $grade_item->grademax = $grademax;
909 $grade_item->grademin = 0;
912 $grade_item->itemname = $modinstance->name;
913 $grade_item->idnumber = $modinstance->cmidnumber;
915 $grade_item->update();
917 return $grade_item;
920 // create new one
921 $params = array('courseid' =>$modinstance->course,
922 'itemtype' =>'mod',
923 'itemmodule' =>$modinstance->modname,
924 'iteminstance'=>$modinstance->id,
925 'itemnumber' =>0,
926 'itemname' =>$modinstance->name,
927 'idnumber' =>$modinstance->cmidnumber);
929 if (is_null($grademax) and is_null($scaleid)) {
930 $params['gradetype'] = GRADE_TYPE_NONE;
932 } else if ($scaleid) {
933 $params['gradetype'] = GRADE_TYPE_SCALE;
934 $params['scaleid'] = $scaleid;
935 $grade_item->grademin = 1;
936 } else {
937 $params['gradetype'] = GRADE_TYPE_VALUE;
938 $params['grademax'] = $grademax;
939 $params['grademin'] = 0;
942 $grade_item = new grade_item($params);
943 $grade_item->insert();
945 return $grade_item;
949 * Remove all grade related course data - history is kept
950 * @param int $courseid
951 * @param bool @showfeedback print feedback
953 function remove_course_grades($courseid, $showfeedback) {
954 $strdeleted = get_string('deleted');
956 $course_category = grade_category::fetch_course_category($courseid);
957 $course_category->delete('coursedelete');
958 if ($showfeedback) {
959 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
962 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
963 foreach ($outcomes as $outcome) {
964 $outcome->delete('coursedelete');
967 delete_records('grade_outcomes_courses', 'courseid', $courseid);
968 if ($showfeedback) {
969 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
972 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
973 foreach ($scales as $scale) {
974 $scale->delete('coursedelete');
977 if ($showfeedback) {
978 notify($strdeleted.' - '.get_string('scales'));
983 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
984 * @param int $steps The value between each level.
985 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
986 * @param int $lowest The lowest value to include
987 * @param int $highest The highest value to include
989 function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
990 // TODO reject or implement
994 * Grading cron job
996 function grade_cron() {
997 global $CFG;
999 $now = time();
1001 $sql = "SELECT i.*
1002 FROM {$CFG->prefix}grade_items i
1003 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1004 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1006 // go through all courses that have proper final grades and lock them if needed
1007 if ($rs = get_recordset_sql($sql)) {
1008 if ($rs->RecordCount() > 0) {
1009 while ($item = rs_fetch_next_record($rs)) {
1010 $grade_item = new grade_item($item, false);
1011 $grade_item->locked = $now;
1012 $grade_item->update('locktime');
1015 rs_close($rs);
1018 $grade_inst = new grade_grade();
1019 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
1021 $sql = "SELECT $fields
1022 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
1023 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1024 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1026 // go through all courses that have proper final grades and lock them if needed
1027 if ($rs = get_recordset_sql($sql)) {
1028 if ($rs->RecordCount() > 0) {
1029 while ($grade = rs_fetch_next_record($rs)) {
1030 $grade_grade = new grade_grade($grade, false);
1031 $grade_grade->locked = $now;
1032 $grade_grade->update('locktime');
1035 rs_close($rs);