PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/gradelib.php

http://github.com/moodle/moodle
PHP | 1642 lines | 1008 code | 236 blank | 398 comment | 230 complexity | a74bea8d95abf0c97ad50453151eb0b9 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Library of functions for gradebook - both public and internal
  18. *
  19. * @package core_grades
  20. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. global $CFG;
  25. /** Include essential files */
  26. require_once($CFG->libdir . '/grade/constants.php');
  27. require_once($CFG->libdir . '/grade/grade_category.php');
  28. require_once($CFG->libdir . '/grade/grade_item.php');
  29. require_once($CFG->libdir . '/grade/grade_grade.php');
  30. require_once($CFG->libdir . '/grade/grade_scale.php');
  31. require_once($CFG->libdir . '/grade/grade_outcome.php');
  32. /////////////////////////////////////////////////////////////////////
  33. ///// Start of public API for communication with modules/blocks /////
  34. /////////////////////////////////////////////////////////////////////
  35. /**
  36. * Submit new or update grade; update/create grade_item definition. Grade must have userid specified,
  37. * rawgrade and feedback with format are optional. rawgrade NULL means 'Not graded'.
  38. * Missing property or key means does not change the existing value.
  39. *
  40. * Only following grade item properties can be changed 'itemname', 'idnumber', 'gradetype', 'grademax',
  41. * 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted' and 'hidden'. 'reset' means delete all current grades including locked ones.
  42. *
  43. * Manual, course or category items can not be updated by this function.
  44. *
  45. * @category grade
  46. * @param string $source Source of the grade such as 'mod/assignment'
  47. * @param int $courseid ID of course
  48. * @param string $itemtype Type of grade item. For example, mod or block
  49. * @param string $itemmodule More specific then $itemtype. For example, assignment or forum. May be NULL for some item types
  50. * @param int $iteminstance Instance ID of graded item
  51. * @param int $itemnumber Most probably 0. Modules can use other numbers when having more than one grade for each user
  52. * @param mixed $grades Grade (object, array) or several grades (arrays of arrays or objects), NULL if updating grade_item definition only
  53. * @param mixed $itemdetails Object or array describing the grading item, NULL if no change
  54. * @return int Returns GRADE_UPDATE_OK, GRADE_UPDATE_FAILED, GRADE_UPDATE_MULTIPLE or GRADE_UPDATE_ITEM_LOCKED
  55. */
  56. function grade_update($source, $courseid, $itemtype, $itemmodule, $iteminstance, $itemnumber, $grades=NULL, $itemdetails=NULL) {
  57. global $USER, $CFG, $DB;
  58. // only following grade_item properties can be changed in this function
  59. $allowed = array('itemname', 'idnumber', 'gradetype', 'grademax', 'grademin', 'scaleid', 'multfactor', 'plusfactor', 'deleted', 'hidden');
  60. // list of 10,5 numeric fields
  61. $floats = array('grademin', 'grademax', 'multfactor', 'plusfactor');
  62. // grade item identification
  63. $params = compact('courseid', 'itemtype', 'itemmodule', 'iteminstance', 'itemnumber');
  64. if (is_null($courseid) or is_null($itemtype)) {
  65. debugging('Missing courseid or itemtype');
  66. return GRADE_UPDATE_FAILED;
  67. }
  68. if (!$grade_items = grade_item::fetch_all($params)) {
  69. // create a new one
  70. $grade_item = false;
  71. } else if (count($grade_items) == 1){
  72. $grade_item = reset($grade_items);
  73. unset($grade_items); //release memory
  74. } else {
  75. debugging('Found more than one grade item');
  76. return GRADE_UPDATE_MULTIPLE;
  77. }
  78. if (!empty($itemdetails['deleted'])) {
  79. if ($grade_item) {
  80. if ($grade_item->delete($source)) {
  81. return GRADE_UPDATE_OK;
  82. } else {
  83. return GRADE_UPDATE_FAILED;
  84. }
  85. }
  86. return GRADE_UPDATE_OK;
  87. }
  88. /// Create or update the grade_item if needed
  89. if (!$grade_item) {
  90. if ($itemdetails) {
  91. $itemdetails = (array)$itemdetails;
  92. // grademin and grademax ignored when scale specified
  93. if (array_key_exists('scaleid', $itemdetails)) {
  94. if ($itemdetails['scaleid']) {
  95. unset($itemdetails['grademin']);
  96. unset($itemdetails['grademax']);
  97. }
  98. }
  99. foreach ($itemdetails as $k=>$v) {
  100. if (!in_array($k, $allowed)) {
  101. // ignore it
  102. continue;
  103. }
  104. if ($k == 'gradetype' and $v == GRADE_TYPE_NONE) {
  105. // no grade item needed!
  106. return GRADE_UPDATE_OK;
  107. }
  108. $params[$k] = $v;
  109. }
  110. }
  111. $grade_item = new grade_item($params);
  112. $grade_item->insert();
  113. } else {
  114. if ($grade_item->is_locked()) {
  115. // no notice() here, test returned value instead!
  116. return GRADE_UPDATE_ITEM_LOCKED;
  117. }
  118. if ($itemdetails) {
  119. $itemdetails = (array)$itemdetails;
  120. $update = false;
  121. foreach ($itemdetails as $k=>$v) {
  122. if (!in_array($k, $allowed)) {
  123. // ignore it
  124. continue;
  125. }
  126. if (in_array($k, $floats)) {
  127. if (grade_floats_different($grade_item->{$k}, $v)) {
  128. $grade_item->{$k} = $v;
  129. $update = true;
  130. }
  131. } else {
  132. if ($grade_item->{$k} != $v) {
  133. $grade_item->{$k} = $v;
  134. $update = true;
  135. }
  136. }
  137. }
  138. if ($update) {
  139. $grade_item->update();
  140. }
  141. }
  142. }
  143. /// reset grades if requested
  144. if (!empty($itemdetails['reset'])) {
  145. $grade_item->delete_all_grades('reset');
  146. return GRADE_UPDATE_OK;
  147. }
  148. /// Some extra checks
  149. // do we use grading?
  150. if ($grade_item->gradetype == GRADE_TYPE_NONE) {
  151. return GRADE_UPDATE_OK;
  152. }
  153. // no grade submitted
  154. if (empty($grades)) {
  155. return GRADE_UPDATE_OK;
  156. }
  157. /// Finally start processing of grades
  158. if (is_object($grades)) {
  159. $grades = array($grades->userid=>$grades);
  160. } else {
  161. if (array_key_exists('userid', $grades)) {
  162. $grades = array($grades['userid']=>$grades);
  163. }
  164. }
  165. /// normalize and verify grade array
  166. foreach($grades as $k=>$g) {
  167. if (!is_array($g)) {
  168. $g = (array)$g;
  169. $grades[$k] = $g;
  170. }
  171. if (empty($g['userid']) or $k != $g['userid']) {
  172. debugging('Incorrect grade array index, must be user id! Grade ignored.');
  173. unset($grades[$k]);
  174. }
  175. }
  176. if (empty($grades)) {
  177. return GRADE_UPDATE_FAILED;
  178. }
  179. $count = count($grades);
  180. if ($count > 0 and $count < 200) {
  181. list($uids, $params) = $DB->get_in_or_equal(array_keys($grades), SQL_PARAMS_NAMED, $start='uid');
  182. $params['gid'] = $grade_item->id;
  183. $sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid AND userid $uids";
  184. } else {
  185. $sql = "SELECT * FROM {grade_grades} WHERE itemid = :gid";
  186. $params = array('gid'=>$grade_item->id);
  187. }
  188. $rs = $DB->get_recordset_sql($sql, $params);
  189. $failed = false;
  190. while (count($grades) > 0) {
  191. $grade_grade = null;
  192. $grade = null;
  193. foreach ($rs as $gd) {
  194. $userid = $gd->userid;
  195. if (!isset($grades[$userid])) {
  196. // this grade not requested, continue
  197. continue;
  198. }
  199. // existing grade requested
  200. $grade = $grades[$userid];
  201. $grade_grade = new grade_grade($gd, false);
  202. unset($grades[$userid]);
  203. break;
  204. }
  205. if (is_null($grade_grade)) {
  206. if (count($grades) == 0) {
  207. // no more grades to process
  208. break;
  209. }
  210. $grade = reset($grades);
  211. $userid = $grade['userid'];
  212. $grade_grade = new grade_grade(array('itemid'=>$grade_item->id, 'userid'=>$userid), false);
  213. $grade_grade->load_optional_fields(); // add feedback and info too
  214. unset($grades[$userid]);
  215. }
  216. $rawgrade = false;
  217. $feedback = false;
  218. $feedbackformat = FORMAT_MOODLE;
  219. $feedbackfiles = [];
  220. $usermodified = $USER->id;
  221. $datesubmitted = null;
  222. $dategraded = null;
  223. if (array_key_exists('rawgrade', $grade)) {
  224. $rawgrade = $grade['rawgrade'];
  225. }
  226. if (array_key_exists('feedback', $grade)) {
  227. $feedback = $grade['feedback'];
  228. }
  229. if (array_key_exists('feedbackformat', $grade)) {
  230. $feedbackformat = $grade['feedbackformat'];
  231. }
  232. if (array_key_exists('feedbackfiles', $grade)) {
  233. $feedbackfiles = $grade['feedbackfiles'];
  234. }
  235. if (array_key_exists('usermodified', $grade)) {
  236. $usermodified = $grade['usermodified'];
  237. }
  238. if (array_key_exists('datesubmitted', $grade)) {
  239. $datesubmitted = $grade['datesubmitted'];
  240. }
  241. if (array_key_exists('dategraded', $grade)) {
  242. $dategraded = $grade['dategraded'];
  243. }
  244. // update or insert the grade
  245. if (!$grade_item->update_raw_grade($userid, $rawgrade, $source, $feedback, $feedbackformat, $usermodified,
  246. $dategraded, $datesubmitted, $grade_grade, $feedbackfiles)) {
  247. $failed = true;
  248. }
  249. }
  250. if ($rs) {
  251. $rs->close();
  252. }
  253. if (!$failed) {
  254. return GRADE_UPDATE_OK;
  255. } else {
  256. return GRADE_UPDATE_FAILED;
  257. }
  258. }
  259. /**
  260. * Updates a user's outcomes. Manual outcomes can not be updated.
  261. *
  262. * @category grade
  263. * @param string $source Source of the grade such as 'mod/assignment'
  264. * @param int $courseid ID of course
  265. * @param string $itemtype Type of grade item. For example, 'mod' or 'block'
  266. * @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
  267. * @param int $iteminstance Instance ID of graded item. For example the forum ID.
  268. * @param int $userid ID of the graded user
  269. * @param array $data Array consisting of grade item itemnumber ({@link grade_update()}) => outcomegrade
  270. * @return bool returns true if grade items were found and updated successfully
  271. */
  272. function grade_update_outcomes($source, $courseid, $itemtype, $itemmodule, $iteminstance, $userid, $data) {
  273. if ($items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
  274. $result = true;
  275. foreach ($items as $item) {
  276. if (!array_key_exists($item->itemnumber, $data)) {
  277. continue;
  278. }
  279. $grade = $data[$item->itemnumber] < 1 ? null : $data[$item->itemnumber];
  280. $result = ($item->update_final_grade($userid, $grade, $source) && $result);
  281. }
  282. return $result;
  283. }
  284. return false; //grade items not found
  285. }
  286. /**
  287. * Return true if the course needs regrading.
  288. *
  289. * @param int $courseid The course ID
  290. * @return bool true if course grades need updating.
  291. */
  292. function grade_needs_regrade_final_grades($courseid) {
  293. $course_item = grade_item::fetch_course_item($courseid);
  294. return $course_item->needsupdate;
  295. }
  296. /**
  297. * Return true if the regrade process is likely to be time consuming and
  298. * will therefore require the progress bar.
  299. *
  300. * @param int $courseid The course ID
  301. * @return bool Whether the regrade process is likely to be time consuming
  302. */
  303. function grade_needs_regrade_progress_bar($courseid) {
  304. global $DB;
  305. $grade_items = grade_item::fetch_all(array('courseid' => $courseid));
  306. list($sql, $params) = $DB->get_in_or_equal(array_keys($grade_items), SQL_PARAMS_NAMED, 'gi');
  307. $gradecount = $DB->count_records_select('grade_grades', 'itemid ' . $sql, $params);
  308. // This figure may seem arbitrary, but after analysis it seems that 100 grade_grades can be calculated in ~= 0.5 seconds.
  309. // Any longer than this and we want to show the progress bar.
  310. return $gradecount > 100;
  311. }
  312. /**
  313. * Check whether regarding of final grades is required and, if so, perform the regrade.
  314. *
  315. * If the regrade is expected to be time consuming (see grade_needs_regrade_progress_bar), then this
  316. * function will output the progress bar, and redirect to the current PAGE->url after regrading
  317. * completes. Otherwise the regrading will happen immediately and the page will be loaded as per
  318. * normal.
  319. *
  320. * A callback may be specified, which is called if regrading has taken place.
  321. * The callback may optionally return a URL which will be redirected to when the progress bar is present.
  322. *
  323. * @param stdClass $course The course to regrade
  324. * @param callable $callback A function to call if regrading took place
  325. * @return moodle_url The URL to redirect to if redirecting
  326. */
  327. function grade_regrade_final_grades_if_required($course, callable $callback = null) {
  328. global $PAGE, $OUTPUT;
  329. if (!grade_needs_regrade_final_grades($course->id)) {
  330. return false;
  331. }
  332. if (grade_needs_regrade_progress_bar($course->id)) {
  333. $PAGE->set_heading($course->fullname);
  334. echo $OUTPUT->header();
  335. echo $OUTPUT->heading(get_string('recalculatinggrades', 'grades'));
  336. $progress = new \core\progress\display(true);
  337. $status = grade_regrade_final_grades($course->id, null, null, $progress);
  338. // Show regrade errors and set the course to no longer needing regrade (stop endless loop).
  339. if (is_array($status)) {
  340. foreach ($status as $error) {
  341. $errortext = new \core\output\notification($error, \core\output\notification::NOTIFY_ERROR);
  342. echo $OUTPUT->render($errortext);
  343. }
  344. $courseitem = grade_item::fetch_course_item($course->id);
  345. $courseitem->regrading_finished();
  346. }
  347. if ($callback) {
  348. //
  349. $url = call_user_func($callback);
  350. }
  351. if (empty($url)) {
  352. $url = $PAGE->url;
  353. }
  354. echo $OUTPUT->continue_button($url);
  355. echo $OUTPUT->footer();
  356. die();
  357. } else {
  358. $result = grade_regrade_final_grades($course->id);
  359. if ($callback) {
  360. call_user_func($callback);
  361. }
  362. return $result;
  363. }
  364. }
  365. /**
  366. * Returns grading information for given activity, optionally with user grades
  367. * Manual, course or category items can not be queried.
  368. *
  369. * @category grade
  370. * @param int $courseid ID of course
  371. * @param string $itemtype Type of grade item. For example, 'mod' or 'block'
  372. * @param string $itemmodule More specific then $itemtype. For example, 'forum' or 'quiz'. May be NULL for some item types
  373. * @param int $iteminstance ID of the item module
  374. * @param mixed $userid_or_ids Either a single user ID, an array of user IDs or null. If user ID or IDs are not supplied returns information about grade_item
  375. * @return array Array of grade information objects (scaleid, name, grade and locked status, etc.) indexed with itemnumbers
  376. */
  377. function grade_get_grades($courseid, $itemtype, $itemmodule, $iteminstance, $userid_or_ids=null) {
  378. global $CFG;
  379. $return = new stdClass();
  380. $return->items = array();
  381. $return->outcomes = array();
  382. $course_item = grade_item::fetch_course_item($courseid);
  383. $needsupdate = array();
  384. if ($course_item->needsupdate) {
  385. $result = grade_regrade_final_grades($courseid);
  386. if ($result !== true) {
  387. $needsupdate = array_keys($result);
  388. }
  389. }
  390. if ($grade_items = grade_item::fetch_all(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid))) {
  391. foreach ($grade_items as $grade_item) {
  392. $decimalpoints = null;
  393. if (empty($grade_item->outcomeid)) {
  394. // prepare information about grade item
  395. $item = new stdClass();
  396. $item->id = $grade_item->id;
  397. $item->itemnumber = $grade_item->itemnumber;
  398. $item->itemtype = $grade_item->itemtype;
  399. $item->itemmodule = $grade_item->itemmodule;
  400. $item->iteminstance = $grade_item->iteminstance;
  401. $item->scaleid = $grade_item->scaleid;
  402. $item->name = $grade_item->get_name();
  403. $item->grademin = $grade_item->grademin;
  404. $item->grademax = $grade_item->grademax;
  405. $item->gradepass = $grade_item->gradepass;
  406. $item->locked = $grade_item->is_locked();
  407. $item->hidden = $grade_item->is_hidden();
  408. $item->grades = array();
  409. switch ($grade_item->gradetype) {
  410. case GRADE_TYPE_NONE:
  411. break;
  412. case GRADE_TYPE_VALUE:
  413. $item->scaleid = 0;
  414. break;
  415. case GRADE_TYPE_TEXT:
  416. $item->scaleid = 0;
  417. $item->grademin = 0;
  418. $item->grademax = 0;
  419. $item->gradepass = 0;
  420. break;
  421. }
  422. if (empty($userid_or_ids)) {
  423. $userids = array();
  424. } else if (is_array($userid_or_ids)) {
  425. $userids = $userid_or_ids;
  426. } else {
  427. $userids = array($userid_or_ids);
  428. }
  429. if ($userids) {
  430. $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
  431. foreach ($userids as $userid) {
  432. $grade_grades[$userid]->grade_item =& $grade_item;
  433. $grade = new stdClass();
  434. $grade->grade = $grade_grades[$userid]->finalgrade;
  435. $grade->locked = $grade_grades[$userid]->is_locked();
  436. $grade->hidden = $grade_grades[$userid]->is_hidden();
  437. $grade->overridden = $grade_grades[$userid]->overridden;
  438. $grade->feedback = $grade_grades[$userid]->feedback;
  439. $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
  440. $grade->usermodified = $grade_grades[$userid]->usermodified;
  441. $grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
  442. $grade->dategraded = $grade_grades[$userid]->get_dategraded();
  443. // create text representation of grade
  444. if ($grade_item->gradetype == GRADE_TYPE_TEXT or $grade_item->gradetype == GRADE_TYPE_NONE) {
  445. $grade->grade = null;
  446. $grade->str_grade = '-';
  447. $grade->str_long_grade = $grade->str_grade;
  448. } else if (in_array($grade_item->id, $needsupdate)) {
  449. $grade->grade = false;
  450. $grade->str_grade = get_string('error');
  451. $grade->str_long_grade = $grade->str_grade;
  452. } else if (is_null($grade->grade)) {
  453. $grade->str_grade = '-';
  454. $grade->str_long_grade = $grade->str_grade;
  455. } else {
  456. $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item);
  457. if ($grade_item->gradetype == GRADE_TYPE_SCALE or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL) {
  458. $grade->str_long_grade = $grade->str_grade;
  459. } else {
  460. $a = new stdClass();
  461. $a->grade = $grade->str_grade;
  462. $a->max = grade_format_gradevalue($grade_item->grademax, $grade_item);
  463. $grade->str_long_grade = get_string('gradelong', 'grades', $a);
  464. }
  465. }
  466. // create html representation of feedback
  467. if (is_null($grade->feedback)) {
  468. $grade->str_feedback = '';
  469. } else {
  470. $feedback = file_rewrite_pluginfile_urls(
  471. $grade->feedback,
  472. 'pluginfile.php',
  473. $grade_grades[$userid]->get_context()->id,
  474. GRADE_FILE_COMPONENT,
  475. GRADE_FEEDBACK_FILEAREA,
  476. $grade_grades[$userid]->id
  477. );
  478. $grade->str_feedback = format_text($feedback, $grade->feedbackformat,
  479. ['context' => $grade_grades[$userid]->get_context()]);
  480. }
  481. $item->grades[$userid] = $grade;
  482. }
  483. }
  484. $return->items[$grade_item->itemnumber] = $item;
  485. } else {
  486. if (!$grade_outcome = grade_outcome::fetch(array('id'=>$grade_item->outcomeid))) {
  487. debugging('Incorect outcomeid found');
  488. continue;
  489. }
  490. // outcome info
  491. $outcome = new stdClass();
  492. $outcome->id = $grade_item->id;
  493. $outcome->itemnumber = $grade_item->itemnumber;
  494. $outcome->itemtype = $grade_item->itemtype;
  495. $outcome->itemmodule = $grade_item->itemmodule;
  496. $outcome->iteminstance = $grade_item->iteminstance;
  497. $outcome->scaleid = $grade_outcome->scaleid;
  498. $outcome->name = $grade_outcome->get_name();
  499. $outcome->locked = $grade_item->is_locked();
  500. $outcome->hidden = $grade_item->is_hidden();
  501. if (empty($userid_or_ids)) {
  502. $userids = array();
  503. } else if (is_array($userid_or_ids)) {
  504. $userids = $userid_or_ids;
  505. } else {
  506. $userids = array($userid_or_ids);
  507. }
  508. if ($userids) {
  509. $grade_grades = grade_grade::fetch_users_grades($grade_item, $userids, true);
  510. foreach ($userids as $userid) {
  511. $grade_grades[$userid]->grade_item =& $grade_item;
  512. $grade = new stdClass();
  513. $grade->grade = $grade_grades[$userid]->finalgrade;
  514. $grade->locked = $grade_grades[$userid]->is_locked();
  515. $grade->hidden = $grade_grades[$userid]->is_hidden();
  516. $grade->feedback = $grade_grades[$userid]->feedback;
  517. $grade->feedbackformat = $grade_grades[$userid]->feedbackformat;
  518. $grade->usermodified = $grade_grades[$userid]->usermodified;
  519. $grade->datesubmitted = $grade_grades[$userid]->get_datesubmitted();
  520. $grade->dategraded = $grade_grades[$userid]->get_dategraded();
  521. // create text representation of grade
  522. if (in_array($grade_item->id, $needsupdate)) {
  523. $grade->grade = false;
  524. $grade->str_grade = get_string('error');
  525. } else if (is_null($grade->grade)) {
  526. $grade->grade = 0;
  527. $grade->str_grade = get_string('nooutcome', 'grades');
  528. } else {
  529. $grade->grade = (int)$grade->grade;
  530. $scale = $grade_item->load_scale();
  531. $grade->str_grade = format_string($scale->scale_items[(int)$grade->grade-1]);
  532. }
  533. // create html representation of feedback
  534. if (is_null($grade->feedback)) {
  535. $grade->str_feedback = '';
  536. } else {
  537. $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat);
  538. }
  539. $outcome->grades[$userid] = $grade;
  540. }
  541. }
  542. if (isset($return->outcomes[$grade_item->itemnumber])) {
  543. // itemnumber duplicates - lets fix them!
  544. $newnumber = $grade_item->itemnumber + 1;
  545. while(grade_item::fetch(array('itemtype'=>$itemtype, 'itemmodule'=>$itemmodule, 'iteminstance'=>$iteminstance, 'courseid'=>$courseid, 'itemnumber'=>$newnumber))) {
  546. $newnumber++;
  547. }
  548. $outcome->itemnumber = $newnumber;
  549. $grade_item->itemnumber = $newnumber;
  550. $grade_item->update('system');
  551. }
  552. $return->outcomes[$grade_item->itemnumber] = $outcome;
  553. }
  554. }
  555. }
  556. // sort results using itemnumbers
  557. ksort($return->items, SORT_NUMERIC);
  558. ksort($return->outcomes, SORT_NUMERIC);
  559. return $return;
  560. }
  561. ///////////////////////////////////////////////////////////////////
  562. ///// End of public API for communication with modules/blocks /////
  563. ///////////////////////////////////////////////////////////////////
  564. ///////////////////////////////////////////////////////////////////
  565. ///// Internal API: used by gradebook plugins and Moodle core /////
  566. ///////////////////////////////////////////////////////////////////
  567. /**
  568. * Returns a course gradebook setting
  569. *
  570. * @param int $courseid
  571. * @param string $name of setting, maybe null if reset only
  572. * @param string $default value to return if setting is not found
  573. * @param bool $resetcache force reset of internal static cache
  574. * @return string value of the setting, $default if setting not found, NULL if supplied $name is null
  575. */
  576. function grade_get_setting($courseid, $name, $default=null, $resetcache=false) {
  577. global $DB;
  578. static $cache = array();
  579. if ($resetcache or !array_key_exists($courseid, $cache)) {
  580. $cache[$courseid] = array();
  581. } else if (is_null($name)) {
  582. return null;
  583. } else if (array_key_exists($name, $cache[$courseid])) {
  584. return $cache[$courseid][$name];
  585. }
  586. if (!$data = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
  587. $result = null;
  588. } else {
  589. $result = $data->value;
  590. }
  591. if (is_null($result)) {
  592. $result = $default;
  593. }
  594. $cache[$courseid][$name] = $result;
  595. return $result;
  596. }
  597. /**
  598. * Returns all course gradebook settings as object properties
  599. *
  600. * @param int $courseid
  601. * @return object
  602. */
  603. function grade_get_settings($courseid) {
  604. global $DB;
  605. $settings = new stdClass();
  606. $settings->id = $courseid;
  607. if ($records = $DB->get_records('grade_settings', array('courseid'=>$courseid))) {
  608. foreach ($records as $record) {
  609. $settings->{$record->name} = $record->value;
  610. }
  611. }
  612. return $settings;
  613. }
  614. /**
  615. * Add, update or delete a course gradebook setting
  616. *
  617. * @param int $courseid The course ID
  618. * @param string $name Name of the setting
  619. * @param string $value Value of the setting. NULL means delete the setting.
  620. */
  621. function grade_set_setting($courseid, $name, $value) {
  622. global $DB;
  623. if (is_null($value)) {
  624. $DB->delete_records('grade_settings', array('courseid'=>$courseid, 'name'=>$name));
  625. } else if (!$existing = $DB->get_record('grade_settings', array('courseid'=>$courseid, 'name'=>$name))) {
  626. $data = new stdClass();
  627. $data->courseid = $courseid;
  628. $data->name = $name;
  629. $data->value = $value;
  630. $DB->insert_record('grade_settings', $data);
  631. } else {
  632. $data = new stdClass();
  633. $data->id = $existing->id;
  634. $data->value = $value;
  635. $DB->update_record('grade_settings', $data);
  636. }
  637. grade_get_setting($courseid, null, null, true); // reset the cache
  638. }
  639. /**
  640. * Returns string representation of grade value
  641. *
  642. * @param float $value The grade value
  643. * @param object $grade_item Grade item object passed by reference to prevent scale reloading
  644. * @param bool $localized use localised decimal separator
  645. * @param int $displaytype type of display. For example GRADE_DISPLAY_TYPE_REAL, GRADE_DISPLAY_TYPE_PERCENTAGE, GRADE_DISPLAY_TYPE_LETTER
  646. * @param int $decimals The number of decimal places when displaying float values
  647. * @return string
  648. */
  649. function grade_format_gradevalue($value, &$grade_item, $localized=true, $displaytype=null, $decimals=null) {
  650. if ($grade_item->gradetype == GRADE_TYPE_NONE or $grade_item->gradetype == GRADE_TYPE_TEXT) {
  651. return '';
  652. }
  653. // no grade yet?
  654. if (is_null($value)) {
  655. return '-';
  656. }
  657. if ($grade_item->gradetype != GRADE_TYPE_VALUE and $grade_item->gradetype != GRADE_TYPE_SCALE) {
  658. //unknown type??
  659. return '';
  660. }
  661. if (is_null($displaytype)) {
  662. $displaytype = $grade_item->get_displaytype();
  663. }
  664. if (is_null($decimals)) {
  665. $decimals = $grade_item->get_decimals();
  666. }
  667. switch ($displaytype) {
  668. case GRADE_DISPLAY_TYPE_REAL:
  669. return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized);
  670. case GRADE_DISPLAY_TYPE_PERCENTAGE:
  671. return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized);
  672. case GRADE_DISPLAY_TYPE_LETTER:
  673. return grade_format_gradevalue_letter($value, $grade_item);
  674. case GRADE_DISPLAY_TYPE_REAL_PERCENTAGE:
  675. return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
  676. grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
  677. case GRADE_DISPLAY_TYPE_REAL_LETTER:
  678. return grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ' (' .
  679. grade_format_gradevalue_letter($value, $grade_item) . ')';
  680. case GRADE_DISPLAY_TYPE_PERCENTAGE_REAL:
  681. return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
  682. grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
  683. case GRADE_DISPLAY_TYPE_LETTER_REAL:
  684. return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
  685. grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) . ')';
  686. case GRADE_DISPLAY_TYPE_LETTER_PERCENTAGE:
  687. return grade_format_gradevalue_letter($value, $grade_item) . ' (' .
  688. grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ')';
  689. case GRADE_DISPLAY_TYPE_PERCENTAGE_LETTER:
  690. return grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) . ' (' .
  691. grade_format_gradevalue_letter($value, $grade_item) . ')';
  692. default:
  693. return '';
  694. }
  695. }
  696. /**
  697. * Returns a float representation of a grade value
  698. *
  699. * @param float $value The grade value
  700. * @param object $grade_item Grade item object
  701. * @param int $decimals The number of decimal places
  702. * @param bool $localized use localised decimal separator
  703. * @return string
  704. */
  705. function grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) {
  706. if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
  707. if (!$scale = $grade_item->load_scale()) {
  708. return get_string('error');
  709. }
  710. $value = $grade_item->bounded_grade($value);
  711. return format_string($scale->scale_items[$value-1]);
  712. } else {
  713. return format_float($value, $decimals, $localized);
  714. }
  715. }
  716. /**
  717. * Returns a percentage representation of a grade value
  718. *
  719. * @param float $value The grade value
  720. * @param object $grade_item Grade item object
  721. * @param int $decimals The number of decimal places
  722. * @param bool $localized use localised decimal separator
  723. * @return string
  724. */
  725. function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) {
  726. $min = $grade_item->grademin;
  727. $max = $grade_item->grademax;
  728. if ($min == $max) {
  729. return '';
  730. }
  731. $value = $grade_item->bounded_grade($value);
  732. $percentage = (($value-$min)*100)/($max-$min);
  733. return format_float($percentage, $decimals, $localized).' %';
  734. }
  735. /**
  736. * Returns a letter grade representation of a grade value
  737. * The array of grade letters used is produced by {@link grade_get_letters()} using the course context
  738. *
  739. * @param float $value The grade value
  740. * @param object $grade_item Grade item object
  741. * @return string
  742. */
  743. function grade_format_gradevalue_letter($value, $grade_item) {
  744. global $CFG;
  745. $context = context_course::instance($grade_item->courseid, IGNORE_MISSING);
  746. if (!$letters = grade_get_letters($context)) {
  747. return ''; // no letters??
  748. }
  749. if (is_null($value)) {
  750. return '-';
  751. }
  752. $value = grade_grade::standardise_score($value, $grade_item->grademin, $grade_item->grademax, 0, 100);
  753. $value = bounded_number(0, $value, 100); // just in case
  754. $gradebookcalculationsfreeze = 'gradebook_calculations_freeze_' . $grade_item->courseid;
  755. foreach ($letters as $boundary => $letter) {
  756. if (property_exists($CFG, $gradebookcalculationsfreeze) && (int)$CFG->{$gradebookcalculationsfreeze} <= 20160518) {
  757. // Do nothing.
  758. } else {
  759. // The boundary is a percentage out of 100 so use 0 as the min and 100 as the max.
  760. $boundary = grade_grade::standardise_score($boundary, 0, 100, 0, 100);
  761. }
  762. if ($value >= $boundary) {
  763. return format_string($letter);
  764. }
  765. }
  766. return '-'; // no match? maybe '' would be more correct
  767. }
  768. /**
  769. * Returns grade options for gradebook grade category menu
  770. *
  771. * @param int $courseid The course ID
  772. * @param bool $includenew Include option for new category at array index -1
  773. * @return array of grade categories in course
  774. */
  775. function grade_get_categories_menu($courseid, $includenew=false) {
  776. $result = array();
  777. if (!$categories = grade_category::fetch_all(array('courseid'=>$courseid))) {
  778. //make sure course category exists
  779. if (!grade_category::fetch_course_category($courseid)) {
  780. debugging('Can not create course grade category!');
  781. return $result;
  782. }
  783. $categories = grade_category::fetch_all(array('courseid'=>$courseid));
  784. }
  785. foreach ($categories as $key=>$category) {
  786. if ($category->is_course_category()) {
  787. $result[$category->id] = get_string('uncategorised', 'grades');
  788. unset($categories[$key]);
  789. }
  790. }
  791. if ($includenew) {
  792. $result[-1] = get_string('newcategory', 'grades');
  793. }
  794. $cats = array();
  795. foreach ($categories as $category) {
  796. $cats[$category->id] = $category->get_name();
  797. }
  798. core_collator::asort($cats);
  799. return ($result+$cats);
  800. }
  801. /**
  802. * Returns the array of grade letters to be used in the supplied context
  803. *
  804. * @param object $context Context object or null for defaults
  805. * @return array of grade_boundary (minimum) => letter_string
  806. */
  807. function grade_get_letters($context=null) {
  808. global $DB;
  809. if (empty($context)) {
  810. //default grading letters
  811. return array('93'=>'A', '90'=>'A-', '87'=>'B+', '83'=>'B', '80'=>'B-', '77'=>'C+', '73'=>'C', '70'=>'C-', '67'=>'D+', '60'=>'D', '0'=>'F');
  812. }
  813. static $cache = array();
  814. if (array_key_exists($context->id, $cache)) {
  815. return $cache[$context->id];
  816. }
  817. if (count($cache) > 100) {
  818. $cache = array(); // cache size limit
  819. }
  820. $letters = array();
  821. $contexts = $context->get_parent_context_ids();
  822. array_unshift($contexts, $context->id);
  823. foreach ($contexts as $ctxid) {
  824. if ($records = $DB->get_records('grade_letters', array('contextid'=>$ctxid), 'lowerboundary DESC')) {
  825. foreach ($records as $record) {
  826. $letters[$record->lowerboundary] = $record->letter;
  827. }
  828. }
  829. if (!empty($letters)) {
  830. $cache[$context->id] = $letters;
  831. return $letters;
  832. }
  833. }
  834. $letters = grade_get_letters(null);
  835. $cache[$context->id] = $letters;
  836. return $letters;
  837. }
  838. /**
  839. * Verify new value of grade item idnumber. Checks for uniqueness of new ID numbers. Old ID numbers are kept intact.
  840. *
  841. * @param string $idnumber string (with magic quotes)
  842. * @param int $courseid ID numbers are course unique only
  843. * @param grade_item $grade_item The grade item this idnumber is associated with
  844. * @param stdClass $cm used for course module idnumbers and items attached to modules
  845. * @return bool true means idnumber ok
  846. */
  847. function grade_verify_idnumber($idnumber, $courseid, $grade_item=null, $cm=null) {
  848. global $DB;
  849. if ($idnumber == '') {
  850. //we allow empty idnumbers
  851. return true;
  852. }
  853. // keep existing even when not unique
  854. if ($cm and $cm->idnumber == $idnumber) {
  855. if ($grade_item and $grade_item->itemnumber != 0) {
  856. // grade item with itemnumber > 0 can't have the same idnumber as the main
  857. // itemnumber 0 which is synced with course_modules
  858. return false;
  859. }
  860. return true;
  861. } else if ($grade_item and $grade_item->idnumber == $idnumber) {
  862. return true;
  863. }
  864. if ($DB->record_exists('course_modules', array('course'=>$courseid, 'idnumber'=>$idnumber))) {
  865. return false;
  866. }
  867. if ($DB->record_exists('grade_items', array('courseid'=>$courseid, 'idnumber'=>$idnumber))) {
  868. return false;
  869. }
  870. return true;
  871. }
  872. /**
  873. * Force final grade recalculation in all course items
  874. *
  875. * @param int $courseid The course ID to recalculate
  876. */
  877. function grade_force_full_regrading($courseid) {
  878. global $DB;
  879. $DB->set_field('grade_items', 'needsupdate', 1, array('courseid'=>$courseid));
  880. }
  881. /**
  882. * Forces regrading of all site grades. Used when changing site setings
  883. */
  884. function grade_force_site_regrading() {
  885. global $CFG, $DB;
  886. $DB->set_field('grade_items', 'needsupdate', 1);
  887. }
  888. /**
  889. * Recover a user's grades from grade_grades_history
  890. * @param int $userid the user ID whose grades we want to recover
  891. * @param int $courseid the relevant course
  892. * @return bool true if successful or false if there was an error or no grades could be recovered
  893. */
  894. function grade_recover_history_grades($userid, $courseid) {
  895. global $CFG, $DB;
  896. if ($CFG->disablegradehistory) {
  897. debugging('Attempting to recover grades when grade history is disabled.');
  898. return false;
  899. }
  900. //Were grades recovered? Flag to return.
  901. $recoveredgrades = false;
  902. //Check the user is enrolled in this course
  903. //Dont bother checking if they have a gradeable role. They may get one later so recover
  904. //whatever grades they have now just in case.
  905. $course_context = context_course::instance($courseid);
  906. if (!is_enrolled($course_context, $userid)) {
  907. debugging('Attempting to recover the grades of a user who is deleted or not enrolled. Skipping recover.');
  908. return false;
  909. }
  910. //Check for existing grades for this user in this course
  911. //Recovering grades when the user already has grades can lead to duplicate indexes and bad data
  912. //In the future we could move the existing grades to the history table then recover the grades from before then
  913. $sql = "SELECT gg.id
  914. FROM {grade_grades} gg
  915. JOIN {grade_items} gi ON gi.id = gg.itemid
  916. WHERE gi.courseid = :courseid AND gg.userid = :userid";
  917. $params = array('userid' => $userid, 'courseid' => $courseid);
  918. if ($DB->record_exists_sql($sql, $params)) {
  919. debugging('Attempting to recover the grades of a user who already has grades. Skipping recover.');
  920. return false;
  921. } else {
  922. //Retrieve the user's old grades
  923. //have history ID as first column to guarantee we a unique first column
  924. $sql = "SELECT h.id, gi.itemtype, gi.itemmodule, gi.iteminstance as iteminstance, gi.itemnumber, h.source, h.itemid, h.userid, h.rawgrade, h.rawgrademax,
  925. h.rawgrademin, h.rawscaleid, h.usermodified, h.finalgrade, h.hidden, h.locked, h.locktime, h.exported, h.overridden, h.excluded, h.feedback,
  926. h.feedbackformat, h.information, h.informationformat, h.timemodified, itemcreated.tm AS timecreated
  927. FROM {grade_grades_history} h
  928. JOIN (SELECT itemid, MAX(id) AS id
  929. FROM {grade_grades_history}
  930. WHERE userid = :userid1
  931. GROUP BY itemid) maxquery ON h.id = maxquery.id AND h.itemid = maxquery.itemid
  932. JOIN {grade_items} gi ON gi.id = h.itemid
  933. JOIN (SELECT itemid, MAX(timemodified) AS tm
  934. FROM {grade_grades_history}
  935. WHERE userid = :userid2 AND action = :insertaction
  936. GROUP BY itemid) itemcreated ON itemcreated.itemid = h.itemid
  937. WHERE gi.courseid = :courseid";
  938. $params = array('userid1' => $userid, 'userid2' => $userid , 'insertaction' => GRADE_HISTORY_INSERT, 'courseid' => $courseid);
  939. $oldgrades = $DB->get_records_sql($sql, $params);
  940. //now move the old grades to the grade_grades table
  941. foreach ($oldgrades as $oldgrade) {
  942. unset($oldgrade->id);
  943. $grade = new grade_grade($oldgrade, false);//2nd arg false as dont want to try and retrieve a record from the DB
  944. $grade->insert($oldgrade->source);
  945. //dont include default empty grades created when activities are created
  946. if (!is_null($oldgrade->finalgrade) || !is_null($oldgrade->feedback)) {
  947. $recoveredgrades = true;
  948. }
  949. }
  950. }
  951. //Some activities require manual grade synching (moving grades from the activity into the gradebook)
  952. //If the student was deleted when synching was done they may have grades in the activity that haven't been moved across
  953. grade_grab_course_grades($courseid, null, $userid);
  954. return $recoveredgrades;
  955. }
  956. /**
  957. * Updates all final grades in course.
  958. *
  959. * @param int $courseid The course ID
  960. * @param int $userid If specified try to do a quick regrading of the grades of this user only
  961. * @param object $updated_item Optional grade item to be marked for regrading. It is required if $userid is set.
  962. * @param \core\progress\base $progress If provided, will be used to update progress on this long operation.
  963. * @return bool true if ok, array of errors if problems found. Grade item id => error message
  964. */
  965. function grade_regrade_final_grades($courseid, $userid=null, $updated_item=null, $progress=null) {
  966. // This may take a very long time and extra memory.
  967. \core_php_time_limit::raise();
  968. raise_memory_limit(MEMORY_EXTRA);
  969. $course_item = grade_item::fetch_course_item($courseid);
  970. if ($progress == null) {
  971. $progress = new \core\progress\none();
  972. }
  973. if ($userid) {
  974. // one raw grade updated for one user
  975. if (empty($updated_item)) {
  976. print_error("cannotbenull", 'debug', '', "updated_item");
  977. }
  978. if ($course_item->needsupdate) {
  979. $updated_item->force_regrading();
  980. return array($course_item->id =>'Can not do fast regrading after updating of raw grades');
  981. }
  982. } else {
  983. if (!$course_item->needsupdate) {
  984. // nothing to do :-)
  985. return true;
  986. }
  987. }
  988. // Categories might have to run some processing before we fetch the grade items.
  989. // This gives them a final opportunity to update and mark their children to be updated.
  990. // We need to work on the children categories up to the parent ones, so that, for instance,
  991. // if a category total is updated it will be reflected in the parent category.
  992. $cats = grade_category::fetch_all(array('courseid' => $courseid));
  993. $flatcattree = array();
  994. foreach ($cats as $cat) {
  995. if (!isset($flatcattree[$cat->depth])) {
  996. $flatcattree[$cat->depth] = array();
  997. }
  998. $flatcattree[$cat->depth][] = $cat;
  999. }
  1000. krsort($flatcattree);
  1001. foreach ($flatcattree as $depth => $cats) {
  1002. foreach ($cats as $cat) {
  1003. $cat->pre_regrade_final_grades();
  1004. }
  1005. }
  1006. $progresstotal = 0;
  1007. $progresscurrent = 0;
  1008. $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
  1009. $depends_on = array();
  1010. foreach ($grade_items as $gid=>$gitem) {
  1011. if ((!empty($updated_item) and $updated_item->id == $gid) ||
  1012. $gitem->is_course_item() || $gitem->is_category_item() || $gitem->is_calculated()) {
  1013. $grade_items[$gid]->needsupdate = 1;
  1014. }
  1015. // We load all dependencies of these items later we can discard some grade_items based on this.
  1016. if ($grade_items[$gid]->needsupdate) {
  1017. $depends_on[$gid] = $grade_items[$gid]->depends_on();
  1018. $progresstotal++;
  1019. }
  1020. }
  1021. $progress->start_progress('regrade_course', $progresstotal);
  1022. $errors = array();
  1023. $finalids = array();
  1024. $updatedids = array();
  1025. $gids = array_keys($grade_items);
  1026. $failed = 0;
  1027. while (count($finalids) < count($gids)) { // work until all grades are final or error found
  1028. $count = 0;
  1029. foreach ($gids as $gid) {
  1030. if (in_array($gid, $finalids)) {
  1031. continue; // already final
  1032. }
  1033. if (!$grade_items[$gid]->needsupdate) {
  1034. $finalids[] = $gid; // we can make it final - does not need update
  1035. continue;
  1036. }
  1037. $thisprogress = $progresstotal;
  1038. foreach ($grade_items as $item) {
  1039. if ($item->needsupdate) {
  1040. $thisprogress--;
  1041. }
  1042. }
  1043. // Clip between $progresscurrent and $progresstotal.
  1044. $thisprogress = max(min($thisprogress, $progresstotal), $progresscurrent);
  1045. $progress->progress($thisprogress);
  1046. $progresscurrent = $thisprogress;
  1047. foreach ($depends_on[$gid] as $did) {
  1048. if (!in_array($did, $finalids)) {
  1049. // This item depends on something that is not yet in finals array.
  1050. continue 2;
  1051. }
  1052. }
  1053. // If this grade item has no dependancy with any updated item at all, then remove it from being recalculated.
  1054. // When we get here, all of this grade item's decendents are marked as final so they would be marked as updated too
  1055. // if they would have been regraded. We don't need to regrade items which dependants (not only the direct ones
  1056. // but any dependant in the cascade) have not been updated.
  1057. // If $updated_item was specified we discard the grade items that do not depend on it or on any grade item that
  1058. // depend on $updated_item.
  1059. // Here we check to see if the direct decendants are marked as updated.
  1060. if (!empty($updated_item) && $gid != $updated_item->id && !in_array($updated_item->id, $depends_on[$gid])) {
  1061. // We need to ensure that none of this item's dependencies have been updated.
  1062. // If we find that one of the direct decendants of this grade item is marked as updated then this
  1063. // grade item needs to be recalculated and marked as updated.
  1064. // Being marked as updated is done further down in the code.
  1065. $updateddependencies = false;
  1066. foreach ($depends_on[$gid] as $dependency) {
  1067. if (in_array($dependency, $updatedids)) {
  1068. $updateddependencies = true;
  1069. break;
  1070. }
  1071. }
  1072. if ($updateddependencies === false) {
  1073. // If no direct descendants are marked as updated, then we don't need to update this grade item. We then mark it
  1074. // as final.
  1075. $count++;
  1076. $finalids[] = $gid;
  1077. continue;
  1078. }
  1079. }
  1080. // Let's update, calculate or aggregate.
  1081. $result = $grade_items[$gid]->regrade_final_grades($userid);
  1082. if ($result === true) {
  1083. // We should only update the database if we regraded all users.
  1084. if (empty($userid)) {
  1085. $grade_items[$gid]->regrading_finished();
  1086. // Do the locktime item locking.
  1087. $grade_items[$gid]->check_locktime();
  1088. } else {
  1089. $grade_items[$gid]->needsupdate = 0;
  1090. }
  1091. $count++;
  1092. $finalids[] = $gid;
  1093. $updatedids[] = $gid;
  1094. } else {
  1095. $grade_items[$gid]->force_regrading();
  1096. $errors[$gid] = $result;
  1097. }
  1098. }
  1099. if ($count == 0) {
  1100. $failed++;
  1101. } else {
  1102. $failed = 0;
  1103. }
  1104. if ($failed > 1) {
  1105. foreach($gids as $gid) {
  1106. if (in_array($gid, $finalids)) {
  1107. continue; // this one is ok
  1108. }
  1109. $grade_items[$gid]->force_regrading();
  1110. $errors[$grade_items[$gid]->id] = get_string('errorcalculationbroken', 'grades');
  1111. }
  1112. break; // Found error.
  1113. }
  1114. }
  1115. $progress->end_progress();
  1116. if (count($errors) == 0) {
  1117. if (empty($userid)) {
  1118. // do the locktime locking of grades, but only when doing full regrading
  1119. grade_grade::check_locktime_all($gids);
  1120. }
  1121. return true;
  1122. } else {
  1123. return $errors;
  1124. }
  1125. }
  1126. /**
  1127. * Refetches grade data from course activities
  1128. *
  1129. * @param int $courseid The course ID
  1130. * @param string $modname Limit the grade fetch to a single module type. For example 'forum'
  1131. * @param int $userid limit the grade fetch to a single user
  1132. */
  1133. function grade_grab_course_grades($courseid, $modname=null, $userid=0) {
  1134. global $CFG, $DB;
  1135. if ($modname) {
  1136. $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
  1137. FROM {".$modname."} a, {course_modules} cm, {modules} m
  1138. WHERE m.name=:modname AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=:courseid";
  1139. $params = array('modname'=>$modname, 'courseid'=>$courseid);
  1140. if ($modinstances = $DB->get_records_sql($sql, $params)) {
  1141. foreach ($modinstances as $modinstance) {
  1142. grade_update_mod_grades($modinstance, $userid);
  1143. }
  1144. }
  1145. return;
  1146. }
  1147. if (!$mods = core_component::get_plugin_list('mod') ) {
  1148. print_error('nomodules', 'debug');
  1149. }
  1150. foreach ($mods as $mod => $fullmod) {
  1151. if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
  1152. continue;
  1153. }
  1154. // include the module lib once
  1155. if (file_exists($fullmod.'/lib.php')) {
  1156. // get all instance of the activity
  1157. $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
  1158. FROM {".$mod."} a, {course_modules} cm, {modules} m
  1159. WHERE m.name=:mod AND m.visible=1 AND m.id=cm.module AND cm.instance=a.id AND cm.course=:courseid";
  1160. $params = array('mod'=>$mod, 'courseid'=>$courseid);
  1161. if ($modinstances = $DB->get_records_sql($sql, $params)) {
  1162. foreach ($modinstances as $modinstance) {
  1163. grade_update_mod_grades($modinstance, $userid);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. /**
  1170. * Force full update of module grades in central gradebook
  1171. *
  1172. * @param object $modinstance Module object with extra cmidnumber and modname property
  1173. * @param int $userid Optional user ID if limiting the update to a single user
  1174. * @return bool True if success
  1175. */
  1176. function grade_update_mod_grades($modinstance, $userid=0) {
  1177. global $CFG, $DB;
  1178. $fullmod = $CFG->dirroot.'/mod/'.$modinstance->modname;
  1179. if (!file_exists($fullmod.'/lib.php')) {
  1180. debugging('missing lib.php file in module ' . $modinstance->modname);
  1181. return false;
  1182. }
  1183. include_once($fullmod.'/lib.php');
  1184. $updateitemfunc = $modinstance->modname.'_grade_item_update';
  1185. $updategradesfunc = $modinstance->modname.'_update_grades';
  1186. if (function_exists($updategradesfunc) and function_exists($updateitemfunc)) {
  1187. //new grading supported, force updating of grades
  1188. $updateitemfunc($modinstance);
  1189. $updategradesfunc($modinstance, $userid);
  1190. } else if (function_exists($updategradesfunc) xor function_exists($updateitemfunc)) {
  1191. // Module does not support grading?
  1192. debugging("You have declared one of $updateitemfunc and $updategradesfunc but not both. " .
  1193. "This will cause broken behaviour.", DEBUG_DEVELOPER);
  1194. }
  1195. return true;
  1196. }
  1197. /**
  1198. * Remove grade letters for given context
  1199. *
  1200. * @param context $context The context
  1201. * @param bool $showfeedback If true a success notification will be displayed
  1202. */
  1203. function remove_grade_letters($context, $showfeedback) {
  1204. global $DB, $OUTPUT;
  1205. $strdeleted = get_string('deleted');
  1206. $records = $DB->get_records('grade_letters', array('contextid' => $context->id));
  1207. foreach ($records as $record) {
  1208. $DB->delete_records('grade_letters', array('id' => $record->id));
  1209. // Trigger the letter grade deleted event.
  1210. $event = \core\event\grade_letter_deleted::create(array(
  1211. 'objectid' => $record->id,
  1212. 'context' => $context,
  1213. ));
  1214. $event->trigger();
  1215. }
  1216. if ($showfeedback) {
  1217. echo $OUTPUT->notification($strdeleted.' - '.get_string('letters', 'grades'), 'notifysuccess');
  1218. }
  1219. }
  1220. /**
  1221. * Remove all grade related course data
  1222. * Grade history is kept
  1223. *
  1224. * @param int $courseid The course ID
  1225. * @param bool $showfeedback If true success notifications will be displayed
  1226. */
  1227. function remove_course_grades($courseid, $showfeedback) {
  1228. global $DB, $OUTPUT;
  1229. $fs = get_file_storage();
  1230. $strdeleted = get_string('deleted');
  1231. $course_category = grade_category::fetch_course_category($courseid);
  1232. $course_category->delete('coursedelete');
  1233. $fs->delete_area_files(context_course::instance($courseid)->id, 'grade', 'feedback');
  1234. if ($showfeedback) {
  1235. echo $OUTPUT->notification($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'), 'notifysuccess');
  1236. }
  1237. if ($outcomes = grade_outcome::fetch_all(array('courseid'=>$courseid))) {
  1238. foreach ($outcomes as $outcome) {
  1239. $outcome->delete('coursedelete');
  1240. }
  1241. }
  1242. $DB->delete_records('grade_outcomes_courses', array('courseid'=>$courseid));
  1243. if ($showfeedback) {
  1244. echo $OUTPUT->notification($strdeleted.' - '.get_string('outcomes', 'grades'), 'notifysuccess');
  1245. }
  1246. if ($scales = grade_scale::fetch_all(array('courseid'=>$courseid))) {
  1247. foreach ($scales as $scale) {
  1248. $scale->delete('coursedelete');
  1249. }
  1250. }
  1251. if ($showfeedback) {
  1252. echo $OUTPUT->notification($strdeleted.' - '.get_string('scales'), 'notifysuccess');
  1253. }
  1254. $DB->delete_records('grade_settings', array('courseid'=>$courseid));
  1255. if ($showfeedback) {
  1256. echo $OUTPUT->notification($strdeleted.' - '.get_string('settings', 'grades'), 'notifysuccess');
  1257. }
  1258. }
  1259. /**
  1260. * Called when course category is deleted
  1261. * Cleans the gradebook of associated data
  1262. *
  1263. * @param int $categoryid The course category id
  1264. * @param int $newparentid If empty everything is deleted. Otherwise the ID of the category where content moved
  1265. * @param bool $showfeedback print feedback
  1266. */
  1267. function grade_course_category_delete($categoryid, $newparentid, $showfeedback) {
  1268. global $DB;
  1269. $context = context_coursecat::instance($categoryid);
  1270. $records = $DB->get_records('grade_letters', array('contextid' => $context->id));
  1271. foreach ($records as $record) {
  1272. $DB->delete_records('grade_letters', array('id' => $record->id));
  1273. // Trigger the letter grade deleted event.
  1274. $event = \core\event\grade_letter_deleted::create(array(
  1275. 'objectid' => $record->id,
  1276. 'context' => $context,
  1277. ));
  1278. $event->trigger();
  1279. }
  1280. }
  1281. /**
  1282. * Does gradebook cleanup when a module is uninstalled
  1283. * Deletes all associated grade items
  1284. *
  1285. * @param string $modname The grade item module name to remove. For example 'forum'
  1286. */
  1287. function grade_uninstalled_module($modname) {
  1288. global $CFG, $DB;
  1289. $sql = "SELECT *
  1290. FROM {grade_items}
  1291. WHERE itemtype='mod' AND itemmodule=?";
  1292. // go all items for this module and delete them including the grades
  1293. $rs = $DB->get_recordset_sql($sql, array($modname));
  1294. foreach ($rs as $item) {
  1295. $grade_item = new grade_item($item, false);
  1296. $grade_item->delete('moduninstall');
  1297. }
  1298. $rs->close();
  1299. }
  1300. /**
  1301. * Deletes all of a user's grade data from gradebook
  1302. *
  1303. * @param int $userid The user whose grade data should be deleted
  1304. */
  1305. function grade_user_delete($userid) {
  1306. if ($grades = grade_grade::fetch_all(array('userid'=>$userid))) {
  1307. foreach ($grades as $grade) {
  1308. $grade->delete('userdelete');
  1309. }
  1310. }
  1311. }
  1312. /**
  1313. * Purge course data when user unenrolls from a course
  1314. *
  1315. * @param int $courseid The ID of the course the user has unenrolled from
  1316. * @param int $userid The ID of the user unenrolling
  1317. */
  1318. function grade_user_unenrol($courseid, $userid) {
  1319. if ($items = grade_item::fetch_all(array('courseid'=>$courseid))) {
  1320. foreach ($items as $item) {
  1321. if ($grades = grade_grade::fetch_all(array('userid'=>$userid, 'itemid'=>$item->id))) {
  1322. foreach ($grades as $grade) {
  1323. $grade->delete('userdelete');
  1324. }
  1325. }
  1326. }
  1327. }
  1328. }
  1329. /**
  1330. * Reset all course grades, refetch from the activities and recalculate
  1331. *
  1332. * @param int $courseid The course to reset
  1333. * @return bool success
  1334. */
  1335. function grade_course_reset($courseid) {
  1336. // no recalculations
  1337. grade_force_full_regrading($courseid);
  1338. $grade_items = grade_item::fetch_all(array('courseid'=>$courseid));
  1339. foreach ($grade_items as $gid=>$grade_item) {
  1340. $grade_item->delete_all_grades('reset');
  1341. }
  1342. //refetch all grades
  1343. grade_grab_course_grades($courseid);
  1344. // recalculate all grades
  1345. grade_regrade_final_grades($courseid);
  1346. return true;
  1347. }
  1348. /**
  1349. * Convert a number to 5 decimal point float, an empty string or a null db compatible format
  1350. * (we need this to decide if db value changed)
  1351. *
  1352. * @param mixed $number The number to convert
  1353. * @return mixed float or null
  1354. */
  1355. function grade_floatval($number) {
  1356. if (is_null($number) or $number === '') {
  1357. return null;
  1358. }
  1359. // we must round to 5 digits to get the same precision as in 10,5 db fields
  1360. // note: db rounding for 10,5 is different from php round() function
  1361. return round($number, 5);
  1362. }
  1363. /**
  1364. * Compare two float numbers safely. Uses 5 decimals php precision using {@link grade_floatval()}. Nulls accepted too.
  1365. * Used for determining if a database update is required
  1366. *
  1367. * @param float $f1 Float one to compare
  1368. * @param float $f2 Float two to compare
  1369. * @return bool True if the supplied values are different
  1370. */
  1371. function grade_floats_different($f1, $f2) {
  1372. // note: db rounding for 10,5 is different from php round() function
  1373. return (grade_floatval($f1) !== grade_floatval($f2));
  1374. }
  1375. /**
  1376. * Compare two float numbers safely. Uses 5 decimals php precision using {@link grade_floatval()}
  1377. *
  1378. * Do not use rounding for 10,5 at the database level as the results may be
  1379. * different from php round() function.
  1380. *
  1381. * @since Moodle 2.0
  1382. * @param float $f1 Float one to compare
  1383. * @param float $f2 Float two to compare
  1384. * @return bool True if the values should be considered as the same grades
  1385. */
  1386. function grade_floats_equal($f1, $f2) {
  1387. return (grade_floatval($f1) === grade_floatval($f2));
  1388. }
  1389. /**
  1390. * Get the most appropriate grade date for a grade item given the user that the grade relates to.
  1391. *
  1392. * @param \stdClass $grade
  1393. * @param \stdClass $user
  1394. * @return int|null
  1395. */
  1396. function grade_get_date_for_user_grade(\stdClass $grade, \stdClass $user): ?int {
  1397. // The `datesubmitted` is the time that the grade was created.
  1398. // The `dategraded` is the time that it was modified or overwritten.
  1399. // If the grade was last modified by the user themselves use the date graded.
  1400. // Otherwise use date submitted.
  1401. if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
  1402. return $grade->dategraded;
  1403. } else {
  1404. return $grade->datesubmitted;
  1405. }
  1406. }