Merging in changes for MDL-9947 and MDL-9923 from MOODLE_18_STABLE
[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);
27f95e9b 39define('GRADE_CHILDTYPE_ITEM', 0);
40define('GRADE_CHILDTYPE_CAT', 1);
41define('GRADE_ITEM', 0); // Used to compare class names with CHILDTYPE values
42define('GRADE_CATEGORY', 1); // Used to compare class names with CHILDTYPE values
6527197b 43define('GRADE_TYPE_VALUE', 0);
44define('GRADE_TYPE_SCALE', 1);
45define('GRADE_TYPE_TEXT', 2);
42bbccd7 46
3058964f 47require_once($CFG->libdir . '/grade/grade_category.php');
48require_once($CFG->libdir . '/grade/grade_item.php');
49require_once($CFG->libdir . '/grade/grade_calculation.php');
a8995b34 50require_once($CFG->libdir . '/grade/grade_grades_raw.php');
869807d8 51require_once($CFG->libdir . '/grade/grade_grades_final.php');
d5bdb228 52require_once($CFG->libdir . '/grade/grade_scale.php');
5501446d 53require_once($CFG->libdir . '/grade/grade_outcome.php');
46566dd8 54require_once($CFG->libdir . '/grade/grade_history.php');
55require_once($CFG->libdir . '/grade/grade_grades_text.php');
8ff4550a 56require_once($CFG->libdir . '/grade/grade_tree.php');
60cf7430 57
5834dcdb 58/**
42bbccd7 59* Extracts from the gradebook all the grade items attached to the calling object.
5834dcdb 60* For example, an assignment may want to retrieve all the grade_items for itself,
61* and get three outcome scales in return. This will affect the grading interface.
62*
63* Note: Each parameter refines the search. So if you only give the courseid,
64* all the grade_items for this course will be returned. If you add the
65* itemtype 'mod', all grade_items for this courseif AND for the 'mod'
66* type will be returned, etc...
67*
42bbccd7 68* @param int $courseid The id of the course to which the grade items belong
5834dcdb 69* @param string $itemname The name of the grade item
70* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
71* @param string $itemmodule 'forum, 'quiz', 'csv' etc
72* @param int $iteminstance id of the item module
73* @param int $itemnumber Can be used to distinguish multiple grades for an activity
42bbccd7 74* @param int $idnumber grade item Primary Key
75* @return array An array of grade items
5834dcdb 76*/
3058964f 77function grade_get_items($courseid, $itemname=NULL, $itemtype=NULL, $itemmodule=NULL, $iteminstance=NULL, $itemnumber=NULL, $idnumber=NULL) {
78 $grade_item = new grade_item(compact('courseid', 'itemname', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber', 'idnumber'), false);
79 $grade_items = $grade_item->fetch_all_using_this();
42bbccd7 80 return $grade_items;
5834dcdb 81}
82
83
84/**
85* Creates a new grade_item in case it doesn't exist. This function would be called when a module
86* is created or updates, for example, to ensure grade_item entries exist.
87* It's not essential though--if grades are being added later and a matching grade_item doesn't
88* yet exist, the gradebook will create them on the fly.
89*
90* @param
91* @return mixed New grade_item id if successful
92*/
3058964f 93function grade_create_item($params) {
42bbccd7 94 $grade_item = new grade_item($params);
d9907766 95
96 if (empty($grade_item->id)) {
97 return $grade_item->insert();
98 } else {
99 return $grade_item->id;
100 }
5834dcdb 101}
102
103/**
104* For a given set of items, create a category to group them together (if one doesn't yet exist).
105* Modules may want to do this when they are created. However, the ultimate control is in the gradebook interface itself.
619a59a7 106*
107* @param int $courseid
42bbccd7 108* @param string $fullname The name of the new category
109* @param array $items An array of grade_items to group under the new category
5834dcdb 110* @param string $aggregation
111* @return mixed New grade_category id if successful
112*/
3058964f 113function grade_create_category($courseid, $fullname, $items, $aggregation=GRADE_AGGREGATE_MEAN) {
114 $grade_category = new grade_category(compact('courseid', 'fullname', 'items', 'aggregation'));
d9907766 115
116 if (empty($grade_category->id)) {
117 return $grade_category->insert();
118 } else {
119 return $grade_category->id;
120 }
5834dcdb 121}
122
123
124/**
125* Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
126* This is a combination of the actual settings in the grade tables and a check on moodle/course:editgradeswhenlocked.
127* If it's locked to the current use then the module can print a nice message or prevent editing in the module.
3058964f 128* If no $userid is given, the method will always return the grade_item's locked state.
129* If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
130* the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
131* return the locked state of the specific grade.
132*
5834dcdb 133* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
134* @param string $itemmodule 'forum, 'quiz', 'csv' etc
135* @param int $iteminstance id of the item module
3058964f 136* @param int $itemnumber Optional number of the item to check
5834dcdb 137* @param int $userid ID of the user who owns the grade
138* @return boolean Whether the grade is locked or not
139*/
3058964f 140function grade_is_locked($itemtype, $itemmodule, $iteminstance, $itemnumber=NULL, $userid=NULL) {
141 $grade_item = new grade_item(compact('itemtype', 'itemmodule', 'iteminstance', 'itemnumber'));
142 return $grade_item->is_locked($userid);
5834dcdb 143}
144
a8995b34 145/**
146 * Updates all grade_grades_final for each grade_item matching the given attributes.
147 * The search is further restricted, so that only grade_items that have needs_update == TRUE
148 * or that use calculation are retrieved.
149 *
150 * @param int $courseid
151 * @param int $gradeitemid
152 * @return int Number of grade_items updated
153 */
154function grade_update_final_grades($courseid=NULL, $gradeitemid=NULL) {
155 $grade_item = new grade_item();
156 $grade_item->courseid = $courseid;
157 $grade_item->id = $gradeitemid;
158 $grade_items = $grade_item->fetch_all_using_this();
159
160 $count = 0;
161
162 foreach ($grade_items as $gi) {
163 $calculation = $gi->get_calculation();
164 if (!empty($calculation) || $gi->needsupdate) {
165 if ($gi->update_final_grade()) {
166 $count++;
167 }
168 }
169 }
170
171 return $count;
172}
967f222f 173
174/*
175 * For backward compatibility with old third-party modules, this function is called
176 * via to admin/cron.php to search all mod/xxx/lib.php files for functions named xxx_grades(),
177 * if the current modules does not have grade events registered with the grade book.
d46306de 178 * Once the data is extracted, the events_trigger() function can be called to initiate
967f222f 179 * an event as usual and copy/ *upgrade the data in the gradebook tables.
180 */
181function grades_grab_grades() {
182
183 global $CFG, $db;
184
185 if (!$mods = get_list_of_plugins('mod') ) {
186 error('No modules installed!');
187 }
188
189 foreach ($mods as $mod) {
190
191 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
192 continue;
193 }
194
195 $fullmod = $CFG->dirroot .'/mod/'. $mod;
196
197 // include the module lib once
198 if (file_exists($fullmod.'/lib.php')) {
199 include_once($fullmod.'/lib.php');
200 // look for mod_grades() function - old grade book pulling function
201 // to see if module supports grades, and check for event registration status
202 $gradefunc = $mod.'_grades';
203 // if this mod has grades, but grade_added event is not registered
204 // then we need to pull grades into the new gradebook
d46306de 205 if (function_exists($gradefunc) && !events_is_registered($gradefunc, $mod)) {//TODO: the use of $gradefunct as eventname here does not seem to be correct
967f222f 206 // get all instance of the mod
207 $module = get_record('modules', 'name', $mod);
9fffb691 208 if ($module && $modinstances = get_records_select('course_modules cm, '.$CFG->prefix.$mod.' m', 'cm.module = '.$module->id.' AND m.id = cm.instance')) {
967f222f 209 foreach ($modinstances as $modinstance) {
210 // for each instance, call the xxx_grades() function
211 if ($grades = $gradefunc($modinstance->instance)) {
9d5c91b1 212
213 $maxgrade = $grades->maxgrade;
5283e959 214 if (is_numeric($maxgrade)) {
215 // no scale used
9d5c91b1 216 $scaleid = null;
5283e959 217 } else {
218 // scale name is provided as a string, try to find it
219 $scale = get_record('scale', 'name', $maxgrade);
220 $scaleid = $scale->id;
221 $maxgrade = null;
9d5c91b1 222 }
223
967f222f 224 foreach ($grades->grades as $userid=>$usergrade) {
225 // make the grade_added eventdata
9d5c91b1 226
d46306de 227 $eventdata = new object();
9492291c 228 $eventdata->courseid = $modinstance->course;
229 $eventdata->itemmodule = $mod;
230 $eventdata->iteminstance = $modinstance->instance;
231 $eventdata->gradetype = 0;
232 $eventdata->userid = $userid;
5283e959 233
234 if ($scaleid) {
235 // scale in use, words used
236 $gradescale = explode(",", $scale->scale);
237 $eventdata->gradevalue = array_search($usergrade, $gradescale) + 1;
238 } else {
239 // good old numeric value
240 $eventdata->gradevalue = $usergrade;
241 }
242
9fffb691 243 $eventdata->itemname = $modinstance->name;
9d5c91b1 244
3abe9945 245 $eventdata->grademax = $maxgrade;
9d5c91b1 246 $eventdata->scaleid = $scaleid;
247
5283e959 248 events_trigger('grade_added', $eventdata);
967f222f 249 }
250 }
251 }
252 }
253 }
254 }
255 }
256}
257
2c72af1f 258/**
259 * Given a float value situated between a source minimum and a source maximum, converts it to the
260 * corresponding value situated between a target minimum and a target maximum. Thanks to Darlene
261 * for the formula :-)
262 * @param float $gradevalue
263 * @param float $source_min
264 * @param float $source_max
265 * @param float $target_min
266 * @param float $target_max
267 * @return float Converted value
268 */
2df71235 269function standardise_score($gradevalue, $source_min, $source_max, $target_min, $target_max, $debug=false) {
096858ff 270 $factor = ($gradevalue - $source_min) / ($source_max - $source_min);
271 $diff = $target_max - $target_min;
272 $standardised_value = $factor * $diff + $target_min;
2df71235 273 if ($debug) {
274 echo 'standardise_score debug info: (lib/gradelib.php)';
275 print_object(array('gradevalue' => $gradevalue,
276 'source_min' => $source_min,
277 'source_max' => $source_max,
278 'target_min' => $target_min,
096858ff 279 'target_max' => $target_max,
280 'result' => $standardised_value));
2df71235 281 }
096858ff 282 return $standardised_value;
2c72af1f 283}
bfe7297e 284
285
7bddd4b7 286/**
bfe7297e 287 * Handles all grade_added and grade_updated events
288 *
bfe7297e 289 * @param object $eventdata contains all the data for the event
290 * @return boolean success
291 *
292 */
293function grade_handler($eventdata) {
7bddd4b7 294 $eventdata = (array)$eventdata;
295
296/// each grade must belong to some user
297 if (empty($eventdata['userid'])) {
298 debugging('Missing user id in event data!');
299 return true;
300 }
bfe7297e 301
302/// First let's make sure a grade_item exists for this grade
7bddd4b7 303 if (!empty($eventdata['itemid'])) { // if itemid specified, do not use searching
304 $gradeitem = new grade_item(array('id'=>$eventdata['itemid']));
305
306 if (empty($gradeitem->id)) { // Item with itemid doesn't exist yet
307 debugging('grade_item does not exist! id:'.$eventdata['itemid']);
308 // this $eventadata can not be fixed, do not block the queue
309 // we should log the error somewhere on production servers
310 return true;
311 }
312
313 } else {
314 $gradeitem = new grade_item($eventdata);
315 if (empty($gradeitem->id)) { // Doesn't exist yet
316 if (!$gradeitem->id = $gradeitem->insert()) { // Try to create a new item...
317 debugging('Could not create a new grade_item!');
318 // do we need false here? - it would stop all other grades indefinitelly!
319 // we shouuld not IMO block other events, one silly bug in 3rd party module would disable all grading
320 // if we return false we must to notify admin and add some gui to fix the trouble
321 // skodak
322 return true; //for now
323 }
bfe7297e 324 }
325 }
326
7bddd4b7 327 $rawgrade = new grade_grades_raw(array('itemid'=>$gradeitem->id, 'userid'=>$eventdata['userid']));
328 $rawgrade->grade_item = &$gradeitem; // we already have it, so let's use it
bfe7297e 329
7bddd4b7 330 // store these to keep track of original grade item settings
331 $rawgrade->grademax = $gradeitem->grademax;
332 $rawgrade->grademin = $gradeitem->grademin;
333 $rawgrade->scaleid = $gradeitem->scaleid;
bfe7297e 334
7bddd4b7 335 if (isset($eventdata['feedback'])) {
336 $rawgrade->feedback = $eventdata['feedback'];
337 if (isset($eventdata['feedbackformat'])) {
338 $rawgrade->feedbackformat = $eventdata['feedbackformat'];
339 } else {
340 $rawgrade->feedbackformat = FORMAT_PLAIN;
341 }
bfe7297e 342
7bddd4b7 343 }
344 if (!isset($eventdata['gradevalue'])) {
345 $eventdata['gradevalue'] = null; // means no grade yet
346 }
bfe7297e 347 if ($rawgrade->id) {
7bddd4b7 348 $rawgrade->update($eventdata['gradevalue'], 'event');
bfe7297e 349 } else {
7bddd4b7 350 $rawgrade->gradevalue = $eventdata['gradevalue'];
bfe7297e 351 $rawgrade->insert();
352 }
bfe7297e 353
7bddd4b7 354 // everything ok :-)
bfe7297e 355 return true;
356
357}
358
359
60cf7430 360?>