source: moodle/trunk/fuentes/grade/import/lib.php @ 136

Last change on this file since 136 was 136, checked in by mabarracus, 3 years ago

Ported code to xenial

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