MDL-30315 grades: Fix up function doc block.
[moodle.git] / grade / import / lib.php
CommitLineData
e060e33d 1<?php
ce40b793 2
e060e33d 3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
8ad36f4c 17
8108909a 18require_once($CFG->libdir.'/gradelib.php');
19
20/**
21 * Returns new improtcode for current user
22 * @return int importcode
23 */
24function get_new_importcode() {
5c75a0a3 25 global $USER, $DB;
8108909a 26
27 $importcode = time();
5c75a0a3 28 while ($DB->get_record('grade_import_values', array('importcode' => $importcode, 'importer' => $USER->id))) {
8108909a 29 $importcode--;
30 }
31
32 return $importcode;
33}
34
ce40b793 35/**
ba74762b 36 * given an import code, commits all entries in buffer tables
ce40b793 37 * (grade_import_value and grade_import_newitem)
ba74762b 38 * If this function is called, we assume that all data collected
ce40b793 39 * up to this point is fine and we can go ahead and commit
9b272cc0
AG
40 * @param int $courseid - ID of the course.
41 * @param int $importcode - Import batch identifier.
42 * @param bool $importfeedback - Whether to import feedback as well.
43 * @param bool $verbose - Print feedback and continue button.
a700b5de 44 * @return bool success
ce40b793 45 */
34058207 46function grade_import_commit($courseid, $importcode, $importfeedback=true, $verbose=true) {
c3b834b4 47 global $CFG, $USER, $DB, $OUTPUT;
ba74762b 48
643e341c
JC
49 $failed = false;
50 $executionerrors = false;
ce40b793 51 $commitstart = time(); // start time in case we need to roll back
52 $newitemids = array(); // array to hold new grade_item ids from grade_import_newitem table, mapping array
ba74762b 53
ce40b793 54 /// first select distinct new grade_items with this batch
5c75a0a3 55 $params = array($importcode, $USER->id);
56 if ($newitems = $DB->get_records_sql("SELECT *
57 FROM {grade_import_newitem}
58 WHERE importcode = ? AND importer=?", $params)) {
ba74762b 59
60 // instances of the new grade_items created, cached
ce40b793 61 // in case grade_update fails, so that we can remove them
62 $instances = array();
63 foreach ($newitems as $newitem) {
64 // get all grades with this item
ba74762b 65
643e341c
JC
66 $gradeimportparams = array('newgradeitem' => $newitem->id, 'importcode' => $importcode, 'importer' => $USER->id);
67 if ($grades = $DB->get_records('grade_import_values', $gradeimportparams)) {
e9dea7af 68 /// create a new grade item for this - must use false as second param!
69 /// TODO: we need some bounds here too
70 $gradeitem = new grade_item(array('courseid'=>$courseid, 'itemtype'=>'manual', 'itemname'=>$newitem->itemname), false);
71 $gradeitem->insert('import');
72 $instances[] = $gradeitem;
b4355273 73
74 // insert each individual grade to this new grade item
ba74762b 75 foreach ($grades as $grade) {
0f392ff4 76 if (!$gradeitem->update_final_grade($grade->userid, $grade->finalgrade, 'import', $grade->feedback, FORMAT_MOODLE)) {
e9dea7af 77 $failed = true;
78 break 2;
ce40b793 79 }
b4355273 80 }
ce40b793 81 }
b263e539 82 }
e9dea7af 83
84 if ($failed) {
85 foreach ($instances as $instance) {
86 $gradeitem->delete('import');
87 }
88 import_cleanup($importcode);
89 return false;
90 }
ce40b793 91 }
b263e539 92
ce40b793 93 /// then find all existing items
94
5c75a0a3 95 if ($gradeitems = $DB->get_records_sql("SELECT DISTINCT (itemid)
96 FROM {grade_import_values}
97 WHERE importcode = ? AND importer=? AND itemid > 0",
98 array($importcode, $USER->id))) {
b4355273 99
ce40b793 100 $modifieditems = array();
ba74762b 101
8108909a 102 foreach ($gradeitems as $itemid=>$notused) {
ba74762b 103
b4355273 104 if (!$gradeitem = new grade_item(array('id'=>$itemid))) {
105 // not supposed to happen, but just in case
106 import_cleanup($importcode);
107 return false;
ce40b793 108 }
109 // get all grades with this item
643e341c
JC
110 $gradeimportparams = array('itemid' => $itemid, 'importcode' => $importcode, 'importer' => $USER->id);
111 if ($grades = $DB->get_records('grade_import_values', $gradeimportparams)) {
b263e539 112
0eeada79 113 // make the grades array for update_grade
ce40b793 114 foreach ($grades as $grade) {
34058207 115 if (!$importfeedback) {
116 $grade->feedback = false; // ignore it
117 }
0305798c
AG
118 if ($grade->importonlyfeedback) {
119 // False means do not change. See grade_itme::update_final_grade().
120 $grade->finalgrade = false;
121 }
0f392ff4 122 if (!$gradeitem->update_final_grade($grade->userid, $grade->finalgrade, 'import', $grade->feedback)) {
643e341c
JC
123 $errordata = new stdClass();
124 $errordata->itemname = $gradeitem->itemname;
125 $errordata->userid = $grade->userid;
126 $executionerrors[] = get_string('errorsettinggrade', 'grades', $errordata);
127 $failed = true;
b263e539 128 break 2;
b4355273 129 }
ce40b793 130 }
b263e539 131 //$itemdetails -> idnumber = $gradeitem->idnumber;
132 $modifieditems[] = $itemid;
b4355273 133
b263e539 134 }
643e341c 135 }
ba74762b 136
643e341c
JC
137 if ($failed) {
138 if ($executionerrors && $verbose) {
139 echo $OUTPUT->notification(get_string('gradeimportfailed', 'grades'));
140 foreach ($executionerrors as $errorstr) {
141 echo $OUTPUT->notification($errorstr);
142 }
b263e539 143 }
643e341c
JC
144 import_cleanup($importcode);
145 return false;
ce40b793 146 }
147 }
b263e539 148
34058207 149 if ($verbose) {
c3b834b4 150 echo $OUTPUT->notification(get_string('importsuccess', 'grades'), 'notifysuccess');
7d69de18 151 $unenrolledusers = get_unenrolled_users_in_import($importcode, $courseid);
152 if ($unenrolledusers) {
5be262b6 153 $list = array();
7d69de18 154 foreach ($unenrolledusers as $u) {
155 $u->fullname = fullname($u);
5be262b6 156 $list[] = get_string('usergrade', 'grades', $u);
7d69de18 157 }
5be262b6 158 echo $OUTPUT->notification(get_string('unenrolledusersinimport', 'grades', html_writer::alist($list)), 'notifysuccess');
7d69de18 159 }
c3b834b4 160 echo $OUTPUT->continue_button($CFG->wwwroot.'/grade/index.php?id='.$courseid);
a700b5de 161 }
ce40b793 162 // clean up
163 import_cleanup($importcode);
a700b5de 164
165 return true;
ce40b793 166}
167
7d69de18 168/**
169 * This function returns an array of grades that were included in the import,
6ef4878b 170 * but where the user does not currently have a graded role on the course. These grades
7d69de18 171 * are still stored in the database, but will not be visible in the gradebook unless
172 * this user subsequently enrols on the course in a graded roles.
173 *
174 * The returned objects have fields user firstname, lastname and useridnumber, and gradeidnumber.
175 *
176 * @param integer $importcode import batch identifier
177 * @param integer $courseid the course we are importing to.
178 * @return mixed and array of user objects, or false if none.
179 */
180function get_unenrolled_users_in_import($importcode, $courseid) {
5c75a0a3 181 global $CFG, $DB;
d24832f9 182
4e829d48
MN
183 $coursecontext = context_course::instance($courseid);
184
185 // We want to query both the current context and parent contexts.
186 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
187
188 // Users with a gradeable role.
cf717dc2 189 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
b61e4f46 190
4e829d48 191 // Enrolled users.
d4060472 192 $context = context_course::instance($courseid);
2dc5e584 193 list($enrolledsql, $enrolledparams) = get_enrolled_sql($context);
9695ff81 194 list($sort, $sortparams) = users_order_by_sql('u');
5c75a0a3 195
d24832f9 196 $sql = "SELECT giv.id, u.firstname, u.lastname, u.idnumber AS useridnumber,
25081b95
SH
197 COALESCE(gi.idnumber, gin.itemname) AS gradeidnumber
198 FROM {grade_import_values} giv
199 JOIN {user} u
200 ON giv.userid = u.id
201 LEFT JOIN {grade_items} gi
202 ON gi.id = giv.itemid
203 LEFT JOIN {grade_import_newitem} gin
204 ON gin.id = giv.newgradeitem
205 LEFT JOIN ($enrolledsql) je
206 ON je.id = u.id
207 LEFT JOIN {role_assignments} ra
4e829d48 208 ON (giv.userid = ra.userid AND ra.roleid $gradebookrolessql AND ra.contextid $relatedctxsql)
25081b95
SH
209 WHERE giv.importcode = :importcode
210 AND (ra.id IS NULL OR je.id IS NULL)
9695ff81 211 ORDER BY gradeidnumber, $sort";
4e829d48 212 $params = array_merge($gradebookrolesparams, $enrolledparams, $sortparams, $relatedctxparams);
f2491a11 213 $params['importcode'] = $importcode;
7d69de18 214
2dc5e584 215 return $DB->get_records_sql($sql, $params);
7d69de18 216}
217
ce40b793 218/**
219 * removes entries from grade import buffer tables grade_import_value and grade_import_newitem
220 * after a successful import, or during an import abort
221 * @param string importcode - import batch identifier
222 */
223function import_cleanup($importcode) {
5c75a0a3 224 global $USER, $DB;
8108909a 225
b263e539 226 // remove entries from buffer table
5c75a0a3 227 $DB->delete_records('grade_import_values', array('importcode' => $importcode, 'importer' => $USER->id));
228 $DB->delete_records('grade_import_newitem', array('importcode' => $importcode, 'importer' => $USER->id));
ce40b793 229}
741bde47 230
6c3ef410 231