Teacher forums are now displayed to admins correctly MDL-9590
[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
b67ec72f 72function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
612607bd 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
b67ec72f 149 if (empty($grades)) {
612607bd 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
b67ec72f 160 if (is_object($grades)) {
161 $grades = array($grades);
612607bd 162 } else {
b67ec72f 163 if (array_key_exists('userid', $grades)) {
164 $grades = array($grades);
612607bd 165 }
166 }
167
612607bd 168 foreach ($grades as $grade) {
169 $grade = (array)$grade;
170 if (empty($grade['userid'])) {
171 debugging('Invalid grade submitted');
172 return GRADE_UPDATE_INVALID_GRADE;
173 }
174
175 // get the raw grade if it exist
176 $rawgrade = new grade_grades_raw(array('itemid'=>$grade_item->id, 'userid'=>$grade['userid']));
177 $rawgrade->grade_item = &$grade_item; // we already have it, so let's use it
178
179 // store these to keep track of original grade item settings
180 $rawgrade->grademax = $grade_item->grademax;
181 $rawgrade->grademin = $grade_item->grademin;
182 $rawgrade->scaleid = $grade_item->scaleid;
183
184 if (isset($grade['feedback'])) {
185 $rawgrade->feedback = $grade['feedback'];
186 if (isset($grade['feedbackformat'])) {
187 $rawgrade->feedbackformat = $grade['feedbackformat'];
188 } else {
189 $rawgrade->feedbackformat = FORMAT_PLAIN;
190 }
191 }
192
193 if (!isset($grade['gradevalue'])) {
194 $grade['gradevalue'] = null; // means no grade yet
195 }
196
197 if ($rawgrade->id) {
198 $rawgrade->update($grade['gradevalue'], 'event');
199 } else {
200 $rawgrade->gradevalue = $grade['gradevalue'];
201 $rawgrade->insert();
202 }
203
b67ec72f 204 // trigger grade_updated event notification
612607bd 205 $eventdata = new object();
b67ec72f 206 $eventdata->source = $source;
207 $eventdata->itemid = $grade_item->id;
208 $eventdata->courseid = $grade_item->courseid;
209 $eventdata->itemtype = $grade_item->itemtype;
210 $eventdata->itemmodule = $grade_item->itemmodule;
211 $eventdata->iteminstance = $grade_item->iteminstance;
212 $eventdata->itemnumber = $grade_item->itemnumber;
213 $eventdata->idnumber = $grade_item->idnumber;
214 $eventdata->grade = $grade;
612607bd 215 events_trigger('grade_updated', $eventdata);
216 }
217
218 return GRADE_UPDATE_OK;
219}
220
b67ec72f 221
222/**
223* Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
224* This is a combination of the actual settings in the grade tables and a check on moodle/course:editgradeswhenlocked.
225* If it's locked to the current use then the module can print a nice message or prevent editing in the module.
226* If no $userid is given, the method will always return the grade_item's locked state.
227* If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
228* the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
229* return the locked state of the specific grade.
230*
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
234* @param int $itemnumber Optional number of the item to check
235* @param int $userid ID of the user who owns the grade
236* @return boolean Whether the grade is locked or not
237*/
238function grade_is_locked($itemtype, $itemmodule, $iteminstance, $itemnumber=NULL, $userid=NULL) {
239 $grade_item = new grade_item(compact('itemtype', 'itemmodule', 'iteminstance', 'itemnumber'));
240 return $grade_item->is_locked($userid);
241}
242
243
612607bd 244/***** END OF PUBLIC API *****/
245
5834dcdb 246/**
612607bd 247* Extracts from the gradebook all the grade items attached to the calling object.
248* For example, an assignment may want to retrieve all the grade_items for itself,
5834dcdb 249* and get three outcome scales in return. This will affect the grading interface.
250*
251* Note: Each parameter refines the search. So if you only give the courseid,
252* all the grade_items for this course will be returned. If you add the
253* itemtype 'mod', all grade_items for this courseif AND for the 'mod'
254* type will be returned, etc...
612607bd 255*
42bbccd7 256* @param int $courseid The id of the course to which the grade items belong
5834dcdb 257* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
258* @param string $itemmodule 'forum, 'quiz', 'csv' etc
259* @param int $iteminstance id of the item module
de420c11 260* @param string $itemname The name of the grade item
5834dcdb 261* @param int $itemnumber Can be used to distinguish multiple grades for an activity
42bbccd7 262* @param int $idnumber grade item Primary Key
263* @return array An array of grade items
5834dcdb 264*/
de420c11 265function grade_get_items($courseid, $itemtype=NULL, $itemmodule=NULL, $iteminstance=NULL, $itemname=NULL, $itemnumber=NULL, $idnumber=NULL) {
266 $grade_item = new grade_item(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemname', 'itemnumber', 'idnumber'), false);
3058964f 267 $grade_items = $grade_item->fetch_all_using_this();
42bbccd7 268 return $grade_items;
5834dcdb 269}
270
271
272/**
de420c11 273* Creates a new grade_item in case it doesn't exist.
274* This function is called when a new module is created.
275*
276* @param mixed $params array or object
5834dcdb 277* @return mixed New grade_item id if successful
278*/
3058964f 279function grade_create_item($params) {
42bbccd7 280 $grade_item = new grade_item($params);
612607bd 281
d9907766 282 if (empty($grade_item->id)) {
283 return $grade_item->insert();
284 } else {
de420c11 285 debugging('Grade item already exists - id:'.$grade_item->id);
d9907766 286 return $grade_item->id;
287 }
5834dcdb 288}
289
290/**
291* For a given set of items, create a category to group them together (if one doesn't yet exist).
292* Modules may want to do this when they are created. However, the ultimate control is in the gradebook interface itself.
619a59a7 293*
294* @param int $courseid
42bbccd7 295* @param string $fullname The name of the new category
296* @param array $items An array of grade_items to group under the new category
5834dcdb 297* @param string $aggregation
298* @return mixed New grade_category id if successful
299*/
3058964f 300function grade_create_category($courseid, $fullname, $items, $aggregation=GRADE_AGGREGATE_MEAN) {
301 $grade_category = new grade_category(compact('courseid', 'fullname', 'items', 'aggregation'));
612607bd 302
d9907766 303 if (empty($grade_category->id)) {
304 return $grade_category->insert();
305 } else {
306 return $grade_category->id;
307 }
5834dcdb 308}
309
a8995b34 310/**
311 * Updates all grade_grades_final for each grade_item matching the given attributes.
312 * The search is further restricted, so that only grade_items that have needs_update == TRUE
313 * or that use calculation are retrieved.
314 *
315 * @param int $courseid
316 * @param int $gradeitemid
317 * @return int Number of grade_items updated
318 */
319function grade_update_final_grades($courseid=NULL, $gradeitemid=NULL) {
320 $grade_item = new grade_item();
321 $grade_item->courseid = $courseid;
322 $grade_item->id = $gradeitemid;
323 $grade_items = $grade_item->fetch_all_using_this();
612607bd 324
a8995b34 325 $count = 0;
326
327 foreach ($grade_items as $gi) {
328 $calculation = $gi->get_calculation();
329 if (!empty($calculation) || $gi->needsupdate) {
330 if ($gi->update_final_grade()) {
331 $count++;
332 }
333 }
334 }
335
336 return $count;
337}
967f222f 338
de420c11 339/**
967f222f 340 * For backward compatibility with old third-party modules, this function is called
341 * via to admin/cron.php to search all mod/xxx/lib.php files for functions named xxx_grades(),
342 * if the current modules does not have grade events registered with the grade book.
612607bd 343 * Once the data is extracted, the events_trigger() function can be called to initiate
344 * an event as usual and copy/ *upgrade the data in the gradebook tables.
967f222f 345 */
de420c11 346function grade_grab_legacy_grades() {
612607bd 347
967f222f 348 global $CFG, $db;
349
350 if (!$mods = get_list_of_plugins('mod') ) {
351 error('No modules installed!');
352 }
353
354 foreach ($mods as $mod) {
355
356 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
357 continue;
358 }
359
360 $fullmod = $CFG->dirroot .'/mod/'. $mod;
361
362 // include the module lib once
363 if (file_exists($fullmod.'/lib.php')) {
364 include_once($fullmod.'/lib.php');
de420c11 365 // look for modname_grades() function - old gradebook pulling function
366 // if present sync the grades with new grading system
967f222f 367 $gradefunc = $mod.'_grades';
de420c11 368 if (function_exists($gradefunc)) {
369
370 // get all instance of the activity
371 $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
372 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id";
373
374 if ($modinstances = get_records_sql($sql)) {
967f222f 375 foreach ($modinstances as $modinstance) {
376 // for each instance, call the xxx_grades() function
de420c11 377 if ($grades = $gradefunc($modinstance->id)) {
378
379 $grademax = $grades->maxgrade;
380 $scaleid = 0;
612607bd 381 if (!is_numeric($grademax)) {
5283e959 382 // scale name is provided as a string, try to find it
de420c11 383 if (!$scale = get_record('scale', 'name', $grademax)) {
384 debugging('Incorrect scale name! name:'.$grademax);
385 continue;
386 }
5283e959 387 $scaleid = $scale->id;
de420c11 388 }
389
390 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
391 debugging('Can not get/create legacy grade item!');
392 continue;
9d5c91b1 393 }
394
612607bd 395 foreach ($grades->grades as $userid=>$usergrade) {
967f222f 396 // make the grade_added eventdata
d46306de 397 $eventdata = new object();
de420c11 398 $eventdata->itemid = $grade_item->id;
9492291c 399 $eventdata->userid = $userid;
de420c11 400
401 if ($usergrade == '-') {
402 // no grade
403 $eventdata->gradevalue = null;
404
405 } else if ($scaleid) {
5283e959 406 // scale in use, words used
407 $gradescale = explode(",", $scale->scale);
408 $eventdata->gradevalue = array_search($usergrade, $gradescale) + 1;
de420c11 409
5283e959 410 } else {
411 // good old numeric value
412 $eventdata->gradevalue = $usergrade;
413 }
414
de420c11 415 events_trigger('grade_updated', $eventdata);
967f222f 416 }
417 }
418 }
419 }
420 }
421 }
422 }
423}
424
de420c11 425
426/**
427 * Get (create if needed) grade item for legacy modules.
428 */
429function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
430
431 // does it already exist?
432 if ($grade_items = grade_get_items($modinstances->courseid, 'mod', $modinstance->modname, $modinstances->id)) {
433 if (count($grade_items) > 1) {
434 return false;
435 }
436
437 $grade_item = reset($grade_items);
438 $updated = false;
439
440 if ($scaleid) {
441 if ($grade_item->scaleid != $scaleid) {
442 $grade_item->gradetype = GRADE_TYPE_SCALE;
443 $grade_item->scaleid = $scaleid;
444 $updated = true;;
445 }
446
447 } else if ($grade_item->scaleid != $scaleid or $grade_item->grademax != $grademax) {
448 $grade_item->gradetype = GRADE_TYPE_VALUE;
449 $grade_item->scaleid = 0;
450 $grade_item->grademax = $grademax;
451 $grade_item->grademin = 0;
452 $updated = true;;
453 }
454
455 if ($grade_item->itemname != $modinstance->name) {
456 $grade_item->itemname = $modinstance->name;
457 $updated = true;;
458 }
459
460 if ($grade_item->idnumber != $modinstance->cmidnumber) {
461 $grade_item->idnumber = $modinstance->cmidnumber;
462 $updated = true;;
463 }
464
465 if ($updated) {
466 $grade_item->update();
467 }
468
469 return $grade_item;
470 }
612607bd 471
de420c11 472 // create new one
473 $params = array('courseid' =>$modinstance->courseid,
474 'itemtype' =>'mod',
475 'itemmodule' =>$modinstance->modname,
476 'iteminstance'=>$modinstance->id,
477 'itemname' =>$modinstance->name,
478 'idnumber' =>$modinstance->cmidnumber);
479
480 if ($scaleid) {
612607bd 481 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 482 $params['scaleid'] = $scaleid;
483
484 } else {
612607bd 485 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 486 $params['grademax'] = $grademax;
487 $params['grademin'] = 0;
488 }
489
490 if (!$itemid = grade_create_item($params)) {
491 return false;
492 }
493
494 return grade_item::fetch('id', $itemid);
495}
496
2c72af1f 497/**
498 * Given a float value situated between a source minimum and a source maximum, converts it to the
499 * corresponding value situated between a target minimum and a target maximum. Thanks to Darlene
500 * for the formula :-)
501 * @param float $gradevalue
502 * @param float $source_min
503 * @param float $source_max
504 * @param float $target_min
505 * @param float $target_max
506 * @return float Converted value
507 */
2df71235 508function standardise_score($gradevalue, $source_min, $source_max, $target_min, $target_max, $debug=false) {
096858ff 509 $factor = ($gradevalue - $source_min) / ($source_max - $source_min);
510 $diff = $target_max - $target_min;
511 $standardised_value = $factor * $diff + $target_min;
2df71235 512 if ($debug) {
513 echo 'standardise_score debug info: (lib/gradelib.php)';
514 print_object(array('gradevalue' => $gradevalue,
515 'source_min' => $source_min,
516 'source_max' => $source_max,
517 'target_min' => $target_min,
096858ff 518 'target_max' => $target_max,
519 'result' => $standardised_value));
2df71235 520 }
612607bd 521 return $standardised_value;
2c72af1f 522}
bfe7297e 523
524
60cf7430 525?>