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