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