MDL-10057 XSS risk flag for Add/update course category
[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',
77 * 'grademin', 'scaleid', '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
612607bd 91 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'deleted');
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
109 debugging('Found more than one grading item');
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 }
130 $itemid = grade_create_item($params);
131 $grade_item = grade_item::fetch('id', $itemid);
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*
274* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
275* @param string $itemmodule 'forum, 'quiz', 'csv' etc
276* @param int $iteminstance id of the item module
277* @param int $itemnumber Optional number of the item to check
278* @param int $userid ID of the user who owns the grade
279* @return boolean Whether the grade is locked or not
280*/
281function grade_is_locked($itemtype, $itemmodule, $iteminstance, $itemnumber=NULL, $userid=NULL) {
282 $grade_item = new grade_item(compact('itemtype', 'itemmodule', 'iteminstance', 'itemnumber'));
283 return $grade_item->is_locked($userid);
284}
285
286
612607bd 287/***** END OF PUBLIC API *****/
288
5834dcdb 289/**
612607bd 290* Extracts from the gradebook all the grade items attached to the calling object.
291* For example, an assignment may want to retrieve all the grade_items for itself,
5834dcdb 292* and get three outcome scales in return. This will affect the grading interface.
293*
294* Note: Each parameter refines the search. So if you only give the courseid,
295* all the grade_items for this course will be returned. If you add the
296* itemtype 'mod', all grade_items for this courseif AND for the 'mod'
297* type will be returned, etc...
612607bd 298*
42bbccd7 299* @param int $courseid The id of the course to which the grade items belong
5834dcdb 300* @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
301* @param string $itemmodule 'forum, 'quiz', 'csv' etc
302* @param int $iteminstance id of the item module
de420c11 303* @param string $itemname The name of the grade item
5834dcdb 304* @param int $itemnumber Can be used to distinguish multiple grades for an activity
42bbccd7 305* @param int $idnumber grade item Primary Key
306* @return array An array of grade items
5834dcdb 307*/
de420c11 308function grade_get_items($courseid, $itemtype=NULL, $itemmodule=NULL, $iteminstance=NULL, $itemname=NULL, $itemnumber=NULL, $idnumber=NULL) {
309 $grade_item = new grade_item(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemname', 'itemnumber', 'idnumber'), false);
3058964f 310 $grade_items = $grade_item->fetch_all_using_this();
42bbccd7 311 return $grade_items;
5834dcdb 312}
313
314
315/**
de420c11 316* Creates a new grade_item in case it doesn't exist.
317* This function is called when a new module is created.
318*
319* @param mixed $params array or object
5834dcdb 320* @return mixed New grade_item id if successful
321*/
3058964f 322function grade_create_item($params) {
42bbccd7 323 $grade_item = new grade_item($params);
612607bd 324
d9907766 325 if (empty($grade_item->id)) {
326 return $grade_item->insert();
327 } else {
de420c11 328 debugging('Grade item already exists - id:'.$grade_item->id);
d9907766 329 return $grade_item->id;
330 }
5834dcdb 331}
332
333/**
334* For a given set of items, create a category to group them together (if one doesn't yet exist).
335* Modules may want to do this when they are created. However, the ultimate control is in the gradebook interface itself.
619a59a7 336*
337* @param int $courseid
42bbccd7 338* @param string $fullname The name of the new category
339* @param array $items An array of grade_items to group under the new category
5834dcdb 340* @param string $aggregation
341* @return mixed New grade_category id if successful
342*/
3058964f 343function grade_create_category($courseid, $fullname, $items, $aggregation=GRADE_AGGREGATE_MEAN) {
344 $grade_category = new grade_category(compact('courseid', 'fullname', 'items', 'aggregation'));
612607bd 345
d9907766 346 if (empty($grade_category->id)) {
347 return $grade_category->insert();
348 } else {
349 return $grade_category->id;
350 }
5834dcdb 351}
352
a8995b34 353/**
354 * Updates all grade_grades_final for each grade_item matching the given attributes.
355 * The search is further restricted, so that only grade_items that have needs_update == TRUE
356 * or that use calculation are retrieved.
357 *
358 * @param int $courseid
359 * @param int $gradeitemid
360 * @return int Number of grade_items updated
361 */
362function grade_update_final_grades($courseid=NULL, $gradeitemid=NULL) {
363 $grade_item = new grade_item();
364 $grade_item->courseid = $courseid;
365 $grade_item->id = $gradeitemid;
366 $grade_items = $grade_item->fetch_all_using_this();
612607bd 367
a8995b34 368 $count = 0;
369
370 foreach ($grade_items as $gi) {
371 $calculation = $gi->get_calculation();
372 if (!empty($calculation) || $gi->needsupdate) {
373 if ($gi->update_final_grade()) {
374 $count++;
375 }
376 }
377 }
378
379 return $count;
380}
967f222f 381
de420c11 382/**
967f222f 383 * For backward compatibility with old third-party modules, this function is called
384 * via to admin/cron.php to search all mod/xxx/lib.php files for functions named xxx_grades(),
385 * if the current modules does not have grade events registered with the grade book.
612607bd 386 * Once the data is extracted, the events_trigger() function can be called to initiate
387 * an event as usual and copy/ *upgrade the data in the gradebook tables.
967f222f 388 */
de420c11 389function grade_grab_legacy_grades() {
612607bd 390
967f222f 391 global $CFG, $db;
392
393 if (!$mods = get_list_of_plugins('mod') ) {
394 error('No modules installed!');
395 }
396
397 foreach ($mods as $mod) {
398
399 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
400 continue;
401 }
402
403 $fullmod = $CFG->dirroot .'/mod/'. $mod;
404
405 // include the module lib once
406 if (file_exists($fullmod.'/lib.php')) {
407 include_once($fullmod.'/lib.php');
de420c11 408 // look for modname_grades() function - old gradebook pulling function
409 // if present sync the grades with new grading system
967f222f 410 $gradefunc = $mod.'_grades';
de420c11 411 if (function_exists($gradefunc)) {
412
413 // get all instance of the activity
414 $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
415 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id";
416
417 if ($modinstances = get_records_sql($sql)) {
967f222f 418 foreach ($modinstances as $modinstance) {
419 // for each instance, call the xxx_grades() function
de420c11 420 if ($grades = $gradefunc($modinstance->id)) {
421
422 $grademax = $grades->maxgrade;
423 $scaleid = 0;
612607bd 424 if (!is_numeric($grademax)) {
5283e959 425 // scale name is provided as a string, try to find it
de420c11 426 if (!$scale = get_record('scale', 'name', $grademax)) {
427 debugging('Incorrect scale name! name:'.$grademax);
428 continue;
429 }
5283e959 430 $scaleid = $scale->id;
de420c11 431 }
432
433 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
434 debugging('Can not get/create legacy grade item!');
435 continue;
9d5c91b1 436 }
437
612607bd 438 foreach ($grades->grades as $userid=>$usergrade) {
967f222f 439 // make the grade_added eventdata
d46306de 440 $eventdata = new object();
de420c11 441 $eventdata->itemid = $grade_item->id;
9492291c 442 $eventdata->userid = $userid;
de420c11 443
444 if ($usergrade == '-') {
445 // no grade
446 $eventdata->gradevalue = null;
447
448 } else if ($scaleid) {
5283e959 449 // scale in use, words used
450 $gradescale = explode(",", $scale->scale);
451 $eventdata->gradevalue = array_search($usergrade, $gradescale) + 1;
de420c11 452
5283e959 453 } else {
454 // good old numeric value
455 $eventdata->gradevalue = $usergrade;
456 }
457
de420c11 458 events_trigger('grade_updated', $eventdata);
967f222f 459 }
460 }
461 }
462 }
463 }
464 }
465 }
466}
467
de420c11 468
469/**
470 * Get (create if needed) grade item for legacy modules.
471 */
472function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
473
474 // does it already exist?
475 if ($grade_items = grade_get_items($modinstances->courseid, 'mod', $modinstance->modname, $modinstances->id)) {
476 if (count($grade_items) > 1) {
477 return false;
478 }
479
480 $grade_item = reset($grade_items);
481 $updated = false;
482
483 if ($scaleid) {
484 if ($grade_item->scaleid != $scaleid) {
485 $grade_item->gradetype = GRADE_TYPE_SCALE;
486 $grade_item->scaleid = $scaleid;
487 $updated = true;;
488 }
489
490 } else if ($grade_item->scaleid != $scaleid or $grade_item->grademax != $grademax) {
491 $grade_item->gradetype = GRADE_TYPE_VALUE;
492 $grade_item->scaleid = 0;
493 $grade_item->grademax = $grademax;
494 $grade_item->grademin = 0;
495 $updated = true;;
496 }
497
498 if ($grade_item->itemname != $modinstance->name) {
499 $grade_item->itemname = $modinstance->name;
500 $updated = true;;
501 }
502
503 if ($grade_item->idnumber != $modinstance->cmidnumber) {
504 $grade_item->idnumber = $modinstance->cmidnumber;
505 $updated = true;;
506 }
507
508 if ($updated) {
509 $grade_item->update();
510 }
511
512 return $grade_item;
513 }
612607bd 514
de420c11 515 // create new one
516 $params = array('courseid' =>$modinstance->courseid,
517 'itemtype' =>'mod',
518 'itemmodule' =>$modinstance->modname,
519 'iteminstance'=>$modinstance->id,
520 'itemname' =>$modinstance->name,
521 'idnumber' =>$modinstance->cmidnumber);
522
523 if ($scaleid) {
612607bd 524 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 525 $params['scaleid'] = $scaleid;
526
527 } else {
612607bd 528 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 529 $params['grademax'] = $grademax;
530 $params['grademin'] = 0;
531 }
532
533 if (!$itemid = grade_create_item($params)) {
534 return false;
535 }
536
537 return grade_item::fetch('id', $itemid);
538}
539
2c72af1f 540/**
541 * Given a float value situated between a source minimum and a source maximum, converts it to the
542 * corresponding value situated between a target minimum and a target maximum. Thanks to Darlene
543 * for the formula :-)
544 * @param float $gradevalue
545 * @param float $source_min
546 * @param float $source_max
547 * @param float $target_min
548 * @param float $target_max
549 * @return float Converted value
550 */
2df71235 551function standardise_score($gradevalue, $source_min, $source_max, $target_min, $target_max, $debug=false) {
096858ff 552 $factor = ($gradevalue - $source_min) / ($source_max - $source_min);
553 $diff = $target_max - $target_min;
554 $standardised_value = $factor * $diff + $target_min;
2df71235 555 if ($debug) {
556 echo 'standardise_score debug info: (lib/gradelib.php)';
557 print_object(array('gradevalue' => $gradevalue,
558 'source_min' => $source_min,
559 'source_max' => $source_max,
560 'target_min' => $target_min,
096858ff 561 'target_max' => $target_max,
562 'result' => $standardised_value));
2df71235 563 }
612607bd 564 return $standardised_value;
2c72af1f 565}
bfe7297e 566
567
60cf7430 568?>