MDL-13945 prevent fatal errors in all rs_xx functions; merged from MOODLE_19_STABLE
[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/**
b9f49659 26 * Library of functions for gradebook - both public and internal
5834dcdb 27 *
28 * @author Moodle HQ developers
d886a7ea 29 * @version $Id$
5834dcdb 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
b9f49659 42/////////////////////////////////////////////////////////////////////
43///// Start of public API for communication with modules/blocks /////
44/////////////////////////////////////////////////////////////////////
612607bd 45
c5b5f18d 46/**
47 * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
ac9b0805 48 * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded', missing property
c5b5f18d 49 * or key means do not change existing.
4cf1b9be 50 *
c5b5f18d 51 * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
f0362b5d 52 * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
4cf1b9be 53 *
fcac8e51 54 * Manual, course or category items can not be updated by this function.
b9f49659 55 * @public
9c8d38fa 56 * @param string $source source of the grade such as 'mod/assignment'
c5b5f18d 57 * @param int $courseid id of course
3a5ae660 58 * @param string $itemtype type of grade item - mod, block
c5b5f18d 59 * @param string $itemmodule more specific then $itemtype - assignment, forum, etc.; maybe NULL for some item types
60 * @param int $iteminstance instance it of graded subject
61 * @param int $itemnumber most probably 0, modules can use other numbers when having more than one grades for each user
b60b2ce6 62 * @param mixed $grades grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
c5b5f18d 63 * @param mixed $itemdetails object or array describing the grading item, NULL if no change
64 */
b67ec72f 65function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
aaff71da 66 global $USER;
612607bd 67
c5b5f18d 68 // only following grade_item properties can be changed in this function
1223d24a 69 $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
25bcd908 70 // list of 10,5 numeric fields
71 $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
612607bd 72
c4e4068f 73 // grade item identification
74 $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
75
612607bd 76 if (is_null($courseid) or is_null($itemtype)) {
77 debugging('Missing courseid or itemtype');
78 return GRADE_UPDATE_FAILED;
79 }
80
c4e4068f 81 if (!$grade_items = grade_item::fetch_all($params)) {
612607bd 82 // create a new one
83 $grade_item = false;
84
85 } else if (count($grade_items) == 1){
86 $grade_item = reset($grade_items);
87 unset($grade_items); //release memory
88
89 } else {
34e67f76 90 debugging('Found more than one grade item');
612607bd 91 return GRADE_UPDATE_MULTIPLE;
92 }
93
aaff71da 94 if (!empty($itemdetails['deleted'])) {
95 if ($grade_item) {
96 if ($grade_item->delete($source)) {
97 return GRADE_UPDATE_OK;
98 } else {
99 return GRADE_UPDATE_FAILED;
100 }
101 }
102 return GRADE_UPDATE_OK;
103 }
104
612607bd 105/// Create or update the grade_item if needed
b159da78 106
612607bd 107 if (!$grade_item) {
612607bd 108 if ($itemdetails) {
109 $itemdetails = (array)$itemdetails;
2e53372c 110
772ddfbf 111 // grademin and grademax ignored when scale specified
2e53372c 112 if (array_key_exists('scaleid', $itemdetails)) {
113 if ($itemdetails['scaleid']) {
114 unset($itemdetails['grademin']);
115 unset($itemdetails['grademax']);
116 }
117 }
118
612607bd 119 foreach ($itemdetails as $k=>$v) {
120 if (!in_array($k, $allowed)) {
121 // ignore it
122 continue;
123 }
124 if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
125 // no grade item needed!
126 return GRADE_UPDATE_OK;
127 }
128 $params[$k] = $v;
129 }
130 }
f70152b7 131 $grade_item = new grade_item($params);
132 $grade_item->insert();
612607bd 133
134 } else {
2cc4b0f9 135 if ($grade_item->is_locked()) {
d6bc2a81 136 // no notice() here, test returned value instead!
678e8898 137 return GRADE_UPDATE_ITEM_LOCKED;
612607bd 138 }
139
140 if ($itemdetails) {
141 $itemdetails = (array)$itemdetails;
142 $update = false;
143 foreach ($itemdetails as $k=>$v) {
144 if (!in_array($k, $allowed)) {
145 // ignore it
146 continue;
147 }
25bcd908 148 if (in_array($k, $floats)) {
149 if (grade_floats_different($grade_item->{$k}, $v)) {
150 $grade_item->{$k} = $v;
151 $update = true;
152 }
153
154 } else {
155 if ($grade_item->{$k} != $v) {
156 $grade_item->{$k} = $v;
157 $update = true;
158 }
612607bd 159 }
160 }
161 if ($update) {
162 $grade_item->update();
163 }
164 }
165 }
166
f0362b5d 167/// reset grades if requested
168 if (!empty($itemdetails['reset'])) {
169 $grade_item->delete_all_grades('reset');
170 return GRADE_UPDATE_OK;
171 }
172
612607bd 173/// Some extra checks
174 // do we use grading?
175 if ($grade_item->gradetype == GRADE_TYPE_NONE) {
176 return GRADE_UPDATE_OK;
177 }
178
179 // no grade submitted
b67ec72f 180 if (empty($grades)) {
612607bd 181 return GRADE_UPDATE_OK;
182 }
183
612607bd 184/// Finally start processing of grades
b67ec72f 185 if (is_object($grades)) {
186 $grades = array($grades);
612607bd 187 } else {
b67ec72f 188 if (array_key_exists('userid', $grades)) {
189 $grades = array($grades);
612607bd 190 }
191 }
192
4cf1b9be 193 $failed = false;
612607bd 194 foreach ($grades as $grade) {
195 $grade = (array)$grade;
196 if (empty($grade['userid'])) {
4cf1b9be 197 $failed = true;
198 debugging('Invalid userid in grade submitted');
199 continue;
ac9b0805 200 } else {
201 $userid = $grade['userid'];
612607bd 202 }
203
2cc4b0f9 204 $rawgrade = false;
ac9b0805 205 $feedback = false;
206 $feedbackformat = FORMAT_MOODLE;
ced5ee59 207 $usermodified = $USER->id;
208 $datesubmitted = null;
209 $dategraded = null;
772ddfbf 210
ac9b0805 211 if (array_key_exists('rawgrade', $grade)) {
212 $rawgrade = $grade['rawgrade'];
213 }
612607bd 214
4cf1b9be 215 if (array_key_exists('feedback', $grade)) {
ac9b0805 216 $feedback = $grade['feedback'];
612607bd 217 }
218
ac9b0805 219 if (array_key_exists('feedbackformat', $grade)) {
220 $feedbackformat = $grade['feedbackformat'];
612607bd 221 }
222
aaff71da 223 if (array_key_exists('usermodified', $grade)) {
224 $usermodified = $grade['usermodified'];
ced5ee59 225 }
226
227 if (array_key_exists('datesubmitted', $grade)) {
228 $datesubmitted = $grade['datesubmitted'];
229 }
230
231 if (array_key_exists('dategraded', $grade)) {
232 $dategraded = $grade['dategraded'];
aaff71da 233 }
234
ac9b0805 235 // update or insert the grade
ced5ee59 236 if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified, $dategraded, $datesubmitted)) {
4cf1b9be 237 $failed = true;
4cf1b9be 238 }
612607bd 239 }
240
4cf1b9be 241 if (!$failed) {
242 return GRADE_UPDATE_OK;
243 } else {
244 return GRADE_UPDATE_FAILED;
245 }
612607bd 246}
247
3a5ae660 248/**
249 * Updates outcomes of user
fcac8e51 250 * Manual outcomes can not be updated.
b9f49659 251 * @public
fcac8e51 252 * @param string $source source of the grade such as 'mod/assignment'
3a5ae660 253 * @param int $courseid id of course
254 * @param string $itemtype 'mod', 'block'
255 * @param string $itemmodule 'forum, 'quiz', etc.
256 * @param int $iteminstance id of the item module
257 * @param int $userid ID of the graded user
d886a7ea 258 * @param array $data array itemnumber=>outcomegrade
3a5ae660 259 */
260function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
261 if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
262 foreach ($items as $item) {
d886a7ea 263 if (!array_key_exists($item->itemnumber, $data)) {
3a5ae660 264 continue;
265 }
d886a7ea 266 $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
3a5ae660 267 $item->update_final_grade($userid, $grade, $source);
11a14999 268 }
3a5ae660 269 }
270}
271
6b5c722d 272/**
fcac8e51 273 * Returns grading information for given activity - optionally with users grades
274 * Manual, course or category items can not be queried.
b9f49659 275 * @public
6b5c722d 276 * @param int $courseid id of course
277 * @param string $itemtype 'mod', 'block'
278 * @param string $itemmodule 'forum, 'quiz', etc.
279 * @param int $iteminstance id of the item module
b9f49659 280 * @param int $userid_or_ids optional id of the graded user or array of ids; if userid not used, returns only information about grade_item
6b5c722d 281 * @return array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
282 */
b9f49659 283function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
a3fbd494 284 global $CFG;
285
fcac8e51 286 $return = new object();
287 $return->items = array();
288 $return->outcomes = array();
6b5c722d 289
fcac8e51 290 $course_item = grade_item::fetch_course_item($courseid);
291 $needsupdate = array();
292 if ($course_item->needsupdate) {
293 $result = grade_regrade_final_grades($courseid);
294 if ($result !== true) {
295 $needsupdate = array_keys($result);
296 }
297 }
6b5c722d 298
fcac8e51 299 if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
300 foreach ($grade_items as $grade_item) {
a3fbd494 301 $decimalpoints = null;
302
fcac8e51 303 if (empty($grade_item->outcomeid)) {
304 // prepare information about grade item
305 $item = new object();
306 $item->itemnumber = $grade_item->itemnumber;
307 $item->scaleid = $grade_item->scaleid;
308 $item->name = $grade_item->get_name();
309 $item->grademin = $grade_item->grademin;
310 $item->grademax = $grade_item->grademax;
311 $item->gradepass = $grade_item->gradepass;
312 $item->locked = $grade_item->is_locked();
313 $item->hidden = $grade_item->is_hidden();
314 $item->grades = array();
315
316 switch ($grade_item->gradetype) {
317 case GRADE_TYPE_NONE:
318 continue;
6b5c722d 319
6b5c722d 320 case GRADE_TYPE_VALUE:
fcac8e51 321 $item->scaleid = 0;
6b5c722d 322 break;
323
fcac8e51 324 case GRADE_TYPE_TEXT:
325 $item->scaleid = 0;
326 $item->grademin = 0;
327 $item->grademax = 0;
328 $item->gradepass = 0;
6b5c722d 329 break;
fcac8e51 330 }
6b5c722d 331
fcac8e51 332 if (empty($userid_or_ids)) {
333 $userids = array();
334
335 } else if (is_array($userid_or_ids)) {
336 $userids = $userid_or_ids;
337
338 } else {
339 $userids = array($userid_or_ids);
6b5c722d 340 }
6b5c722d 341
fcac8e51 342 if ($userids) {
343 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
344 foreach ($userids as $userid) {
345 $grade_grades[$userid]->grade_item =& $grade_item;
346
347 $grade = new object();
348 $grade->grade = $grade_grades[$userid]->finalgrade;
349 $grade->locked = $grade_grades[$userid]->is_locked();
350 $grade->hidden = $grade_grades[$userid]->is_hidden();
351 $grade->overridden = $grade_grades[$userid]->overridden;
352 $grade->feedback = $grade_grades[$userid]->feedback;
353 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
a3fbd494 354 $grade->usermodified = $grade_grades[$userid]->usermodified;
ced5ee59 355 $grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
356 $grade->dategraded = $grade_grades[$userid]->get_dategraded();
fcac8e51 357
358 // create text representation of grade
5048575d 359 if ($grade_item->gradetype == GRADE_TYPE_TEXT or $grade_item->gradetype == GRADE_TYPE_NONE) {
360 $grade->grade = null;
361 $grade->str_grade = '-';
362 $grade->str_long_grade = $grade->str_grade;
363
364 } else if (in_array($grade_item->id, $needsupdate)) {
85a0a69f 365 $grade->grade = false;
366 $grade->str_grade = get_string('error');
367 $grade->str_long_grade = $grade->str_grade;
fcac8e51 368
369 } else if (is_null($grade->grade)) {
85a0a69f 370 $grade->str_grade = '-';
371 $grade->str_long_grade = $grade->str_grade;
fcac8e51 372
373 } else {
e9096dc2 374 $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
85a0a69f 375 if ($grade_item->gradetype == GRADE_TYPE_SCALE or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL) {
376 $grade->str_long_grade = $grade->str_grade;
377 } else {
378 $a = new object();
379 $a->grade = $grade->str_grade;
380 $a->max = grade_format_gradevalue($grade_item->grademax, $grade_item);
381 $grade->str_long_grade = get_string('gradelong', 'grades', $a);
382 }
fcac8e51 383 }
384
385 // create html representation of feedback
386 if (is_null($grade->feedback)) {
387 $grade->str_feedback = '';
388 } else {
389 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
390 }
391
392 $item->grades[$userid] = $grade;
393 }
394 }
395 $return->items[$grade_item->itemnumber] = $item;
396
6b5c722d 397 } else {
fcac8e51 398 if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
399 debugging('Incorect outcomeid found');
400 continue;
401 }
402
403 // outcome info
404 $outcome = new object();
405 $outcome->itemnumber = $grade_item->itemnumber;
406 $outcome->scaleid = $grade_outcome->scaleid;
407 $outcome->name = $grade_outcome->get_name();
408 $outcome->locked = $grade_item->is_locked();
409 $outcome->hidden = $grade_item->is_hidden();
410
411 if (empty($userid_or_ids)) {
412 $userids = array();
413 } else if (is_array($userid_or_ids)) {
414 $userids = $userid_or_ids;
415 } else {
416 $userids = array($userid_or_ids);
417 }
6b5c722d 418
fcac8e51 419 if ($userids) {
420 $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
421 foreach ($userids as $userid) {
422 $grade_grades[$userid]->grade_item =& $grade_item;
423
424 $grade = new object();
425 $grade->grade = $grade_grades[$userid]->finalgrade;
426 $grade->locked = $grade_grades[$userid]->is_locked();
427 $grade->hidden = $grade_grades[$userid]->is_hidden();
428 $grade->feedback = $grade_grades[$userid]->feedback;
429 $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
a3fbd494 430 $grade->usermodified = $grade_grades[$userid]->usermodified;
fcac8e51 431
432 // create text representation of grade
433 if (in_array($grade_item->id, $needsupdate)) {
434 $grade->grade = false;
435 $grade->str_grade = get_string('error');
436
437 } else if (is_null($grade->grade)) {
438 $grade->grade = 0;
439 $grade->str_grade = get_string('nooutcome', 'grades');
440
441 } else {
442 $grade->grade = (int)$grade->grade;
443 $scale = $grade_item->load_scale();
444 $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
445 }
446
447 // create html representation of feedback
448 if (is_null($grade->feedback)) {
449 $grade->str_feedback = '';
450 } else {
451 $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
452 }
453
454 $outcome->grades[$userid] = $grade;
455 }
456 }
d19f4770 457
458 if (isset($return->outcomes[$grade_item->itemnumber])) {
459 // itemnumber duplicates - lets fix them!
460 $newnumber = $grade_item->itemnumber + 1;
461 while(grade_item::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
462 $newnumber++;
463 }
464 $outcome->itemnumber = $newnumber;
465 $grade_item->itemnumber = $newnumber;
466 $grade_item->update('system');
467 }
468
d886a7ea 469 $return->outcomes[$grade_item->itemnumber] = $outcome;
fcac8e51 470
471 }
6b5c722d 472 }
473 }
474
fcac8e51 475 // sort results using itemnumbers
476 ksort($return->items, SORT_NUMERIC);
477 ksort($return->outcomes, SORT_NUMERIC);
478
479 return $return;
6b5c722d 480}
481
b9f49659 482///////////////////////////////////////////////////////////////////
483///// End of public API for communication with modules/blocks /////
484///////////////////////////////////////////////////////////////////
77dbe708 485
77dbe708 486
612607bd 487
b9f49659 488///////////////////////////////////////////////////////////////////
489///// Internal API: used by gradebook plugins and Moodle core /////
490///////////////////////////////////////////////////////////////////
e0724506 491
492/**
493 * Returns course gradebook setting
494 * @param int $courseid
495 * @param string $name of setting, maybe null if reset only
496 * @param bool $resetcache force reset of internal static cache
497 * @return string value, NULL if no setting
498 */
499function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
500 static $cache = array();
501
502 if ($resetcache or !array_key_exists($courseid, $cache)) {
503 $cache[$courseid] = array();
504
505 } else if (is_null($name)) {
506 return null;
507
508 } else if (array_key_exists($name, $cache[$courseid])) {
509 return $cache[$courseid][$name];
510 }
511
512 if (!$data = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
513 $result = null;
514 } else {
515 $result = $data->value;
516 }
517
518 if (is_null($result)) {
519 $result = $default;
520 }
521
522 $cache[$courseid][$name] = $result;
523 return $result;
524}
525
26ed0305 526/**
527 * Returns all course gradebook settings as object properties
528 * @param int $courseid
529 * @return object
530 */
531function grade_get_settings($courseid) {
532 $settings = new object();
533 $settings->id = $courseid;
534
535 if ($records = get_records('grade_settings', 'courseid', $courseid)) {
536 foreach ($records as $record) {
537 $settings->{$record->name} = $record->value;
538 }
539 }
540
541 return $settings;
542}
543
e0724506 544/**
545 * Add/update course gradebook setting
546 * @param int $courseid
547 * @param string $name of setting
548 * @param string value, NULL means no setting==remove
549 * @return void
550 */
551function grade_set_setting($courseid, $name, $value) {
552 if (is_null($value)) {
553 delete_records('grade_settings', 'courseid', $courseid, 'name', addslashes($name));
554
555 } else if (!$existing = get_record('grade_settings', 'courseid', $courseid, 'name', addslashes($name))) {
556 $data = new object();
557 $data->courseid = $courseid;
558 $data->name = addslashes($name);
559 $data->value = addslashes($value);
560 insert_record('grade_settings', $data);
561
562 } else {
563 $data = new object();
564 $data->id = $existing->id;
565 $data->value = addslashes($value);
566 update_record('grade_settings', $data);
567 }
568
569 grade_get_setting($courseid, null, null, true); // reset the cache
570}
571
e9096dc2 572/**
573 * Returns string representation of grade value
574 * @param float $value grade value
575 * @param object $grade_item - by reference to prevent scale reloading
576 * @param bool $localized use localised decimal separator
b9f49659 577 * @param int $displaytype type of display - GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
e9096dc2 578 * @param int $decimalplaces number of decimal places when displaying float values
579 * @return string
580 */
581function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
582 if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
583 return '';
584 }
585
586 // no grade yet?
587 if (is_null($value)) {
588 return '-';
589 }
590
591 if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
592 //unknown type??
593 return '';
594 }
595
596 if (is_null($displaytype)) {
597 $displaytype = $grade_item->get_displaytype();
598 }
599
600 if (is_null($decimals)) {
601 $decimals = $grade_item->get_decimals();
602 }
603
604 switch ($displaytype) {
605 case GRADE_DISPLAY_TYPE_REAL:
606 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
1878f55d 607 if (!$scale = $grade_item->load_scale()) {
608 return get_string('error');
609 }
610
e9096dc2 611 $value = (int)bounded_number($grade_item->grademin, $value, $grade_item->grademax);
612 return format_string($scale->scale_items[$value-1]);
613
614 } else {
615 return format_float($value, $decimals, $localized);
616 }
617
618 case GRADE_DISPLAY_TYPE_PERCENTAGE:
619 $min = $grade_item->grademin;
620 $max = $grade_item->grademax;
621 if ($min == $max) {
622 return '';
623 }
624 $value = bounded_number($min, $value, $max);
625 $percentage = (($value-$min)*100)/($max-$min);
626 return format_float($percentage, $decimals, $localized).' %';
627
628 case GRADE_DISPLAY_TYPE_LETTER:
629 $context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid);
630 if (!$letters = grade_get_letters($context)) {
631 return ''; // no letters??
632 }
633
634 $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
635 $value = bounded_number(0, $value, 100); // just in case
636 foreach ($letters as $boundary => $letter) {
637 if ($value >= $boundary) {
638 return format_string($letter);
639 }
640 }
641 return '-'; // no match? maybe '' would be more correct
642
643 default:
644 return '';
645 }
646}
4b86bb08 647
648/**
649 * Returns grade options for gradebook category menu
650 * @param int $courseid
651 * @param bool $includenew include option for new category (-1)
652 * @return array of grade categories in course
653 */
654function grade_get_categories_menu($courseid, $includenew=false) {
655 $result = array();
656 if (!$categories = grade_category::fetch_all(array('courseid'=>$courseid))) {
657 //make sure course category exists
29c660c4 658 if (!grade_category::fetch_course_category($courseid)) {
4b86bb08 659 debugging('Can not create course grade category!');
660 return $result;
661 }
662 $categories = grade_category::fetch_all(array('courseid'=>$courseid));
663 }
664 foreach ($categories as $key=>$category) {
665 if ($category->is_course_category()) {
666 $result[$category->id] = get_string('uncategorised', 'grades');
667 unset($categories[$key]);
668 }
669 }
670 if ($includenew) {
671 $result[-1] = get_string('newcategory', 'grades');
672 }
673 $cats = array();
674 foreach ($categories as $category) {
675 $cats[$category->id] = $category->get_name();
676 }
677 asort($cats, SORT_LOCALE_STRING);
678
679 return ($result+$cats);
680}
e9096dc2 681
682/**
683 * Returns grade letters array used in context
684 * @param object $context object or null for defaults
685 * @return array of grade_boundary=>letter_string
686 */
687function grade_get_letters($context=null) {
688 if (empty($context)) {
284abb09 689 //default grading letters
690 return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
e9096dc2 691 }
692
693 static $cache = array();
694
695 if (array_key_exists($context->id, $cache)) {
696 return $cache[$context->id];
697 }
698
699 if (count($cache) > 100) {
700 $cache = array(); // cache size limit
701 }
702
703 $letters = array();
704
705 $contexts = get_parent_contexts($context);
706 array_unshift($contexts, $context->id);
707
708 foreach ($contexts as $ctxid) {
284abb09 709 if ($records = get_records('grade_letters', 'contextid', $ctxid, 'lowerboundary DESC')) {
e9096dc2 710 foreach ($records as $record) {
284abb09 711 $letters[$record->lowerboundary] = $record->letter;
e9096dc2 712 }
713 }
714
715 if (!empty($letters)) {
716 $cache[$context->id] = $letters;
717 return $letters;
718 }
719 }
720
721 $letters = grade_get_letters(null);
722 $cache[$context->id] = $letters;
723 return $letters;
724}
725
60243313 726
727/**
2c5e52e2 728 * Verify new value of idnumber - checks for uniqueness of new idnumbers, old are kept intact
60243313 729 * @param string idnumber string (with magic quotes)
204175c5 730 * @param int $courseid - id numbers are course unique only
60243313 731 * @param object $cm used for course module idnumbers and items attached to modules
732 * @param object $gradeitem is item idnumber
733 * @return boolean true means idnumber ok
734 */
204175c5 735function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
60243313 736 if ($idnumber == '') {
737 //we allow empty idnumbers
738 return true;
739 }
740
741 // keep existing even when not unique
742 if ($cm and $cm->idnumber == $idnumber) {
743 return true;
744 } else if ($grade_item and $grade_item->idnumber == $idnumber) {
745 return true;
746 }
747
204175c5 748 if (get_records_select('course_modules', "course = $courseid AND idnumber='$idnumber'")) {
60243313 749 return false;
750 }
751
204175c5 752 if (get_records_select('grade_items', "courseid = $courseid AND idnumber='$idnumber'")) {
60243313 753 return false;
754 }
755
756 return true;
757}
758
759/**
760 * Force final grade recalculation in all course items
761 * @param int $courseid
762 */
f8e6e4db 763function grade_force_full_regrading($courseid) {
764 set_field('grade_items', 'needsupdate', 1, 'courseid', $courseid);
765}
34e67f76 766
5834dcdb 767/**
ac9b0805 768 * Updates all final grades in course.
a8995b34 769 *
770 * @param int $courseid
f8e6e4db 771 * @param int $userid if specified, try to do a quick regrading of grades of this user only
772 * @param object $updated_item the item in which
773 * @return boolean true if ok, array of errors if problems found (item id is used as key)
a8995b34 774 */
c86caae7 775function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null) {
b8ff92b6 776
514a3467 777 $course_item = grade_item::fetch_course_item($courseid);
f04873a9 778
f8e6e4db 779 if ($userid) {
780 // one raw grade updated for one user
781 if (empty($updated_item)) {
782 error("updated_item_id can not be null!");
783 }
784 if ($course_item->needsupdate) {
785 $updated_item->force_regrading();
b45d8391 786 return array($course_item->id =>'Can not do fast regrading after updating of raw grades');
a8995b34 787 }
772ddfbf 788
f8e6e4db 789 } else {
790 if (!$course_item->needsupdate) {
791 // nothing to do :-)
b8ff92b6 792 return true;
b8ff92b6 793 }
a8995b34 794 }
795
f8e6e4db 796 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
797 $depends_on = array();
798
799 // first mark all category and calculated items as needing regrading
fb0e3570 800 // this is slower, but 100% accurate
f8e6e4db 801 foreach ($grade_items as $gid=>$gitem) {
fb46b5b6 802 if (!empty($updated_item) and $updated_item->id == $gid) {
f8e6e4db 803 $grade_items[$gid]->needsupdate = 1;
804
eacd3700 805 } else if ($gitem->is_course_item() or $gitem->is_category_item() or $gitem->is_calculated()) {
f8e6e4db 806 $grade_items[$gid]->needsupdate = 1;
807 }
2e53372c 808
f8e6e4db 809 // construct depends_on lookup array
810 $depends_on[$gid] = $grade_items[$gid]->depends_on();
811 }
2e53372c 812
d14ae855 813 $errors = array();
b8ff92b6 814 $finalids = array();
d14ae855 815 $gids = array_keys($grade_items);
eacd3700 816 $failed = 0;
d14ae855 817
818 while (count($finalids) < count($gids)) { // work until all grades are final or error found
819 $count = 0;
820 foreach ($gids as $gid) {
821 if (in_array($gid, $finalids)) {
822 continue; // already final
823 }
824
825 if (!$grade_items[$gid]->needsupdate) {
826 $finalids[] = $gid; // we can make it final - does not need update
b8ff92b6 827 continue;
828 }
829
b8ff92b6 830 $doupdate = true;
f8e6e4db 831 foreach ($depends_on[$gid] as $did) {
b8ff92b6 832 if (!in_array($did, $finalids)) {
833 $doupdate = false;
d14ae855 834 continue; // this item depends on something that is not yet in finals array
b8ff92b6 835 }
836 }
837
838 //oki - let's update, calculate or aggregate :-)
839 if ($doupdate) {
d14ae855 840 $result = $grade_items[$gid]->regrade_final_grades($userid);
f8e6e4db 841
842 if ($result === true) {
d14ae855 843 $grade_items[$gid]->regrading_finished();
fb0e3570 844 $grade_items[$gid]->check_locktime(); // do the locktime item locking
f8e6e4db 845 $count++;
b8ff92b6 846 $finalids[] = $gid;
fb0e3570 847
f8e6e4db 848 } else {
d14ae855 849 $grade_items[$gid]->force_regrading();
f8e6e4db 850 $errors[$gid] = $result;
b8ff92b6 851 }
852 }
853 }
854
855 if ($count == 0) {
eacd3700 856 $failed++;
857 } else {
858 $failed = 0;
859 }
860
861 if ($failed > 1) {
d14ae855 862 foreach($gids as $gid) {
863 if (in_array($gid, $finalids)) {
864 continue; // this one is ok
865 }
866 $grade_items[$gid]->force_regrading();
867 $errors[$grade_items[$gid]->id] = 'Probably circular reference or broken calculation formula'; // TODO: localize
b8ff92b6 868 }
d14ae855 869 break; // oki, found error
b8ff92b6 870 }
871 }
872
873 if (count($errors) == 0) {
fb0e3570 874 if (empty($userid)) {
875 // do the locktime locking of grades, but only when doing full regrading
fed7cdc9 876 grade_grade::check_locktime_all($gids);
fb0e3570 877 }
b8ff92b6 878 return true;
879 } else {
880 return $errors;
881 }
a8995b34 882}
967f222f 883
de420c11 884/**
d185c3ee 885 * For backwards compatibility with old third-party modules, this function can
886 * be used to import all grades from activities with legacy grading.
f0362b5d 887 * @param int $courseid
967f222f 888 */
f0362b5d 889function grade_grab_legacy_grades($courseid) {
ac9b0805 890 global $CFG;
967f222f 891
892 if (!$mods = get_list_of_plugins('mod') ) {
893 error('No modules installed!');
894 }
895
896 foreach ($mods as $mod) {
967f222f 897 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
898 continue;
899 }
900
d185c3ee 901 $fullmod = $CFG->dirroot.'/mod/'.$mod;
967f222f 902
903 // include the module lib once
904 if (file_exists($fullmod.'/lib.php')) {
905 include_once($fullmod.'/lib.php');
de420c11 906 // look for modname_grades() function - old gradebook pulling function
907 // if present sync the grades with new grading system
967f222f 908 $gradefunc = $mod.'_grades';
de420c11 909 if (function_exists($gradefunc)) {
f0362b5d 910 grade_grab_course_grades($courseid, $mod);
967f222f 911 }
912 }
913 }
914}
915
ac9b0805 916/**
f0362b5d 917 * Refetches data from all course activities
918 * @param int $courseid
919 * @param string $modname
920 * @return success
ac9b0805 921 */
f0362b5d 922function grade_grab_course_grades($courseid, $modname=null) {
ac9b0805 923 global $CFG;
924
f0362b5d 925 if ($modname) {
926 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
927 FROM {$CFG->prefix}$modname a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
928 WHERE m.name='$modname' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
929
930 if ($modinstances = get_records_sql($sql)) {
931 foreach ($modinstances as $modinstance) {
932 grade_update_mod_grades($modinstance);
933 }
934 }
935 return;
936 }
937
ac9b0805 938 if (!$mods = get_list_of_plugins('mod') ) {
939 error('No modules installed!');
940 }
941
942 foreach ($mods as $mod) {
ac9b0805 943 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
944 continue;
945 }
946
ac9b0805 947 $fullmod = $CFG->dirroot.'/mod/'.$mod;
948
949 // include the module lib once
950 if (file_exists($fullmod.'/lib.php')) {
f0362b5d 951 // get all instance of the activity
952 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
953 FROM {$CFG->prefix}$mod a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
954 WHERE m.name='$mod' AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=$courseid";
955
956 if ($modinstances = get_records_sql($sql)) {
957 foreach ($modinstances as $modinstance) {
958 grade_update_mod_grades($modinstance);
959 }
ac9b0805 960 }
961 }
962 }
963}
964
d185c3ee 965/**
966 * Force full update of module grades in central gradebook - works for both legacy and converted activities.
967 * @param object $modinstance object with extra cmidnumber and modname property
968 * @return boolean success
969 */
2b0f65e2 970function grade_update_mod_grades($modinstance, $userid=0) {
d185c3ee 971 global $CFG;
972
973 $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
974 if (!file_exists($fullmod.'/lib.php')) {
975 debugging('missing lib.php file in module');
976 return false;
977 }
978 include_once($fullmod.'/lib.php');
979
980 // does it use legacy grading?
981 $gradefunc = $modinstance->modname.'_grades';
982 $updategradesfunc = $modinstance->modname.'_update_grades';
983 $updateitemfunc = $modinstance->modname.'_grade_item_update';
984
985 if (function_exists($gradefunc)) {
2b0f65e2 986
987 // legacy module - not yet converted
d185c3ee 988 if ($oldgrades = $gradefunc($modinstance->id)) {
989
990 $grademax = $oldgrades->maxgrade;
991 $scaleid = NULL;
992 if (!is_numeric($grademax)) {
993 // scale name is provided as a string, try to find it
994 if (!$scale = get_record('scale', 'name', $grademax)) {
995 debugging('Incorrect scale name! name:'.$grademax);
996 return false;
997 }
998 $scaleid = $scale->id;
999 }
1000
1001 if (!$grade_item = grade_get_legacy_grade_item($modinstance, $grademax, $scaleid)) {
1002 debugging('Can not get/create legacy grade item!');
1003 return false;
1004 }
1005
0b5a80a1 1006 if (!empty($oldgrades->grades)) {
1007 $grades = array();
d185c3ee 1008
0b5a80a1 1009 foreach ($oldgrades->grades as $uid=>$usergrade) {
1010 if ($userid and $uid != $userid) {
1011 continue;
1012 }
1013 $grade = new object();
1014 $grade->userid = $uid;
d185c3ee 1015
0b5a80a1 1016 if ($usergrade == '-') {
1017 // no grade
1018 $grade->rawgrade = null;
d185c3ee 1019
0b5a80a1 1020 } else if ($scaleid) {
1021 // scale in use, words used
1022 $gradescale = explode(",", $scale->scale);
1023 $grade->rawgrade = array_search($usergrade, $gradescale) + 1;
1024
1025 } else {
1026 // good old numeric value
1027 $grade->rawgrade = $usergrade;
1028 }
1029 $grades[] = $grade;
d185c3ee 1030 }
d185c3ee 1031
0b5a80a1 1032 grade_update('legacygrab', $grade_item->courseid, $grade_item->itemtype, $grade_item->itemmodule,
1033 $grade_item->iteminstance, $grade_item->itemnumber, $grades);
1034 }
d185c3ee 1035 }
1036
1037 } else if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
1038 //new grading supported, force updating of grades
1039 $updateitemfunc($modinstance);
2b0f65e2 1040 $updategradesfunc($modinstance, $userid);
d185c3ee 1041
1042 } else {
2b0f65e2 1043 // mudule does not support grading??
d185c3ee 1044 }
1045
1046 return true;
1047}
de420c11 1048
1049/**
d185c3ee 1050 * Get and update/create grade item for legacy modules.
de420c11 1051 */
1052function grade_get_legacy_grade_item($modinstance, $grademax, $scaleid) {
1053
1054 // does it already exist?
42ff9ce6 1055 if ($grade_items = grade_item::fetch_all(array('courseid'=>$modinstance->course, 'itemtype'=>'mod', 'itemmodule'=>$modinstance->modname, 'iteminstance'=>$modinstance->id, 'itemnumber'=>0))) {
de420c11 1056 if (count($grade_items) > 1) {
d185c3ee 1057 debugging('Multiple legacy grade_items found.');
de420c11 1058 return false;
1059 }
1060
1061 $grade_item = reset($grade_items);
de420c11 1062
d185c3ee 1063 if (is_null($grademax) and is_null($scaleid)) {
1064 $grade_item->gradetype = GRADE_TYPE_NONE;
de420c11 1065
d185c3ee 1066 } else if ($scaleid) {
1067 $grade_item->gradetype = GRADE_TYPE_SCALE;
1068 $grade_item->scaleid = $scaleid;
97d608ba 1069 $grade_item->grademin = 1;
de420c11 1070
d185c3ee 1071 } else {
97d608ba 1072 $grade_item->gradetype = GRADE_TYPE_VALUE;
1073 $grade_item->grademax = $grademax;
1074 $grade_item->grademin = 0;
de420c11 1075 }
1076
d185c3ee 1077 $grade_item->itemname = $modinstance->name;
1078 $grade_item->idnumber = $modinstance->cmidnumber;
de420c11 1079
d185c3ee 1080 $grade_item->update();
de420c11 1081
1082 return $grade_item;
1083 }
612607bd 1084
de420c11 1085 // create new one
d185c3ee 1086 $params = array('courseid' =>$modinstance->course,
de420c11 1087 'itemtype' =>'mod',
1088 'itemmodule' =>$modinstance->modname,
1089 'iteminstance'=>$modinstance->id,
d185c3ee 1090 'itemnumber' =>0,
de420c11 1091 'itemname' =>$modinstance->name,
1092 'idnumber' =>$modinstance->cmidnumber);
1093
d185c3ee 1094 if (is_null($grademax) and is_null($scaleid)) {
1095 $params['gradetype'] = GRADE_TYPE_NONE;
1096
1097 } else if ($scaleid) {
612607bd 1098 $params['gradetype'] = GRADE_TYPE_SCALE;
de420c11 1099 $params['scaleid'] = $scaleid;
b3ac6c3e 1100 $grade_item->grademin = 1;
de420c11 1101 } else {
612607bd 1102 $params['gradetype'] = GRADE_TYPE_VALUE;
de420c11 1103 $params['grademax'] = $grademax;
1104 $params['grademin'] = 0;
1105 }
1106
f70152b7 1107 $grade_item = new grade_item($params);
1108 $grade_item->insert();
de420c11 1109
f70152b7 1110 return $grade_item;
de420c11 1111}
1112
b51ece5b 1113/**
1114 * Remove grade letters for given context
1115 * @param object $context
1116 */
1117function remove_grade_letters($context, $showfeedback) {
1118 $strdeleted = get_string('deleted');
1119
1120 delete_records('grade_letters', 'contextid', $context->id);
1121 if ($showfeedback) {
1122 notify($strdeleted.' - '.get_string('letters', 'grades'));
1123 }
1124}
f615fbab 1125/**
1126 * Remove all grade related course data - history is kept
1127 * @param int $courseid
6b5c722d 1128 * @param bool @showfeedback print feedback
f615fbab 1129 */
1130function remove_course_grades($courseid, $showfeedback) {
1131 $strdeleted = get_string('deleted');
1132
1133 $course_category = grade_category::fetch_course_category($courseid);
1134 $course_category->delete('coursedelete');
1135 if ($showfeedback) {
1136 notify($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'));
1137 }
1138
1139 if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
1140 foreach ($outcomes as $outcome) {
1141 $outcome->delete('coursedelete');
1142 }
1143 }
1144 delete_records('grade_outcomes_courses', 'courseid', $courseid);
1145 if ($showfeedback) {
1146 notify($strdeleted.' - '.get_string('outcomes', 'grades'));
1147 }
1148
1149 if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
1150 foreach ($scales as $scale) {
1151 $scale->delete('coursedelete');
1152 }
1153 }
1154 if ($showfeedback) {
1155 notify($strdeleted.' - '.get_string('scales'));
1156 }
b51ece5b 1157
1158 delete_records('grade_settings', 'courseid', $courseid);
1159 if ($showfeedback) {
1160 notify($strdeleted.' - '.get_string('settings', 'grades'));
1161 }
f615fbab 1162}
bfe7297e 1163
8a0a6046 1164/**
1165 * Does gradebook cleanup when module uninstalled.
1166 */
1167function grade_uninstalled_module($modname) {
1168 global $CFG;
1169
1170 $sql = "SELECT *
1171 FROM {$CFG->prefix}grade_items
1172 WHERE itemtype='mod' AND itemmodule='$modname'";
1173
1174 // go all items for this module and delete them including the grades
1175 if ($rs = get_recordset_sql($sql)) {
1176 while ($item = rs_fetch_next_record($rs)) {
1177 $grade_item = new grade_item($item, false);
1178 $grade_item->delete('moduninstall');
1179 }
1180 rs_close($rs);
1181 }
1182}
1183
2650c51e 1184/**
1185 * Grading cron job
1186 */
1187function grade_cron() {
26101be8 1188 global $CFG;
1189
1190 $now = time();
1191
1192 $sql = "SELECT i.*
1193 FROM {$CFG->prefix}grade_items i
1194 WHERE i.locked = 0 AND i.locktime > 0 AND i.locktime < $now AND EXISTS (
1f4a0320 1195 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 1196
2650c51e 1197 // go through all courses that have proper final grades and lock them if needed
26101be8 1198 if ($rs = get_recordset_sql($sql)) {
03cedd62 1199 while ($item = rs_fetch_next_record($rs)) {
1200 $grade_item = new grade_item($item, false);
1201 $grade_item->locked = $now;
1202 $grade_item->update('locktime');
2650c51e 1203 }
1204 rs_close($rs);
1205 }
26101be8 1206
fcac8e51 1207 $grade_inst = new grade_grade();
1208 $fields = 'g.'.implode(',g.', $grade_inst->required_fields);
1209
1210 $sql = "SELECT $fields
26101be8 1211 FROM {$CFG->prefix}grade_grades g, {$CFG->prefix}grade_items i
1212 WHERE g.locked = 0 AND g.locktime > 0 AND g.locktime < $now AND g.itemid=i.id AND EXISTS (
1f4a0320 1213 SELECT 'x' FROM {$CFG->prefix}grade_items c WHERE c.itemtype='course' AND c.needsupdate=0 AND c.courseid=i.courseid)";
26101be8 1214
1215 // go through all courses that have proper final grades and lock them if needed
1216 if ($rs = get_recordset_sql($sql)) {
03cedd62 1217 while ($grade = rs_fetch_next_record($rs)) {
1218 $grade_grade = new grade_grade($grade, false);
1219 $grade_grade->locked = $now;
1220 $grade_grade->update('locktime');
26101be8 1221 }
1222 rs_close($rs);
1223 }
1224
1ee0df06 1225 //TODO: do not run this cleanup every cron invocation
1226 // cleanup history tables
f0362b5d 1227 if (!empty($CFG->gradehistorylifetime)) { // value in days
1228 $histlifetime = $now - ($CFG->gradehistorylifetime * 3600 * 24);
1229 $tables = array('grade_outcomes_history', 'grade_categories_history', 'grade_items_history', 'grade_grades_history', 'scale_history');
1230 foreach ($tables as $table) {
1231 if (delete_records_select($table, "timemodified < $histlifetime")) {
1232 mtrace(" Deleted old grade history records from '$table'");
1ee0df06 1233 }
1234 }
f0362b5d 1235 }
1236}
1237
1238/**
1239 * Resel all course grades
1240 * @param int $courseid
1241 * @return success
1242 */
1243function grade_course_reset($courseid) {
1244
1245 // no recalculations
1246 grade_force_full_regrading($courseid);
1247
1248 $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
1249 foreach ($grade_items as $gid=>$grade_item) {
1250 $grade_item->delete_all_grades('reset');
1251 }
1ee0df06 1252
f0362b5d 1253 //refetch all grades
1254 grade_grab_course_grades($courseid);
1ee0df06 1255
f0362b5d 1256 // recalculate all grades
1257 grade_regrade_final_grades($courseid);
1258 return true;
2650c51e 1259}
1260
b45d8391 1261/**
66690b69 1262 * Convert number to 5 decimalfloat, empty tring or null db compatible format
1263 * (we need this to decide if db value changed)
b45d8391 1264 * @param mixed number
1265 * @return mixed float or null
1266 */
1267function grade_floatval($number) {
66690b69 1268 if (is_null($number) or $number === '') {
b45d8391 1269 return null;
1270 }
66690b69 1271 // we must round to 5 digits to get the same precision as in 10,5 db fields
25bcd908 1272 // note: db rounding for 10,5 is different from php round() function
66690b69 1273 return round($number, 5);
b45d8391 1274}
25bcd908 1275
1276/**
1277 * Compare two float numbers safely. Uses 5 decimals php precision. Nulls accepted too.
1278 * Used for skipping of db updates
1279 * @param float $f1
1280 * @param float $f2
1281 * @return true if different
1282 */
1283function grade_floats_different($f1, $f2) {
1284 // note: db rounding for 10,5 is different from php round() function
1285 return (grade_floatval($f1) !== grade_floatval($f2));
1286}
1287
60cf7430 1288?>