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