3 ///////////////////////////////////////////////////////////////////////////
4 // NOTICE OF COPYRIGHT //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
9 // Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
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. //
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: //
21 // http://www.gnu.org/copyleft/gpl.html //
23 ///////////////////////////////////////////////////////////////////////////
26 * Library of functions for gradebook - both public and internal
28 * @author Moodle HQ developers
30 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
34 require_once($CFG->libdir
. '/grade/constants.php');
36 require_once($CFG->libdir
. '/grade/grade_category.php');
37 require_once($CFG->libdir
. '/grade/grade_item.php');
38 require_once($CFG->libdir
. '/grade/grade_grade.php');
39 require_once($CFG->libdir
. '/grade/grade_scale.php');
40 require_once($CFG->libdir
. '/grade/grade_outcome.php');
42 /////////////////////////////////////////////////////////////////////
43 ///// Start of public API for communication with modules/blocks /////
44 /////////////////////////////////////////////////////////////////////
47 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
48 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
49 * or key means do not change existing.
51 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
52 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
54 * Manual, course or category items can not be updated by this function.
56 * @param string $source source of the grade such as 'mod/assignment'
57 * @param int $courseid id of course
58 * @param string $itemtype type of grade item - mod, block
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
62 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
63 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
65 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
68 // only following grade_item properties can be changed in this function
69 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
70 // list of 10,5 numeric fields
71 $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
73 // grade item identification
74 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
76 if (is_null($courseid) or is_null($itemtype)) {
77 debugging('Missing courseid or itemtype');
78 return GRADE_UPDATE_FAILED
;
81 if (!$grade_items = grade_item
::fetch_all($params)) {
85 } else if (count($grade_items) == 1){
86 $grade_item = reset($grade_items);
87 unset($grade_items); //release memory
90 debugging('Found more than one grade item');
91 return GRADE_UPDATE_MULTIPLE
;
94 if (!empty($itemdetails['deleted'])) {
96 if ($grade_item->delete($source)) {
97 return GRADE_UPDATE_OK
;
99 return GRADE_UPDATE_FAILED
;
102 return GRADE_UPDATE_OK
;
105 /// Create or update the grade_item if needed
109 $itemdetails = (array)$itemdetails;
111 // grademin and grademax ignored when scale specified
112 if (array_key_exists('scaleid', $itemdetails)) {
113 if ($itemdetails['scaleid']) {
114 unset($itemdetails['grademin']);
115 unset($itemdetails['grademax']);
119 foreach ($itemdetails as $k=>$v) {
120 if (!in_array($k, $allowed)) {
124 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE
) {
125 // no grade item needed!
126 return GRADE_UPDATE_OK
;
131 $grade_item = new grade_item($params);
132 $grade_item->insert();
135 if ($grade_item->is_locked()) {
136 // no notice() here, test returned value instead!
137 return GRADE_UPDATE_ITEM_LOCKED
;
141 $itemdetails = (array)$itemdetails;
143 foreach ($itemdetails as $k=>$v) {
144 if (!in_array($k, $allowed)) {
148 if (in_array($k, $floats)) {
149 if (grade_floats_different($grade_item->{$k}, $v)) {
150 $grade_item->{$k} = $v;
155 if ($grade_item->{$k} != $v) {
156 $grade_item->{$k} = $v;
162 $grade_item->update();
167 /// reset grades if requested
168 if (!empty($itemdetails['reset'])) {
169 $grade_item->delete_all_grades('reset');
170 return GRADE_UPDATE_OK
;
173 /// Some extra checks
174 // do we use grading?
175 if ($grade_item->gradetype
== GRADE_TYPE_NONE
) {
176 return GRADE_UPDATE_OK
;
179 // no grade submitted
180 if (empty($grades)) {
181 return GRADE_UPDATE_OK
;
184 /// Finally start processing of grades
185 if (is_object($grades)) {
186 $grades = array($grades->userid
=>$grades);
188 if (array_key_exists('userid', $grades)) {
189 $grades = array($grades['userid']=>$grades);
193 /// normalize and verify grade array
194 foreach($grades as $k=>$g) {
200 if (empty($g['userid']) or $k != $g['userid']) {
201 debugging('Incorrect grade array index, must be user id! Grade ignored.');
206 if (empty($grades)) {
207 return GRADE_UPDATE_FAILED
;
210 $count = count($grades);
214 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id AND userid = $uid";
216 } else if ($count < 200) {
217 $uids = implode(',', array_keys($grades));
218 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id AND userid IN ($uids)";
221 $sql = "SELECT * FROM {$CFG->prefix}grade_grades WHERE itemid = $grade_item->id";
224 $rs = get_recordset_sql($sql);
228 while (count($grades) > 0) {
232 while ($rs and !rs_EOF($rs)) {
233 if (!$gd = rs_fetch_next_record($rs)) {
236 $userid = $gd->userid
;
237 if (!isset($grades[$userid])) {
238 // this grade not requested, continue
241 // existing grade requested
242 $grade = $grades[$userid];
243 $grade_grade = new grade_grade($gd, false);
244 unset($grades[$userid]);
248 if (is_null($grade_grade)) {
249 if (count($grades) == 0) {
250 // no more grades to process
254 $grade = reset($grades);
255 $userid = $grade['userid'];
256 $grade_grade = new grade_grade(array('itemid'=>$grade_item->id
, 'userid'=>$userid), false);
257 $grade_grade->load_optional_fields(); // add feedback and info too
258 unset($grades[$userid]);
263 $feedbackformat = FORMAT_MOODLE
;
264 $usermodified = $USER->id
;
265 $datesubmitted = null;
268 if (array_key_exists('rawgrade', $grade)) {
269 $rawgrade = $grade['rawgrade'];
272 if (array_key_exists('feedback', $grade)) {
273 $feedback = $grade['feedback'];
276 if (array_key_exists('feedbackformat', $grade)) {
277 $feedbackformat = $grade['feedbackformat'];
280 if (array_key_exists('usermodified', $grade)) {
281 $usermodified = $grade['usermodified'];
284 if (array_key_exists('datesubmitted', $grade)) {
285 $datesubmitted = $grade['datesubmitted'];
288 if (array_key_exists('dategraded', $grade)) {
289 $dategraded = $grade['dategraded'];
292 // update or insert the grade
293 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted, $grade_grade)) {
303 return GRADE_UPDATE_OK
;
305 return GRADE_UPDATE_FAILED
;
310 * Updates outcomes of user
311 * Manual outcomes can not be updated.
313 * @param string $source source of the grade such as 'mod/assignment'
314 * @param int $courseid id of course
315 * @param string $itemtype 'mod', 'block'
316 * @param string $itemmodule 'forum, 'quiz', etc.
317 * @param int $iteminstance id of the item module
318 * @param int $userid ID of the graded user
319 * @param array $data array itemnumber=>outcomegrade
321 function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
322 if ($items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
323 foreach ($items as $item) {
324 if (!array_key_exists($item->itemnumber
, $data)) {
327 $grade = $data[$item->itemnumber
] < 1 ?
null : $data[$item->itemnumber
];
328 $item->update_final_grade($userid, $grade, $source);
334 * Returns grading information for given activity - optionally with users grades
335 * Manual, course or category items can not be queried.
337 * @param int $courseid id of course
338 * @param string $itemtype 'mod', 'block'
339 * @param string $itemmodule 'forum, 'quiz', etc.
340 * @param int $iteminstance id of the item module
341 * @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
342 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
344 function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
347 $return = new object();
348 $return->items
= array();
349 $return->outcomes
= array();
351 $course_item = grade_item
::fetch_course_item($courseid);
352 $needsupdate = array();
353 if ($course_item->needsupdate
) {
354 $result = grade_regrade_final_grades($courseid);
355 if ($result !== true) {
356 $needsupdate = array_keys($result);
360 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
361 foreach ($grade_items as $grade_item) {
362 $decimalpoints = null;
364 if (empty($grade_item->outcomeid
)) {
365 // prepare information about grade item
366 $item = new object();
367 $item->itemnumber
= $grade_item->itemnumber
;
368 $item->scaleid
= $grade_item->scaleid
;
369 $item->name
= $grade_item->get_name();
370 $item->grademin
= $grade_item->grademin
;
371 $item->grademax
= $grade_item->grademax
;
372 $item->gradepass
= $grade_item->gradepass
;
373 $item->locked
= $grade_item->is_locked();
374 $item->hidden
= $grade_item->is_hidden();
375 $item->grades
= array();
377 switch ($grade_item->gradetype
) {
378 case GRADE_TYPE_NONE
:
381 case GRADE_TYPE_VALUE
:
385 case GRADE_TYPE_TEXT
:
389 $item->gradepass
= 0;
393 if (empty($userid_or_ids)) {
396 } else if (is_array($userid_or_ids)) {
397 $userids = $userid_or_ids;
400 $userids = array($userid_or_ids);
404 $grade_grades = grade_grade
::fetch_users_grades($grade_item, $userids, true);
405 foreach ($userids as $userid) {
406 $grade_grades[$userid]->grade_item
=& $grade_item;
408 $grade = new object();
409 $grade->grade
= $grade_grades[$userid]->finalgrade
;
410 $grade->locked
= $grade_grades[$userid]->is_locked();
411 $grade->hidden
= $grade_grades[$userid]->is_hidden();
412 $grade->overridden
= $grade_grades[$userid]->overridden
;
413 $grade->feedback
= $grade_grades[$userid]->feedback
;
414 $grade->feedbackformat
= $grade_grades[$userid]->feedbackformat
;
415 $grade->usermodified
= $grade_grades[$userid]->usermodified
;
416 $grade->datesubmitted
= $grade_grades[$userid]->get_datesubmitted();
417 $grade->dategraded
= $grade_grades[$userid]->get_dategraded();
419 // create text representation of grade
420 if ($grade_item->gradetype
== GRADE_TYPE_TEXT
or $grade_item->gradetype
== GRADE_TYPE_NONE
) {
421 $grade->grade
= null;
422 $grade->str_grade
= '-';
423 $grade->str_long_grade
= $grade->str_grade
;
425 } else if (in_array($grade_item->id
, $needsupdate)) {
426 $grade->grade
= false;
427 $grade->str_grade
= get_string('error');
428 $grade->str_long_grade
= $grade->str_grade
;
430 } else if (is_null($grade->grade
)) {
431 $grade->str_grade
= '-';
432 $grade->str_long_grade
= $grade->str_grade
;
435 $grade->str_grade
= grade_format_gradevalue($grade->grade
, $grade_item);
436 if ($grade_item->gradetype
== GRADE_TYPE_SCALE
or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL
) {
437 $grade->str_long_grade
= $grade->str_grade
;
440 $a->grade
= $grade->str_grade
;
441 $a->max
= grade_format_gradevalue($grade_item->grademax
, $grade_item);
442 $grade->str_long_grade
= get_string('gradelong', 'grades', $a);
446 // create html representation of feedback
447 if (is_null($grade->feedback
)) {
448 $grade->str_feedback
= '';
450 $grade->str_feedback
= format_text($grade->feedback
, $grade->feedbackformat
);
453 $item->grades
[$userid] = $grade;
456 $return->items
[$grade_item->itemnumber
] = $item;
459 if (!$grade_outcome = grade_outcome
::fetch(array('id'=>$grade_item->outcomeid
))) {
460 debugging('Incorect outcomeid found');
465 $outcome = new object();
466 $outcome->itemnumber
= $grade_item->itemnumber
;
467 $outcome->scaleid
= $grade_outcome->scaleid
;
468 $outcome->name
= $grade_outcome->get_name();
469 $outcome->locked
= $grade_item->is_locked();
470 $outcome->hidden
= $grade_item->is_hidden();
472 if (empty($userid_or_ids)) {
474 } else if (is_array($userid_or_ids)) {
475 $userids = $userid_or_ids;
477 $userids = array($userid_or_ids);
481 $grade_grades = grade_grade
::fetch_users_grades($grade_item, $userids, true);
482 foreach ($userids as $userid) {
483 $grade_grades[$userid]->grade_item
=& $grade_item;
485 $grade = new object();
486 $grade->grade
= $grade_grades[$userid]->finalgrade
;
487 $grade->locked
= $grade_grades[$userid]->is_locked();
488 $grade->hidden
= $grade_grades[$userid]->is_hidden();
489 $grade->feedback
= $grade_grades[$userid]->feedback
;
490 $grade->feedbackformat
= $grade_grades[$userid]->feedbackformat
;
491 $grade->usermodified
= $grade_grades[$userid]->usermodified
;
493 // create text representation of grade
494 if (in_array($grade_item->id
, $needsupdate)) {
495 $grade->grade
= false;
496 $grade->str_grade
= get_string('error');
498 } else if (is_null($grade->grade
)) {
500 $grade->str_grade
= get_string('nooutcome', 'grades');
503 $grade->grade
= (int)$grade->grade
;
504 $scale = $grade_item->load_scale();
505 $grade->str_grade
= format_string($scale->scale_items
[(int)$grade->grade
-1]);
508 // create html representation of feedback
509 if (is_null($grade->feedback
)) {
510 $grade->str_feedback
= '';
512 $grade->str_feedback
= format_text($grade->feedback
, $grade->feedbackformat
);
515 $outcome->grades
[$userid] = $grade;
519 if (isset($return->outcomes
[$grade_item->itemnumber
])) {
520 // itemnumber duplicates - lets fix them!
521 $newnumber = $grade_item->itemnumber +
1;
522 while(grade_item
::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
525 $outcome->itemnumber
= $newnumber;
526 $grade_item->itemnumber
= $newnumber;
527 $grade_item->update('system');
530 $return->outcomes
[$grade_item->itemnumber
] = $outcome;
536 // sort results using itemnumbers
537 ksort($return->items
, SORT_NUMERIC
);
538 ksort($return->outcomes
, SORT_NUMERIC
);
543 ///////////////////////////////////////////////////////////////////
544 ///// End of public API for communication with modules/blocks /////
545 ///////////////////////////////////////////////////////////////////
549 ///////////////////////////////////////////////////////////////////
550 ///// Internal API: used by gradebook plugins and Moodle core /////
551 ///////////////////////////////////////////////////////////////////
554 * Returns course gradebook setting
555 * @param int $courseid
556 * @param string $name of setting, maybe null if reset only
557 * @param bool $resetcache force reset of internal static cache
558 * @return string value, NULL if no setting
560 function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
561 static $cache = array();
563 if ($resetcache or !array_key_exists($courseid, $cache)) {
564 $cache[$courseid] = array();
566 } else if (is_null($name)) {
569 } else if (array_key_exists($name, $cache[$courseid])) {
570 return $cache[$courseid][$name];
573 if (!$data = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
576 $result = $data->value
;
579 if (is_null($result)) {
583 $cache[$courseid][$name] = $result;
588 * Returns all course gradebook settings as object properties
589 * @param int $courseid
592 function grade_get_settings($courseid) {
593 $settings = new object();
594 $settings->id
= $courseid;
596 if ($records = get_records('grade_settings', 'courseid', $courseid)) {
597 foreach ($records as $record) {
598 $settings->{$record->name
} = $record->value
;
606 * Add/update course gradebook setting
607 * @param int $courseid
608 * @param string $name of setting
609 * @param string value, NULL means no setting==remove
612 function grade_set_setting($courseid, $name, $value) {
613 if (is_null($value)) {
614 delete_records('grade_settings', 'courseid', $courseid, 'name', addslashes($name));
616 } else if (!$existing = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
617 $data = new object();
618 $data->courseid
= $courseid;
619 $data->name
= addslashes($name);
620 $data->value
= addslashes($value);
621 insert_record('grade_settings', $data);
624 $data = new object();
625 $data->id
= $existing->id
;
626 $data->value
= addslashes($value);
627 update_record('grade_settings', $data);
630 grade_get_setting($courseid, null, null, true); // reset the cache
634 * Returns string representation of grade value
635 * @param float $value grade value
636 * @param object $grade_item - by reference to prevent scale reloading
637 * @param bool $localized use localised decimal separator
638 * @param int $displaytype type of display - GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
639 * @param int $decimalplaces number of decimal places when displaying float values
642 function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
643 if ($grade_item->gradetype
== GRADE_TYPE_NONE
or $grade_item->gradetype
== GRADE_TYPE_TEXT
) {
648 if (is_null($value)) {
652 if ($grade_item->gradetype
!= GRADE_TYPE_VALUE
and $grade_item->gradetype
!= GRADE_TYPE_SCALE
) {
657 if (is_null($displaytype)) {
658 $displaytype = $grade_item->get_displaytype();
661 if (is_null($decimals)) {
662 $decimals = $grade_item->get_decimals();
665 switch ($displaytype) {
666 case GRADE_DISPLAY_TYPE_REAL
:
667 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized);
669 case GRADE_DISPLAY_TYPE_PERCENTAGE
:
670 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized);
672 case GRADE_DISPLAY_TYPE_LETTER
:
673 return grade_format_gradevalue_letter($value, $grade_item);
675 case GRADE_DISPLAY_TYPE_REAL_PERCENTAGE
:
676 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
677 grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
679 case GRADE_DISPLAY_TYPE_REAL_LETTER
:
680 return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
681 grade_format_gradevalue_letter($value, $grade_item) . ')';
683 case GRADE_DISPLAY_TYPE_PERCENTAGE_REAL
:
684 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
685 grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
687 case GRADE_DISPLAY_TYPE_LETTER_REAL
:
688 return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
689 grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
691 case GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE
:
692 return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
693 grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
695 case GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER
:
696 return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
697 grade_format_gradevalue_letter($value, $grade_item) . ')';
703 function grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) {
704 if ($grade_item->gradetype
== GRADE_TYPE_SCALE
) {
705 if (!$scale = $grade_item->load_scale()) {
706 return get_string('error');
709 $value = $grade_item->bounded_grade($value);
710 return format_string($scale->scale_items
[$value-1]);
713 return format_float($value, $decimals, $localized);
717 function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) {
718 $min = $grade_item->grademin
;
719 $max = $grade_item->grademax
;
723 $value = $grade_item->bounded_grade($value);
724 $percentage = (($value-$min)*100)/($max-$min);
725 return format_float($percentage, $decimals, $localized).' %';
728 function grade_format_gradevalue_letter($value, $grade_item) {
729 $context = get_context_instance(CONTEXT_COURSE
, $grade_item->courseid
);
730 if (!$letters = grade_get_letters($context)) {
731 return ''; // no letters??
734 if (is_null($value)) {
738 $value = grade_grade
::standardise_score($value, $grade_item->grademin
, $grade_item->grademax
, 0, 100);
739 $value = bounded_number(0, $value, 100); // just in case
740 foreach ($letters as $boundary => $letter) {
741 if ($value >= $boundary) {
742 return format_string($letter);
745 return '-'; // no match? maybe '' would be more correct
750 * Returns grade options for gradebook category menu
751 * @param int $courseid
752 * @param bool $includenew include option for new category (-1)
753 * @return array of grade categories in course
755 function grade_get_categories_menu($courseid, $includenew=false) {
757 if (!$categories = grade_category
::fetch_all(array('courseid'=>$courseid))) {
758 //make sure course category exists
759 if (!grade_category
::fetch_course_category($courseid)) {
760 debugging('Can not create course grade category!');
763 $categories = grade_category
::fetch_all(array('courseid'=>$courseid));
765 foreach ($categories as $key=>$category) {
766 if ($category->is_course_category()) {
767 $result[$category->id
] = get_string('uncategorised', 'grades');
768 unset($categories[$key]);
772 $result[-1] = get_string('newcategory', 'grades');
775 foreach ($categories as $category) {
776 $cats[$category->id
] = $category->get_name();
778 asort($cats, SORT_LOCALE_STRING
);
780 return ($result+
$cats);
784 * Returns grade letters array used in context
785 * @param object $context object or null for defaults
786 * @return array of grade_boundary=>letter_string
788 function grade_get_letters($context=null) {
789 if (empty($context)) {
790 //default grading letters
791 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
794 static $cache = array();
796 if (array_key_exists($context->id
, $cache)) {
797 return $cache[$context->id
];
800 if (count($cache) > 100) {
801 $cache = array(); // cache size limit
806 $contexts = get_parent_contexts($context);
807 array_unshift($contexts, $context->id
);
809 foreach ($contexts as $ctxid) {
810 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
811 foreach ($records as $record) {
812 $letters[$record->lowerboundary
] = $record->letter
;
816 if (!empty($letters)) {
817 $cache[$context->id
] = $letters;
822 $letters = grade_get_letters(null);
823 $cache[$context->id
] = $letters;
829 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
830 * @param string idnumber string (with magic quotes)
831 * @param int $courseid - id numbers are course unique only
832 * @param object $cm used for course module idnumbers and items attached to modules
833 * @param object $gradeitem is item idnumber
834 * @return boolean true means idnumber ok
836 function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
837 if ($idnumber == '') {
838 //we allow empty idnumbers
842 // keep existing even when not unique
843 if ($cm and $cm->idnumber
== $idnumber) {
845 } else if ($grade_item and $grade_item->idnumber
== $idnumber) {
849 if (get_records_select('course_modules', "course = $courseid AND idnumber='$idnumber'")) {
853 if (get_records_select('grade_items', "courseid = $courseid AND idnumber='$idnumber'")) {
861 * Force final grade recalculation in all course items
862 * @param int $courseid
864 function grade_force_full_regrading($courseid) {
865 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
869 * Forces regrading of all site grades - usualy when chanign site setings
871 function grade_force_site_regrading() {
873 $sql = "UPDATE {$CFG->prefix}grade_items SET needsupdate=1";
874 execute_sql($sql, false);
878 * Updates all final grades in course.
880 * @param int $courseid
881 * @param int $userid if specified, try to do a quick regrading of grades of this user only
882 * @param object $updated_item the item in which
883 * @return boolean true if ok, array of errors if problems found (item id is used as key)
885 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
887 $course_item = grade_item
::fetch_course_item($courseid);
890 // one raw grade updated for one user
891 if (empty($updated_item)) {
892 error("updated_item_id can not be null!");
894 if ($course_item->needsupdate
) {
895 $updated_item->force_regrading();
896 return array($course_item->id
=>'Can not do fast regrading after updating of raw grades');
900 if (!$course_item->needsupdate
) {
906 $grade_items = grade_item
::fetch_all(array('courseid'=>$courseid));
907 $depends_on = array();
909 // first mark all category and calculated items as needing regrading
910 // this is slower, but 100% accurate
911 foreach ($grade_items as $gid=>$gitem) {
912 if (!empty($updated_item) and $updated_item->id
== $gid) {
913 $grade_items[$gid]->needsupdate
= 1;
915 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
916 $grade_items[$gid]->needsupdate
= 1;
919 // construct depends_on lookup array
920 $depends_on[$gid] = $grade_items[$gid]->depends_on();
925 $gids = array_keys($grade_items);
928 while (count($finalids) < count($gids)) { // work until all grades are final or error found
930 foreach ($gids as $gid) {
931 if (in_array($gid, $finalids)) {
932 continue; // already final
935 if (!$grade_items[$gid]->needsupdate
) {
936 $finalids[] = $gid; // we can make it final - does not need update
941 foreach ($depends_on[$gid] as $did) {
942 if (!in_array($did, $finalids)) {
944 continue; // this item depends on something that is not yet in finals array
948 //oki - let's update, calculate or aggregate :-)
950 $result = $grade_items[$gid]->regrade_final_grades($userid);
952 if ($result === true) {
953 $grade_items[$gid]->regrading_finished();
954 $grade_items[$gid]->check_locktime(); // do the locktime item locking
959 $grade_items[$gid]->force_regrading();
960 $errors[$gid] = $result;
972 foreach($gids as $gid) {
973 if (in_array($gid, $finalids)) {
974 continue; // this one is ok
976 $grade_items[$gid]->force_regrading();
977 $errors[$grade_items[$gid]->id
] = 'Probably circular reference or broken calculation formula'; // TODO: localize
979 break; // oki, found error
983 if (count($errors) == 0) {
984 if (empty($userid)) {
985 // do the locktime locking of grades, but only when doing full regrading
986 grade_grade
::check_locktime_all($gids);
995 * For backwards compatibility with old third-party modules, this function can
996 * be used to import all grades from activities with legacy grading.
997 * @param int $courseid
999 function grade_grab_legacy_grades($courseid) {
1002 if (!$mods = get_list_of_plugins('mod') ) {
1003 error('No modules installed!');
1006 foreach ($mods as $mod) {
1007 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
1011 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
1013 // include the module lib once
1014 if (file_exists($fullmod.'/lib.php')) {
1015 include_once($fullmod.'/lib.php');
1016 // look for modname_grades() function - old gradebook pulling function
1017 // if present sync the grades with new grading system
1018 $gradefunc = $mod.'_grades';
1019 if (function_exists($gradefunc)) {
1020 grade_grab_course_grades($courseid, $mod);
1027 * Refetches data from all course activities
1028 * @param int $courseid
1029 * @param string $modname
1032 function grade_grab_course_grades($courseid, $modname=null) {
1036 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
1037 FROM {$CFG->prefix}$modname a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
1038 WHERE m.name='$modname' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
1040 if ($modinstances = get_records_sql($sql)) {
1041 foreach ($modinstances as $modinstance) {
1042 grade_update_mod_grades($modinstance);
1048 if (!$mods = get_list_of_plugins('mod') ) {
1049 error('No modules installed!');
1052 foreach ($mods as $mod) {
1053 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
1057 $fullmod = $CFG->dirroot
.'/mod/'.$mod;
1059 // include the module lib once
1060 if (file_exists($fullmod.'/lib.php')) {
1061 // get all instance of the activity
1062 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
1063 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
1064 WHERE m.name='$mod' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
1066 if ($modinstances = get_records_sql($sql)) {
1067 foreach ($modinstances as $modinstance) {
1068 grade_update_mod_grades($modinstance);
1076 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
1077 * @param object $modinstance object with extra cmidnumber and modname property
1078 * @return boolean success
1080 function grade_update_mod_grades($modinstance, $userid=0) {
1083 $fullmod = $CFG->dirroot
.'/mod/'.$modinstance->modname
;
1084 if (!file_exists($fullmod.'/lib.php')) {
1085 debugging('missing lib.php file in module ' . $modinstance->modname
);
1088 include_once($fullmod.'/lib.php');
1090 // does it use legacy grading?
1091 $gradefunc = $modinstance->modname
.'_grades';
1092 $updategradesfunc = $modinstance->modname
.'_update_grades';
1093 $updateitemfunc = $modinstance->modname
.'_grade_item_update';
1095 if (function_exists($gradefunc)) {
1097 // legacy module - not yet converted
1098 if ($oldgrades = $gradefunc($modinstance->id
)) {
1100 $grademax = $oldgrades->maxgrade
;
1102 if (!is_numeric($grademax)) {
1103 // scale name is provided as a string, try to find it
1104 if (!$scale = get_record('scale', 'name', $grademax)) {
1105 debugging('Incorrect scale name! name:'.$grademax);
1108 $scaleid = $scale->id
;
1111 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
1112 debugging('Can not get/create legacy grade item!');
1116 if (!empty($oldgrades->grades
)) {
1119 foreach ($oldgrades->grades
as $uid=>$usergrade) {
1120 if ($userid and $uid != $userid) {
1123 $grade = new object();
1124 $grade->userid
= $uid;
1126 if ($usergrade == '-') {
1128 $grade->rawgrade
= null;
1130 } else if ($scaleid) {
1131 // scale in use, words used
1132 $gradescale = explode(",", $scale->scale
);
1133 $grade->rawgrade
= array_search($usergrade, $gradescale) +
1;
1136 // good old numeric value
1137 $grade->rawgrade
= $usergrade;
1139 $grades[$uid] = $grade;
1142 grade_update('legacygrab', $grade_item->courseid
, $grade_item->itemtype
, $grade_item->itemmodule
,
1143 $grade_item->iteminstance
, $grade_item->itemnumber
, $grades);
1147 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
1148 //new grading supported, force updating of grades
1149 $updateitemfunc($modinstance);
1150 $updategradesfunc($modinstance, $userid);
1153 // mudule does not support grading??
1160 * Returns list of currently used mods with legacy grading in course
1161 * @param $courseid int
1162 * @return array of modname=>modulenamestring mods with legacy grading
1164 function grade_get_legacy_modules($courseid) {
1167 if (!$mods = get_course_mods($courseid)) {
1172 foreach ($mods as $mod) {
1173 $modname = $mod->modname
;
1175 $modlib = "$CFG->dirroot/mod/$modname/lib.php";
1179 include_once($modlib);
1180 $gradefunc = $modname.'_grades';
1181 if (!function_exists($gradefunc)) {
1184 $legacy[$modname] = get_string('modulename', $modname);
1191 * Get and update/create grade item for legacy modules.
1193 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
1195 // does it already exist?
1196 if ($grade_items = grade_item
::fetch_all(array('courseid'=>$modinstance->course
, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname
, 'iteminstance'=>$modinstance->id
, 'itemnumber'=>0))) {
1197 if (count($grade_items) > 1) {
1198 debugging('Multiple legacy grade_items found.');
1202 $grade_item = reset($grade_items);
1204 if (is_null($grademax) and is_null($scaleid)) {
1205 $grade_item->gradetype
= GRADE_TYPE_NONE
;
1207 } else if ($scaleid) {
1208 $grade_item->gradetype
= GRADE_TYPE_SCALE
;
1209 $grade_item->scaleid
= $scaleid;
1210 $grade_item->grademin
= 1;
1213 $grade_item->gradetype
= GRADE_TYPE_VALUE
;
1214 $grade_item->grademax
= $grademax;
1215 $grade_item->grademin
= 0;
1218 $grade_item->itemname
= $modinstance->name
;
1219 $grade_item->idnumber
= $modinstance->cmidnumber
;
1221 $grade_item->update();
1227 $params = array('courseid' =>$modinstance->course
,
1229 'itemmodule' =>$modinstance->modname
,
1230 'iteminstance'=>$modinstance->id
,
1232 'itemname' =>$modinstance->name
,
1233 'idnumber' =>$modinstance->cmidnumber
);
1235 if (is_null($grademax) and is_null($scaleid)) {
1236 $params['gradetype'] = GRADE_TYPE_NONE
;
1238 } else if ($scaleid) {
1239 $params['gradetype'] = GRADE_TYPE_SCALE
;
1240 $params['scaleid'] = $scaleid;
1241 $grade_item->grademin
= 1;
1243 $params['gradetype'] = GRADE_TYPE_VALUE
;
1244 $params['grademax'] = $grademax;
1245 $params['grademin'] = 0;
1248 $grade_item = new grade_item($params);
1249 $grade_item->insert();
1255 * Remove grade letters for given context
1256 * @param object $context
1258 function remove_grade_letters($context, $showfeedback) {
1259 $strdeleted = get_string('deleted');
1261 delete_records('grade_letters', 'contextid', $context->id
);
1262 if ($showfeedback) {
1263 notify($strdeleted.' - '.get_string('letters', 'grades'));
1267 * Remove all grade related course data - history is kept
1268 * @param int $courseid
1269 * @param bool $showfeedback print feedback
1271 function remove_course_grades($courseid, $showfeedback) {
1272 $strdeleted = get_string('deleted');
1274 $course_category = grade_category
::fetch_course_category($courseid);
1275 $course_category->delete('coursedelete');
1276 if ($showfeedback) {
1277 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
1280 if ($outcomes = grade_outcome
::fetch_all(array('courseid'=>$courseid))) {
1281 foreach ($outcomes as $outcome) {
1282 $outcome->delete('coursedelete');
1285 delete_records('grade_outcomes_courses', 'courseid', $courseid);
1286 if ($showfeedback) {
1287 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
1290 if ($scales = grade_scale
::fetch_all(array('courseid'=>$courseid))) {
1291 foreach ($scales as $scale) {
1292 $scale->delete('coursedelete');
1295 if ($showfeedback) {
1296 notify($strdeleted.' - '.get_string('scales'));
1299 delete_records('grade_settings', 'courseid', $courseid);
1300 if ($showfeedback) {
1301 notify($strdeleted.' - '.get_string('settings', 'grades'));
1306 * Called when course category deleted - cleanup gradebook
1307 * @param int $categoryid course category id
1308 * @param int $newparentid empty means everything deleted, otherwise id of category where content moved
1309 * @param bool $showfeedback print feedback
1311 function grade_course_category_delete($categoryid, $newparentid, $showfeedback) {
1312 $context = get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1313 delete_records('grade_letters', 'contextid', $context->id
);
1317 * Does gradebook cleanup when module uninstalled.
1319 function grade_uninstalled_module($modname) {
1323 FROM {$CFG->prefix}grade_items
1324 WHERE itemtype='mod' AND itemmodule='$modname'";
1326 // go all items for this module and delete them including the grades
1327 if ($rs = get_recordset_sql($sql)) {
1328 while ($item = rs_fetch_next_record($rs)) {
1329 $grade_item = new grade_item($item, false);
1330 $grade_item->delete('moduninstall');
1339 function grade_cron() {
1345 FROM {$CFG->prefix}grade_items i
1346 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1347 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1349 // go through all courses that have proper final grades and lock them if needed
1350 if ($rs = get_recordset_sql($sql)) {
1351 while ($item = rs_fetch_next_record($rs)) {
1352 $grade_item = new grade_item($item, false);
1353 $grade_item->locked
= $now;
1354 $grade_item->update('locktime');
1359 $grade_inst = new grade_grade();
1360 $fields = 'g.'.implode(',g.', $grade_inst->required_fields
);
1362 $sql = "SELECT $fields
1363 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
1364 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1365 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
1367 // go through all courses that have proper final grades and lock them if needed
1368 if ($rs = get_recordset_sql($sql)) {
1369 while ($grade = rs_fetch_next_record($rs)) {
1370 $grade_grade = new grade_grade($grade, false);
1371 $grade_grade->locked
= $now;
1372 $grade_grade->update('locktime');
1377 //TODO: do not run this cleanup every cron invocation
1378 // cleanup history tables
1379 if (!empty($CFG->gradehistorylifetime
)) { // value in days
1380 $histlifetime = $now - ($CFG->gradehistorylifetime
* 3600 * 24);
1381 $tables = array('grade_outcomes_history', 'grade_categories_history', 'grade_items_history', 'grade_grades_history', 'scale_history');
1382 foreach ($tables as $table) {
1383 if (delete_records_select($table, "timemodified < $histlifetime")) {
1384 mtrace(" Deleted old grade history records from '$table'");
1391 * Resel all course grades
1392 * @param int $courseid
1395 function grade_course_reset($courseid) {
1397 // no recalculations
1398 grade_force_full_regrading($courseid);
1400 $grade_items = grade_item
::fetch_all(array('courseid'=>$courseid));
1401 foreach ($grade_items as $gid=>$grade_item) {
1402 $grade_item->delete_all_grades('reset');
1405 //refetch all grades
1406 grade_grab_course_grades($courseid);
1408 // recalculate all grades
1409 grade_regrade_final_grades($courseid);
1414 * Convert number to 5 decimalfloat, empty tring or null db compatible format
1415 * (we need this to decide if db value changed)
1416 * @param mixed number
1417 * @return mixed float or null
1419 function grade_floatval($number) {
1420 if (is_null($number) or $number === '') {
1423 // we must round to 5 digits to get the same precision as in 10,5 db fields
1424 // note: db rounding for 10,5 is different from php round() function
1425 return round($number, 5);
1429 * Compare two float numbers safely. Uses 5 decimals php precision. Nulls accepted too.
1430 * Used for skipping of db updates
1433 * @return true if different
1435 function grade_floats_different($f1, $f2) {
1436 // note: db rounding for 10,5 is different from php round() function
1437 return (grade_floatval($f1) !== grade_floatval($f2));