PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/grade/import/lib.php

https://gitlab.com/JrLucena/moodle
PHP | 231 lines | 134 code | 33 blank | 64 comment | 16 complexity | d884cc9e7bc8202f74725cd10c8d1905 MD5 | raw file
  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. require_once($CFG->libdir.'/gradelib.php');
  17. /**
  18. * Returns new improtcode for current user
  19. * @return int importcode
  20. */
  21. function get_new_importcode() {
  22. global $USER, $DB;
  23. $importcode = time();
  24. while ($DB->get_record('grade_import_values', array('importcode' => $importcode, 'importer' => $USER->id))) {
  25. $importcode--;
  26. }
  27. return $importcode;
  28. }
  29. /**
  30. * given an import code, commits all entries in buffer tables
  31. * (grade_import_value and grade_import_newitem)
  32. * If this function is called, we assume that all data collected
  33. * up to this point is fine and we can go ahead and commit
  34. * @param int $courseid - ID of the course.
  35. * @param int $importcode - Import batch identifier.
  36. * @param bool $importfeedback - Whether to import feedback as well.
  37. * @param bool $verbose - Print feedback and continue button.
  38. * @return bool success
  39. */
  40. function grade_import_commit($courseid, $importcode, $importfeedback=true, $verbose=true) {
  41. global $CFG, $USER, $DB, $OUTPUT;
  42. $failed = false;
  43. $executionerrors = false;
  44. $commitstart = time(); // start time in case we need to roll back
  45. $newitemids = array(); // array to hold new grade_item ids from grade_import_newitem table, mapping array
  46. /// first select distinct new grade_items with this batch
  47. $params = array($importcode, $USER->id);
  48. if ($newitems = $DB->get_records_sql("SELECT *
  49. FROM {grade_import_newitem}
  50. WHERE importcode = ? AND importer=?", $params)) {
  51. // instances of the new grade_items created, cached
  52. // in case grade_update fails, so that we can remove them
  53. $instances = array();
  54. foreach ($newitems as $newitem) {
  55. // get all grades with this item
  56. $gradeimportparams = array('newgradeitem' => $newitem->id, 'importcode' => $importcode, 'importer' => $USER->id);
  57. if ($grades = $DB->get_records('grade_import_values', $gradeimportparams)) {
  58. /// create a new grade item for this - must use false as second param!
  59. /// TODO: we need some bounds here too
  60. $gradeitem = new grade_item(array('courseid'=>$courseid, 'itemtype'=>'manual', 'itemname'=>$newitem->itemname), false);
  61. $gradeitem->insert('import');
  62. $instances[] = $gradeitem;
  63. // insert each individual grade to this new grade item
  64. foreach ($grades as $grade) {
  65. if (!$gradeitem->update_final_grade($grade->userid, $grade->finalgrade, 'import', $grade->feedback, FORMAT_MOODLE)) {
  66. $failed = true;
  67. break 2;
  68. }
  69. }
  70. }
  71. }
  72. if ($failed) {
  73. foreach ($instances as $instance) {
  74. $gradeitem->delete('import');
  75. }
  76. import_cleanup($importcode);
  77. return false;
  78. }
  79. }
  80. /// then find all existing items
  81. if ($gradeitems = $DB->get_records_sql("SELECT DISTINCT (itemid)
  82. FROM {grade_import_values}
  83. WHERE importcode = ? AND importer=? AND itemid > 0",
  84. array($importcode, $USER->id))) {
  85. $modifieditems = array();
  86. foreach ($gradeitems as $itemid=>$notused) {
  87. if (!$gradeitem = new grade_item(array('id'=>$itemid))) {
  88. // not supposed to happen, but just in case
  89. import_cleanup($importcode);
  90. return false;
  91. }
  92. // get all grades with this item
  93. $gradeimportparams = array('itemid' => $itemid, 'importcode' => $importcode, 'importer' => $USER->id);
  94. if ($grades = $DB->get_records('grade_import_values', $gradeimportparams)) {
  95. // make the grades array for update_grade
  96. foreach ($grades as $grade) {
  97. if (!$importfeedback) {
  98. $grade->feedback = false; // ignore it
  99. }
  100. if ($grade->importonlyfeedback) {
  101. // False means do not change. See grade_itme::update_final_grade().
  102. $grade->finalgrade = false;
  103. }
  104. if (!$gradeitem->update_final_grade($grade->userid, $grade->finalgrade, 'import', $grade->feedback)) {
  105. $errordata = new stdClass();
  106. $errordata->itemname = $gradeitem->itemname;
  107. $errordata->userid = $grade->userid;
  108. $executionerrors[] = get_string('errorsettinggrade', 'grades', $errordata);
  109. $failed = true;
  110. break 2;
  111. }
  112. }
  113. //$itemdetails -> idnumber = $gradeitem->idnumber;
  114. $modifieditems[] = $itemid;
  115. }
  116. }
  117. if ($failed) {
  118. if ($executionerrors && $verbose) {
  119. echo $OUTPUT->notification(get_string('gradeimportfailed', 'grades'));
  120. foreach ($executionerrors as $errorstr) {
  121. echo $OUTPUT->notification($errorstr);
  122. }
  123. }
  124. import_cleanup($importcode);
  125. return false;
  126. }
  127. }
  128. if ($verbose) {
  129. echo $OUTPUT->notification(get_string('importsuccess', 'grades'), 'notifysuccess');
  130. $unenrolledusers = get_unenrolled_users_in_import($importcode, $courseid);
  131. if ($unenrolledusers) {
  132. $list = array();
  133. foreach ($unenrolledusers as $u) {
  134. $u->fullname = fullname($u);
  135. $list[] = get_string('usergrade', 'grades', $u);
  136. }
  137. echo $OUTPUT->notification(get_string('unenrolledusersinimport', 'grades', html_writer::alist($list)), 'notifysuccess');
  138. }
  139. echo $OUTPUT->continue_button($CFG->wwwroot.'/grade/index.php?id='.$courseid);
  140. }
  141. // clean up
  142. import_cleanup($importcode);
  143. return true;
  144. }
  145. /**
  146. * This function returns an array of grades that were included in the import,
  147. * but where the user does not currently have a graded role on the course. These grades
  148. * are still stored in the database, but will not be visible in the gradebook unless
  149. * this user subsequently enrols on the course in a graded roles.
  150. *
  151. * The returned objects have fields user firstname, lastname and useridnumber, and gradeidnumber.
  152. *
  153. * @param integer $importcode import batch identifier
  154. * @param integer $courseid the course we are importing to.
  155. * @return mixed and array of user objects, or false if none.
  156. */
  157. function get_unenrolled_users_in_import($importcode, $courseid) {
  158. global $CFG, $DB;
  159. $coursecontext = context_course::instance($courseid);
  160. // We want to query both the current context and parent contexts.
  161. list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
  162. // Users with a gradeable role.
  163. list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
  164. // Enrolled users.
  165. $context = context_course::instance($courseid);
  166. list($enrolledsql, $enrolledparams) = get_enrolled_sql($context);
  167. list($sort, $sortparams) = users_order_by_sql('u');
  168. $sql = "SELECT giv.id, u.firstname, u.lastname, u.idnumber AS useridnumber,
  169. COALESCE(gi.idnumber, gin.itemname) AS gradeidnumber
  170. FROM {grade_import_values} giv
  171. JOIN {user} u
  172. ON giv.userid = u.id
  173. LEFT JOIN {grade_items} gi
  174. ON gi.id = giv.itemid
  175. LEFT JOIN {grade_import_newitem} gin
  176. ON gin.id = giv.newgradeitem
  177. LEFT JOIN ($enrolledsql) je
  178. ON je.id = u.id
  179. LEFT JOIN {role_assignments} ra
  180. ON (giv.userid = ra.userid AND ra.roleid $gradebookrolessql AND ra.contextid $relatedctxsql)
  181. WHERE giv.importcode = :importcode
  182. AND (ra.id IS NULL OR je.id IS NULL)
  183. ORDER BY gradeidnumber, $sort";
  184. $params = array_merge($gradebookrolesparams, $enrolledparams, $sortparams, $relatedctxparams);
  185. $params['importcode'] = $importcode;
  186. return $DB->get_records_sql($sql, $params);
  187. }
  188. /**
  189. * removes entries from grade import buffer tables grade_import_value and grade_import_newitem
  190. * after a successful import, or during an import abort
  191. * @param string importcode - import batch identifier
  192. */
  193. function import_cleanup($importcode) {
  194. global $USER, $DB;
  195. // remove entries from buffer table
  196. $DB->delete_records('grade_import_values', array('importcode' => $importcode, 'importer' => $USER->id));
  197. $DB->delete_records('grade_import_newitem', array('importcode' => $importcode, 'importer' => $USER->id));
  198. }