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