Automatic installer.php lang files by installer_builder (20070726)
[moodle-linuxchix.git] / lib / gradelib.php
blobb5d9ae1dc08b2b66d7e888e8f35a1ab1e4a1eb9b
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for gradebook
29 * @author Moodle HQ developers
30 * @version $Id$
31 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
32 * @package moodlecore
35 // category aggregation types
36 define('GRADE_AGGREGATE_MEAN_ALL', 0);
37 define('GRADE_AGGREGATE_MEAN_GRADED', 1);
38 define('GRADE_AGGREGATE_MEDIAN_ALL', 2);
39 define('GRADE_AGGREGATE_MEDIAN_GRADED', 3);
40 define('GRADE_AGGREGATE_MIN_ALL', 4);
41 define('GRADE_AGGREGATE_MIN_GRADED', 5);
42 define('GRADE_AGGREGATE_MAX_ALL', 6);
43 define('GRADE_AGGREGATE_MAX_GRADED', 7);
44 define('GRADE_AGGREGATE_MODE_ALL', 8);
45 define('GRADE_AGGREGATE_MODE_GRADED', 9);
46 define('GRADE_AGGREGATE_WEIGHTED_MEAN_ALL', 10);
47 define('GRADE_AGGREGATE_WEIGHTED_MEAN_GRADED', 11);
48 define('GRADE_AGGREGATE_EXTRACREDIT_MEAN_ALL', 12);
49 define('GRADE_AGGREGATE_EXTRACREDIT_MEAN_GRADED', 13);
51 // grade types
52 define('GRADE_TYPE_NONE', 0);
53 define('GRADE_TYPE_VALUE', 1);
54 define('GRADE_TYPE_SCALE', 2);
55 define('GRADE_TYPE_TEXT', 3);
57 // grade_update() return status
58 define('GRADE_UPDATE_OK', 0);
59 define('GRADE_UPDATE_FAILED', 1);
60 define('GRADE_UPDATE_MULTIPLE', 2);
61 define('GRADE_UPDATE_ITEM_DELETED', 3);
62 define('GRADE_UPDATE_ITEM_LOCKED', 4);
64 // Grate teables history tracking actions
65 define('GRADE_HISTORY_INSERT', 1);
66 define('GRADE_HISTORY_UPDATE', 2);
67 define('GRADE_HISTORY_DELETE', 3);
69 define('GRADE_REPORT_AGGREGATION_POSITION_LEFT', 0);
70 define('GRADE_REPORT_AGGREGATION_POSITION_RIGHT', 1);
71 define('GRADE_REPORT_AGGREGATION_VIEW_FULL', 0);
72 define('GRADE_REPORT_AGGREGATION_VIEW_COMPACT', 1);
73 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL', 0);
74 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE', 1);
75 define('GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER', 2);
76 define('GRADE_REPORT_PREFERENCE_DEFAULT', 'default');
77 define('GRADE_REPORT_PREFERENCE_INHERIT', 'inherit');
78 define('GRADE_REPORT_PREFERENCE_UNUSED', -1);
80 require_once($CFG->libdir . '/grade/grade_category.php');
81 require_once($CFG->libdir . '/grade/grade_item.php');
82 require_once($CFG->libdir . '/grade/grade_grade.php');
83 require_once($CFG->libdir . '/grade/grade_scale.php');
84 require_once($CFG->libdir . '/grade/grade_outcome.php');
85 require_once($CFG->libdir . '/grade/grade_grade_text.php');
87 /***** PUBLIC GRADE API *****/
89 /**
90 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
91 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
92 * or key means do not change existing.
94 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
95 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted'.
97 * @param string $source source of the grade such as 'mod/assignment', often used to prevent infinite loops when processing grade_updated events
98 * @param int $courseid id of course
99 * @param string $itemtype type of grade item - mod, block, gradecategory, calculated
100 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
101 * @param int $iteminstance instance it of graded subject
102 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
103 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating rgade_item definition only\
104 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
106 function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
107 global $USER;
109 // only following grade_item properties can be changed in this function
110 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted');
112 // grade item identification
113 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
115 if (is_null($courseid) or is_null($itemtype)) {
116 debugging('Missing courseid or itemtype');
117 return GRADE_UPDATE_FAILED;
120 if (!$grade_items = grade_item::fetch_all($params)) {
121 // create a new one
122 $grade_item = false;
124 } else if (count($grade_items) == 1){
125 $grade_item = reset($grade_items);
126 unset($grade_items); //release memory
128 } else {
129 debugging('Found more than one grade item');
130 return GRADE_UPDATE_MULTIPLE;
133 if (!empty($itemdetails['deleted'])) {
134 if ($grade_item) {
135 if ($grade_item->delete($source)) {
136 return GRADE_UPDATE_OK;
137 } else {
138 return GRADE_UPDATE_FAILED;
141 return GRADE_UPDATE_OK;
144 /// Create or update the grade_item if needed
145 if (!$grade_item) {
146 if ($itemdetails) {
147 $itemdetails = (array)$itemdetails;
149 // grademin and grademax ignored when scale specified
150 if (array_key_exists('scaleid', $itemdetails)) {
151 if ($itemdetails['scaleid']) {
152 unset($itemdetails['grademin']);
153 unset($itemdetails['grademax']);
157 foreach ($itemdetails as $k=>$v) {
158 if (!in_array($k, $allowed)) {
159 // ignore it
160 continue;
162 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
163 // no grade item needed!
164 return GRADE_UPDATE_OK;
166 $params[$k] = $v;
169 $grade_item = new grade_item($params);
170 $grade_item->insert();
172 } else {
173 if ($grade_item->is_locked()) {
174 debugging('Grading item is locked!');
175 return GRADE_UPDATE_ITEM_LOCKED;
178 if ($itemdetails) {
179 $itemdetails = (array)$itemdetails;
180 $update = false;
181 foreach ($itemdetails as $k=>$v) {
182 if (!in_array($k, $allowed)) {
183 // ignore it
184 continue;
186 if ($grade_item->{$k} != $v) {
187 $grade_item->{$k} = $v;
188 $update = true;
191 if ($update) {
192 $grade_item->update();
197 /// Some extra checks
198 // do we use grading?
199 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
200 return GRADE_UPDATE_OK;
203 // no grade submitted
204 if (empty($grades)) {
205 return GRADE_UPDATE_OK;
208 /// Finally start processing of grades
209 if (is_object($grades)) {
210 $grades = array($grades);
211 } else {
212 if (array_key_exists('userid', $grades)) {
213 $grades = array($grades);
217 $failed = false;
218 foreach ($grades as $grade) {
219 $grade = (array)$grade;
220 if (empty($grade['userid'])) {
221 $failed = true;
222 debugging('Invalid userid in grade submitted');
223 continue;
224 } else {
225 $userid = $grade['userid'];
228 $rawgrade = false;
229 $feedback = false;
230 $feedbackformat = FORMAT_MOODLE;
232 if (array_key_exists('rawgrade', $grade)) {
233 $rawgrade = $grade['rawgrade'];
236 if (array_key_exists('feedback', $grade)) {
237 $feedback = $grade['feedback'];
240 if (array_key_exists('feedbackformat', $grade)) {
241 $feedbackformat = $grade['feedbackformat'];
244 if (array_key_exists('usermodified', $grade)) {
245 $usermodified = $grade['usermodified'];
246 } else {
247 $usermodified = $USER->id;
250 // update or insert the grade
251 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, null, $feedback, $feedbackformat, $usermodified)) {
252 $failed = true;
256 if (!$failed) {
257 return GRADE_UPDATE_OK;
258 } else {
259 return GRADE_UPDATE_FAILED;
265 * Tells a module whether a grade (or grade_item if $userid is not given) is currently locked or not.
266 * This is a combination of the actual settings in the grade tables and a check on moodle/course:editgradeswhenlocked.
267 * If it's locked to the current use then the module can print a nice message or prevent editing in the module.
268 * If no $userid is given, the method will always return the grade_item's locked state.
269 * If a $userid is given, the method will first check the grade_item's locked state (the column). If it is locked,
270 * the method will return true no matter the locked state of the specific grade being checked. If unlocked, it will
271 * return the locked state of the specific grade.
273 * @param int $courseid id of course
274 * @param string $itemtype 'mod', 'blocks', 'import', 'calculated' etc
275 * @param string $itemmodule 'forum, 'quiz', 'csv' etc
276 * @param int $iteminstance id of the item module
277 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
278 * @param int $userid ID of the graded user
279 * @return boolean Whether the grade is locked or not
281 function grade_is_locked($courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $userid=NULL) {
283 if (!$grade_items = grade_item::fetch_all(compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber'))) {
284 return false;
286 } else if (count($grade_items) == 1){
287 $grade_item = reset($grade_items);
288 return $grade_item->is_locked($userid);
290 } else {
291 debugging('Found more than one grade item');
292 foreach ($grade_items as $grade_item) {
293 if ($grade_item->is_locked($userid)) {
294 return true;
297 return false;
301 /***** END OF PUBLIC API *****/
303 function grade_force_full_regrading($courseid) {
304 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
308 * Updates all final grades in course.
310 * @param int $courseid
311 * @param int $userid if specified, try to do a quick regrading of grades of this user only
312 * @param object $updated_item the item in which
313 * @return boolean true if ok, array of errors if problems found (item id is used as key)
315 function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
317 $course_item = grade_item::fetch_course_item($courseid);
319 if ($userid) {
320 // one raw grade updated for one user
321 if (empty($updated_item)) {
322 error("updated_item_id can not be null!");
324 if ($course_item->needsupdate) {
325 $updated_item->force_regrading();
326 return 'Can not do fast regrading after updating of raw grades';
329 } else {
330 if (!$course_item->needsupdate) {
331 // nothing to do :-)
332 return true;
336 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
337 $depends_on = array();
339 // first mark all category and calculated items as needing regrading
340 // this is slower, but 100% accurate - this function is called only when there is
341 // a change in grading setup, update of individual grade does not trigger this function
342 foreach ($grade_items as $gid=>$gitem) {
343 if (!empty($updated_item) and $updated_item->id == $gid) {
344 $grade_items[$gid]->needsupdate = 1;
346 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
347 $grade_items[$gid]->needsupdate = 1;
350 // construct depends_on lookup array
351 $depends_on[$gid] = $grade_items[$gid]->depends_on();
354 $errors = array();
355 $finalids = array();
356 $gids = array_keys($grade_items);
357 $failed = 0;
359 while (count($finalids) < count($gids)) { // work until all grades are final or error found
360 $count = 0;
361 foreach ($gids as $gid) {
362 if (in_array($gid, $finalids)) {
363 continue; // already final
366 if (!$grade_items[$gid]->needsupdate) {
367 $finalids[] = $gid; // we can make it final - does not need update
368 continue;
371 $doupdate = true;
372 foreach ($depends_on[$gid] as $did) {
373 if (!in_array($did, $finalids)) {
374 $doupdate = false;
375 continue; // this item depends on something that is not yet in finals array
379 //oki - let's update, calculate or aggregate :-)
380 if ($doupdate) {
381 $result = $grade_items[$gid]->regrade_final_grades($userid);
383 if ($result === true) {
384 $grade_items[$gid]->regrading_finished();
385 $count++;
386 $finalids[] = $gid;
387 } else {
388 $grade_items[$gid]->force_regrading();
389 $errors[$gid] = $result;
394 if ($count == 0) {
395 $failed++;
396 } else {
397 $failed = 0;
400 if ($failed > 1) {
401 foreach($gids as $gid) {
402 if (in_array($gid, $finalids)) {
403 continue; // this one is ok
405 $grade_items[$gid]->force_regrading();
406 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
408 break; // oki, found error
412 if (count($errors) == 0) {
413 return true;
414 } else {
415 return $errors;
420 * For backwards compatibility with old third-party modules, this function can
421 * be used to import all grades from activities with legacy grading.
422 * @param int $courseid or null if all courses
424 function grade_grab_legacy_grades($courseid=null) {
426 global $CFG;
428 if (!$mods = get_list_of_plugins('mod') ) {
429 error('No modules installed!');
432 if ($courseid) {
433 $course_sql = " AND cm.course=$courseid";
434 } else {
435 $course_sql = "";
438 foreach ($mods as $mod) {
440 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
441 continue;
444 if (!$module = get_record('modules', 'name', $mod)) {
445 //not installed
446 continue;
449 if (!$module->visible) {
450 //disabled module
451 continue;
454 $fullmod = $CFG->dirroot.'/mod/'.$mod;
456 // include the module lib once
457 if (file_exists($fullmod.'/lib.php')) {
458 include_once($fullmod.'/lib.php');
459 // look for modname_grades() function - old gradebook pulling function
460 // if present sync the grades with new grading system
461 $gradefunc = $mod.'_grades';
462 if (function_exists($gradefunc)) {
464 // get all instance of the activity
465 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
466 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
467 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
469 if ($modinstances = get_records_sql($sql)) {
470 foreach ($modinstances as $modinstance) {
471 grade_update_mod_grades($modinstance);
480 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
482 function grade_grab_grades() {
484 global $CFG;
486 if (!$mods = get_list_of_plugins('mod') ) {
487 error('No modules installed!');
490 foreach ($mods as $mod) {
492 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
493 continue;
496 if (!$module = get_record('modules', 'name', $mod)) {
497 //not installed
498 continue;
501 if (!$module->visible) {
502 //disabled module
503 continue;
506 $fullmod = $CFG->dirroot.'/mod/'.$mod;
508 // include the module lib once
509 if (file_exists($fullmod.'/lib.php')) {
510 include_once($fullmod.'/lib.php');
511 // look for modname_grades() function - old gradebook pulling function
512 // if present sync the grades with new grading system
513 $gradefunc = $mod.'_update_grades';
514 if (function_exists($gradefunc)) {
515 $gradefunc();
522 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
523 * @param object $modinstance object with extra cmidnumber and modname property
524 * @return boolean success
526 function grade_update_mod_grades($modinstance) {
527 global $CFG;
529 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
530 if (!file_exists($fullmod.'/lib.php')) {
531 debugging('missing lib.php file in module');
532 return false;
534 include_once($fullmod.'/lib.php');
536 // does it use legacy grading?
537 $gradefunc = $modinstance->modname.'_grades';
538 $updategradesfunc = $modinstance->modname.'_update_grades';
539 $updateitemfunc = $modinstance->modname.'_grade_item_update';
541 if (function_exists($gradefunc)) {
542 if ($oldgrades = $gradefunc($modinstance->id)) {
544 $grademax = $oldgrades->maxgrade;
545 $scaleid = NULL;
546 if (!is_numeric($grademax)) {
547 // scale name is provided as a string, try to find it
548 if (!$scale = get_record('scale', 'name', $grademax)) {
549 debugging('Incorrect scale name! name:'.$grademax);
550 return false;
552 $scaleid = $scale->id;
555 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
556 debugging('Can not get/create legacy grade item!');
557 return false;
560 $grades = array();
561 foreach ($oldgrades->grades as $userid=>$usergrade) {
562 $grade = new object();
563 $grade->userid = $userid;
565 if ($usergrade == '-') {
566 // no grade
567 $grade->rawgrade = null;
569 } else if ($scaleid) {
570 // scale in use, words used
571 $gradescale = explode(",", $scale->scale);
572 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
574 } else {
575 // good old numeric value
576 $grade->rawgrade = $usergrade;
578 $grades[] = $grade;
581 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
582 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
585 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
586 //new grading supported, force updating of grades
587 $updateitemfunc($modinstance);
588 $updategradesfunc($modinstance);
590 } else {
591 // mudule does not support grading
594 return true;
598 * Get and update/create grade item for legacy modules.
600 function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
602 // does it already exist?
603 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
604 if (count($grade_items) > 1) {
605 debugging('Multiple legacy grade_items found.');
606 return false;
609 $grade_item = reset($grade_items);
611 if (is_null($grademax) and is_null($scaleid)) {
612 $grade_item->gradetype = GRADE_TYPE_NONE;
614 } else if ($scaleid) {
615 $grade_item->gradetype = GRADE_TYPE_SCALE;
616 $grade_item->scaleid = $scaleid;
617 $grade_item->grademin = 1;
619 } else {
620 $grade_item->gradetype = GRADE_TYPE_VALUE;
621 $grade_item->grademax = $grademax;
622 $grade_item->grademin = 0;
625 $grade_item->itemname = $modinstance->name;
626 $grade_item->idnumber = $modinstance->cmidnumber;
628 $grade_item->update();
630 return $grade_item;
633 // create new one
634 $params = array('courseid' =>$modinstance->course,
635 'itemtype' =>'mod',
636 'itemmodule' =>$modinstance->modname,
637 'iteminstance'=>$modinstance->id,
638 'itemnumber' =>0,
639 'itemname' =>$modinstance->name,
640 'idnumber' =>$modinstance->cmidnumber);
642 if (is_null($grademax) and is_null($scaleid)) {
643 $params['gradetype'] = GRADE_TYPE_NONE;
645 } else if ($scaleid) {
646 $params['gradetype'] = GRADE_TYPE_SCALE;
647 $params['scaleid'] = $scaleid;
648 $grade_item->grademin = 1;
649 } else {
650 $params['gradetype'] = GRADE_TYPE_VALUE;
651 $params['grademax'] = $grademax;
652 $params['grademin'] = 0;
655 $grade_item = new grade_item($params);
656 $grade_item->insert();
658 return $grade_item;
663 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
664 * @param int $steps The value between each level.
665 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
666 * @param int $lowest The lowest value to include
667 * @param int $highest The highest value to include
669 function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
670 // TODO reject or implement