MDL-10604:
[moodle-linuxchix.git] / lib / gradelib.php
blob68599109f806664f8bf46bbe5a3fa570085fa8ac
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for gradebook
29 * @author Moodle HQ developers
30 * @version $Id$
31 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
32 * @package moodlecore
35 // category aggregation types
36 define('GRADE_AGGREGATE_MEAN_ALL', 0);
37 define('GRADE_AGGREGATE_MEAN_GRADED', 1);
38 define('GRADE_AGGREGATE_MEDIAN_ALL', 2);
39 define('GRADE_AGGREGATE_MEDIAN_GRADED', 3);
40 define('GRADE_AGGREGATE_MIN_ALL', 4);
41 define('GRADE_AGGREGATE_MIN_GRADED', 5);
42 define('GRADE_AGGREGATE_MAX_ALL', 6);
43 define('GRADE_AGGREGATE_MAX_GRADED', 7);
44 define('GRADE_AGGREGATE_MODE_ALL', 8);
45 define('GRADE_AGGREGATE_MODE_GRADED', 9);
46 define('GRADE_AGGREGATE_WEIGHTED_MEAN_ALL', 10);
47 define('GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED', 11);
48 define('GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL', 12);
49 define('GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED', 13);
51 // grade types
52 define('GRADE_TYPE_NONE', 0);
53 define('GRADE_TYPE_VALUE', 1);
54 define('GRADE_TYPE_SCALE', 2);
55 define('GRADE_TYPE_TEXT', 3);
57 // grade_update() return status
58 define('GRADE_UPDATE_OK', 0);
59 define('GRADE_UPDATE_FAILED', 1);
60 define('GRADE_UPDATE_MULTIPLE', 2);
61 define('GRADE_UPDATE_ITEM_DELETED', 3);
62 define('GRADE_UPDATE_ITEM_LOCKED', 4);
64 // Grate teables history tracking actions
65 define('GRADE_HISTORY_INSERT', 1);
66 define('GRADE_HISTORY_UPDATE', 2);
67 define('GRADE_HISTORY_DELETE', 3);
69 // Grader reports
70 define('GRADE_CATEGORY_CONTRACTED', 0); // The state of a category header in the grader report
71 define('GRADE_CATEGORY_EXPANDED', 1); // The state of a category header in the grader report
73 define('GRADE_REPORT_AGGREGATION_POSITION_LEFT', 0);
74 define('GRADE_REPORT_AGGREGATION_POSITION_RIGHT', 1);
75 define('GRADE_REPORT_AGGREGATION_VIEW_FULL', 0);
76 define('GRADE_REPORT_AGGREGATION_VIEW_COMPACT', 1);
77 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL', 0);
78 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE', 1);
79 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER', 2);
80 define('GRADE_REPORT_PREFERENCE_DEFAULT', 'default');
81 define('GRADE_REPORT_PREFERENCE_INHERIT', 'inherit');
82 define('GRADE_REPORT_PREFERENCE_UNUSED', -1);
84 require_once($CFG->libdir . '/grade/grade_category.php');
85 require_once($CFG->libdir . '/grade/grade_item.php');
86 require_once($CFG->libdir . '/grade/grade_grade.php');
87 require_once($CFG->libdir . '/grade/grade_scale.php');
88 require_once($CFG->libdir . '/grade/grade_outcome.php');
89 require_once($CFG->libdir . '/grade/grade_grade_text.php');
91 /***** PUBLIC GRADE API *****/
93 /**
94 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
95 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
96 * or key means do not change existing.
98 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
99 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted'.
101 * @param string $source source of the grade such as 'mod/assignment', often used to prevent infinite loops when processing grade_updated events
102 * @param int $courseid id of course
103 * @param string $itemtype type of grade item - mod, block, gradecategory, calculated
104 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
105 * @param int $iteminstance instance it of graded subject
106 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
107 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating rgade_item definition only\
108 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
110 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
111 global $USER;
113 // only following grade_item properties can be changed in this function
114 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted');
116 // grade item identification
117 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
119 if (is_null($courseid) or is_null($itemtype)) {
120 debugging('Missing courseid or itemtype');
121 return GRADE_UPDATE_FAILED;
124 if (!$grade_items = grade_item::fetch_all($params)) {
125 // create a new one
126 $grade_item = false;
128 } else if (count($grade_items) == 1){
129 $grade_item = reset($grade_items);
130 unset($grade_items); //release memory
132 } else {
133 debugging('Found more than one grade item');
134 return GRADE_UPDATE_MULTIPLE;
137 if (!empty($itemdetails['deleted'])) {
138 if ($grade_item) {
139 if ($grade_item->delete($source)) {
140 return GRADE_UPDATE_OK;
141 } else {
142 return GRADE_UPDATE_FAILED;
145 return GRADE_UPDATE_OK;
148 /// Create or update the grade_item if needed
149 if (!$grade_item) {
150 if ($itemdetails) {
151 $itemdetails = (array)$itemdetails;
153 // grademin and grademax ignored when scale specified
154 if (array_key_exists('scaleid', $itemdetails)) {
155 if ($itemdetails['scaleid']) {
156 unset($itemdetails['grademin']);
157 unset($itemdetails['grademax']);
161 foreach ($itemdetails as $k=>$v) {
162 if (!in_array($k, $allowed)) {
163 // ignore it
164 continue;
166 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
167 // no grade item needed!
168 return GRADE_UPDATE_OK;
170 $params[$k] = $v;
173 $grade_item = new grade_item($params);
174 $grade_item->insert();
176 } else {
177 if ($grade_item->is_locked()) {
178 debugging('Grading item is locked!');
179 return GRADE_UPDATE_ITEM_LOCKED;
182 if ($itemdetails) {
183 $itemdetails = (array)$itemdetails;
184 $update = false;
185 foreach ($itemdetails as $k=>$v) {
186 if (!in_array($k, $allowed)) {
187 // ignore it
188 continue;
190 if ($grade_item->{$k} != $v) {
191 $grade_item->{$k} = $v;
192 $update = true;
195 if ($update) {
196 $grade_item->update();
201 /// Some extra checks
202 // do we use grading?
203 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
204 return GRADE_UPDATE_OK;
207 // no grade submitted
208 if (empty($grades)) {
209 return GRADE_UPDATE_OK;
212 /// Finally start processing of grades
213 if (is_object($grades)) {
214 $grades = array($grades);
215 } else {
216 if (array_key_exists('userid', $grades)) {
217 $grades = array($grades);
221 $failed = false;
222 foreach ($grades as $grade) {
223 $grade = (array)$grade;
224 if (empty($grade['userid'])) {
225 $failed = true;
226 debugging('Invalid userid in grade submitted');
227 continue;
228 } else {
229 $userid = $grade['userid'];
232 $rawgrade = false;
233 $feedback = false;
234 $feedbackformat = FORMAT_MOODLE;
236 if (array_key_exists('rawgrade', $grade)) {
237 $rawgrade = $grade['rawgrade'];
240 if (array_key_exists('feedback', $grade)) {
241 $feedback = $grade['feedback'];
244 if (array_key_exists('feedbackformat', $grade)) {
245 $feedbackformat = $grade['feedbackformat'];
248 if (array_key_exists('usermodified', $grade)) {
249 $usermodified = $grade['usermodified'];
250 } else {
251 $usermodified = $USER->id;
254 // update or insert the grade
255 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
256 $failed = true;
260 if (!$failed) {
261 return GRADE_UPDATE_OK;
262 } else {
263 return GRADE_UPDATE_FAILED;
269 * Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
270 * This is a combination of the actual settings in the grade tables and a check on moodle/course:editgradeswhenlocked.
271 * If it's locked to the current use then the module can print a nice message or prevent editing in the module.
272 * If no $userid is given, the method will always return the grade_item's locked state.
273 * If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
274 * the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
275 * return the locked state of the specific grade.
277 * @param int $courseid id of course
278 * @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
279 * @param string $itemmodule 'forum, 'quiz', 'csv' etc
280 * @param int $iteminstance id of the item module
281 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
282 * @param int $userid ID of the graded user
283 * @return boolean Whether the grade is locked or not
285 function grade_is_locked($courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $userid=NULL) {
287 if (!$grade_items = grade_item::fetch_all(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber'))) {
288 return false;
290 } else if (count($grade_items) == 1){
291 $grade_item = reset($grade_items);
292 return $grade_item->is_locked($userid);
294 } else {
295 debugging('Found more than one grade item');
296 foreach ($grade_items as $grade_item) {
297 if ($grade_item->is_locked($userid)) {
298 return true;
301 return false;
305 /***** END OF PUBLIC API *****/
307 function grade_force_full_regrading($courseid) {
308 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
312 * Updates all final grades in course.
314 * @param int $courseid
315 * @param int $userid if specified, try to do a quick regrading of grades of this user only
316 * @param object $updated_item the item in which
317 * @return boolean true if ok, array of errors if problems found (item id is used as key)
319 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
321 $course_item = grade_item::fetch_course_item($courseid);
323 if ($userid) {
324 // one raw grade updated for one user
325 if (empty($updated_item)) {
326 error("updated_item_id can not be null!");
328 if ($course_item->needsupdate) {
329 $updated_item->force_regrading();
330 return 'Can not do fast regrading after updating of raw grades';
333 } else {
334 if (!$course_item->needsupdate) {
335 // nothing to do :-)
336 return true;
340 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
341 $depends_on = array();
343 // first mark all category and calculated items as needing regrading
344 // this is slower, but 100% accurate - this function is called only when there is
345 // a change in grading setup, update of individual grade does not trigger this function
346 foreach ($grade_items as $gid=>$gitem) {
347 if (!empty($updated_item) and $updated_item->id == $gid) {
348 $grade_items[$gid]->needsupdate = 1;
350 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
351 $grade_items[$gid]->needsupdate = 1;
354 // construct depends_on lookup array
355 $depends_on[$gid] = $grade_items[$gid]->depends_on();
358 $errors = array();
359 $finalids = array();
360 $gids = array_keys($grade_items);
361 $failed = 0;
363 while (count($finalids) < count($gids)) { // work until all grades are final or error found
364 $count = 0;
365 foreach ($gids as $gid) {
366 if (in_array($gid, $finalids)) {
367 continue; // already final
370 if (!$grade_items[$gid]->needsupdate) {
371 $finalids[] = $gid; // we can make it final - does not need update
372 continue;
375 $doupdate = true;
376 foreach ($depends_on[$gid] as $did) {
377 if (!in_array($did, $finalids)) {
378 $doupdate = false;
379 continue; // this item depends on something that is not yet in finals array
383 //oki - let's update, calculate or aggregate :-)
384 if ($doupdate) {
385 $result = $grade_items[$gid]->regrade_final_grades($userid);
387 if ($result === true) {
388 $grade_items[$gid]->regrading_finished();
389 $count++;
390 $finalids[] = $gid;
391 } else {
392 $grade_items[$gid]->force_regrading();
393 $errors[$gid] = $result;
398 if ($count == 0) {
399 $failed++;
400 } else {
401 $failed = 0;
404 if ($failed > 1) {
405 foreach($gids as $gid) {
406 if (in_array($gid, $finalids)) {
407 continue; // this one is ok
409 $grade_items[$gid]->force_regrading();
410 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
412 break; // oki, found error
416 if (count($errors) == 0) {
417 return true;
418 } else {
419 return $errors;
424 * For backwards compatibility with old third-party modules, this function can
425 * be used to import all grades from activities with legacy grading.
426 * @param int $courseid or null if all courses
428 function grade_grab_legacy_grades($courseid=null) {
430 global $CFG;
432 if (!$mods = get_list_of_plugins('mod') ) {
433 error('No modules installed!');
436 if ($courseid) {
437 $course_sql = " AND cm.course=$courseid";
438 } else {
439 $course_sql = "";
442 foreach ($mods as $mod) {
444 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
445 continue;
448 if (!$module = get_record('modules', 'name', $mod)) {
449 //not installed
450 continue;
453 if (!$module->visible) {
454 //disabled module
455 continue;
458 $fullmod = $CFG->dirroot.'/mod/'.$mod;
460 // include the module lib once
461 if (file_exists($fullmod.'/lib.php')) {
462 include_once($fullmod.'/lib.php');
463 // look for modname_grades() function - old gradebook pulling function
464 // if present sync the grades with new grading system
465 $gradefunc = $mod.'_grades';
466 if (function_exists($gradefunc)) {
468 // get all instance of the activity
469 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
470 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
471 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
473 if ($modinstances = get_records_sql($sql)) {
474 foreach ($modinstances as $modinstance) {
475 grade_update_mod_grades($modinstance);
484 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
486 function grade_grab_grades() {
488 global $CFG;
490 if (!$mods = get_list_of_plugins('mod') ) {
491 error('No modules installed!');
494 foreach ($mods as $mod) {
496 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
497 continue;
500 if (!$module = get_record('modules', 'name', $mod)) {
501 //not installed
502 continue;
505 if (!$module->visible) {
506 //disabled module
507 continue;
510 $fullmod = $CFG->dirroot.'/mod/'.$mod;
512 // include the module lib once
513 if (file_exists($fullmod.'/lib.php')) {
514 include_once($fullmod.'/lib.php');
515 // look for modname_grades() function - old gradebook pulling function
516 // if present sync the grades with new grading system
517 $gradefunc = $mod.'_update_grades';
518 if (function_exists($gradefunc)) {
519 $gradefunc();
526 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
527 * @param object $modinstance object with extra cmidnumber and modname property
528 * @return boolean success
530 function grade_update_mod_grades($modinstance) {
531 global $CFG;
533 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
534 if (!file_exists($fullmod.'/lib.php')) {
535 debugging('missing lib.php file in module');
536 return false;
538 include_once($fullmod.'/lib.php');
540 // does it use legacy grading?
541 $gradefunc = $modinstance->modname.'_grades';
542 $updategradesfunc = $modinstance->modname.'_update_grades';
543 $updateitemfunc = $modinstance->modname.'_grade_item_update';
545 if (function_exists($gradefunc)) {
546 if ($oldgrades = $gradefunc($modinstance->id)) {
548 $grademax = $oldgrades->maxgrade;
549 $scaleid = NULL;
550 if (!is_numeric($grademax)) {
551 // scale name is provided as a string, try to find it
552 if (!$scale = get_record('scale', 'name', $grademax)) {
553 debugging('Incorrect scale name! name:'.$grademax);
554 return false;
556 $scaleid = $scale->id;
559 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
560 debugging('Can not get/create legacy grade item!');
561 return false;
564 $grades = array();
565 foreach ($oldgrades->grades as $userid=>$usergrade) {
566 $grade = new object();
567 $grade->userid = $userid;
569 if ($usergrade == '-') {
570 // no grade
571 $grade->rawgrade = null;
573 } else if ($scaleid) {
574 // scale in use, words used
575 $gradescale = explode(",", $scale->scale);
576 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
578 } else {
579 // good old numeric value
580 $grade->rawgrade = $usergrade;
582 $grades[] = $grade;
585 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
586 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
589 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
590 //new grading supported, force updating of grades
591 $updateitemfunc($modinstance);
592 $updategradesfunc($modinstance);
594 } else {
595 // mudule does not support grading
598 return true;
602 * Get and update/create grade item for legacy modules.
604 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
606 // does it already exist?
607 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
608 if (count($grade_items) > 1) {
609 debugging('Multiple legacy grade_items found.');
610 return false;
613 $grade_item = reset($grade_items);
615 if (is_null($grademax) and is_null($scaleid)) {
616 $grade_item->gradetype = GRADE_TYPE_NONE;
618 } else if ($scaleid) {
619 $grade_item->gradetype = GRADE_TYPE_SCALE;
620 $grade_item->scaleid = $scaleid;
621 $grade_item->grademin = 1;
623 } else {
624 $grade_item->gradetype = GRADE_TYPE_VALUE;
625 $grade_item->grademax = $grademax;
626 $grade_item->grademin = 0;
629 $grade_item->itemname = $modinstance->name;
630 $grade_item->idnumber = $modinstance->cmidnumber;
632 $grade_item->update();
634 return $grade_item;
637 // create new one
638 $params = array('courseid' =>$modinstance->course,
639 'itemtype' =>'mod',
640 'itemmodule' =>$modinstance->modname,
641 'iteminstance'=>$modinstance->id,
642 'itemnumber' =>0,
643 'itemname' =>$modinstance->name,
644 'idnumber' =>$modinstance->cmidnumber);
646 if (is_null($grademax) and is_null($scaleid)) {
647 $params['gradetype'] = GRADE_TYPE_NONE;
649 } else if ($scaleid) {
650 $params['gradetype'] = GRADE_TYPE_SCALE;
651 $params['scaleid'] = $scaleid;
652 $grade_item->grademin = 1;
653 } else {
654 $params['gradetype'] = GRADE_TYPE_VALUE;
655 $params['grademax'] = $grademax;
656 $params['grademin'] = 0;
659 $grade_item = new grade_item($params);
660 $grade_item->insert();
662 return $grade_item;
667 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
668 * @param int $steps The value between each level.
669 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
670 * @param int $lowest The lowest value to include
671 * @param int $highest The highest value to include
673 function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
674 // TODO reject or implement