fixed unit grade tests - missing grade types
[moodle.git] / lib / gradelib.php
CommitLineData
5834dcdb 1<?php // $Id$
2
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///////////////////////////////////////////////////////////////////////////
25
26/**
42bbccd7 27 * Library of functions for gradebook
5834dcdb 28 *
29 * @author Moodle HQ developers
30 * @version $Id$
31 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
32 * @package moodlecore
33 */
34
42bbccd7 35define('GRADE_AGGREGATE_MEAN', 0);
36define('GRADE_AGGREGATE_MEDIAN', 1);
37define('GRADE_AGGREGATE_SUM', 2);
38define('GRADE_AGGREGATE_MODE', 3);
612607bd 39
27f95e9b 40define('GRADE_CHILDTYPE_ITEM', 0);
41define('GRADE_CHILDTYPE_CAT', 1);
612607bd 42
27f95e9b 43define('GRADE_ITEM', 0); // Used to compare class names with CHILDTYPE values
44define('GRADE_CATEGORY', 1); // Used to compare class names with CHILDTYPE values
612607bd 45
210611f6 46define('GRADE_TYPE_NONE', 0);
47define('GRADE_TYPE_VALUE', 1);
48define('GRADE_TYPE_SCALE', 2);
49define('GRADE_TYPE_TEXT', 3);
42bbccd7 50
612607bd 51define('GRADE_UPDATE_OK', 0);
52define('GRADE_UPDATE_FAILED', 1);
53define('GRADE_UPDATE_MULTIPLE', 2);
54define('GRADE_UPDATE_ITEM_DELETED', 3);
55define('GRADE_UPDATE_INVALID_GRADE', 4);
56define('GRADE_UPDATE_LOCKED', 5);
57
58
3058964f 59require_once($CFG->libdir . '/grade/grade_category.php');
60require_once($CFG->libdir . '/grade/grade_item.php');
61require_once($CFG->libdir . '/grade/grade_calculation.php');
a8995b34 62require_once($CFG->libdir . '/grade/grade_grades_raw.php');
869807d8 63require_once($CFG->libdir . '/grade/grade_grades_final.php');
d5bdb228 64require_once($CFG->libdir . '/grade/grade_scale.php');
5501446d 65require_once($CFG->libdir . '/grade/grade_outcome.php');
46566dd8 66require_once($CFG->libdir . '/grade/grade_history.php');
67require_once($CFG->libdir . '/grade/grade_grades_text.php');
8ff4550a 68require_once($CFG->libdir . '/grade/grade_tree.php');
60cf7430 69
612607bd 70/***** PUBLIC GRADE API *****/
71
72function grade_update($courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grade=NULL, $itemdetails=NULL) {
73
74 // only following grade_item properties can be changed/used in this function
75 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'deleted');
76
77 if (is_null($courseid) or is_null($itemtype)) {
78 debugging('Missing courseid or itemtype');
79 return GRADE_UPDATE_FAILED;
80 }
81
82 $grade_item = new grade_item(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber'), false);
83 if (!$grade_items = $grade_item->fetch_all_using_this()) {
84 // create a new one
85 $grade_item = false;
86
87 } else if (count($grade_items) == 1){
88 $grade_item = reset($grade_items);
89 unset($grade_items); //release memory
90
91 } else {
92
93 debugging('Found more than one grading item');
94 return GRADE_UPDATE_MULTIPLE;
95 }
96
97/// Create or update the grade_item if needed
98 if (!$grade_item) {
99 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
100 if ($itemdetails) {
101 $itemdetails = (array)$itemdetails;
102 foreach ($itemdetails as $k=>$v) {
103 if (!in_array($k, $allowed)) {
104 // ignore it
105 continue;
106 }
107 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
108 // no grade item needed!
109 return GRADE_UPDATE_OK;
110 }
111 $params[$k] = $v;
112 }
113 }
114 $itemid = grade_create_item($params);
115 $grade_item = grade_item::fetch('id', $itemid);
116
117 } else {
118 if ($grade_item->locked) {
119 debugging('Grading item is locked!');
120 return GRADE_UPDATE_LOCKED;
121 }
122
123 if ($itemdetails) {
124 $itemdetails = (array)$itemdetails;
125 $update = false;
126 foreach ($itemdetails as $k=>$v) {
127 if (!in_array($k, $allowed)) {
128 // ignore it
129 continue;
130 }
131 if ($grade_item->{$k} != $v) {
132 $grade_item->{$k} = $v;
133 $update = true;
134 }
135 }
136 if ($update) {
137 $grade_item->update();
138 }
139 }
140 }
141
142/// Some extra checks
143 // do we use grading?
144 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
145 return GRADE_UPDATE_OK;
146 }
147
148 // no grade submitted
149 if (empty($grade)) {
150 return GRADE_UPDATE_OK;
151 }
152
153 // no grading in deleted items
154 if ($grade_item->deleted) {
155 debugging('Grade item was already deleted!');
156 return GRADE_UPDATE_ITEM_DELETED;
157 }
158
159/// Finally start processing of grades
160 if (is_object($grade)) {
161 $grades = array($grade);
162 } else {
163 if (array_key_exists('userid', $grade)) {
164 $grades = array($grade);
165 } else {
166 $grades = $grade;
167 }
168 }
169
170 unset($grade);
171
172 foreach ($grades as $grade) {
173 $grade = (array)$grade;
174 if (empty($grade['userid'])) {
175 debugging('Invalid grade submitted');
176 return GRADE_UPDATE_INVALID_GRADE;
177 }
178
179 // get the raw grade if it exist
180 $rawgrade = new grade_grades_raw(array('itemid'=>$grade_item->id, 'userid'=>$grade['userid']));
181 $rawgrade->grade_item = &$grade_item; // we already have it, so let's use it
182
183 // store these to keep track of original grade item settings
184 $rawgrade->grademax = $grade_item->grademax;
185 $rawgrade->grademin = $grade_item->grademin;
186 $rawgrade->scaleid = $grade_item->scaleid;
187
188 if (isset($grade['feedback'])) {
189 $rawgrade->feedback = $grade['feedback'];
190 if (isset($grade['feedbackformat'])) {
191 $rawgrade->feedbackformat = $grade['feedbackformat'];
192 } else {
193 $rawgrade->feedbackformat = FORMAT_PLAIN;
194 }
195 }
196
197 if (!isset($grade['gradevalue'])) {
198 $grade['gradevalue'] = null; // means no grade yet
199 }
200
201 if ($rawgrade->id) {
202 $rawgrade->update($grade['gradevalue'], 'event');
203 } else {
204 $rawgrade->gradevalue = $grade['gradevalue'];
205 $rawgrade->insert();
206 }
207
208 //trigger grade_updated event notification
209 $eventdata = new object();
210 $eventdata->itemid = $grade_item->id;
211 $eventdata->grade = $grade;
212 events_trigger('grade_updated', $eventdata);
213 }
214
215 return GRADE_UPDATE_OK;
216}
217
218/***** END OF PUBLIC API *****/
219
5834dcdb 220/**
612607bd 221* Extracts from the gradebook all the grade items attached to the calling object.
222* For example, an assignment may want to retrieve all the grade_items for itself,
5834dcdb 223* and get three outcome scales in return. This will affect the grading interface.
224*
225* Note: Each parameter refines the search. So if you only give the courseid,
226* all the grade_items for this course will be returned. If you add the
227* itemtype 'mod', all grade_items for this courseif AND for the 'mod'
228* type will be returned, etc...
612607bd 229*
42bbccd7 230* @param int $courseid The id of the course to which the grade items belong
5834dcdb 231* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
232* @param string $itemmodule 'forum, 'quiz', 'csv' etc
233* @param int $iteminstance id of the item module
de420c11 234* @param string $itemname The name of the grade item
5834dcdb 235* @param int $itemnumber Can be used to distinguish multiple grades for an activity
42bbccd7 236* @param int $idnumber grade item Primary Key
237* @return array An array of grade items
5834dcdb 238*/
de420c11 239function grade_get_items($courseid, $itemtype=NULL, $itemmodule=NULL, $iteminstance=NULL, $itemname=NULL, $itemnumber=NULL, $idnumber=NULL) {
240 $grade_item = new grade_item(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemname', 'itemnumber', 'idnumber'), false);
3058964f 241 $grade_items = $grade_item->fetch_all_using_this();
42bbccd7 242 return $grade_items;
5834dcdb 243}
244
245
246/**
de420c11 247* Creates a new grade_item in case it doesn't exist.
248* This function is called when a new module is created.
249*
250* @param mixed $params array or object
5834dcdb 251* @return mixed New grade_item id if successful
252*/
3058964f 253function grade_create_item($params) {
42bbccd7 254 $grade_item = new grade_item($params);
612607bd 255
d9907766 256 if (empty($grade_item->id)) {
257 return $grade_item->insert();
258 } else {
de420c11 259 debugging('Grade item already exists - id:'.$grade_item->id);
d9907766 260 return $grade_item->id;
261 }
5834dcdb 262}
263
264/**
265* For a given set of items, create a category to group them together (if one doesn't yet exist).
266* Modules may want to do this when they are created. However, the ultimate control is in the gradebook interface itself.
619a59a7 267*
268* @param int $courseid
42bbccd7 269* @param string $fullname The name of the new category
270* @param array $items An array of grade_items to group under the new category
5834dcdb 271* @param string $aggregation
272* @return mixed New grade_category id if successful
273*/
3058964f 274function grade_create_category($courseid, $fullname, $items, $aggregation=GRADE_AGGREGATE_MEAN) {
275 $grade_category = new grade_category(compact('courseid', 'fullname', 'items', 'aggregation'));
612607bd 276
d9907766 277 if (empty($grade_category->id)) {
278 return $grade_category->insert();
279 } else {
280 return $grade_category->id;
281 }
5834dcdb 282}
283
284
285/**
286* Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
287* This is a combination of the actual settings in the grade tables and a check on moodle/course:editgradeswhenlocked.
288* If it's locked to the current use then the module can print a nice message or prevent editing in the module.
3058964f 289* If no $userid is given, the method will always return the grade_item's locked state.
290* If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
612607bd 291* the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
3058964f 292* return the locked state of the specific grade.
293*
5834dcdb 294* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
295* @param string $itemmodule 'forum, 'quiz', 'csv' etc
296* @param int $iteminstance id of the item module
3058964f 297* @param int $itemnumber Optional number of the item to check
5834dcdb 298* @param int $userid ID of the user who owns the grade
299* @return boolean Whether the grade is locked or not
300*/
3058964f 301function grade_is_locked($itemtype, $itemmodule, $iteminstance, $itemnumber=NULL, $userid=NULL) {
302 $grade_item = new grade_item(compact('itemtype', 'itemmodule', 'iteminstance', 'itemnumber'));
303 return $grade_item->is_locked($userid);
612607bd 304}
5834dcdb 305
a8995b34 306/**
307 * Updates all grade_grades_final for each grade_item matching the given attributes.
308 * The search is further restricted, so that only grade_items that have needs_update == TRUE
309 * or that use calculation are retrieved.
310 *
311 * @param int $courseid
312 * @param int $gradeitemid
313 * @return int Number of grade_items updated
314 */
315function grade_update_final_grades($courseid=NULL, $gradeitemid=NULL) {
316 $grade_item = new grade_item();
317 $grade_item->courseid = $courseid;
318 $grade_item->id = $gradeitemid;
319 $grade_items = $grade_item->fetch_all_using_this();
612607bd 320
a8995b34 321 $count = 0;
322
323 foreach ($grade_items as $gi) {
324 $calculation = $gi->get_calculation();
325 if (!empty($calculation) || $gi->needsupdate) {
326 if ($gi->update_final_grade()) {
327 $count++;
328 }
329 }
330 }
331
332 return $count;
333}
967f222f 334
de420c11 335/**
967f222f 336 * For backward compatibility with old third-party modules, this function is called
337 * via to admin/cron.php to search all mod/xxx/lib.php files for functions named xxx_grades(),
338 * if the current modules does not have grade events registered with the grade book.
612607bd 339 * Once the data is extracted, the events_trigger() function can be called to initiate
340 * an event as usual and copy/ *upgrade the data in the gradebook tables.
967f222f 341 */
de420c11 342function grade_grab_legacy_grades() {
612607bd 343
967f222f 344 global $CFG, $db;
345
346 if (!$mods = get_list_of_plugins('mod') ) {
347 error('No modules installed!');
348 }
349
350 foreach ($mods as $mod) {
351
352 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
353 continue;
354 }
355
356 $fullmod = $CFG->dirroot .'/mod/'. $mod;
357
358 // include the module lib once
359 if (file_exists($fullmod.'/lib.php')) {
360 include_once($fullmod.'/lib.php');
de420c11 361 // look for modname_grades() function - old gradebook pulling function
362 // if present sync the grades with new grading system
967f222f 363 $gradefunc = $mod.'_grades';
de420c11 364 if (function_exists($gradefunc)) {
365
366 // get all instance of the activity
367 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid, m.name as modname FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
368 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id";
369
370 if ($modinstances = get_records_sql($sql)) {
967f222f 371 foreach ($modinstances as $modinstance) {
372 // for each instance, call the xxx_grades() function
de420c11 373 if ($grades = $gradefunc($modinstance->id)) {
374
375 $grademax = $grades->maxgrade;
376 $scaleid = 0;
612607bd 377 if (!is_numeric($grademax)) {
5283e959 378 // scale name is provided as a string, try to find it
de420c11 379 if (!$scale = get_record('scale', 'name', $grademax)) {
380 debugging('Incorrect scale name! name:'.$grademax);
381 continue;
382 }
5283e959 383 $scaleid = $scale->id;
de420c11 384 }
385
386 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
387 debugging('Can not get/create legacy grade item!');
388 continue;
9d5c91b1 389 }
390
612607bd 391 foreach ($grades->grades as $userid=>$usergrade) {
967f222f 392 // make the grade_added eventdata
d46306de 393 $eventdata = new object();
de420c11 394 $eventdata->itemid = $grade_item->id;
9492291c 395 $eventdata->userid = $userid;
de420c11 396
397 if ($usergrade == '-') {
398 // no grade
399 $eventdata->gradevalue = null;
400
401 } else if ($scaleid) {
5283e959 402 // scale in use, words used
403 $gradescale = explode(",", $scale->scale);
404 $eventdata->gradevalue = array_search($usergrade, $gradescale) + 1;
de420c11 405
5283e959 406 } else {
407 // good old numeric value
408 $eventdata->gradevalue = $usergrade;
409 }
410
de420c11 411 events_trigger('grade_updated', $eventdata);
967f222f 412 }
413 }
414 }
415 }
416 }
417 }
418 }
419}
420
de420c11 421
422/**
423 * Get (create if needed) grade item for legacy modules.
424 */
425function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
426
427 // does it already exist?
428 if ($grade_items = grade_get_items($modinstances->courseid, 'mod', $modinstance->modname, $modinstances->id)) {
429 if (count($grade_items) > 1) {
430 return false;
431 }
432
433 $grade_item = reset($grade_items);
434 $updated = false;
435
436 if ($scaleid) {
437 if ($grade_item->scaleid != $scaleid) {
438 $grade_item->gradetype = GRADE_TYPE_SCALE;
439 $grade_item->scaleid = $scaleid;
440 $updated = true;;
441 }
442
443 } else if ($grade_item->scaleid != $scaleid or $grade_item->grademax != $grademax) {
444 $grade_item->gradetype = GRADE_TYPE_VALUE;
445 $grade_item->scaleid = 0;
446 $grade_item->grademax = $grademax;
447 $grade_item->grademin = 0;
448 $updated = true;;
449 }
450
451 if ($grade_item->itemname != $modinstance->name) {
452 $grade_item->itemname = $modinstance->name;
453 $updated = true;;
454 }
455
456 if ($grade_item->idnumber != $modinstance->cmidnumber) {
457 $grade_item->idnumber = $modinstance->cmidnumber;
458 $updated = true;;
459 }
460
461 if ($updated) {
462 $grade_item->update();
463 }
464
465 return $grade_item;
466 }
612607bd 467
de420c11 468 // create new one
469 $params = array('courseid' =>$modinstance->courseid,
470 'itemtype' =>'mod',
471 'itemmodule' =>$modinstance->modname,
472 'iteminstance'=>$modinstance->id,
473 'itemname' =>$modinstance->name,
474 'idnumber' =>$modinstance->cmidnumber);
475
476 if ($scaleid) {
612607bd 477 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 478 $params['scaleid'] = $scaleid;
479
480 } else {
612607bd 481 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 482 $params['grademax'] = $grademax;
483 $params['grademin'] = 0;
484 }
485
486 if (!$itemid = grade_create_item($params)) {
487 return false;
488 }
489
490 return grade_item::fetch('id', $itemid);
491}
492
2c72af1f 493/**
494 * Given a float value situated between a source minimum and a source maximum, converts it to the
495 * corresponding value situated between a target minimum and a target maximum. Thanks to Darlene
496 * for the formula :-)
497 * @param float $gradevalue
498 * @param float $source_min
499 * @param float $source_max
500 * @param float $target_min
501 * @param float $target_max
502 * @return float Converted value
503 */
2df71235 504function standardise_score($gradevalue, $source_min, $source_max, $target_min, $target_max, $debug=false) {
096858ff 505 $factor = ($gradevalue - $source_min) / ($source_max - $source_min);
506 $diff = $target_max - $target_min;
507 $standardised_value = $factor * $diff + $target_min;
2df71235 508 if ($debug) {
509 echo 'standardise_score debug info: (lib/gradelib.php)';
510 print_object(array('gradevalue' => $gradevalue,
511 'source_min' => $source_min,
512 'source_max' => $source_max,
513 'target_min' => $target_min,
096858ff 514 'target_max' => $target_max,
515 'result' => $standardised_value));
2df71235 516 }
612607bd 517 return $standardised_value;
2c72af1f 518}
bfe7297e 519
520
7bddd4b7 521/**
612607bd 522 * Handles some specific grade_update_request events,
de420c11 523 * see lib/db/events.php for description of $eventdata format.
bfe7297e 524 *
bfe7297e 525 * @param object $eventdata contains all the data for the event
526 * @return boolean success
527 *
528 */
529function grade_handler($eventdata) {
7bddd4b7 530 $eventdata = (array)$eventdata;
531
de420c11 532 // each grade must belong to some user
7bddd4b7 533 if (empty($eventdata['userid'])) {
534 debugging('Missing user id in event data!');
535 return true;
536 }
bfe7297e 537
612607bd 538 // grade item idnumber must be specified or else it could be accidentally duplicated,
539 if (empty($eventdata['idnumber'])) {
540 debugging('Missing grade item idnumber in event!');
de420c11 541 return true;
bfe7297e 542 }
543
de420c11 544 // get the grade item from db
612607bd 545 $grade_item = new grade_item(array('idnumber'=>$eventdata['idnumber']), false);
546 if (!$grade_items = $grade_item->fetch_all_using_this()) {
547 // TODO: create a new one - tricky, watch out for duplicates !!
548 // use only special type 'import'(y) or 'manual'(?)
549 debugging('Can not create new grade items yet :-(');
de420c11 550 return true;
de420c11 551
612607bd 552 } else if (count($grade_items) == 1) {
553 $grade_item = reset($grade_items);
554 unset($grade_items); //release memory
bfe7297e 555
612607bd 556 } else {
557 debugging('More than one grade item matched, grade update request failed');
558 return true;
559 }
bfe7297e 560
612607bd 561 // !! TODO: whitelist only some types such as 'import'(?) 'manual'(?) and ignore the rest!!
b919d680 562 if ($grade_item->itemtype == 'mod') {
612607bd 563 // modules must have own handlers for grade update requests
564 return true;
565 }
bfe7297e 566
612607bd 567 $grade = new object();
568 $grade->userid = $eventdata['userid'];
569 if (isset($eventdata['gradevalue'])) {
570 $grade->feedback = $eventdata['gradevalue'];
7bddd4b7 571 }
612607bd 572 if (isset($eventdata['feedback'])) {
573 $grade->feedback = $eventdata['feedback'];
7bddd4b7 574 }
612607bd 575 if (isset($eventdata['feedbackformat'])) {
576 $grade->feedbackformat = $eventdata['feedbackformat'];
bfe7297e 577 }
bfe7297e 578
612607bd 579 grade_update($grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
580 $grade_item->iteminstance, $grade_item->itemnumber, $grade, $eventdata);
581
7bddd4b7 582 // everything ok :-)
bfe7297e 583 return true;
584
585}
586
587
60cf7430 588?>