MDL-11718 grader report now does not show column totals if user does not have view...
[moodle.git] / lib / gradelib.php
CommitLineData
5834dcdb 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
5834dcdb 4// NOTICE OF COPYRIGHT //
5// //
6// Moodle - Modular Object-Oriented Dynamic Learning Environment //
53461661 7// http://moodle.org //
5834dcdb 8// //
53461661 9// Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
5834dcdb 10// //
11// This program is free software; you can redistribute it and/or modify //
12// it under the terms of the GNU General Public License as published by //
13// the Free Software Foundation; either version 2 of the License, or //
14// (at your option) any later version. //
15// //
16// This program is distributed in the hope that it will be useful, //
17// but WITHOUT ANY WARRANTY; without even the implied warranty of //
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
19// GNU General Public License for more details: //
20// //
21// http://www.gnu.org/copyleft/gpl.html //
22// //
23///////////////////////////////////////////////////////////////////////////
24
25/**
42bbccd7 26 * Library of functions for gradebook
5834dcdb 27 *
28 * @author Moodle HQ developers
29 * @version $Id$
30 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
31 * @package moodlecore
32 */
33
53461661 34require_once($CFG->libdir . '/grade/constants.php');
eea6690a 35
3058964f 36require_once($CFG->libdir . '/grade/grade_category.php');
37require_once($CFG->libdir . '/grade/grade_item.php');
3ee5c201 38require_once($CFG->libdir . '/grade/grade_grade.php');
d5bdb228 39require_once($CFG->libdir . '/grade/grade_scale.php');
5501446d 40require_once($CFG->libdir . '/grade/grade_outcome.php');
60cf7430 41
6b5c722d 42/***** PUBLIC GRADE API - only these functions should be used in modules *****/
612607bd 43
c5b5f18d 44/**
45 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
ac9b0805 46 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
c5b5f18d 47 * or key means do not change existing.
4cf1b9be 48 *
c5b5f18d 49 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
1223d24a 50 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'.
4cf1b9be 51 *
fcac8e51 52 * Manual, course or category items can not be updated by this function.
53
9c8d38fa 54 * @param string $source source of the grade such as 'mod/assignment'
c5b5f18d 55 * @param int $courseid id of course
3a5ae660 56 * @param string $itemtype type of grade item - mod, block
c5b5f18d 57 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
58 * @param int $iteminstance instance it of graded subject
59 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
b60b2ce6 60 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
c5b5f18d 61 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
62 */
b67ec72f 63function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
aaff71da 64 global $USER;
612607bd 65
c5b5f18d 66 // only following grade_item properties can be changed in this function
1223d24a 67 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
612607bd 68
c4e4068f 69 // grade item identification
70 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
71
612607bd 72 if (is_null($courseid) or is_null($itemtype)) {
73 debugging('Missing courseid or itemtype');
74 return GRADE_UPDATE_FAILED;
75 }
76
c4e4068f 77 if (!$grade_items = grade_item::fetch_all($params)) {
612607bd 78 // create a new one
79 $grade_item = false;
80
81 } else if (count($grade_items) == 1){
82 $grade_item = reset($grade_items);
83 unset($grade_items); //release memory
84
85 } else {
34e67f76 86 debugging('Found more than one grade item');
612607bd 87 return GRADE_UPDATE_MULTIPLE;
88 }
89
aaff71da 90 if (!empty($itemdetails['deleted'])) {
91 if ($grade_item) {
92 if ($grade_item->delete($source)) {
93 return GRADE_UPDATE_OK;
94 } else {
95 return GRADE_UPDATE_FAILED;
96 }
97 }
98 return GRADE_UPDATE_OK;
99 }
100
612607bd 101/// Create or update the grade_item if needed
b159da78 102
612607bd 103 if (!$grade_item) {
612607bd 104 if ($itemdetails) {
105 $itemdetails = (array)$itemdetails;
2e53372c 106
772ddfbf 107 // grademin and grademax ignored when scale specified
2e53372c 108 if (array_key_exists('scaleid', $itemdetails)) {
109 if ($itemdetails['scaleid']) {
110 unset($itemdetails['grademin']);
111 unset($itemdetails['grademax']);
112 }
113 }
114
612607bd 115 foreach ($itemdetails as $k=>$v) {
116 if (!in_array($k, $allowed)) {
117 // ignore it
118 continue;
119 }
120 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
121 // no grade item needed!
122 return GRADE_UPDATE_OK;
123 }
124 $params[$k] = $v;
125 }
126 }
f70152b7 127 $grade_item = new grade_item($params);
128 $grade_item->insert();
612607bd 129
130 } else {
2cc4b0f9 131 if ($grade_item->is_locked()) {
678e8898 132 $message = get_string('gradeitemislocked', 'grades', $grade_item->itemname);
133 notice($message);
134 return GRADE_UPDATE_ITEM_LOCKED;
612607bd 135 }
136
137 if ($itemdetails) {
138 $itemdetails = (array)$itemdetails;
139 $update = false;
140 foreach ($itemdetails as $k=>$v) {
141 if (!in_array($k, $allowed)) {
142 // ignore it
143 continue;
144 }
145 if ($grade_item->{$k} != $v) {
146 $grade_item->{$k} = $v;
147 $update = true;
148 }
149 }
150 if ($update) {
151 $grade_item->update();
152 }
153 }
154 }
155
156/// Some extra checks
157 // do we use grading?
158 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
159 return GRADE_UPDATE_OK;
160 }
161
162 // no grade submitted
b67ec72f 163 if (empty($grades)) {
612607bd 164 return GRADE_UPDATE_OK;
165 }
166
612607bd 167/// Finally start processing of grades
b67ec72f 168 if (is_object($grades)) {
169 $grades = array($grades);
612607bd 170 } else {
b67ec72f 171 if (array_key_exists('userid', $grades)) {
172 $grades = array($grades);
612607bd 173 }
174 }
175
4cf1b9be 176 $failed = false;
612607bd 177 foreach ($grades as $grade) {
178 $grade = (array)$grade;
179 if (empty($grade['userid'])) {
4cf1b9be 180 $failed = true;
181 debugging('Invalid userid in grade submitted');
182 continue;
ac9b0805 183 } else {
184 $userid = $grade['userid'];
612607bd 185 }
186
2cc4b0f9 187 $rawgrade = false;
ac9b0805 188 $feedback = false;
189 $feedbackformat = FORMAT_MOODLE;
772ddfbf 190
ac9b0805 191 if (array_key_exists('rawgrade', $grade)) {
192 $rawgrade = $grade['rawgrade'];
193 }
612607bd 194
4cf1b9be 195 if (array_key_exists('feedback', $grade)) {
ac9b0805 196 $feedback = $grade['feedback'];
612607bd 197 }
198
ac9b0805 199 if (array_key_exists('feedbackformat', $grade)) {
200 $feedbackformat = $grade['feedbackformat'];
612607bd 201 }
202
aaff71da 203 if (array_key_exists('usermodified', $grade)) {
204 $usermodified = $grade['usermodified'];
205 } else {
206 $usermodified = $USER->id;
207 }
208
ac9b0805 209 // update or insert the grade
aaff71da 210 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
4cf1b9be 211 $failed = true;
4cf1b9be 212 }
612607bd 213 }
214
4cf1b9be 215 if (!$failed) {
216 return GRADE_UPDATE_OK;
217 } else {
218 return GRADE_UPDATE_FAILED;
219 }
612607bd 220}
221
3a5ae660 222/**
223 * Updates outcomes of user
fcac8e51 224 * Manual outcomes can not be updated.
225 * @param string $source source of the grade such as 'mod/assignment'
3a5ae660 226 * @param int $courseid id of course
227 * @param string $itemtype 'mod', 'block'
228 * @param string $itemmodule 'forum, 'quiz', etc.
229 * @param int $iteminstance id of the item module
230 * @param int $userid ID of the graded user
fcac8e51 231 * @param array $data array itemnumber=>outcomegrade
3a5ae660 232 */
233function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
234 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
235 foreach ($items as $item) {
236 if (!array_key_exists($item->itemnumber, $data)) {
237 continue;
238 }
239 $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
240 $item->update_final_grade($userid, $grade, $source);
11a14999 241 }
3a5ae660 242 }
243}
244
6b5c722d 245/**
fcac8e51 246 * Returns grading information for given activity - optionally with users grades
247 * Manual, course or category items can not be queried.
6b5c722d 248 * @param int $courseid id of course
249 * @param string $itemtype 'mod', 'block'
250 * @param string $itemmodule 'forum, 'quiz', etc.
251 * @param int $iteminstance id of the item module
252 * @param int $userid optional id of the graded user; if userid not used, returns only information about grade_item
253 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
254 */
fcac8e51 255function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=0) {
a3fbd494 256 global $CFG;
257
fcac8e51 258 $return = new object();
259 $return->items = array();
260 $return->outcomes = array();
6b5c722d 261
fcac8e51 262 $course_item = grade_item::fetch_course_item($courseid);
263 $needsupdate = array();
264 if ($course_item->needsupdate) {
265 $result = grade_regrade_final_grades($courseid);
266 if ($result !== true) {
267 $needsupdate = array_keys($result);
268 }
269 }
6b5c722d 270
fcac8e51 271 if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
272 foreach ($grade_items as $grade_item) {
a3fbd494 273 $decimalpoints = null;
274
fcac8e51 275 if (empty($grade_item->outcomeid)) {
276 // prepare information about grade item
277 $item = new object();
278 $item->itemnumber = $grade_item->itemnumber;
279 $item->scaleid = $grade_item->scaleid;
280 $item->name = $grade_item->get_name();
281 $item->grademin = $grade_item->grademin;
282 $item->grademax = $grade_item->grademax;
283 $item->gradepass = $grade_item->gradepass;
284 $item->locked = $grade_item->is_locked();
285 $item->hidden = $grade_item->is_hidden();
286 $item->grades = array();
287
288 switch ($grade_item->gradetype) {
289 case GRADE_TYPE_NONE:
290 continue;
6b5c722d 291
6b5c722d 292 case GRADE_TYPE_VALUE:
fcac8e51 293 $item->scaleid = 0;
6b5c722d 294 break;
295
fcac8e51 296 case GRADE_TYPE_TEXT:
297 $item->scaleid = 0;
298 $item->grademin = 0;
299 $item->grademax = 0;
300 $item->gradepass = 0;
6b5c722d 301 break;
fcac8e51 302 }
6b5c722d 303
fcac8e51 304 if (empty($userid_or_ids)) {
305 $userids = array();
306
307 } else if (is_array($userid_or_ids)) {
308 $userids = $userid_or_ids;
309
310 } else {
311 $userids = array($userid_or_ids);
6b5c722d 312 }
6b5c722d 313
fcac8e51 314 if ($userids) {
315 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
316 foreach ($userids as $userid) {
317 $grade_grades[$userid]->grade_item =& $grade_item;
318
319 $grade = new object();
320 $grade->grade = $grade_grades[$userid]->finalgrade;
321 $grade->locked = $grade_grades[$userid]->is_locked();
322 $grade->hidden = $grade_grades[$userid]->is_hidden();
323 $grade->overridden = $grade_grades[$userid]->overridden;
324 $grade->feedback = $grade_grades[$userid]->feedback;
325 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
a3fbd494 326 $grade->usermodified = $grade_grades[$userid]->usermodified;
fcac8e51 327
328 // create text representation of grade
329 if (in_array($grade_item->id, $needsupdate)) {
330 $grade->grade = false;
331 $grade->str_grade = get_string('error');
332
333 } else if (is_null($grade->grade)) {
a3fbd494 334 $grade->str_grade = '-';
fcac8e51 335
336 } else {
e9096dc2 337 $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
fcac8e51 338 }
339
340 // create html representation of feedback
341 if (is_null($grade->feedback)) {
342 $grade->str_feedback = '';
343 } else {
344 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
345 }
346
347 $item->grades[$userid] = $grade;
348 }
349 }
350 $return->items[$grade_item->itemnumber] = $item;
351
6b5c722d 352 } else {
fcac8e51 353 if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
354 debugging('Incorect outcomeid found');
355 continue;
356 }
357
358 // outcome info
359 $outcome = new object();
360 $outcome->itemnumber = $grade_item->itemnumber;
361 $outcome->scaleid = $grade_outcome->scaleid;
362 $outcome->name = $grade_outcome->get_name();
363 $outcome->locked = $grade_item->is_locked();
364 $outcome->hidden = $grade_item->is_hidden();
365
366 if (empty($userid_or_ids)) {
367 $userids = array();
368 } else if (is_array($userid_or_ids)) {
369 $userids = $userid_or_ids;
370 } else {
371 $userids = array($userid_or_ids);
372 }
6b5c722d 373
fcac8e51 374 if ($userids) {
375 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
376 foreach ($userids as $userid) {
377 $grade_grades[$userid]->grade_item =& $grade_item;
378
379 $grade = new object();
380 $grade->grade = $grade_grades[$userid]->finalgrade;
381 $grade->locked = $grade_grades[$userid]->is_locked();
382 $grade->hidden = $grade_grades[$userid]->is_hidden();
383 $grade->feedback = $grade_grades[$userid]->feedback;
384 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
a3fbd494 385 $grade->usermodified = $grade_grades[$userid]->usermodified;
fcac8e51 386
387 // create text representation of grade
388 if (in_array($grade_item->id, $needsupdate)) {
389 $grade->grade = false;
390 $grade->str_grade = get_string('error');
391
392 } else if (is_null($grade->grade)) {
393 $grade->grade = 0;
394 $grade->str_grade = get_string('nooutcome', 'grades');
395
396 } else {
397 $grade->grade = (int)$grade->grade;
398 $scale = $grade_item->load_scale();
399 $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
400 }
401
402 // create html representation of feedback
403 if (is_null($grade->feedback)) {
404 $grade->str_feedback = '';
405 } else {
406 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
407 }
408
409 $outcome->grades[$userid] = $grade;
410 }
411 }
412 $return->outcomes[$grade_item->itemnumber] = $outcome;
413
414 }
6b5c722d 415 }
416 }
417
fcac8e51 418 // sort results using itemnumbers
419 ksort($return->items, SORT_NUMERIC);
420 ksort($return->outcomes, SORT_NUMERIC);
421
422 return $return;
6b5c722d 423}
424
612607bd 425/***** END OF PUBLIC API *****/
426
e0724506 427
428/**
429 * Returns course gradebook setting
430 * @param int $courseid
431 * @param string $name of setting, maybe null if reset only
432 * @param bool $resetcache force reset of internal static cache
433 * @return string value, NULL if no setting
434 */
435function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
436 static $cache = array();
437
438 if ($resetcache or !array_key_exists($courseid, $cache)) {
439 $cache[$courseid] = array();
440
441 } else if (is_null($name)) {
442 return null;
443
444 } else if (array_key_exists($name, $cache[$courseid])) {
445 return $cache[$courseid][$name];
446 }
447
448 if (!$data = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
449 $result = null;
450 } else {
451 $result = $data->value;
452 }
453
454 if (is_null($result)) {
455 $result = $default;
456 }
457
458 $cache[$courseid][$name] = $result;
459 return $result;
460}
461
462/**
463 * Add/update course gradebook setting
464 * @param int $courseid
465 * @param string $name of setting
466 * @param string value, NULL means no setting==remove
467 * @return void
468 */
469function grade_set_setting($courseid, $name, $value) {
470 if (is_null($value)) {
471 delete_records('grade_settings', 'courseid', $courseid, 'name', addslashes($name));
472
473 } else if (!$existing = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
474 $data = new object();
475 $data->courseid = $courseid;
476 $data->name = addslashes($name);
477 $data->value = addslashes($value);
478 insert_record('grade_settings', $data);
479
480 } else {
481 $data = new object();
482 $data->id = $existing->id;
483 $data->value = addslashes($value);
484 update_record('grade_settings', $data);
485 }
486
487 grade_get_setting($courseid, null, null, true); // reset the cache
488}
489
e9096dc2 490/**
491 * Returns string representation of grade value
492 * @param float $value grade value
493 * @param object $grade_item - by reference to prevent scale reloading
494 * @param bool $localized use localised decimal separator
495 * @param int $display type of display - raw, letter, percentage
496 * @param int $decimalplaces number of decimal places when displaying float values
497 * @return string
498 */
499function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
500 if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
501 return '';
502 }
503
504 // no grade yet?
505 if (is_null($value)) {
506 return '-';
507 }
508
509 if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
510 //unknown type??
511 return '';
512 }
513
514 if (is_null($displaytype)) {
515 $displaytype = $grade_item->get_displaytype();
516 }
517
518 if (is_null($decimals)) {
519 $decimals = $grade_item->get_decimals();
520 }
521
522 switch ($displaytype) {
523 case GRADE_DISPLAY_TYPE_REAL:
524 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
1878f55d 525 if (!$scale = $grade_item->load_scale()) {
526 return get_string('error');
527 }
528
e9096dc2 529 $value = (int)bounded_number($grade_item->grademin, $value, $grade_item->grademax);
530 return format_string($scale->scale_items[$value-1]);
531
532 } else {
533 return format_float($value, $decimals, $localized);
534 }
535
536 case GRADE_DISPLAY_TYPE_PERCENTAGE:
537 $min = $grade_item->grademin;
538 $max = $grade_item->grademax;
539 if ($min == $max) {
540 return '';
541 }
542 $value = bounded_number($min, $value, $max);
543 $percentage = (($value-$min)*100)/($max-$min);
544 return format_float($percentage, $decimals, $localized).' %';
545
546 case GRADE_DISPLAY_TYPE_LETTER:
547 $context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid);
548 if (!$letters = grade_get_letters($context)) {
549 return ''; // no letters??
550 }
551
552 $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
553 $value = bounded_number(0, $value, 100); // just in case
554 foreach ($letters as $boundary => $letter) {
555 if ($value >= $boundary) {
556 return format_string($letter);
557 }
558 }
559 return '-'; // no match? maybe '' would be more correct
560
561 default:
562 return '';
563 }
564}
565
566/**
567 * Returns grade letters array used in context
568 * @param object $context object or null for defaults
569 * @return array of grade_boundary=>letter_string
570 */
571function grade_get_letters($context=null) {
572 if (empty($context)) {
284abb09 573 //default grading letters
574 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
e9096dc2 575 }
576
577 static $cache = array();
578
579 if (array_key_exists($context->id, $cache)) {
580 return $cache[$context->id];
581 }
582
583 if (count($cache) > 100) {
584 $cache = array(); // cache size limit
585 }
586
587 $letters = array();
588
589 $contexts = get_parent_contexts($context);
590 array_unshift($contexts, $context->id);
591
592 foreach ($contexts as $ctxid) {
284abb09 593 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
e9096dc2 594 foreach ($records as $record) {
284abb09 595 $letters[$record->lowerboundary] = $record->letter;
e9096dc2 596 }
597 }
598
599 if (!empty($letters)) {
600 $cache[$context->id] = $letters;
601 return $letters;
602 }
603 }
604
605 $letters = grade_get_letters(null);
606 $cache[$context->id] = $letters;
607 return $letters;
608}
609
60243313 610
611/**
2c5e52e2 612 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
60243313 613 * @param string idnumber string (with magic quotes)
614 * @param object $cm used for course module idnumbers and items attached to modules
615 * @param object $gradeitem is item idnumber
616 * @return boolean true means idnumber ok
617 */
618function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
619 if ($idnumber == '') {
620 //we allow empty idnumbers
621 return true;
622 }
623
624 // keep existing even when not unique
625 if ($cm and $cm->idnumber == $idnumber) {
626 return true;
627 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
628 return true;
629 }
630
631 if (get_records('course_modules', 'idnumber', $idnumber)) {
632 return false;
633 }
634
635 if (get_records('grade_items', 'idnumber', $idnumber)) {
636 return false;
637 }
638
639 return true;
640}
641
642/**
643 * Force final grade recalculation in all course items
644 * @param int $courseid
645 */
f8e6e4db 646function grade_force_full_regrading($courseid) {
647 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
648}
34e67f76 649
5834dcdb 650/**
ac9b0805 651 * Updates all final grades in course.
a8995b34 652 *
653 * @param int $courseid
f8e6e4db 654 * @param int $userid if specified, try to do a quick regrading of grades of this user only
655 * @param object $updated_item the item in which
656 * @return boolean true if ok, array of errors if problems found (item id is used as key)
a8995b34 657 */
c86caae7 658function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
b8ff92b6 659
514a3467 660 $course_item = grade_item::fetch_course_item($courseid);
f04873a9 661
f8e6e4db 662 if ($userid) {
663 // one raw grade updated for one user
664 if (empty($updated_item)) {
665 error("updated_item_id can not be null!");
666 }
667 if ($course_item->needsupdate) {
668 $updated_item->force_regrading();
669 return 'Can not do fast regrading after updating of raw grades';
a8995b34 670 }
772ddfbf 671
f8e6e4db 672 } else {
673 if (!$course_item->needsupdate) {
674 // nothing to do :-)
b8ff92b6 675 return true;
b8ff92b6 676 }
a8995b34 677 }
678
f8e6e4db 679 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
680 $depends_on = array();
681
682 // first mark all category and calculated items as needing regrading
fb0e3570 683 // this is slower, but 100% accurate
f8e6e4db 684 foreach ($grade_items as $gid=>$gitem) {
fb46b5b6 685 if (!empty($updated_item) and $updated_item->id == $gid) {
f8e6e4db 686 $grade_items[$gid]->needsupdate = 1;
687
eacd3700 688 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
f8e6e4db 689 $grade_items[$gid]->needsupdate = 1;
690 }
2e53372c 691
f8e6e4db 692 // construct depends_on lookup array
693 $depends_on[$gid] = $grade_items[$gid]->depends_on();
694 }
2e53372c 695
d14ae855 696 $errors = array();
b8ff92b6 697 $finalids = array();
d14ae855 698 $gids = array_keys($grade_items);
eacd3700 699 $failed = 0;
d14ae855 700
701 while (count($finalids) < count($gids)) { // work until all grades are final or error found
702 $count = 0;
703 foreach ($gids as $gid) {
704 if (in_array($gid, $finalids)) {
705 continue; // already final
706 }
707
708 if (!$grade_items[$gid]->needsupdate) {
709 $finalids[] = $gid; // we can make it final - does not need update
b8ff92b6 710 continue;
711 }
712
b8ff92b6 713 $doupdate = true;
f8e6e4db 714 foreach ($depends_on[$gid] as $did) {
b8ff92b6 715 if (!in_array($did, $finalids)) {
716 $doupdate = false;
d14ae855 717 continue; // this item depends on something that is not yet in finals array
b8ff92b6 718 }
719 }
720
721 //oki - let's update, calculate or aggregate :-)
722 if ($doupdate) {
d14ae855 723 $result = $grade_items[$gid]->regrade_final_grades($userid);
f8e6e4db 724
725 if ($result === true) {
d14ae855 726 $grade_items[$gid]->regrading_finished();
fb0e3570 727 $grade_items[$gid]->check_locktime(); // do the locktime item locking
f8e6e4db 728 $count++;
b8ff92b6 729 $finalids[] = $gid;
fb0e3570 730
f8e6e4db 731 } else {
d14ae855 732 $grade_items[$gid]->force_regrading();
f8e6e4db 733 $errors[$gid] = $result;
b8ff92b6 734 }
735 }
736 }
737
738 if ($count == 0) {
eacd3700 739 $failed++;
740 } else {
741 $failed = 0;
742 }
743
744 if ($failed > 1) {
d14ae855 745 foreach($gids as $gid) {
746 if (in_array($gid, $finalids)) {
747 continue; // this one is ok
748 }
749 $grade_items[$gid]->force_regrading();
750 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
b8ff92b6 751 }
d14ae855 752 break; // oki, found error
b8ff92b6 753 }
754 }
755
756 if (count($errors) == 0) {
fb0e3570 757 if (empty($userid)) {
758 // do the locktime locking of grades, but only when doing full regrading
fed7cdc9 759 grade_grade::check_locktime_all($gids);
fb0e3570 760 }
b8ff92b6 761 return true;
762 } else {
763 return $errors;
764 }
a8995b34 765}
967f222f 766
de420c11 767/**
d185c3ee 768 * For backwards compatibility with old third-party modules, this function can
769 * be used to import all grades from activities with legacy grading.
739196ba 770 * @param int $courseid or null if all courses
967f222f 771 */
739196ba 772function grade_grab_legacy_grades($courseid=null) {
612607bd 773
ac9b0805 774 global $CFG;
967f222f 775
776 if (!$mods = get_list_of_plugins('mod') ) {
777 error('No modules installed!');
778 }
779
739196ba 780 if ($courseid) {
781 $course_sql = " AND cm.course=$courseid";
782 } else {
783 $course_sql = "";
784 }
785
967f222f 786 foreach ($mods as $mod) {
787
788 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
789 continue;
790 }
791
d185c3ee 792 if (!$module = get_record('modules', 'name', $mod)) {
793 //not installed
794 continue;
795 }
796
797 if (!$module->visible) {
798 //disabled module
799 continue;
800 }
801
802 $fullmod = $CFG->dirroot.'/mod/'.$mod;
967f222f 803
804 // include the module lib once
805 if (file_exists($fullmod.'/lib.php')) {
806 include_once($fullmod.'/lib.php');
de420c11 807 // look for modname_grades() function - old gradebook pulling function
808 // if present sync the grades with new grading system
967f222f 809 $gradefunc = $mod.'_grades';
de420c11 810 if (function_exists($gradefunc)) {
811
812 // get all instance of the activity
d185c3ee 813 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
814 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
739196ba 815 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
de420c11 816
817 if ($modinstances = get_records_sql($sql)) {
967f222f 818 foreach ($modinstances as $modinstance) {
d185c3ee 819 grade_update_mod_grades($modinstance);
967f222f 820 }
821 }
822 }
823 }
824 }
825}
826
ac9b0805 827/**
828 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
829 */
830function grade_grab_grades() {
831
832 global $CFG;
833
834 if (!$mods = get_list_of_plugins('mod') ) {
835 error('No modules installed!');
836 }
837
838 foreach ($mods as $mod) {
839
840 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
841 continue;
842 }
843
844 if (!$module = get_record('modules', 'name', $mod)) {
845 //not installed
846 continue;
847 }
848
849 if (!$module->visible) {
850 //disabled module
851 continue;
852 }
853
854 $fullmod = $CFG->dirroot.'/mod/'.$mod;
855
856 // include the module lib once
857 if (file_exists($fullmod.'/lib.php')) {
858 include_once($fullmod.'/lib.php');
859 // look for modname_grades() function - old gradebook pulling function
860 // if present sync the grades with new grading system
861 $gradefunc = $mod.'_update_grades';
862 if (function_exists($gradefunc)) {
863 $gradefunc();
864 }
865 }
866 }
867}
868
d185c3ee 869/**
870 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
871 * @param object $modinstance object with extra cmidnumber and modname property
872 * @return boolean success
873 */
2b0f65e2 874function grade_update_mod_grades($modinstance, $userid=0) {
d185c3ee 875 global $CFG;
876
877 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
878 if (!file_exists($fullmod.'/lib.php')) {
879 debugging('missing lib.php file in module');
880 return false;
881 }
882 include_once($fullmod.'/lib.php');
883
884 // does it use legacy grading?
885 $gradefunc = $modinstance->modname.'_grades';
886 $updategradesfunc = $modinstance->modname.'_update_grades';
887 $updateitemfunc = $modinstance->modname.'_grade_item_update';
888
889 if (function_exists($gradefunc)) {
2b0f65e2 890
891 // legacy module - not yet converted
d185c3ee 892 if ($oldgrades = $gradefunc($modinstance->id)) {
893
894 $grademax = $oldgrades->maxgrade;
895 $scaleid = NULL;
896 if (!is_numeric($grademax)) {
897 // scale name is provided as a string, try to find it
898 if (!$scale = get_record('scale', 'name', $grademax)) {
899 debugging('Incorrect scale name! name:'.$grademax);
900 return false;
901 }
902 $scaleid = $scale->id;
903 }
904
905 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
906 debugging('Can not get/create legacy grade item!');
907 return false;
908 }
909
910 $grades = array();
2b0f65e2 911 foreach ($oldgrades->grades as $uid=>$usergrade) {
912 if ($userid and $uid != $userid) {
913 continue;
914 }
d185c3ee 915 $grade = new object();
2b0f65e2 916 $grade->userid = $uid;
d185c3ee 917
918 if ($usergrade == '-') {
919 // no grade
ac9b0805 920 $grade->rawgrade = null;
d185c3ee 921
922 } else if ($scaleid) {
923 // scale in use, words used
924 $gradescale = explode(",", $scale->scale);
ac9b0805 925 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
d185c3ee 926
927 } else {
928 // good old numeric value
ac9b0805 929 $grade->rawgrade = $usergrade;
d185c3ee 930 }
931 $grades[] = $grade;
932 }
933
934 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
935 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
936 }
937
938 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
939 //new grading supported, force updating of grades
940 $updateitemfunc($modinstance);
2b0f65e2 941 $updategradesfunc($modinstance, $userid);
d185c3ee 942
943 } else {
2b0f65e2 944 // mudule does not support grading??
d185c3ee 945 }
946
947 return true;
948}
de420c11 949
950/**
d185c3ee 951 * Get and update/create grade item for legacy modules.
de420c11 952 */
953function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
954
955 // does it already exist?
42ff9ce6 956 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
de420c11 957 if (count($grade_items) > 1) {
d185c3ee 958 debugging('Multiple legacy grade_items found.');
de420c11 959 return false;
960 }
961
962 $grade_item = reset($grade_items);
de420c11 963
d185c3ee 964 if (is_null($grademax) and is_null($scaleid)) {
965 $grade_item->gradetype = GRADE_TYPE_NONE;
de420c11 966
d185c3ee 967 } else if ($scaleid) {
968 $grade_item->gradetype = GRADE_TYPE_SCALE;
969 $grade_item->scaleid = $scaleid;
97d608ba 970 $grade_item->grademin = 1;
de420c11 971
d185c3ee 972 } else {
97d608ba 973 $grade_item->gradetype = GRADE_TYPE_VALUE;
974 $grade_item->grademax = $grademax;
975 $grade_item->grademin = 0;
de420c11 976 }
977
d185c3ee 978 $grade_item->itemname = $modinstance->name;
979 $grade_item->idnumber = $modinstance->cmidnumber;
de420c11 980
d185c3ee 981 $grade_item->update();
de420c11 982
983 return $grade_item;
984 }
612607bd 985
de420c11 986 // create new one
d185c3ee 987 $params = array('courseid' =>$modinstance->course,
de420c11 988 'itemtype' =>'mod',
989 'itemmodule' =>$modinstance->modname,
990 'iteminstance'=>$modinstance->id,
d185c3ee 991 'itemnumber' =>0,
de420c11 992 'itemname' =>$modinstance->name,
993 'idnumber' =>$modinstance->cmidnumber);
994
d185c3ee 995 if (is_null($grademax) and is_null($scaleid)) {
996 $params['gradetype'] = GRADE_TYPE_NONE;
997
998 } else if ($scaleid) {
612607bd 999 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 1000 $params['scaleid'] = $scaleid;
b3ac6c3e 1001 $grade_item->grademin = 1;
de420c11 1002 } else {
612607bd 1003 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 1004 $params['grademax'] = $grademax;
1005 $params['grademin'] = 0;
1006 }
1007
f70152b7 1008 $grade_item = new grade_item($params);
1009 $grade_item->insert();
de420c11 1010
f70152b7 1011 return $grade_item;
de420c11 1012}
1013
b51ece5b 1014/**
1015 * Remove grade letters for given context
1016 * @param object $context
1017 */
1018function remove_grade_letters($context, $showfeedback) {
1019 $strdeleted = get_string('deleted');
1020
1021 delete_records('grade_letters', 'contextid', $context->id);
1022 if ($showfeedback) {
1023 notify($strdeleted.' - '.get_string('letters', 'grades'));
1024 }
1025}
f615fbab 1026/**
1027 * Remove all grade related course data - history is kept
1028 * @param int $courseid
6b5c722d 1029 * @param bool @showfeedback print feedback
f615fbab 1030 */
1031function remove_course_grades($courseid, $showfeedback) {
1032 $strdeleted = get_string('deleted');
1033
1034 $course_category = grade_category::fetch_course_category($courseid);
1035 $course_category->delete('coursedelete');
1036 if ($showfeedback) {
1037 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
1038 }
1039
1040 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
1041 foreach ($outcomes as $outcome) {
1042 $outcome->delete('coursedelete');
1043 }
1044 }
1045 delete_records('grade_outcomes_courses', 'courseid', $courseid);
1046 if ($showfeedback) {
1047 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
1048 }
1049
1050 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
1051 foreach ($scales as $scale) {
1052 $scale->delete('coursedelete');
1053 }
1054 }
1055 if ($showfeedback) {
1056 notify($strdeleted.' - '.get_string('scales'));
1057 }
b51ece5b 1058
1059 delete_records('grade_settings', 'courseid', $courseid);
1060 if ($showfeedback) {
1061 notify($strdeleted.' - '.get_string('settings', 'grades'));
1062 }
f615fbab 1063}
bfe7297e 1064
32b97bb2 1065/**
1066 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
1067 * @param int $steps The value between each level.
1068 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
1069 * @param int $lowest The lowest value to include
1070 * @param int $highest The highest value to include
1071 */
1072function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
1073 // TODO reject or implement
1074}
42ff9ce6 1075
2650c51e 1076/**
1077 * Grading cron job
1078 */
1079function grade_cron() {
26101be8 1080 global $CFG;
1081
1082 $now = time();
1083
1084 $sql = "SELECT i.*
1085 FROM {$CFG->prefix}grade_items i
1086 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1f4a0320 1087 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 1088
2650c51e 1089 // go through all courses that have proper final grades and lock them if needed
26101be8 1090 if ($rs = get_recordset_sql($sql)) {
03cedd62 1091 while ($item = rs_fetch_next_record($rs)) {
1092 $grade_item = new grade_item($item, false);
1093 $grade_item->locked = $now;
1094 $grade_item->update('locktime');
2650c51e 1095 }
1096 rs_close($rs);
1097 }
26101be8 1098
fcac8e51 1099 $grade_inst = new grade_grade();
1100 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
1101
1102 $sql = "SELECT $fields
26101be8 1103 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
1104 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1f4a0320 1105 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 1106
1107 // go through all courses that have proper final grades and lock them if needed
1108 if ($rs = get_recordset_sql($sql)) {
03cedd62 1109 while ($grade = rs_fetch_next_record($rs)) {
1110 $grade_grade = new grade_grade($grade, false);
1111 $grade_grade->locked = $now;
1112 $grade_grade->update('locktime');
26101be8 1113 }
1114 rs_close($rs);
1115 }
1116
2650c51e 1117}
1118
60cf7430 1119?>