Test for empty dataset to suppress a warning
[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
0f392ff4 210 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $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
26ed0305 462/**
463 * Returns all course gradebook settings as object properties
464 * @param int $courseid
465 * @return object
466 */
467function grade_get_settings($courseid) {
468 $settings = new object();
469 $settings->id = $courseid;
470
471 if ($records = get_records('grade_settings', 'courseid', $courseid)) {
472 foreach ($records as $record) {
473 $settings->{$record->name} = $record->value;
474 }
475 }
476
477 return $settings;
478}
479
e0724506 480/**
481 * Add/update course gradebook setting
482 * @param int $courseid
483 * @param string $name of setting
484 * @param string value, NULL means no setting==remove
485 * @return void
486 */
487function grade_set_setting($courseid, $name, $value) {
488 if (is_null($value)) {
489 delete_records('grade_settings', 'courseid', $courseid, 'name', addslashes($name));
490
491 } else if (!$existing = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
492 $data = new object();
493 $data->courseid = $courseid;
494 $data->name = addslashes($name);
495 $data->value = addslashes($value);
496 insert_record('grade_settings', $data);
497
498 } else {
499 $data = new object();
500 $data->id = $existing->id;
501 $data->value = addslashes($value);
502 update_record('grade_settings', $data);
503 }
504
505 grade_get_setting($courseid, null, null, true); // reset the cache
506}
507
e9096dc2 508/**
509 * Returns string representation of grade value
510 * @param float $value grade value
511 * @param object $grade_item - by reference to prevent scale reloading
512 * @param bool $localized use localised decimal separator
513 * @param int $display type of display - raw, letter, percentage
514 * @param int $decimalplaces number of decimal places when displaying float values
515 * @return string
516 */
517function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
518 if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
519 return '';
520 }
521
522 // no grade yet?
523 if (is_null($value)) {
524 return '-';
525 }
526
527 if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
528 //unknown type??
529 return '';
530 }
531
532 if (is_null($displaytype)) {
533 $displaytype = $grade_item->get_displaytype();
534 }
535
536 if (is_null($decimals)) {
537 $decimals = $grade_item->get_decimals();
538 }
539
540 switch ($displaytype) {
541 case GRADE_DISPLAY_TYPE_REAL:
542 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
1878f55d 543 if (!$scale = $grade_item->load_scale()) {
544 return get_string('error');
545 }
546
e9096dc2 547 $value = (int)bounded_number($grade_item->grademin, $value, $grade_item->grademax);
548 return format_string($scale->scale_items[$value-1]);
549
550 } else {
551 return format_float($value, $decimals, $localized);
552 }
553
554 case GRADE_DISPLAY_TYPE_PERCENTAGE:
555 $min = $grade_item->grademin;
556 $max = $grade_item->grademax;
557 if ($min == $max) {
558 return '';
559 }
560 $value = bounded_number($min, $value, $max);
561 $percentage = (($value-$min)*100)/($max-$min);
562 return format_float($percentage, $decimals, $localized).' %';
563
564 case GRADE_DISPLAY_TYPE_LETTER:
565 $context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid);
566 if (!$letters = grade_get_letters($context)) {
567 return ''; // no letters??
568 }
569
570 $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
571 $value = bounded_number(0, $value, 100); // just in case
572 foreach ($letters as $boundary => $letter) {
573 if ($value >= $boundary) {
574 return format_string($letter);
575 }
576 }
577 return '-'; // no match? maybe '' would be more correct
578
579 default:
580 return '';
581 }
582}
583
584/**
585 * Returns grade letters array used in context
586 * @param object $context object or null for defaults
587 * @return array of grade_boundary=>letter_string
588 */
589function grade_get_letters($context=null) {
590 if (empty($context)) {
284abb09 591 //default grading letters
592 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 593 }
594
595 static $cache = array();
596
597 if (array_key_exists($context->id, $cache)) {
598 return $cache[$context->id];
599 }
600
601 if (count($cache) > 100) {
602 $cache = array(); // cache size limit
603 }
604
605 $letters = array();
606
607 $contexts = get_parent_contexts($context);
608 array_unshift($contexts, $context->id);
609
610 foreach ($contexts as $ctxid) {
284abb09 611 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
e9096dc2 612 foreach ($records as $record) {
284abb09 613 $letters[$record->lowerboundary] = $record->letter;
e9096dc2 614 }
615 }
616
617 if (!empty($letters)) {
618 $cache[$context->id] = $letters;
619 return $letters;
620 }
621 }
622
623 $letters = grade_get_letters(null);
624 $cache[$context->id] = $letters;
625 return $letters;
626}
627
60243313 628
629/**
2c5e52e2 630 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
60243313 631 * @param string idnumber string (with magic quotes)
632 * @param object $cm used for course module idnumbers and items attached to modules
633 * @param object $gradeitem is item idnumber
634 * @return boolean true means idnumber ok
635 */
636function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
637 if ($idnumber == '') {
638 //we allow empty idnumbers
639 return true;
640 }
641
642 // keep existing even when not unique
643 if ($cm and $cm->idnumber == $idnumber) {
644 return true;
645 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
646 return true;
647 }
648
649 if (get_records('course_modules', 'idnumber', $idnumber)) {
650 return false;
651 }
652
653 if (get_records('grade_items', 'idnumber', $idnumber)) {
654 return false;
655 }
656
657 return true;
658}
659
660/**
661 * Force final grade recalculation in all course items
662 * @param int $courseid
663 */
f8e6e4db 664function grade_force_full_regrading($courseid) {
665 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
666}
34e67f76 667
5834dcdb 668/**
ac9b0805 669 * Updates all final grades in course.
a8995b34 670 *
671 * @param int $courseid
f8e6e4db 672 * @param int $userid if specified, try to do a quick regrading of grades of this user only
673 * @param object $updated_item the item in which
674 * @return boolean true if ok, array of errors if problems found (item id is used as key)
a8995b34 675 */
c86caae7 676function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
b8ff92b6 677
514a3467 678 $course_item = grade_item::fetch_course_item($courseid);
f04873a9 679
f8e6e4db 680 if ($userid) {
681 // one raw grade updated for one user
682 if (empty($updated_item)) {
683 error("updated_item_id can not be null!");
684 }
685 if ($course_item->needsupdate) {
686 $updated_item->force_regrading();
687 return 'Can not do fast regrading after updating of raw grades';
a8995b34 688 }
772ddfbf 689
f8e6e4db 690 } else {
691 if (!$course_item->needsupdate) {
692 // nothing to do :-)
b8ff92b6 693 return true;
b8ff92b6 694 }
a8995b34 695 }
696
f8e6e4db 697 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
698 $depends_on = array();
699
700 // first mark all category and calculated items as needing regrading
fb0e3570 701 // this is slower, but 100% accurate
f8e6e4db 702 foreach ($grade_items as $gid=>$gitem) {
fb46b5b6 703 if (!empty($updated_item) and $updated_item->id == $gid) {
f8e6e4db 704 $grade_items[$gid]->needsupdate = 1;
705
eacd3700 706 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
f8e6e4db 707 $grade_items[$gid]->needsupdate = 1;
708 }
2e53372c 709
f8e6e4db 710 // construct depends_on lookup array
711 $depends_on[$gid] = $grade_items[$gid]->depends_on();
712 }
2e53372c 713
d14ae855 714 $errors = array();
b8ff92b6 715 $finalids = array();
d14ae855 716 $gids = array_keys($grade_items);
eacd3700 717 $failed = 0;
d14ae855 718
719 while (count($finalids) < count($gids)) { // work until all grades are final or error found
720 $count = 0;
721 foreach ($gids as $gid) {
722 if (in_array($gid, $finalids)) {
723 continue; // already final
724 }
725
726 if (!$grade_items[$gid]->needsupdate) {
727 $finalids[] = $gid; // we can make it final - does not need update
b8ff92b6 728 continue;
729 }
730
b8ff92b6 731 $doupdate = true;
f8e6e4db 732 foreach ($depends_on[$gid] as $did) {
b8ff92b6 733 if (!in_array($did, $finalids)) {
734 $doupdate = false;
d14ae855 735 continue; // this item depends on something that is not yet in finals array
b8ff92b6 736 }
737 }
738
739 //oki - let's update, calculate or aggregate :-)
740 if ($doupdate) {
d14ae855 741 $result = $grade_items[$gid]->regrade_final_grades($userid);
f8e6e4db 742
743 if ($result === true) {
d14ae855 744 $grade_items[$gid]->regrading_finished();
fb0e3570 745 $grade_items[$gid]->check_locktime(); // do the locktime item locking
f8e6e4db 746 $count++;
b8ff92b6 747 $finalids[] = $gid;
fb0e3570 748
f8e6e4db 749 } else {
d14ae855 750 $grade_items[$gid]->force_regrading();
f8e6e4db 751 $errors[$gid] = $result;
b8ff92b6 752 }
753 }
754 }
755
756 if ($count == 0) {
eacd3700 757 $failed++;
758 } else {
759 $failed = 0;
760 }
761
762 if ($failed > 1) {
d14ae855 763 foreach($gids as $gid) {
764 if (in_array($gid, $finalids)) {
765 continue; // this one is ok
766 }
767 $grade_items[$gid]->force_regrading();
768 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
b8ff92b6 769 }
d14ae855 770 break; // oki, found error
b8ff92b6 771 }
772 }
773
774 if (count($errors) == 0) {
fb0e3570 775 if (empty($userid)) {
776 // do the locktime locking of grades, but only when doing full regrading
fed7cdc9 777 grade_grade::check_locktime_all($gids);
fb0e3570 778 }
b8ff92b6 779 return true;
780 } else {
781 return $errors;
782 }
a8995b34 783}
967f222f 784
de420c11 785/**
d185c3ee 786 * For backwards compatibility with old third-party modules, this function can
787 * be used to import all grades from activities with legacy grading.
739196ba 788 * @param int $courseid or null if all courses
967f222f 789 */
739196ba 790function grade_grab_legacy_grades($courseid=null) {
612607bd 791
ac9b0805 792 global $CFG;
967f222f 793
794 if (!$mods = get_list_of_plugins('mod') ) {
795 error('No modules installed!');
796 }
797
739196ba 798 if ($courseid) {
799 $course_sql = " AND cm.course=$courseid";
800 } else {
801 $course_sql = "";
802 }
803
967f222f 804 foreach ($mods as $mod) {
805
806 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
807 continue;
808 }
809
d185c3ee 810 if (!$module = get_record('modules', 'name', $mod)) {
811 //not installed
812 continue;
813 }
814
815 if (!$module->visible) {
816 //disabled module
817 continue;
818 }
819
820 $fullmod = $CFG->dirroot.'/mod/'.$mod;
967f222f 821
822 // include the module lib once
823 if (file_exists($fullmod.'/lib.php')) {
824 include_once($fullmod.'/lib.php');
de420c11 825 // look for modname_grades() function - old gradebook pulling function
826 // if present sync the grades with new grading system
967f222f 827 $gradefunc = $mod.'_grades';
de420c11 828 if (function_exists($gradefunc)) {
829
830 // get all instance of the activity
d185c3ee 831 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
832 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
739196ba 833 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
de420c11 834
835 if ($modinstances = get_records_sql($sql)) {
967f222f 836 foreach ($modinstances as $modinstance) {
d185c3ee 837 grade_update_mod_grades($modinstance);
967f222f 838 }
839 }
840 }
841 }
842 }
843}
844
ac9b0805 845/**
846 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
847 */
848function grade_grab_grades() {
849
850 global $CFG;
851
852 if (!$mods = get_list_of_plugins('mod') ) {
853 error('No modules installed!');
854 }
855
856 foreach ($mods as $mod) {
857
858 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
859 continue;
860 }
861
862 if (!$module = get_record('modules', 'name', $mod)) {
863 //not installed
864 continue;
865 }
866
867 if (!$module->visible) {
868 //disabled module
869 continue;
870 }
871
872 $fullmod = $CFG->dirroot.'/mod/'.$mod;
873
874 // include the module lib once
875 if (file_exists($fullmod.'/lib.php')) {
876 include_once($fullmod.'/lib.php');
877 // look for modname_grades() function - old gradebook pulling function
878 // if present sync the grades with new grading system
879 $gradefunc = $mod.'_update_grades';
880 if (function_exists($gradefunc)) {
881 $gradefunc();
882 }
883 }
884 }
885}
886
d185c3ee 887/**
888 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
889 * @param object $modinstance object with extra cmidnumber and modname property
890 * @return boolean success
891 */
2b0f65e2 892function grade_update_mod_grades($modinstance, $userid=0) {
d185c3ee 893 global $CFG;
894
895 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
896 if (!file_exists($fullmod.'/lib.php')) {
897 debugging('missing lib.php file in module');
898 return false;
899 }
900 include_once($fullmod.'/lib.php');
901
902 // does it use legacy grading?
903 $gradefunc = $modinstance->modname.'_grades';
904 $updategradesfunc = $modinstance->modname.'_update_grades';
905 $updateitemfunc = $modinstance->modname.'_grade_item_update';
906
907 if (function_exists($gradefunc)) {
2b0f65e2 908
909 // legacy module - not yet converted
d185c3ee 910 if ($oldgrades = $gradefunc($modinstance->id)) {
911
912 $grademax = $oldgrades->maxgrade;
913 $scaleid = NULL;
914 if (!is_numeric($grademax)) {
915 // scale name is provided as a string, try to find it
916 if (!$scale = get_record('scale', 'name', $grademax)) {
917 debugging('Incorrect scale name! name:'.$grademax);
918 return false;
919 }
920 $scaleid = $scale->id;
921 }
922
923 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
924 debugging('Can not get/create legacy grade item!');
925 return false;
926 }
927
928 $grades = array();
2b0f65e2 929 foreach ($oldgrades->grades as $uid=>$usergrade) {
930 if ($userid and $uid != $userid) {
931 continue;
932 }
d185c3ee 933 $grade = new object();
2b0f65e2 934 $grade->userid = $uid;
d185c3ee 935
936 if ($usergrade == '-') {
937 // no grade
ac9b0805 938 $grade->rawgrade = null;
d185c3ee 939
940 } else if ($scaleid) {
941 // scale in use, words used
942 $gradescale = explode(",", $scale->scale);
ac9b0805 943 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
d185c3ee 944
945 } else {
946 // good old numeric value
ac9b0805 947 $grade->rawgrade = $usergrade;
d185c3ee 948 }
949 $grades[] = $grade;
950 }
951
952 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
953 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
954 }
955
956 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
957 //new grading supported, force updating of grades
958 $updateitemfunc($modinstance);
2b0f65e2 959 $updategradesfunc($modinstance, $userid);
d185c3ee 960
961 } else {
2b0f65e2 962 // mudule does not support grading??
d185c3ee 963 }
964
965 return true;
966}
de420c11 967
968/**
d185c3ee 969 * Get and update/create grade item for legacy modules.
de420c11 970 */
971function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
972
973 // does it already exist?
42ff9ce6 974 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
de420c11 975 if (count($grade_items) > 1) {
d185c3ee 976 debugging('Multiple legacy grade_items found.');
de420c11 977 return false;
978 }
979
980 $grade_item = reset($grade_items);
de420c11 981
d185c3ee 982 if (is_null($grademax) and is_null($scaleid)) {
983 $grade_item->gradetype = GRADE_TYPE_NONE;
de420c11 984
d185c3ee 985 } else if ($scaleid) {
986 $grade_item->gradetype = GRADE_TYPE_SCALE;
987 $grade_item->scaleid = $scaleid;
97d608ba 988 $grade_item->grademin = 1;
de420c11 989
d185c3ee 990 } else {
97d608ba 991 $grade_item->gradetype = GRADE_TYPE_VALUE;
992 $grade_item->grademax = $grademax;
993 $grade_item->grademin = 0;
de420c11 994 }
995
d185c3ee 996 $grade_item->itemname = $modinstance->name;
997 $grade_item->idnumber = $modinstance->cmidnumber;
de420c11 998
d185c3ee 999 $grade_item->update();
de420c11 1000
1001 return $grade_item;
1002 }
612607bd 1003
de420c11 1004 // create new one
d185c3ee 1005 $params = array('courseid' =>$modinstance->course,
de420c11 1006 'itemtype' =>'mod',
1007 'itemmodule' =>$modinstance->modname,
1008 'iteminstance'=>$modinstance->id,
d185c3ee 1009 'itemnumber' =>0,
de420c11 1010 'itemname' =>$modinstance->name,
1011 'idnumber' =>$modinstance->cmidnumber);
1012
d185c3ee 1013 if (is_null($grademax) and is_null($scaleid)) {
1014 $params['gradetype'] = GRADE_TYPE_NONE;
1015
1016 } else if ($scaleid) {
612607bd 1017 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 1018 $params['scaleid'] = $scaleid;
b3ac6c3e 1019 $grade_item->grademin = 1;
de420c11 1020 } else {
612607bd 1021 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 1022 $params['grademax'] = $grademax;
1023 $params['grademin'] = 0;
1024 }
1025
f70152b7 1026 $grade_item = new grade_item($params);
1027 $grade_item->insert();
de420c11 1028
f70152b7 1029 return $grade_item;
de420c11 1030}
1031
b51ece5b 1032/**
1033 * Remove grade letters for given context
1034 * @param object $context
1035 */
1036function remove_grade_letters($context, $showfeedback) {
1037 $strdeleted = get_string('deleted');
1038
1039 delete_records('grade_letters', 'contextid', $context->id);
1040 if ($showfeedback) {
1041 notify($strdeleted.' - '.get_string('letters', 'grades'));
1042 }
1043}
f615fbab 1044/**
1045 * Remove all grade related course data - history is kept
1046 * @param int $courseid
6b5c722d 1047 * @param bool @showfeedback print feedback
f615fbab 1048 */
1049function remove_course_grades($courseid, $showfeedback) {
1050 $strdeleted = get_string('deleted');
1051
1052 $course_category = grade_category::fetch_course_category($courseid);
1053 $course_category->delete('coursedelete');
1054 if ($showfeedback) {
1055 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
1056 }
1057
1058 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
1059 foreach ($outcomes as $outcome) {
1060 $outcome->delete('coursedelete');
1061 }
1062 }
1063 delete_records('grade_outcomes_courses', 'courseid', $courseid);
1064 if ($showfeedback) {
1065 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
1066 }
1067
1068 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
1069 foreach ($scales as $scale) {
1070 $scale->delete('coursedelete');
1071 }
1072 }
1073 if ($showfeedback) {
1074 notify($strdeleted.' - '.get_string('scales'));
1075 }
b51ece5b 1076
1077 delete_records('grade_settings', 'courseid', $courseid);
1078 if ($showfeedback) {
1079 notify($strdeleted.' - '.get_string('settings', 'grades'));
1080 }
f615fbab 1081}
bfe7297e 1082
32b97bb2 1083/**
1084 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
1085 * @param int $steps The value between each level.
1086 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
1087 * @param int $lowest The lowest value to include
1088 * @param int $highest The highest value to include
1089 */
1090function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
1091 // TODO reject or implement
1092}
42ff9ce6 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
2650c51e 1135}
1136
60cf7430 1137?>