adding a fieldset
[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',
e648f890 50 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted'.
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
e648f890 67 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted');
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 {
337 switch ($grade_item->gradetype) {
338 case GRADE_TYPE_VALUE:
a3fbd494 339 if (!isset($decimalpoints)) {
340 require_once($CFG->dirroot.'/grade/report/user/lib.php');//TODO: which setting to use?
341 $decimalpoints = grade_report_user::get_pref('decimalpoints', $grade_item->id);
342 }
343 $grade->str_grade = format_float($grade->grade, $decimalpoints);
fcac8e51 344 break;
345
346 case GRADE_TYPE_SCALE:
347 $scale = $grade_item->load_scale();
a3fbd494 348 $grade->grade = (int)bounded_number($item->grademin, $grade->grade, $item->grademax);
fcac8e51 349 $grade->str_grade = format_string($scale->scale_items[$grade->grade-1]);
350 break;
351
352 case GRADE_TYPE_TEXT:
353 default:
354 $grade->str_grade = '';
355 }
356 }
357
358 // create html representation of feedback
359 if (is_null($grade->feedback)) {
360 $grade->str_feedback = '';
361 } else {
362 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
363 }
364
365 $item->grades[$userid] = $grade;
366 }
367 }
368 $return->items[$grade_item->itemnumber] = $item;
369
6b5c722d 370 } else {
fcac8e51 371 if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
372 debugging('Incorect outcomeid found');
373 continue;
374 }
375
376 // outcome info
377 $outcome = new object();
378 $outcome->itemnumber = $grade_item->itemnumber;
379 $outcome->scaleid = $grade_outcome->scaleid;
380 $outcome->name = $grade_outcome->get_name();
381 $outcome->locked = $grade_item->is_locked();
382 $outcome->hidden = $grade_item->is_hidden();
383
384 if (empty($userid_or_ids)) {
385 $userids = array();
386 } else if (is_array($userid_or_ids)) {
387 $userids = $userid_or_ids;
388 } else {
389 $userids = array($userid_or_ids);
390 }
6b5c722d 391
fcac8e51 392 if ($userids) {
393 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
394 foreach ($userids as $userid) {
395 $grade_grades[$userid]->grade_item =& $grade_item;
396
397 $grade = new object();
398 $grade->grade = $grade_grades[$userid]->finalgrade;
399 $grade->locked = $grade_grades[$userid]->is_locked();
400 $grade->hidden = $grade_grades[$userid]->is_hidden();
401 $grade->feedback = $grade_grades[$userid]->feedback;
402 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
a3fbd494 403 $grade->usermodified = $grade_grades[$userid]->usermodified;
fcac8e51 404
405 // create text representation of grade
406 if (in_array($grade_item->id, $needsupdate)) {
407 $grade->grade = false;
408 $grade->str_grade = get_string('error');
409
410 } else if (is_null($grade->grade)) {
411 $grade->grade = 0;
412 $grade->str_grade = get_string('nooutcome', 'grades');
413
414 } else {
415 $grade->grade = (int)$grade->grade;
416 $scale = $grade_item->load_scale();
417 $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
418 }
419
420 // create html representation of feedback
421 if (is_null($grade->feedback)) {
422 $grade->str_feedback = '';
423 } else {
424 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
425 }
426
427 $outcome->grades[$userid] = $grade;
428 }
429 }
430 $return->outcomes[$grade_item->itemnumber] = $outcome;
431
432 }
6b5c722d 433 }
434 }
435
fcac8e51 436 // sort results using itemnumbers
437 ksort($return->items, SORT_NUMERIC);
438 ksort($return->outcomes, SORT_NUMERIC);
439
440 return $return;
6b5c722d 441}
442
612607bd 443/***** END OF PUBLIC API *****/
444
60243313 445
446/**
2c5e52e2 447 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
60243313 448 * @param string idnumber string (with magic quotes)
449 * @param object $cm used for course module idnumbers and items attached to modules
450 * @param object $gradeitem is item idnumber
451 * @return boolean true means idnumber ok
452 */
453function grade_verify_idnumber($idnumber, $grade_item=null, $cm=null) {
454 if ($idnumber == '') {
455 //we allow empty idnumbers
456 return true;
457 }
458
459 // keep existing even when not unique
460 if ($cm and $cm->idnumber == $idnumber) {
461 return true;
462 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
463 return true;
464 }
465
466 if (get_records('course_modules', 'idnumber', $idnumber)) {
467 return false;
468 }
469
470 if (get_records('grade_items', 'idnumber', $idnumber)) {
471 return false;
472 }
473
474 return true;
475}
476
477/**
478 * Force final grade recalculation in all course items
479 * @param int $courseid
480 */
f8e6e4db 481function grade_force_full_regrading($courseid) {
482 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
483}
34e67f76 484
5834dcdb 485/**
ac9b0805 486 * Updates all final grades in course.
a8995b34 487 *
488 * @param int $courseid
f8e6e4db 489 * @param int $userid if specified, try to do a quick regrading of grades of this user only
490 * @param object $updated_item the item in which
491 * @return boolean true if ok, array of errors if problems found (item id is used as key)
a8995b34 492 */
c86caae7 493function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
b8ff92b6 494
514a3467 495 $course_item = grade_item::fetch_course_item($courseid);
f04873a9 496
f8e6e4db 497 if ($userid) {
498 // one raw grade updated for one user
499 if (empty($updated_item)) {
500 error("updated_item_id can not be null!");
501 }
502 if ($course_item->needsupdate) {
503 $updated_item->force_regrading();
504 return 'Can not do fast regrading after updating of raw grades';
a8995b34 505 }
772ddfbf 506
f8e6e4db 507 } else {
508 if (!$course_item->needsupdate) {
509 // nothing to do :-)
b8ff92b6 510 return true;
b8ff92b6 511 }
a8995b34 512 }
513
f8e6e4db 514 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
515 $depends_on = array();
516
517 // first mark all category and calculated items as needing regrading
fb0e3570 518 // this is slower, but 100% accurate
f8e6e4db 519 foreach ($grade_items as $gid=>$gitem) {
fb46b5b6 520 if (!empty($updated_item) and $updated_item->id == $gid) {
f8e6e4db 521 $grade_items[$gid]->needsupdate = 1;
522
eacd3700 523 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
f8e6e4db 524 $grade_items[$gid]->needsupdate = 1;
525 }
2e53372c 526
f8e6e4db 527 // construct depends_on lookup array
528 $depends_on[$gid] = $grade_items[$gid]->depends_on();
529 }
2e53372c 530
d14ae855 531 $errors = array();
b8ff92b6 532 $finalids = array();
d14ae855 533 $gids = array_keys($grade_items);
eacd3700 534 $failed = 0;
d14ae855 535
536 while (count($finalids) < count($gids)) { // work until all grades are final or error found
537 $count = 0;
538 foreach ($gids as $gid) {
539 if (in_array($gid, $finalids)) {
540 continue; // already final
541 }
542
543 if (!$grade_items[$gid]->needsupdate) {
544 $finalids[] = $gid; // we can make it final - does not need update
b8ff92b6 545 continue;
546 }
547
b8ff92b6 548 $doupdate = true;
f8e6e4db 549 foreach ($depends_on[$gid] as $did) {
b8ff92b6 550 if (!in_array($did, $finalids)) {
551 $doupdate = false;
d14ae855 552 continue; // this item depends on something that is not yet in finals array
b8ff92b6 553 }
554 }
555
556 //oki - let's update, calculate or aggregate :-)
557 if ($doupdate) {
d14ae855 558 $result = $grade_items[$gid]->regrade_final_grades($userid);
f8e6e4db 559
560 if ($result === true) {
d14ae855 561 $grade_items[$gid]->regrading_finished();
fb0e3570 562 $grade_items[$gid]->check_locktime(); // do the locktime item locking
f8e6e4db 563 $count++;
b8ff92b6 564 $finalids[] = $gid;
fb0e3570 565
f8e6e4db 566 } else {
d14ae855 567 $grade_items[$gid]->force_regrading();
f8e6e4db 568 $errors[$gid] = $result;
b8ff92b6 569 }
570 }
571 }
572
573 if ($count == 0) {
eacd3700 574 $failed++;
575 } else {
576 $failed = 0;
577 }
578
579 if ($failed > 1) {
d14ae855 580 foreach($gids as $gid) {
581 if (in_array($gid, $finalids)) {
582 continue; // this one is ok
583 }
584 $grade_items[$gid]->force_regrading();
585 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
b8ff92b6 586 }
d14ae855 587 break; // oki, found error
b8ff92b6 588 }
589 }
590
591 if (count($errors) == 0) {
fb0e3570 592 if (empty($userid)) {
593 // do the locktime locking of grades, but only when doing full regrading
fed7cdc9 594 grade_grade::check_locktime_all($gids);
fb0e3570 595 }
b8ff92b6 596 return true;
597 } else {
598 return $errors;
599 }
a8995b34 600}
967f222f 601
de420c11 602/**
d185c3ee 603 * For backwards compatibility with old third-party modules, this function can
604 * be used to import all grades from activities with legacy grading.
739196ba 605 * @param int $courseid or null if all courses
967f222f 606 */
739196ba 607function grade_grab_legacy_grades($courseid=null) {
612607bd 608
ac9b0805 609 global $CFG;
967f222f 610
611 if (!$mods = get_list_of_plugins('mod') ) {
612 error('No modules installed!');
613 }
614
739196ba 615 if ($courseid) {
616 $course_sql = " AND cm.course=$courseid";
617 } else {
618 $course_sql = "";
619 }
620
967f222f 621 foreach ($mods as $mod) {
622
623 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
624 continue;
625 }
626
d185c3ee 627 if (!$module = get_record('modules', 'name', $mod)) {
628 //not installed
629 continue;
630 }
631
632 if (!$module->visible) {
633 //disabled module
634 continue;
635 }
636
637 $fullmod = $CFG->dirroot.'/mod/'.$mod;
967f222f 638
639 // include the module lib once
640 if (file_exists($fullmod.'/lib.php')) {
641 include_once($fullmod.'/lib.php');
de420c11 642 // look for modname_grades() function - old gradebook pulling function
643 // if present sync the grades with new grading system
967f222f 644 $gradefunc = $mod.'_grades';
de420c11 645 if (function_exists($gradefunc)) {
646
647 // get all instance of the activity
d185c3ee 648 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
649 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
739196ba 650 WHERE m.name='$mod' AND m.id=cm.module AND cm.instance=a.id $course_sql";
de420c11 651
652 if ($modinstances = get_records_sql($sql)) {
967f222f 653 foreach ($modinstances as $modinstance) {
d185c3ee 654 grade_update_mod_grades($modinstance);
967f222f 655 }
656 }
657 }
658 }
659 }
660}
661
ac9b0805 662/**
663 * For testing purposes mainly, reloads grades from all non legacy modules into gradebook.
664 */
665function grade_grab_grades() {
666
667 global $CFG;
668
669 if (!$mods = get_list_of_plugins('mod') ) {
670 error('No modules installed!');
671 }
672
673 foreach ($mods as $mod) {
674
675 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
676 continue;
677 }
678
679 if (!$module = get_record('modules', 'name', $mod)) {
680 //not installed
681 continue;
682 }
683
684 if (!$module->visible) {
685 //disabled module
686 continue;
687 }
688
689 $fullmod = $CFG->dirroot.'/mod/'.$mod;
690
691 // include the module lib once
692 if (file_exists($fullmod.'/lib.php')) {
693 include_once($fullmod.'/lib.php');
694 // look for modname_grades() function - old gradebook pulling function
695 // if present sync the grades with new grading system
696 $gradefunc = $mod.'_update_grades';
697 if (function_exists($gradefunc)) {
698 $gradefunc();
699 }
700 }
701 }
702}
703
d185c3ee 704/**
705 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
706 * @param object $modinstance object with extra cmidnumber and modname property
707 * @return boolean success
708 */
2b0f65e2 709function grade_update_mod_grades($modinstance, $userid=0) {
d185c3ee 710 global $CFG;
711
712 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
713 if (!file_exists($fullmod.'/lib.php')) {
714 debugging('missing lib.php file in module');
715 return false;
716 }
717 include_once($fullmod.'/lib.php');
718
719 // does it use legacy grading?
720 $gradefunc = $modinstance->modname.'_grades';
721 $updategradesfunc = $modinstance->modname.'_update_grades';
722 $updateitemfunc = $modinstance->modname.'_grade_item_update';
723
724 if (function_exists($gradefunc)) {
2b0f65e2 725
726 // legacy module - not yet converted
d185c3ee 727 if ($oldgrades = $gradefunc($modinstance->id)) {
728
729 $grademax = $oldgrades->maxgrade;
730 $scaleid = NULL;
731 if (!is_numeric($grademax)) {
732 // scale name is provided as a string, try to find it
733 if (!$scale = get_record('scale', 'name', $grademax)) {
734 debugging('Incorrect scale name! name:'.$grademax);
735 return false;
736 }
737 $scaleid = $scale->id;
738 }
739
740 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
741 debugging('Can not get/create legacy grade item!');
742 return false;
743 }
744
745 $grades = array();
2b0f65e2 746 foreach ($oldgrades->grades as $uid=>$usergrade) {
747 if ($userid and $uid != $userid) {
748 continue;
749 }
d185c3ee 750 $grade = new object();
2b0f65e2 751 $grade->userid = $uid;
d185c3ee 752
753 if ($usergrade == '-') {
754 // no grade
ac9b0805 755 $grade->rawgrade = null;
d185c3ee 756
757 } else if ($scaleid) {
758 // scale in use, words used
759 $gradescale = explode(",", $scale->scale);
ac9b0805 760 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
d185c3ee 761
762 } else {
763 // good old numeric value
ac9b0805 764 $grade->rawgrade = $usergrade;
d185c3ee 765 }
766 $grades[] = $grade;
767 }
768
769 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
770 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
771 }
772
773 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
774 //new grading supported, force updating of grades
775 $updateitemfunc($modinstance);
2b0f65e2 776 $updategradesfunc($modinstance, $userid);
d185c3ee 777
778 } else {
2b0f65e2 779 // mudule does not support grading??
d185c3ee 780 }
781
782 return true;
783}
de420c11 784
785/**
d185c3ee 786 * Get and update/create grade item for legacy modules.
de420c11 787 */
788function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
789
790 // does it already exist?
42ff9ce6 791 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
de420c11 792 if (count($grade_items) > 1) {
d185c3ee 793 debugging('Multiple legacy grade_items found.');
de420c11 794 return false;
795 }
796
797 $grade_item = reset($grade_items);
de420c11 798
d185c3ee 799 if (is_null($grademax) and is_null($scaleid)) {
800 $grade_item->gradetype = GRADE_TYPE_NONE;
de420c11 801
d185c3ee 802 } else if ($scaleid) {
803 $grade_item->gradetype = GRADE_TYPE_SCALE;
804 $grade_item->scaleid = $scaleid;
97d608ba 805 $grade_item->grademin = 1;
de420c11 806
d185c3ee 807 } else {
97d608ba 808 $grade_item->gradetype = GRADE_TYPE_VALUE;
809 $grade_item->grademax = $grademax;
810 $grade_item->grademin = 0;
de420c11 811 }
812
d185c3ee 813 $grade_item->itemname = $modinstance->name;
814 $grade_item->idnumber = $modinstance->cmidnumber;
de420c11 815
d185c3ee 816 $grade_item->update();
de420c11 817
818 return $grade_item;
819 }
612607bd 820
de420c11 821 // create new one
d185c3ee 822 $params = array('courseid' =>$modinstance->course,
de420c11 823 'itemtype' =>'mod',
824 'itemmodule' =>$modinstance->modname,
825 'iteminstance'=>$modinstance->id,
d185c3ee 826 'itemnumber' =>0,
de420c11 827 'itemname' =>$modinstance->name,
828 'idnumber' =>$modinstance->cmidnumber);
829
d185c3ee 830 if (is_null($grademax) and is_null($scaleid)) {
831 $params['gradetype'] = GRADE_TYPE_NONE;
832
833 } else if ($scaleid) {
612607bd 834 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 835 $params['scaleid'] = $scaleid;
b3ac6c3e 836 $grade_item->grademin = 1;
de420c11 837 } else {
612607bd 838 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 839 $params['grademax'] = $grademax;
840 $params['grademin'] = 0;
841 }
842
f70152b7 843 $grade_item = new grade_item($params);
844 $grade_item->insert();
de420c11 845
f70152b7 846 return $grade_item;
de420c11 847}
848
f615fbab 849/**
850 * Remove all grade related course data - history is kept
851 * @param int $courseid
6b5c722d 852 * @param bool @showfeedback print feedback
f615fbab 853 */
854function remove_course_grades($courseid, $showfeedback) {
855 $strdeleted = get_string('deleted');
856
857 $course_category = grade_category::fetch_course_category($courseid);
858 $course_category->delete('coursedelete');
859 if ($showfeedback) {
860 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
861 }
862
863 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
864 foreach ($outcomes as $outcome) {
865 $outcome->delete('coursedelete');
866 }
867 }
868 delete_records('grade_outcomes_courses', 'courseid', $courseid);
869 if ($showfeedback) {
870 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
871 }
872
873 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
874 foreach ($scales as $scale) {
875 $scale->delete('coursedelete');
876 }
877 }
878 if ($showfeedback) {
879 notify($strdeleted.' - '.get_string('scales'));
880 }
f615fbab 881}
bfe7297e 882
32b97bb2 883/**
884 * Builds an array of percentages indexed by integers for the purpose of building a select drop-down element.
885 * @param int $steps The value between each level.
886 * @param string $order 'asc' for 0-100 and 'desc' for 100-0
887 * @param int $lowest The lowest value to include
888 * @param int $highest The highest value to include
889 */
890function build_percentages_array($steps=1, $order='desc', $lowest=0, $highest=100) {
891 // TODO reject or implement
892}
42ff9ce6 893
2650c51e 894/**
895 * Grading cron job
896 */
897function grade_cron() {
26101be8 898 global $CFG;
899
900 $now = time();
901
902 $sql = "SELECT i.*
903 FROM {$CFG->prefix}grade_items i
904 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1f4a0320 905 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 906
2650c51e 907 // go through all courses that have proper final grades and lock them if needed
26101be8 908 if ($rs = get_recordset_sql($sql)) {
2650c51e 909 if ($rs->RecordCount() > 0) {
26101be8 910 while ($item = rs_fetch_next_record($rs)) {
911 $grade_item = new grade_item($item, false);
912 $grade_item->locked = $now;
913 $grade_item->update('locktime');
2650c51e 914 }
915 }
916 rs_close($rs);
917 }
26101be8 918
fcac8e51 919 $grade_inst = new grade_grade();
920 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
921
922 $sql = "SELECT $fields
26101be8 923 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
924 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1f4a0320 925 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 926
927 // go through all courses that have proper final grades and lock them if needed
928 if ($rs = get_recordset_sql($sql)) {
929 if ($rs->RecordCount() > 0) {
930 while ($grade = rs_fetch_next_record($rs)) {
1f4a0320 931 $grade_grade = new grade_grade($grade, false);
26101be8 932 $grade_grade->locked = $now;
933 $grade_grade->update('locktime');
934 }
935 }
936 rs_close($rs);
937 }
938
2650c51e 939}
940
60cf7430 941?>