MDL-13899 assignments should be now sending proper submissions and grading dates...
[moodle.git] / lib / grade / grade_item.php
CommitLineData
3c2e81ee 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
4fc9ec1e 10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
3c2e81ee 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///////////////////////////////////////////////////////////////////////////
25
26require_once('grade_object.php');
4ac209d5 27
3c2e81ee 28/**
29 * Class representing a grade item. It is responsible for handling its DB representation,
30 * modifying and returning its metadata.
31 */
32class grade_item extends grade_object {
33 /**
34 * DB Table (used by grade_object).
35 * @var string $table
36 */
37 var $table = 'grade_items';
38
39 /**
40 * Array of required table fields, must start with 'id'.
41 * @var array $required_fields
42 */
43 var $required_fields = array('id', 'courseid', 'categoryid', 'itemname', 'itemtype', 'itemmodule', 'iteminstance',
44 'itemnumber', 'iteminfo', 'idnumber', 'calculation', 'gradetype', 'grademax', 'grademin',
45 'scaleid', 'outcomeid', 'gradepass', 'multfactor', 'plusfactor', 'aggregationcoef',
46 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime', 'needsupdate', 'timecreated',
47 'timemodified');
48
49 /**
50 * The course this grade_item belongs to.
51 * @var int $courseid
52 */
53 var $courseid;
54
55 /**
56 * The category this grade_item belongs to (optional).
57 * @var int $categoryid
58 */
59 var $categoryid;
60
61 /**
62 * The grade_category object referenced $this->iteminstance (itemtype must be == 'category' or == 'course' in that case).
63 * @var object $item_category
64 */
65 var $item_category;
66
67 /**
68 * The grade_category object referenced by $this->categoryid.
69 * @var object $parent_category
70 */
71 var $parent_category;
72
73
74 /**
75 * The name of this grade_item (pushed by the module).
76 * @var string $itemname
77 */
78 var $itemname;
79
80 /**
81 * e.g. 'category', 'course' and 'mod', 'blocks', 'import', etc...
82 * @var string $itemtype
83 */
84 var $itemtype;
85
86 /**
87 * The module pushing this grade (e.g. 'forum', 'quiz', 'assignment' etc).
88 * @var string $itemmodule
89 */
90 var $itemmodule;
91
92 /**
93 * ID of the item module
94 * @var int $iteminstance
95 */
96 var $iteminstance;
97
98 /**
99 * Number of the item in a series of multiple grades pushed by an activity.
100 * @var int $itemnumber
101 */
102 var $itemnumber;
103
104 /**
105 * Info and notes about this item.
106 * @var string $iteminfo
107 */
108 var $iteminfo;
109
110 /**
111 * Arbitrary idnumber provided by the module responsible.
112 * @var string $idnumber
113 */
114 var $idnumber;
115
116 /**
117 * Calculation string used for this item.
118 * @var string $calculation
119 */
120 var $calculation;
121
122 /**
123 * Indicates if we already tried to normalize the grade calculation formula.
124 * This flag helps to minimize db access when broken formulas used in calculation.
125 * @var boolean
126 */
127 var $calculation_normalized;
128 /**
129 * Math evaluation object
130 */
131 var $formula;
132
133 /**
134 * The type of grade (0 = none, 1 = value, 2 = scale, 3 = text)
135 * @var int $gradetype
136 */
137 var $gradetype = GRADE_TYPE_VALUE;
138
139 /**
140 * Maximum allowable grade.
141 * @var float $grademax
142 */
143 var $grademax = 100;
144
145 /**
146 * Minimum allowable grade.
147 * @var float $grademin
148 */
149 var $grademin = 0;
150
151 /**
152 * id of the scale, if this grade is based on a scale.
153 * @var int $scaleid
154 */
155 var $scaleid;
156
157 /**
158 * A grade_scale object (referenced by $this->scaleid).
159 * @var object $scale
160 */
161 var $scale;
162
163 /**
164 * The id of the optional grade_outcome associated with this grade_item.
165 * @var int $outcomeid
166 */
167 var $outcomeid;
168
169 /**
170 * The grade_outcome this grade is associated with, if applicable.
171 * @var object $outcome
172 */
173 var $outcome;
174
175 /**
176 * grade required to pass. (grademin <= gradepass <= grademax)
177 * @var float $gradepass
178 */
179 var $gradepass = 0;
180
181 /**
182 * Multiply all grades by this number.
183 * @var float $multfactor
184 */
185 var $multfactor = 1.0;
186
187 /**
188 * Add this to all grades.
189 * @var float $plusfactor
190 */
191 var $plusfactor = 0;
192
193 /**
194 * Aggregation coeficient used for weighted averages
195 * @var float $aggregationcoef
196 */
197 var $aggregationcoef = 0;
198
199 /**
200 * Sorting order of the columns.
201 * @var int $sortorder
202 */
203 var $sortorder = 0;
204
205 /**
206 * Display type of the grades (Real, Percentage, Letter, or default).
207 * @var int $display
208 */
209 var $display = GRADE_DISPLAY_TYPE_DEFAULT;
210
211 /**
212 * The number of digits after the decimal point symbol. Applies only to REAL and PERCENTAGE grade display types.
213 * @var int $decimals
214 */
215 var $decimals = null;
216
217 /**
218 * 0 if visible, 1 always hidden or date not visible until
219 * @var int $hidden
220 */
221 var $hidden = 0;
222
223 /**
224 * Grade item lock flag. Empty if not locked, locked if any value present, usually date when item was locked. Locking prevents updating.
225 * @var int $locked
226 */
227 var $locked = 0;
228
229 /**
230 * Date after which the grade will be locked. Empty means no automatic locking.
231 * @var int $locktime
232 */
233 var $locktime = 0;
234
235 /**
236 * If set, the whole column will be recalculated, then this flag will be switched off.
237 * @var boolean $needsupdate
238 */
239 var $needsupdate = 1;
240
241 /**
242 * Cached dependson array
243 */
244 var $dependson_cache = null;
245
246 /**
247 * In addition to update() as defined in grade_object, handle the grade_outcome and grade_scale objects.
25bcd908 248 * Force regrading if necessary, rounds the float numbers using php function,
249 * the reason is we need to compare the db value with computed number to skip regrading if possible.
3c2e81ee 250 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
251 * @return boolean success
252 */
253 function update($source=null) {
254 // reset caches
255 $this->dependson_cache = null;
256
257 // Retrieve scale and infer grademax/min from it if needed
258 $this->load_scale();
259
260 // make sure there is not 0 in outcomeid
261 if (empty($this->outcomeid)) {
262 $this->outcomeid = null;
263 }
264
265 if ($this->qualifies_for_regrading()) {
266 $this->force_regrading();
267 }
268
ced5ee59 269 $this->timemodified = time();
270
25bcd908 271 $this->grademin = grade_floatval($this->grademin);
272 $this->grademax = grade_floatval($this->grademax);
273 $this->multfactor = grade_floatval($this->multfactor);
274 $this->plusfactor = grade_floatval($this->plusfactor);
275 $this->aggregationcoef = grade_floatval($this->aggregationcoef);
276
3c2e81ee 277 return parent::update($source);
278 }
279
280 /**
281 * Compares the values held by this object with those of the matching record in DB, and returns
282 * whether or not these differences are sufficient to justify an update of all parent objects.
283 * This assumes that this object has an id number and a matching record in DB. If not, it will return false.
284 * @return boolean
285 */
286 function qualifies_for_regrading() {
287 if (empty($this->id)) {
288 return false;
289 }
290
f3ac8eb4 291 $db_item = new grade_item(array('id' => $this->id));
292
293 $calculationdiff = $db_item->calculation != $this->calculation;
294 $categorydiff = $db_item->categoryid != $this->categoryid;
295 $gradetypediff = $db_item->gradetype != $this->gradetype;
f3ac8eb4 296 $scaleiddiff = $db_item->scaleid != $this->scaleid;
297 $outcomeiddiff = $db_item->outcomeid != $this->outcomeid;
f3ac8eb4 298 $locktimediff = $db_item->locktime != $this->locktime;
25bcd908 299 $grademindiff = grade_floats_different($db_item->grademin, $this->grademin);
300 $grademaxdiff = grade_floats_different($db_item->grademax, $this->grademax);
301 $multfactordiff = grade_floats_different($db_item->multfactor, $this->multfactor);
302 $plusfactordiff = grade_floats_different($db_item->plusfactor, $this->plusfactor);
303 $acoefdiff = grade_floats_different($db_item->aggregationcoef, $this->aggregationcoef);
3c2e81ee 304
305 $needsupdatediff = !$db_item->needsupdate && $this->needsupdate; // force regrading only if setting the flag first time
306 $lockeddiff = !empty($db_item->locked) && empty($this->locked); // force regrading only when unlocking
307
308 return ($calculationdiff || $categorydiff || $gradetypediff || $grademaxdiff || $grademindiff || $scaleiddiff
309 || $outcomeiddiff || $multfactordiff || $plusfactordiff || $needsupdatediff
310 || $lockeddiff || $acoefdiff || $locktimediff);
311 }
312
313 /**
314 * Finds and returns a grade_item instance based on params.
315 * @static
316 *
317 * @param array $params associative arrays varname=>value
318 * @return object grade_item instance or false if none found.
319 */
320 function fetch($params) {
f3ac8eb4 321 return grade_object::fetch_helper('grade_items', 'grade_item', $params);
3c2e81ee 322 }
323
324 /**
325 * Finds and returns all grade_item instances based on params.
326 * @static
327 *
328 * @param array $params associative arrays varname=>value
329 * @return array array of grade_item insatnces or false if none found.
330 */
331 function fetch_all($params) {
f3ac8eb4 332 return grade_object::fetch_all_helper('grade_items', 'grade_item', $params);
3c2e81ee 333 }
334
335 /**
336 * Delete all grades and force_regrading of parent category.
337 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
338 * @return boolean success
339 */
340 function delete($source=null) {
f0362b5d 341 $this->delete_all_grades($source);
342 return parent::delete($source);
343 }
344
345 /**
346 * Delete all grades
347 * @param string $source from where was the object deleted (mod/forum, manual, etc.)
348 * @return boolean success
349 */
350 function delete_all_grades($source=null) {
3c2e81ee 351 if (!$this->is_course_item()) {
352 $this->force_regrading();
353 }
4ac209d5 354
f3ac8eb4 355 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
3c2e81ee 356 foreach ($grades as $grade) {
357 $grade->delete($source);
358 }
359 }
360
f0362b5d 361 return true;
3c2e81ee 362 }
363
364 /**
365 * In addition to perform parent::insert(), calls force_regrading() method too.
366 * @param string $source from where was the object inserted (mod/forum, manual, etc.)
367 * @return int PK ID if successful, false otherwise
368 */
369 function insert($source=null) {
370 global $CFG;
371
372 if (empty($this->courseid)) {
373 error('Can not insert grade item without course id!');
374 }
375
376 // load scale if needed
377 $this->load_scale();
378
379 // add parent category if needed
380 if (empty($this->categoryid) and !$this->is_course_item() and !$this->is_category_item()) {
f3ac8eb4 381 $course_category = grade_category::fetch_course_category($this->courseid);
3c2e81ee 382 $this->categoryid = $course_category->id;
383
384 }
385
386 // always place the new items at the end, move them after insert if needed
f3ac8eb4 387 $last_sortorder = get_field_select('grade_items', 'MAX(sortorder)', "courseid = {$this->courseid}");
3c2e81ee 388 if (!empty($last_sortorder)) {
389 $this->sortorder = $last_sortorder + 1;
390 } else {
391 $this->sortorder = 1;
392 }
393
394 // add proper item numbers to manual items
395 if ($this->itemtype == 'manual') {
396 if (empty($this->itemnumber)) {
397 $this->itemnumber = 0;
398 }
399 }
400
401 // make sure there is not 0 in outcomeid
402 if (empty($this->outcomeid)) {
403 $this->outcomeid = null;
404 }
405
ced5ee59 406 $this->timecreated = $this->timemodified = time();
407
3c2e81ee 408 if (parent::insert($source)) {
409 // force regrading of items if needed
410 $this->force_regrading();
411 return $this->id;
412
413 } else {
414 debugging("Could not insert this grade_item in the database!");
415 return false;
416 }
417 }
418
419 /**
420 * Set idnumber of grade item, updates also course_modules table
421 * @param string $idnumber (without magic quotes)
422 * @return boolean success
423 */
424 function add_idnumber($idnumber) {
425 if (!empty($this->idnumber)) {
426 return false;
427 }
428
429 if ($this->itemtype == 'mod' and !$this->is_outcome_item()) {
f3ac8eb4 430 if (!$cm = get_coursemodule_from_instance($this->itemmodule, $this->iteminstance, $this->courseid)) {
3c2e81ee 431 return false;
432 }
433 if (!empty($cm->idnumber)) {
434 return false;
435 }
f3ac8eb4 436 if (set_field('course_modules', 'idnumber', addslashes($idnumber), 'id', $cm->id)) {
3c2e81ee 437 $this->idnumber = $idnumber;
438 return $this->update();
439 }
440 return false;
441
442 } else {
443 $this->idnumber = $idnumber;
444 return $this->update();
445 }
446 }
447
448 /**
449 * Returns the locked state of this grade_item (if the grade_item is locked OR no specific
450 * $userid is given) or the locked state of a specific grade within this item if a specific
451 * $userid is given and the grade_item is unlocked.
452 *
453 * @param int $userid
454 * @return boolean Locked state
455 */
456 function is_locked($userid=NULL) {
457 if (!empty($this->locked)) {
458 return true;
459 }
460
461 if (!empty($userid)) {
f3ac8eb4 462 if ($grade = grade_grade::fetch(array('itemid'=>$this->id, 'userid'=>$userid))) {
3c2e81ee 463 $grade->grade_item =& $this; // prevent db fetching of cached grade_item
464 return $grade->is_locked();
465 }
466 }
467
468 return false;
469 }
470
471 /**
472 * Locks or unlocks this grade_item and (optionally) all its associated final grades.
473 * @param int $locked 0, 1 or a timestamp int(10) after which date the item will be locked.
474 * @param boolean $cascade lock/unlock child objects too
475 * @param boolean $refresh refresh grades when unlocking
476 * @return boolean true if grade_item all grades updated, false if at least one update fails
477 */
478 function set_locked($lockedstate, $cascade=false, $refresh=true) {
479 if ($lockedstate) {
480 /// setting lock
481 if ($this->needsupdate) {
482 return false; // can not lock grade without first having final grade
483 }
484
485 $this->locked = time();
486 $this->update();
487
488 if ($cascade) {
489 $grades = $this->get_final();
490 foreach($grades as $g) {
f3ac8eb4 491 $grade = new grade_grade($g, false);
3c2e81ee 492 $grade->grade_item =& $this;
493 $grade->set_locked(1, null, false);
494 }
495 }
496
497 return true;
498
499 } else {
500 /// removing lock
501 if (!empty($this->locked) and $this->locktime < time()) {
502 //we have to reset locktime or else it would lock up again
503 $this->locktime = 0;
504 }
505
506 $this->locked = 0;
507 $this->update();
508
509 if ($cascade) {
f3ac8eb4 510 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
3c2e81ee 511 foreach($grades as $grade) {
512 $grade->grade_item =& $this;
513 $grade->set_locked(0, null, false);
514 }
515 }
516 }
517
518 if ($refresh) {
519 //refresh when unlocking
520 $this->refresh_grades();
521 }
522
523 return true;
524 }
525 }
526
527 /**
528 * Lock the grade if needed - make sure this is called only when final grades are valid
529 */
530 function check_locktime() {
531 if (!empty($this->locked)) {
532 return; // already locked
533 }
534
535 if ($this->locktime and $this->locktime < time()) {
536 $this->locked = time();
537 $this->update('locktime');
538 }
539 }
540
541 /**
542 * Set the locktime for this grade item.
543 *
544 * @param int $locktime timestamp for lock to activate
545 * @return void
546 */
547 function set_locktime($locktime) {
548 $this->locktime = $locktime;
549 $this->update();
550 }
551
552 /**
553 * Set the locktime for this grade item.
554 *
555 * @return int $locktime timestamp for lock to activate
556 */
557 function get_locktime() {
558 return $this->locktime;
559 }
560
561 /**
562 * Returns the hidden state of this grade_item
563 * @return boolean hidden state
564 */
565 function is_hidden() {
566 return ($this->hidden == 1 or ($this->hidden != 0 and $this->hidden > time()));
567 }
568
597f50e6 569 /**
570 * Check grade hidden status. Uses data from both grade item and grade.
571 * @return boolean true if hiddenuntil, false if not
572 */
573 function is_hiddenuntil() {
574 return $this->hidden > 1;
575 }
576
3c2e81ee 577 /**
578 * Check grade item hidden status.
579 * @return int 0 means visible, 1 hidden always, timestamp hidden until
580 */
581 function get_hidden() {
582 return $this->hidden;
583 }
584
585 /**
586 * Set the hidden status of grade_item and all grades, 0 mean visible, 1 always hidden, number means date to hide until.
587 * @param int $hidden new hidden status
588 * @param boolean $cascade apply to child objects too
589 * @return void
590 */
591 function set_hidden($hidden, $cascade=false) {
592 $this->hidden = $hidden;
593 $this->update();
594
595 if ($cascade) {
f3ac8eb4 596 if ($grades = grade_grade::fetch_all(array('itemid'=>$this->id))) {
3c2e81ee 597 foreach($grades as $grade) {
598 $grade->grade_item =& $this;
599 $grade->set_hidden($hidden, $cascade);
600 }
601 }
602 }
603 }
604
605 /**
606 * Returns the number of grades that are hidden.
607 * @param return int Number of hidden grades
608 */
609 function has_hidden_grades($groupsql="", $groupwheresql="") {
610 global $CFG;
f3ac8eb4 611 return get_field_sql("SELECT COUNT(*) FROM {$CFG->prefix}grade_grades g LEFT JOIN "
3c2e81ee 612 ."{$CFG->prefix}user u ON g.userid = u.id $groupsql WHERE itemid = $this->id AND hidden = 1 $groupwheresql");
613 }
614
615 /**
616 * Mark regrading as finished successfully.
617 */
618 function regrading_finished() {
619 $this->needsupdate = 0;
620 //do not use $this->update() because we do not want this logged in grade_item_history
f3ac8eb4 621 set_field('grade_items', 'needsupdate', 0, 'id', $this->id);
3c2e81ee 622 }
623
624 /**
625 * Performs the necessary calculations on the grades_final referenced by this grade_item.
626 * Also resets the needsupdate flag once successfully performed.
627 *
628 * This function must be used ONLY from lib/gradeslib.php/grade_regrade_final_grades(),
629 * because the regrading must be done in correct order!!
630 *
631 * @return boolean true if ok, error string otherwise
632 */
633 function regrade_final_grades($userid=null) {
634 global $CFG;
635
636 // locked grade items already have correct final grades
637 if ($this->is_locked()) {
638 return true;
639 }
640
641 // calculation produces final value using formula from other final values
642 if ($this->is_calculated()) {
643 if ($this->compute($userid)) {
644 return true;
645 } else {
646 return "Could not calculate grades for grade item"; // TODO: improve and localize
647 }
648
649 // noncalculated outcomes already have final values - raw grades not used
650 } else if ($this->is_outcome_item()) {
651 return true;
652
653 // aggregate the category grade
654 } else if ($this->is_category_item() or $this->is_course_item()) {
655 // aggregate category grade item
656 $category = $this->get_item_category();
657 $category->grade_item =& $this;
658 if ($category->generate_grades($userid)) {
659 return true;
660 } else {
661 return "Could not aggregate final grades for category:".$this->id; // TODO: improve and localize
662 }
663
664 } else if ($this->is_manual_item()) {
665 // manual items track only final grades, no raw grades
666 return true;
667
668 } else if (!$this->is_raw_used()) {
669 // hmm - raw grades are not used- nothing to regrade
670 return true;
671 }
672
673 // normal grade item - just new final grades
674 $result = true;
f3ac8eb4 675 $grade_inst = new grade_grade();
3c2e81ee 676 $fields = implode(',', $grade_inst->required_fields);
677 if ($userid) {
f3ac8eb4 678 $rs = get_recordset_select('grade_grades', "itemid={$this->id} AND userid=$userid", '', $fields);
3c2e81ee 679 } else {
f3ac8eb4 680 $rs = get_recordset('grade_grades', 'itemid', $this->id, '', $fields);
3c2e81ee 681 }
682 if ($rs) {
f3ac8eb4 683 while ($grade_record = rs_fetch_next_record($rs)) {
684 $grade = new grade_grade($grade_record, false);
3c2e81ee 685
686 if (!empty($grade_record->locked) or !empty($grade_record->overridden)) {
687 // this grade is locked - final grade must be ok
688 continue;
689 }
690
691 $grade->finalgrade = $this->adjust_raw_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
692
25bcd908 693 if (grade_floats_different($grade_record->finalgrade, $grade->finalgrade)) {
3c2e81ee 694 if (!$grade->update('system')) {
695 $result = "Internal error updating final grade";
696 }
697 }
698 }
f3ac8eb4 699 rs_close($rs);
3c2e81ee 700 }
701
702 return $result;
703 }
704
705 /**
706 * Given a float grade value or integer grade scale, applies a number of adjustment based on
707 * grade_item variables and returns the result.
b45d8391 708 * @param float $rawgrade The raw grade value.
709 * @param float $rawmin original rawmin
710 * @param float $rawmax original rawmax
3c2e81ee 711 * @return mixed
712 */
713 function adjust_raw_grade($rawgrade, $rawmin, $rawmax) {
714 if (is_null($rawgrade)) {
715 return null;
716 }
717
718 if ($this->gradetype == GRADE_TYPE_VALUE) { // Dealing with numerical grade
719
720 if ($this->grademax < $this->grademin) {
721 return null;
722 }
723
724 if ($this->grademax == $this->grademin) {
725 return $this->grademax; // no range
726 }
727
728 // Standardise score to the new grade range
729 // NOTE: this is not compatible with current assignment grading
b45d8391 730 if ($this->itemmodule != 'assignment' and ($rawmin != $this->grademin or $rawmax != $this->grademax)) {
9a68cffc 731 $rawgrade = grade_grade::standardise_score($rawgrade, $rawmin, $rawmax, $this->grademin, $this->grademax);
3c2e81ee 732 }
733
734 // Apply other grade_item factors
735 $rawgrade *= $this->multfactor;
736 $rawgrade += $this->plusfactor;
737
738 return bounded_number($this->grademin, $rawgrade, $this->grademax);
739
740 } else if ($this->gradetype == GRADE_TYPE_SCALE) { // Dealing with a scale value
741 if (empty($this->scale)) {
742 $this->load_scale();
743 }
744
745 if ($this->grademax < 0) {
746 return null; // scale not present - no grade
747 }
748
749 if ($this->grademax == 0) {
750 return $this->grademax; // only one option
751 }
752
753 // Convert scale if needed
754 // NOTE: this is not compatible with current assignment grading
b45d8391 755 if ($this->itemmodule != 'assignment' and ($rawmin != $this->grademin or $rawmax != $this->grademax)) {
9a68cffc 756 $rawgrade = grade_grade::standardise_score($rawgrade, $rawmin, $rawmax, $this->grademin, $this->grademax);
3c2e81ee 757 }
758
759 return (int)bounded_number(0, round($rawgrade+0.00001), $this->grademax);
760
761
762 } else if ($this->gradetype == GRADE_TYPE_TEXT or $this->gradetype == GRADE_TYPE_NONE) { // no value
763 // somebody changed the grading type when grades already existed
764 return null;
765
766 } else {
a7bea6c8 767 debugging("Unknown grade type");
f3ac8eb4 768 return null;
3c2e81ee 769 }
770 }
771
772 /**
773 * Sets this grade_item's needsupdate to true. Also marks the course item as needing update.
774 * @return void
775 */
776 function force_regrading() {
777 $this->needsupdate = 1;
778 //mark this item and course item only - categories and calculated items are always regraded
779 $wheresql = "(itemtype='course' OR id={$this->id}) AND courseid={$this->courseid}";
f3ac8eb4 780 set_field_select('grade_items', 'needsupdate', 1, $wheresql);
3c2e81ee 781 }
782
783 /**
784 * Instantiates a grade_scale object whose data is retrieved from the DB,
785 * if this item's scaleid variable is set.
786 * @return object grade_scale or null if no scale used
787 */
788 function load_scale() {
789 if ($this->gradetype != GRADE_TYPE_SCALE) {
790 $this->scaleid = null;
791 }
792
793 if (!empty($this->scaleid)) {
794 //do not load scale if already present
795 if (empty($this->scale->id) or $this->scale->id != $this->scaleid) {
f3ac8eb4 796 $this->scale = grade_scale::fetch(array('id'=>$this->scaleid));
92b0d47c 797 if (!$this->scale) {
798 debugging('Incorrect scale id: '.$this->scaleid);
799 $this->scale = null;
800 return null;
801 }
3c2e81ee 802 $this->scale->load_items();
803 }
804
805 // Until scales are uniformly set to min=0 max=count(scaleitems)-1 throughout Moodle, we
806 // stay with the current min=1 max=count(scaleitems)
807 $this->grademax = count($this->scale->scale_items);
808 $this->grademin = 1;
809
810 } else {
811 $this->scale = null;
812 }
813
814 return $this->scale;
815 }
816
817 /**
818 * Instantiates a grade_outcome object whose data is retrieved from the DB,
819 * if this item's outcomeid variable is set.
820 * @return object grade_outcome
821 */
822 function load_outcome() {
823 if (!empty($this->outcomeid)) {
f3ac8eb4 824 $this->outcome = grade_outcome::fetch(array('id'=>$this->outcomeid));
3c2e81ee 825 }
826 return $this->outcome;
827 }
828
829 /**
830 * Returns the grade_category object this grade_item belongs to (referenced by categoryid)
831 * or category attached to category item.
832 *
833 * @return mixed grade_category object if applicable, false if course item
834 */
835 function get_parent_category() {
836 if ($this->is_category_item() or $this->is_course_item()) {
837 return $this->get_item_category();
838
839 } else {
f3ac8eb4 840 return grade_category::fetch(array('id'=>$this->categoryid));
3c2e81ee 841 }
842 }
843
844 /**
845 * Calls upon the get_parent_category method to retrieve the grade_category object
846 * from the DB and assigns it to $this->parent_category. It also returns the object.
847 * @return object Grade_category
848 */
849 function load_parent_category() {
850 if (empty($this->parent_category->id)) {
851 $this->parent_category = $this->get_parent_category();
852 }
853 return $this->parent_category;
854 }
855
856 /**
857 * Returns the grade_category for category item
858 *
859 * @return mixed grade_category object if applicable, false otherwise
860 */
861 function get_item_category() {
862 if (!$this->is_course_item() and !$this->is_category_item()) {
863 return false;
864 }
f3ac8eb4 865 return grade_category::fetch(array('id'=>$this->iteminstance));
3c2e81ee 866 }
867
868 /**
869 * Calls upon the get_item_category method to retrieve the grade_category object
870 * from the DB and assigns it to $this->item_category. It also returns the object.
871 * @return object Grade_category
872 */
873 function load_item_category() {
874 if (empty($this->category->id)) {
875 $this->item_category = $this->get_item_category();
876 }
877 return $this->item_category;
878 }
879
880 /**
881 * Is the grade item associated with category?
882 * @return boolean
883 */
884 function is_category_item() {
885 return ($this->itemtype == 'category');
886 }
887
888 /**
889 * Is the grade item associated with course?
890 * @return boolean
891 */
892 function is_course_item() {
893 return ($this->itemtype == 'course');
894 }
895
896 /**
897 * Is this a manualy graded item?
898 * @return boolean
899 */
900 function is_manual_item() {
901 return ($this->itemtype == 'manual');
902 }
903
904 /**
905 * Is this an outcome item?
906 * @return boolean
907 */
908 function is_outcome_item() {
909 return !empty($this->outcomeid);
910 }
911
912 /**
0f392ff4 913 * Is the grade item external - associated with module, plugin or something else?
3c2e81ee 914 * @return boolean
915 */
0f392ff4 916 function is_external_item() {
917 return ($this->itemtype == 'mod');
918 }
919
920 /**
921 * Is the grade item overridable
922 * @return boolean
923 */
924 function is_overridable_item() {
925 return !$this->is_outcome_item() and ($this->is_external_item() or $this->is_calculated() or $this->is_course_item() or $this->is_category_item());
3c2e81ee 926 }
927
5048575d 928 /**
929 * Is the grade item feedback overridable
930 * @return boolean
931 */
932 function is_overridable_item_feedback() {
933 return !$this->is_outcome_item() and $this->is_external_item();
934 }
935
3c2e81ee 936 /**
937 * Returns true if grade items uses raw grades
938 * @return boolean
939 */
940 function is_raw_used() {
0f392ff4 941 return ($this->is_external_item() and !$this->is_calculated() and !$this->is_outcome_item());
3c2e81ee 942 }
943
944 /**
945 * Returns grade item associated with the course
946 * @param int $courseid
947 * @return course item object
948 */
949 function fetch_course_item($courseid) {
f3ac8eb4 950 if ($course_item = grade_item::fetch(array('courseid'=>$courseid, 'itemtype'=>'course'))) {
3c2e81ee 951 return $course_item;
952 }
953
954 // first get category - it creates the associated grade item
f3ac8eb4 955 $course_category = grade_category::fetch_course_category($courseid);
076aeb01 956 return $course_category->get_grade_item();
3c2e81ee 957 }
958
959 /**
960 * Is grading object editable?
961 * @return boolean
962 */
963 function is_editable() {
964 return true;
965 }
966
967 /**
968 * Checks if grade calculated. Returns this object's calculation.
969 * @return boolean true if grade item calculated.
970 */
971 function is_calculated() {
972 if (empty($this->calculation)) {
973 return false;
974 }
975
976 /*
977 * The main reason why we use the ##gixxx## instead of [[idnumber]] is speed of depends_on(),
978 * we would have to fetch all course grade items to find out the ids.
979 * Also if user changes the idnumber the formula does not need to be updated.
980 */
981
982 // first detect if we need to change calculation formula from [[idnumber]] to ##giXXX## (after backup, etc.)
25bcd908 983 if (!$this->calculation_normalized and strpos('[[', $this->calculation) !== false) {
3c2e81ee 984 $this->set_calculation($this->calculation);
985 }
986
987 return !empty($this->calculation);
988 }
989
990 /**
991 * Returns calculation string if grade calculated.
992 * @return mixed string if calculation used, null if not
993 */
994 function get_calculation() {
995 if ($this->is_calculated()) {
f3ac8eb4 996 return grade_item::denormalize_formula($this->calculation, $this->courseid);
3c2e81ee 997
998 } else {
999 return NULL;
1000 }
1001 }
1002
1003 /**
1004 * Sets this item's calculation (creates it) if not yet set, or
1005 * updates it if already set (in the DB). If no calculation is given,
1006 * the calculation is removed.
1007 * @param string $formula string representation of formula used for calculation
1008 * @return boolean success
1009 */
1010 function set_calculation($formula) {
f3ac8eb4 1011 $this->calculation = grade_item::normalize_formula($formula, $this->courseid);
3c2e81ee 1012 $this->calculation_normalized = true;
1013 return $this->update();
1014 }
1015
1016 /**
1017 * Denormalizes the calculation formula to [idnumber] form
1018 * @static
1019 * @param string $formula
1020 * @return string denormalized string
1021 */
1022 function denormalize_formula($formula, $courseid) {
1023 if (empty($formula)) {
1024 return '';
1025 }
1026
1027 // denormalize formula - convert ##giXX## to [[idnumber]]
1028 if (preg_match_all('/##gi(\d+)##/', $formula, $matches)) {
1029 foreach ($matches[1] as $id) {
f3ac8eb4 1030 if ($grade_item = grade_item::fetch(array('id'=>$id, 'courseid'=>$courseid))) {
3c2e81ee 1031 if (!empty($grade_item->idnumber)) {
1032 $formula = str_replace('##gi'.$grade_item->id.'##', '[['.$grade_item->idnumber.']]', $formula);
1033 }
1034 }
1035 }
1036 }
1037
1038 return $formula;
1039
1040 }
1041
1042 /**
1043 * Normalizes the calculation formula to [#giXX#] form
1044 * @static
1045 * @param string $formula
1046 * @return string normalized string
1047 */
1048 function normalize_formula($formula, $courseid) {
1049 $formula = trim($formula);
1050
1051 if (empty($formula)) {
1052 return NULL;
1053
1054 }
1055
1056 // normalize formula - we want grade item ids ##giXXX## instead of [[idnumber]]
f3ac8eb4 1057 if ($grade_items = grade_item::fetch_all(array('courseid'=>$courseid))) {
3c2e81ee 1058 foreach ($grade_items as $grade_item) {
1059 $formula = str_replace('[['.$grade_item->idnumber.']]', '##gi'.$grade_item->id.'##', $formula);
1060 }
1061 }
1062
1063 return $formula;
1064 }
1065
1066 /**
1067 * Returns the final values for this grade item (as imported by module or other source).
1068 * @param int $userid Optional: to retrieve a single final grade
1069 * @return mixed An array of all final_grades (stdClass objects) for this grade_item, or a single final_grade.
1070 */
1071 function get_final($userid=NULL) {
1072 if ($userid) {
f3ac8eb4 1073 if ($user = get_record('grade_grades', 'itemid', $this->id, 'userid', $userid)) {
3c2e81ee 1074 return $user;
1075 }
1076
1077 } else {
f3ac8eb4 1078 if ($grades = get_records('grade_grades', 'itemid', $this->id)) {
3c2e81ee 1079 //TODO: speed up with better SQL
1080 $result = array();
1081 foreach ($grades as $grade) {
1082 $result[$grade->userid] = $grade;
1083 }
1084 return $result;
1085 } else {
1086 return array();
1087 }
1088 }
1089 }
1090
1091 /**
1092 * Get (or create if not exist yet) grade for this user
1093 * @param int $userid
1094 * @return object grade_grade object instance
1095 */
1096 function get_grade($userid, $create=true) {
1097 if (empty($this->id)) {
1098 debugging('Can not use before insert');
1099 return false;
1100 }
1101
f3ac8eb4 1102 $grade = new grade_grade(array('userid'=>$userid, 'itemid'=>$this->id));
3c2e81ee 1103 if (empty($grade->id) and $create) {
1104 $grade->insert();
1105 }
1106
1107 return $grade;
1108 }
1109
1110 /**
1111 * Returns the sortorder of this grade_item. This method is also available in
1112 * grade_category, for cases where the object type is not know.
1113 * @return int Sort order
1114 */
1115 function get_sortorder() {
1116 return $this->sortorder;
1117 }
1118
1119 /**
1120 * Returns the idnumber of this grade_item. This method is also available in
1121 * grade_category, for cases where the object type is not know.
1122 * @return string idnumber
1123 */
1124 function get_idnumber() {
1125 return $this->idnumber;
1126 }
1127
1128 /**
1129 * Returns this grade_item. This method is also available in
1130 * grade_category, for cases where the object type is not know.
1131 * @return string idnumber
1132 */
1133 function get_grade_item() {
1134 return $this;
1135 }
1136
1137 /**
1138 * Sets the sortorder of this grade_item. This method is also available in
1139 * grade_category, for cases where the object type is not know.
1140 * @param int $sortorder
1141 * @return void
1142 */
1143 function set_sortorder($sortorder) {
25bcd908 1144 if ($this->sortorder == $sortorder) {
1145 return;
1146 }
3c2e81ee 1147 $this->sortorder = $sortorder;
1148 $this->update();
1149 }
1150
1151 function move_after_sortorder($sortorder) {
1152 global $CFG;
1153
1154 //make some room first
1155 $sql = "UPDATE {$CFG->prefix}grade_items
1156 SET sortorder = sortorder + 1
1157 WHERE sortorder > $sortorder AND courseid = {$this->courseid}";
f3ac8eb4 1158 execute_sql($sql, false);
3c2e81ee 1159
1160 $this->set_sortorder($sortorder + 1);
1161 }
1162
1163 /**
1164 * Returns the most descriptive field for this object. This is a standard method used
1165 * when we do not know the exact type of an object.
1166 * @return string name
1167 */
1168 function get_name() {
1169 if (!empty($this->itemname)) {
1170 // MDL-10557
1171 return format_string($this->itemname);
1172
1173 } else if ($this->is_course_item()) {
1174 return get_string('coursetotal', 'grades');
1175
1176 } else if ($this->is_category_item()) {
1177 return get_string('categorytotal', 'grades');
1178
1179 } else {
1180 return get_string('grade');
1181 }
1182 }
1183
1184 /**
1185 * Sets this item's categoryid. A generic method shared by objects that have a parent id of some kind.
1186 * @param int $parentid
1187 * @return boolean success;
1188 */
1189 function set_parent($parentid) {
1190 if ($this->is_course_item() or $this->is_category_item()) {
1191 error('Can not set parent for category or course item!');
1192 }
1193
1194 if ($this->categoryid == $parentid) {
1195 return true;
1196 }
1197
1198 // find parent and check course id
f3ac8eb4 1199 if (!$parent_category = grade_category::fetch(array('id'=>$parentid, 'courseid'=>$this->courseid))) {
3c2e81ee 1200 return false;
1201 }
1202
1203 $this->force_regrading();
1204
1205 // set new parent
1206 $this->categoryid = $parent_category->id;
1207 $this->parent_category =& $parent_category;
1208
1209 return $this->update();
1210 }
1211
1212 /**
1213 * Finds out on which other items does this depend directly when doing calculation or category agregation
1214 * @param bool $reset_cache
1215 * @return array of grade_item ids this one depends on
1216 */
1217 function depends_on($reset_cache=false) {
1218 global $CFG;
1219
1220 if ($reset_cache) {
1221 $this->dependson_cache = null;
1222 } else if (isset($this->dependson_cache)) {
1223 return $this->dependson_cache;
1224 }
1225
1226 if ($this->is_locked()) {
1227 // locked items do not need to be regraded
1228 $this->dependson_cache = array();
1229 return $this->dependson_cache;
1230 }
1231
1232 if ($this->is_calculated()) {
1233 if (preg_match_all('/##gi(\d+)##/', $this->calculation, $matches)) {
1234 $this->dependson_cache = array_unique($matches[1]); // remove duplicates
1235 return $this->dependson_cache;
1236 } else {
1237 $this->dependson_cache = array();
1238 return $this->dependson_cache;
1239 }
1240
1241 } else if ($grade_category = $this->load_item_category()) {
1242 //only items with numeric or scale values can be aggregated
1243 if ($this->gradetype != GRADE_TYPE_VALUE and $this->gradetype != GRADE_TYPE_SCALE) {
1244 $this->dependson_cache = array();
1245 return $this->dependson_cache;
1246 }
1247
a6771652 1248 $grade_category->apply_forced_settings();
3c2e81ee 1249
1250 if (empty($CFG->enableoutcomes) or $grade_category->aggregateoutcomes) {
1251 $outcomes_sql = "";
1252 } else {
1253 $outcomes_sql = "AND gi.outcomeid IS NULL";
1254 }
1255
91f9a62c 1256 if (empty($CFG->grade_includescalesinaggregation)) {
1257 $gtypes = "gi.gradetype = ".GRADE_TYPE_VALUE;
1258 } else {
1259 $gtypes = "(gi.gradetype = ".GRADE_TYPE_VALUE." OR gi.gradetype = ".GRADE_TYPE_SCALE.")";
1260 }
1261
3c2e81ee 1262 if ($grade_category->aggregatesubcats) {
1263 // return all children excluding category items
1264 $sql = "SELECT gi.id
1265 FROM {$CFG->prefix}grade_items gi
91f9a62c 1266 WHERE $gtypes
3c2e81ee 1267 $outcomes_sql
1268 AND gi.categoryid IN (
1269 SELECT gc.id
1270 FROM {$CFG->prefix}grade_categories gc
1271 WHERE gc.path LIKE '%/{$grade_category->id}/%')";
1272
1273 } else {
1274 $sql = "SELECT gi.id
1275 FROM {$CFG->prefix}grade_items gi
1276 WHERE gi.categoryid = {$grade_category->id}
91f9a62c 1277 AND $gtypes
3c2e81ee 1278 $outcomes_sql
1279
1280 UNION
1281
1282 SELECT gi.id
1283 FROM {$CFG->prefix}grade_items gi, {$CFG->prefix}grade_categories gc
1284 WHERE (gi.itemtype = 'category' OR gi.itemtype = 'course') AND gi.iteminstance=gc.id
1285 AND gc.parent = {$grade_category->id}
91f9a62c 1286 AND $gtypes
3c2e81ee 1287 $outcomes_sql";
1288 }
1289
f3ac8eb4 1290 if ($children = get_records_sql($sql)) {
3c2e81ee 1291 $this->dependson_cache = array_keys($children);
1292 return $this->dependson_cache;
1293 } else {
1294 $this->dependson_cache = array();
1295 return $this->dependson_cache;
1296 }
1297
1298 } else {
1299 $this->dependson_cache = array();
1300 return $this->dependson_cache;
1301 }
1302 }
1303
1304 /**
1994d890 1305 * Refetch grades from modules, plugins.
3c2e81ee 1306 * @param int $userid optional, one user only
1307 */
1308 function refresh_grades($userid=0) {
1309 if ($this->itemtype == 'mod') {
1310 if ($this->is_outcome_item()) {
1311 //nothing to do
1312 return;
1313 }
1314
f3ac8eb4 1315 if (!$activity = get_record($this->itemmodule, 'id', $this->iteminstance)) {
1994d890 1316 debugging("Can not find $this->itemmodule activity with id $this->iteminstance");
3c2e81ee 1317 return;
1318 }
1319
f3ac8eb4 1320 if (!$cm = get_coursemodule_from_instance($this->itemmodule, $activity->id, $this->courseid)) {
1994d890 1321 debugging('Can not find course module');
3c2e81ee 1322 return;
1323 }
1324
1325 $activity->modname = $this->itemmodule;
1326 $activity->cmidnumber = $cm->idnumber;
1327
1328 grade_update_mod_grades($activity);
1329 }
1330 }
1331
1332 /**
1333 * Updates final grade value for given user, this is a only way to update final
1334 * grades from gradebook and import because it logs the change in history table
1335 * and deals with overridden flag. This flag is set to prevent later overriding
1336 * from raw grades submitted from modules.
1337 *
1338 * @param int $userid the graded user
1339 * @param mixed $finalgrade float value of final grade - false means do not change
1340 * @param string $howmodified modification source
1341 * @param string $note optional note
1342 * @param mixed $feedback teachers feedback as string - false means do not change
1343 * @param int $feedbackformat
1344 * @return boolean success
1345 */
0f392ff4 1346 function update_final_grade($userid, $finalgrade=false, $source=NULL, $feedback=false, $feedbackformat=FORMAT_MOODLE, $usermodified=null) {
3c2e81ee 1347 global $USER, $CFG;
1348
3c2e81ee 1349 $result = true;
1350
1351 // no grading used or locked
1352 if ($this->gradetype == GRADE_TYPE_NONE or $this->is_locked()) {
1353 return false;
1354 }
1355
f3ac8eb4 1356 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid));
3c2e81ee 1357 $grade->grade_item =& $this; // prevent db fetching of this grade_item
1358
ced5ee59 1359 if (empty($usermodified)) {
1360 $grade->usermodified = $USER->id;
1361 } else {
1362 $grade->usermodified = $usermodified;
1363 }
3c2e81ee 1364
1365 if ($grade->is_locked()) {
1366 // do not update locked grades at all
1367 return false;
1368 }
1369
1370 $locktime = $grade->get_locktime();
1371 if ($locktime and $locktime < time()) {
1372 // do not update grades that should be already locked, force regrade instead
1373 $this->force_regrading();
1374 return false;
1375 }
1376
1377 $oldgrade = new object();
1378 $oldgrade->finalgrade = $grade->finalgrade;
1379 $oldgrade->overridden = $grade->overridden;
1380 $oldgrade->feedback = $grade->feedback;
1381 $oldgrade->feedbackformat = $grade->feedbackformat;
1382
0f392ff4 1383 // changed grade?
1384 if ($finalgrade !== false) {
1385 if ($this->is_overridable_item()) {
3c2e81ee 1386 $grade->overridden = time();
0f392ff4 1387 } else {
1388 $grade->overridden = 0;
3c2e81ee 1389 }
3c2e81ee 1390
717f432f 1391 if (is_null($finalgrade)) {
1392 $grade->finalgrade = null;
3c2e81ee 1393 } else {
66690b69 1394 $grade->finalgrade = bounded_number($this->grademin, $finalgrade, $this->grademax);
3c2e81ee 1395 }
3c2e81ee 1396 }
1397
1398 // do we have comment from teacher?
1399 if ($feedback !== false) {
5048575d 1400 if ($this->is_overridable_item_feedback()) {
0f392ff4 1401 // external items (modules, plugins) may have own feedback
1402 $grade->overridden = time();
1403 }
1404
3c2e81ee 1405 $grade->feedback = $feedback;
1406 $grade->feedbackformat = $feedbackformat;
1407 }
1408
1409 if (empty($grade->id)) {
ced5ee59 1410 $grade->timecreated = null; // no submission yet
1411 $grade->timemodified = time(); // overridden flag might take over, but anyway
3c2e81ee 1412 $result = (boolean)$grade->insert($source);
1413
25bcd908 1414 } else if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)
1415 or $grade->feedback !== $oldgrade->feedback
5048575d 1416 or $grade->feedbackformat != $oldgrade->feedbackformat
1417 or $grade->overridden != $oldgrade->overridden) {
ced5ee59 1418 $grade->timemodified = time(); // overridden flag might take over, but anyway
3c2e81ee 1419 $result = $grade->update($source);
0f392ff4 1420 } else {
1421 // no grade change
1422 return $result;
3c2e81ee 1423 }
1424
1425 if (!$result) {
1426 // something went wrong - better force final grade recalculation
1427 $this->force_regrading();
1428
1429 } else if ($this->is_course_item() and !$this->needsupdate) {
b45d8391 1430 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
3c2e81ee 1431 $this->force_regrading();
1432 }
1433
1434 } else if (!$this->needsupdate) {
f3ac8eb4 1435 $course_item = grade_item::fetch_course_item($this->courseid);
3c2e81ee 1436 if (!$course_item->needsupdate) {
b45d8391 1437 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
3c2e81ee 1438 $this->force_regrading();
1439 }
1440 } else {
1441 $this->force_regrading();
1442 }
1443 }
1444
1445 return $result;
1446 }
1447
1448
1449 /**
1450 * Updates raw grade value for given user, this is a only way to update raw
1451 * grades from external source (modules, etc.),
1452 * because it logs the change in history table and deals with final grade recalculation.
1453 *
1454 * @param int $userid the graded user
1455 * @param mixed $rawgrade float value of raw grade - false means do not change
1456 * @param string $howmodified modification source
1457 * @param string $note optional note
1458 * @param mixed $feedback teachers feedback as string - false means do not change
1459 * @param int $feedbackformat
ced5ee59 1460 * @param int $usermodified - user which did the grading
1461 * @param int $dategraded
1462 * @param int $datesubmitted
55231be0 1463 * @param object $grade object - usefull for bulk upgrades
3c2e81ee 1464 * @return boolean success
1465 */
55231be0 1466 function update_raw_grade($userid, $rawgrade=false, $source=NULL, $feedback=false, $feedbackformat=FORMAT_MOODLE, $usermodified=null, $dategraded=null, $datesubmitted=null, $grade=null) {
3c2e81ee 1467 global $USER;
1468
3c2e81ee 1469 $result = true;
1470
1471 // calculated grades can not be updated; course and category can not be updated because they are aggregated
0f392ff4 1472 if (!$this->is_raw_used() or $this->gradetype == GRADE_TYPE_NONE or $this->is_locked()) {
3c2e81ee 1473 return false;
1474 }
1475
55231be0 1476 if (is_null($grade)) {
1477 //fetch from db
1478 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid));
1479 }
3c2e81ee 1480 $grade->grade_item =& $this; // prevent db fetching of this grade_item
1481
ced5ee59 1482 if (empty($usermodified)) {
1483 $grade->usermodified = $USER->id;
1484 } else {
1485 $grade->usermodified = $usermodified;
1486 }
1487
1488 // TODO: hack alert - create new fields for these
1489
1490 $grade->timecreated = $datesubmitted;
1491
1492 if (empty($dategraded)) {
717f432f 1493 $grade->timemodified = time();
ced5ee59 1494 } else {
717f432f 1495 $grade->timemodified = $dategraded;
ced5ee59 1496 }
3c2e81ee 1497
1498 if ($grade->is_locked()) {
1499 // do not update locked grades at all
1500 return false;
1501 }
1502
1503 $locktime = $grade->get_locktime();
1504 if ($locktime and $locktime < time()) {
1505 // do not update grades that should be already locked and force regrade
1506 $this->force_regrading();
1507 return false;
1508 }
1509
1510 $oldgrade = new object();
66690b69 1511 $oldgrade->finalgrade = $grade->finalgrade;
1512 $oldgrade->rawgrade = $grade->rawgrade;
1513 $oldgrade->rawgrademin = $grade->rawgrademin;
1514 $oldgrade->rawgrademax = $grade->rawgrademax;
1515 $oldgrade->rawscaleid = $grade->rawscaleid;
3c2e81ee 1516 $oldgrade->feedback = $grade->feedback;
1517 $oldgrade->feedbackformat = $grade->feedbackformat;
1518
b45d8391 1519 // use new min and max
66690b69 1520 $grade->rawgrade = $grade->rawgrade;
1521 $grade->rawgrademin = $this->grademin;
1522 $grade->rawgrademax = $this->grademax;
1523 $grade->rawscaleid = $this->scaleid;
3c2e81ee 1524
1525 // change raw grade?
1526 if ($rawgrade !== false) {
66690b69 1527 $grade->rawgrade = $rawgrade;
3c2e81ee 1528 }
1529
1530 // do we have comment from teacher?
25bcd908 1531 if ($feedback !== false and !$grade->is_overridden()) {
3c2e81ee 1532 $grade->feedback = $feedback;
1533 $grade->feedbackformat = $feedbackformat;
1534 }
1535
b45d8391 1536 // update final grade if possible
1537 if (!$grade->is_locked() and !$grade->is_overridden()) {
66690b69 1538 $grade->finalgrade = $this->adjust_raw_grade($grade->rawgrade, $grade->rawgrademin, $grade->rawgrademax);
b45d8391 1539 }
1540
c55c9d73 1541 if (is_null($grade->rawgrade) and is_null($grade->feedback)) {
1542 $grade->timemodified = null; //TODO: dategraded hack - feedback counts as grading too ;-)
717f432f 1543 }
1544
3c2e81ee 1545 if (empty($grade->id)) {
1546 $result = (boolean)$grade->insert($source);
1547
25bcd908 1548 } else if (grade_floats_different($grade->finalgrade, $oldgrade->finalgrade)
1549 or grade_floats_different($grade->rawgrade, $oldgrade->rawgrade)
1550 or grade_floats_different($grade->rawgrademin, $oldgrade->rawgrademin)
1551 or grade_floats_different($grade->rawgrademax, $oldgrade->rawgrademax)
1552 or $grade->rawscaleid != $oldgrade->rawscaleid
1553 or $grade->feedback !== $oldgrade->feedback
1554 or $grade->feedbackformat != $oldgrade->feedbackformat) {
3c2e81ee 1555 $result = $grade->update($source);
66690b69 1556 } else {
1557 return $result;
3c2e81ee 1558 }
1559
1560 if (!$result) {
1561 // something went wrong - better force final grade recalculation
1562 $this->force_regrading();
1563
1564 } else if (!$this->needsupdate) {
f3ac8eb4 1565 $course_item = grade_item::fetch_course_item($this->courseid);
3c2e81ee 1566 if (!$course_item->needsupdate) {
b45d8391 1567 if (grade_regrade_final_grades($this->courseid, $userid, $this) !== true) {
3c2e81ee 1568 $this->force_regrading();
1569 }
3c2e81ee 1570 }
1571 }
1572
1573 return $result;
1574 }
1575
1576 /**
1577 * Calculates final grade values using the formula in calculation property.
1578 * The parameters are taken from final grades of grade items in current course only.
1579 * @return boolean false if error
1580 */
1581 function compute($userid=null) {
1582 global $CFG;
1583
1584 if (!$this->is_calculated()) {
1585 return false;
1586 }
1587
1588 require_once($CFG->libdir.'/mathslib.php');
1589
1590 if ($this->is_locked()) {
1591 return true; // no need to recalculate locked items
1592 }
1593
52e95845 1594 // precreate grades - we need them to exist
1595 $sql = "SELECT DISTINCT go.userid
1596 FROM {$CFG->prefix}grade_grades go
1597 JOIN {$CFG->prefix}grade_items gi
1598 ON gi.id = go.itemid
1599 LEFT OUTER JOIN {$CFG->prefix}grade_grades g
1600 ON (g.userid = go.userid AND g.itemid = $this->id)
1601 WHERE gi.id <> $this->id AND g.id IS NULL";
1602 if ($missing = get_records_sql($sql)) {
1603 foreach ($missing as $m) {
1604 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$m->userid), false);
1605 $grade->grade_item =& $this;
1606 $grade->insert('system');
1607 }
1608 }
1609
3c2e81ee 1610 // get used items
1611 $useditems = $this->depends_on();
1612
1613 // prepare formula and init maths library
1614 $formula = preg_replace('/##(gi\d+)##/', '\1', $this->calculation);
9c9a3259 1615 if (strpos($formula, '[[') !== false) {
1616 // missing item
1617 return false;
1618 }
3c2e81ee 1619 $this->formula = new calc_formula($formula);
1620
1621 // where to look for final grades?
1622 // this itemid is added so that we use only one query for source and final grades
1623 $gis = implode(',', array_merge($useditems, array($this->id)));
1624
1625 if ($userid) {
1626 $usersql = "AND g.userid=$userid";
1627 } else {
1628 $usersql = "";
1629 }
1630
f3ac8eb4 1631 $grade_inst = new grade_grade();
3c2e81ee 1632 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
1633
1634 $sql = "SELECT $fields
1635 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items gi
1636 WHERE gi.id = g.itemid AND gi.courseid={$this->courseid} AND gi.id IN ($gis) $usersql
1637 ORDER BY g.userid";
1638
1639 $return = true;
1640
1641 // group the grades by userid and use formula on the group
f3ac8eb4 1642 if ($rs = get_recordset_sql($sql)) {
3c2e81ee 1643 $prevuser = 0;
1644 $grade_records = array();
1645 $oldgrade = null;
f3ac8eb4 1646 while ($used = rs_fetch_next_record($rs)) {
3c2e81ee 1647 if ($used->userid != $prevuser) {
1648 if (!$this->use_formula($prevuser, $grade_records, $useditems, $oldgrade)) {
1649 $return = false;
1650 }
1651 $prevuser = $used->userid;
1652 $grade_records = array();
1653 $oldgrade = null;
1654 }
1655 if ($used->itemid == $this->id) {
1656 $oldgrade = $used;
1657 }
1658 $grade_records['gi'.$used->itemid] = $used->finalgrade;
1659 }
1660 if (!$this->use_formula($prevuser, $grade_records, $useditems, $oldgrade)) {
1661 $return = false;
1662 }
1663 }
f3ac8eb4 1664 rs_close($rs);
3c2e81ee 1665
1666 return $return;
1667 }
1668
1669 /**
1670 * internal function - does the final grade calculation
1671 */
1672 function use_formula($userid, $params, $useditems, $oldgrade) {
1673 if (empty($userid)) {
1674 return true;
1675 }
1676
1677 // add missing final grade values
1678 // not graded (null) is counted as 0 - the spreadsheet way
1679 foreach($useditems as $gi) {
1680 if (!array_key_exists('gi'.$gi, $params)) {
1681 $params['gi'.$gi] = 0;
1682 } else {
1683 $params['gi'.$gi] = (float)$params['gi'.$gi];
1684 }
1685 }
1686
1687 // can not use own final grade during calculation
1688 unset($params['gi'.$this->id]);
1689
1690 // insert final grade - will be needed later anyway
1691 if ($oldgrade) {
66690b69 1692 $oldfinalgrade = $oldgrade->finalgrade;
f3ac8eb4 1693 $grade = new grade_grade($oldgrade, false); // fetching from db is not needed
3c2e81ee 1694 $grade->grade_item =& $this;
1695
1696 } else {
f3ac8eb4 1697 $grade = new grade_grade(array('itemid'=>$this->id, 'userid'=>$userid), false);
3c2e81ee 1698 $grade->grade_item =& $this;
4ac209d5 1699 $grade->insert('system');
1700 $oldfinalgrade = null;
3c2e81ee 1701 }
1702
1703 // no need to recalculate locked or overridden grades
1704 if ($grade->is_locked() or $grade->is_overridden()) {
1705 return true;
1706 }
1707
1708 // do the calculation
1709 $this->formula->set_params($params);
1710 $result = $this->formula->evaluate();
1711
3c2e81ee 1712 if ($result === false) {
1713 $grade->finalgrade = null;
1714
1715 } else {
1716 // normalize
1717 $result = bounded_number($this->grademin, $result, $this->grademax);
1718 if ($this->gradetype == GRADE_TYPE_SCALE) {
1719 $result = round($result+0.00001); // round scales upwards
1720 }
66690b69 1721 $grade->finalgrade = $result;
3c2e81ee 1722 }
1723
1724 // update in db if changed
25bcd908 1725 if (grade_floats_different($grade->finalgrade, $oldfinalgrade)) {
4ac209d5 1726 $grade->update('compute');
3c2e81ee 1727 }
1728
1729 if ($result !== false) {
1730 //lock grade if needed
1731 }
1732
1733 if ($result === false) {
1734 return false;
1735 } else {
1736 return true;
1737 }
1738
1739 }
1740
1741 /**
1742 * Validate the formula.
1743 * @param string $formula
1744 * @return boolean true if calculation possible, false otherwise
1745 */
1746 function validate_formula($formulastr) {
1747 global $CFG;
1748 require_once($CFG->libdir.'/mathslib.php');
1749
f3ac8eb4 1750 $formulastr = grade_item::normalize_formula($formulastr, $this->courseid);
3c2e81ee 1751
1752 if (empty($formulastr)) {
1753 return true;
1754 }
1755
1756 if (strpos($formulastr, '=') !== 0) {
1757 return get_string('errorcalculationnoequal', 'grades');
1758 }
1759
1760 // get used items
1761 if (preg_match_all('/##gi(\d+)##/', $formulastr, $matches)) {
1762 $useditems = array_unique($matches[1]); // remove duplicates
1763 } else {
1764 $useditems = array();
1765 }
ced5ee59 1766
26d7de8b 1767 // MDL-11902
1768 // unset the value if formula is trying to reference to itself
1769 // but array keys does not match itemid
3c2e81ee 1770 if (!empty($this->id)) {
26d7de8b 1771 $useditems = array_diff($useditems, array($this->id));
1772 //unset($useditems[$this->id]);
3c2e81ee 1773 }
1774
1775 // prepare formula and init maths library
1776 $formula = preg_replace('/##(gi\d+)##/', '\1', $formulastr);
1777 $formula = new calc_formula($formula);
1778
1779
1780 if (empty($useditems)) {
1781 $grade_items = array();
1782
1783 } else {
1784 $gis = implode(',', $useditems);
1785
1786 $sql = "SELECT gi.*
1787 FROM {$CFG->prefix}grade_items gi
1788 WHERE gi.id IN ($gis) and gi.courseid={$this->courseid}"; // from the same course only!
1789
f3ac8eb4 1790 if (!$grade_items = get_records_sql($sql)) {
3c2e81ee 1791 $grade_items = array();
1792 }
1793 }
1794
1795 $params = array();
1796 foreach ($useditems as $itemid) {
1797 // make sure all grade items exist in this course
1798 if (!array_key_exists($itemid, $grade_items)) {
1799 return false;
1800 }
1801 // use max grade when testing formula, this should be ok in 99.9%
1802 // division by 0 is one of possible problems
1803 $params['gi'.$grade_items[$itemid]->id] = $grade_items[$itemid]->grademax;
1804 }
1805
1806 // do the calculation
1807 $formula->set_params($params);
1808 $result = $formula->evaluate();
1809
1810 // false as result indicates some problem
1811 if ($result === false) {
1812 // TODO: add more error hints
1813 return get_string('errorcalculationunknown', 'grades');
1814 } else {
1815 return true;
1816 }
1817 }
1818
1819 /**
1820 * Returns the value of the display type. It can be set at 3 levels: grade_item, course setting and site. The lowest level overrides the higher ones.
1821 * @return int Display type
1822 */
1823 function get_displaytype() {
1824 global $CFG;
1825
1826 if ($this->display == GRADE_DISPLAY_TYPE_DEFAULT) {
1827 return grade_get_setting($this->courseid, 'displaytype', $CFG->grade_displaytype);
1828
1829 } else {
1830 return $this->display;
1831 }
1832 }
1833
1834 /**
1835 * Returns the value of the decimals field. It can be set at 3 levels: grade_item, course setting and site. The lowest level overrides the higher ones.
1836 * @return int Decimals (0 - 5)
1837 */
1838 function get_decimals() {
1839 global $CFG;
1840
1841 if (is_null($this->decimals)) {
1842 return grade_get_setting($this->courseid, 'decimalpoints', $CFG->grade_decimalpoints);
1843
1844 } else {
1845 return $this->decimals;
1846 }
1847 }
1848}
1849?>