MDL-32895: Improvements to assignment upgrade tool for large numbers of assignments.
[moodle.git] / mod / assign / upgradelib.php
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/>.
17 /**
18  * This file contains the upgrade code to upgrade from mod_assignment to mod_assign
19  *
20  * @package   mod_assign
21  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 defined('MOODLE_INTERNAL') || die();
27 /** Include locallib.php */
28 require_once($CFG->dirroot.'/mod/assign/locallib.php');
29 /** Include accesslib.php */
30 require_once($CFG->libdir.'/accesslib.php');
32 /**
33  * The maximum amount of time to spend upgrading a single assignment.
34  * This is intentionally generous (5 mins) as the effect of a timeout
35  * for a legitimate upgrade would be quite harsh (roll back code will not run)
36  */
37 define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
39 /**
40  * Class to manage upgrades from mod_assignment to mod_assign
41  *
42  * @package   mod_assign
43  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
44  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45  */
46 class assign_upgrade_manager {
48     /**
49      * This function converts all of the base settings for an instance of
50      * the old assignment to the new format. Then it calls each of the plugins
51      * to see if they can help upgrade this assignment.
52      * @param int $oldassignmentid (don't rely on the old assignment type even being installed)
53      * @param string $log This string gets appended to during the conversion process
54      * @return bool true or false
55      */
56     public function upgrade_assignment($oldassignmentid, & $log) {
57         // steps to upgrade an assignment
58         global $DB, $CFG, $USER;
59         // steps to upgrade an assignment
61         // is the user the admin? admin check goes here
62         if (!is_siteadmin($USER->id)) {
63               return false;
64         }
66         // should we use a shutdown handler to rollback on timeout?
67         @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
70         // get the module details
71         $oldmodule = $DB->get_record('modules', array('name'=>'assignment'), '*', MUST_EXIST);
72         $oldcoursemodule = $DB->get_record('course_modules', array('module'=>$oldmodule->id, 'instance'=>$oldassignmentid), '*', MUST_EXIST);
73         $oldcontext = context_module::instance($oldcoursemodule->id);
75         // first insert an assign instance to get the id
76         $oldassignment = $DB->get_record('assignment', array('id'=>$oldassignmentid), '*', MUST_EXIST);
78         $oldversion = get_config('assignment_' . $oldassignment->assignmenttype, 'version');
80         $data = new stdClass();
81         $data->course = $oldassignment->course;
82         $data->name = $oldassignment->name;
83         $data->intro = $oldassignment->intro;
84         $data->introformat = $oldassignment->introformat;
85         $data->alwaysshowdescription = 1;
86         $data->sendnotifications = $oldassignment->emailteachers;
87         $data->duedate = $oldassignment->timedue;
88         $data->allowsubmissionsfromdate = $oldassignment->timeavailable;
89         $data->grade = $oldassignment->grade;
90         $data->submissiondrafts = $oldassignment->resubmit;
91         $data->preventlatesubmissions = $oldassignment->preventlate;
93         $newassignment = new assign(null, null, null);
95         if (!$newassignment->add_instance($data, false)) {
96             $log = get_string('couldnotcreatenewassignmentinstance', 'mod_assign');
97             return false;
98         }
100         // now create a new coursemodule from the old one
101         $newmodule = $DB->get_record('modules', array('name'=>'assign'), '*', MUST_EXIST);
102         $newcoursemodule = $this->duplicate_course_module($oldcoursemodule, $newmodule->id, $newassignment->get_instance()->id);
103         if (!$newcoursemodule) {
104             $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
105             return false;
106         }
108         // convert the base database tables (assignment, submission, grade)
110         // these are used to store information in case a rollback is required
111         $gradingarea = null;
112         $gradingdefinitions = null;
113         $gradeidmap = array();
114         $completiondone = false;
116         // from this point we want to rollback on failure
117         $rollback = false;
118         try {
119             $newassignment->set_context(context_module::instance($newcoursemodule->id));
121             // the course module has now been created - time to update the core tables
123             // copy intro files
124             $newassignment->copy_area_files_for_upgrade($oldcontext->id, 'mod_assignment', 'intro', 0,
125                                             $newassignment->get_context()->id, 'mod_assign', 'intro', 0);
128             // get the plugins to do their bit
129             foreach ($newassignment->get_submission_plugins() as $plugin) {
130                 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
131                     $plugin->enable();
132                     if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
133                         $rollback = true;
134                     }
135                 }
136             }
137             foreach ($newassignment->get_feedback_plugins() as $plugin) {
138                 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
139                     $plugin->enable();
140                     if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
141                         $rollback = true;
142                     }
143                 }
144             }
146             // see if there is advanced grading upgrades required
147             $gradingarea = $DB->get_record('grading_areas', array('contextid'=>$oldcontext->id, 'areaname'=>'submission'), '*', IGNORE_MISSING);
148             if ($gradingarea) {
149                 $DB->update_record('grading_areas', array('id'=>$gradingarea->id, 'contextid'=>$newassignment->get_context()->id, 'component'=>'mod_assign', 'areaname'=>'submissions'));
150                 $gradingdefinitions = $DB->get_records('grading_definitions', array('areaid'=>$gradingarea->id));
151             }
153             // upgrade completion data
154             $DB->set_field('course_modules_completion', 'coursemoduleid', $newcoursemodule->id, array('coursemoduleid'=>$oldcoursemodule->id));
155             $DB->set_field('course_completion_criteria', 'module', 'assign', array('moduleinstance'=>$oldcoursemodule->id));
156             $DB->set_field('course_completion_criteria', 'moduleinstance', $newcoursemodule->id, array('moduleinstance'=>$oldcoursemodule->id));
157             $completiondone = true;
160             // copy all the submission data (and get plugins to do their bit)
161             $oldsubmissions = $DB->get_records('assignment_submissions', array('assignment'=>$oldassignmentid));
163             foreach ($oldsubmissions as $oldsubmission) {
164                 $submission = new stdClass();
165                 $submission->assignment = $newassignment->get_instance()->id;
166                 $submission->userid = $oldsubmission->userid;
167                 $submission->timecreated = $oldsubmission->timecreated;
168                 $submission->timemodified = $oldsubmission->timemodified;
169                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
170                 $submission->id = $DB->insert_record('assign_submission', $submission);
171                 if (!$submission->id) {
172                     $log .= get_string('couldnotinsertsubmission', 'mod_assign', $submission->userid);
173                     $rollback = true;
174                 }
175                 foreach ($newassignment->get_submission_plugins() as $plugin) {
176                     if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
177                         if (!$plugin->upgrade($oldcontext, $oldassignment, $oldsubmission, $submission, $log)) {
178                             $rollback = true;
179                         }
180                     }
181                 }
182                 if ($oldsubmission->timemarked) {
183                     // submission has been graded - create a grade record
184                     $grade = new stdClass();
185                     $grade->assignment = $newassignment->get_instance()->id;
186                     $grade->userid = $oldsubmission->userid;
187                     $grade->grader = $oldsubmission->teacher;
188                     $grade->timemodified = $oldsubmission->timemarked;
189                     $grade->timecreated = $oldsubmission->timecreated;
190                     // $grade->locked = $oldsubmission->locked;
191                     $grade->grade = $oldsubmission->grade;
192                     $grade->mailed = $oldsubmission->mailed;
193                     $grade->id = $DB->insert_record('assign_grades', $grade);
194                     if (!$grade->id) {
195                         $log .= get_string('couldnotinsertgrade', 'mod_assign', $grade->userid);
196                         $rollback = true;
197                     }
199                     // copy any grading instances
200                     if ($gradingarea) {
202                         $gradeidmap[$grade->id] = $oldsubmission->id;
204                         foreach ($gradingdefinitions as $definition) {
205                             $DB->set_field('grading_instances', 'itemid', $grade->id, array('definitionid'=>$definition->id, 'itemid'=>$oldsubmission->id));
206                         }
208                     }
209                     foreach ($newassignment->get_feedback_plugins() as $plugin) {
210                         if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
211                             if (!$plugin->upgrade($oldcontext, $oldassignment, $oldsubmission, $grade, $log)) {
212                                 $rollback = true;
213                             }
214                         }
215                     }
216                 }
217             }
219             $newassignment->update_calendar($newcoursemodule->id);
220             $newassignment->update_gradebook(false,$newcoursemodule->id);
222             // copy the grades from the old assignment to the new one
223             $this->copy_grades_for_upgrade($oldassignment, $newassignment);
225         } catch (Exception $exception) {
226             $rollback = true;
227             $log .= get_string('conversionexception', 'mod_assign', $exception->error);
228         }
230         if ($rollback) {
231             // roll back the completion changes
232             if ($completiondone) {
233                 $DB->set_field('course_modules_completion', 'coursemoduleid', $oldcoursemodule->id, array('coursemoduleid'=>$newcoursemodule->id));
234                 $DB->set_field('course_completion_criteria', 'module', 'assignment', array('moduleinstance'=>$newcoursemodule->id));
235                 $DB->set_field('course_completion_criteria', 'moduleinstance', $oldcoursemodule->id, array('moduleinstance'=>$newcoursemodule->id));
236             }
237             // roll back the advanced grading update
238             if ($gradingarea) {
239                 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
240                     foreach ($gradingdefinitions as $definition) {
241                         $DB->set_field('grading_instances', 'itemid', $oldsubmissionid, array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
242                     }
243                 }
244                 $DB->update_record('grading_areas', array('id'=>$gradingarea->id, 'contextid'=>$oldcontext->id, 'component'=>'mod_assignment', 'areaname'=>'submission'));
245             }
246             $newassignment->delete_instance();
248             return false;
249         }
250         // all is well,
251         // delete the old assignment (use object delete)
252         $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
253         if ($cm) {
254             $this->delete_course_module($cm);
255         }
256         rebuild_course_cache($oldcoursemodule->course);
257         return true;
258     }
261     /**
262      * Create a duplicate course module record so we can create the upgraded
263      * assign module alongside the old assignment module.
264      *
265      * @param stdClass $cm The old course module record
266      * @param int $moduleid The id of the new assign module
267      * @param int $newinstanceid The id of the new instance of the assign module
268      * @return mixed stdClass|bool The new course module record or FALSE
269      */
270     private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
271         global $DB, $CFG;
273         $newcm = new stdClass();
274         $newcm->course           = $cm->course;
275         $newcm->module           = $moduleid;
276         $newcm->instance         = $newinstanceid;
277         $newcm->visible          = $cm->visible;
278         $newcm->section          = $cm->section;
279         $newcm->score            = $cm->score;
280         $newcm->indent           = $cm->indent;
281         $newcm->groupmode        = $cm->groupmode;
282         $newcm->groupingid       = $cm->groupingid;
283         $newcm->groupmembersonly = $cm->groupmembersonly;
284         $newcm->completion                = $cm->completion;
285         $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
286         $newcm->completionview            = $cm->completionview;
287         $newcm->completionexpected        = $cm->completionexpected;
288         if(!empty($CFG->enableavailability)) {
289             $newcm->availablefrom             = $cm->availablefrom;
290             $newcm->availableuntil            = $cm->availableuntil;
291             $newcm->showavailability          = $cm->showavailability;
292         }
293         $newcm->showdescription = $cm->showdescription;
295         $newcmid = add_course_module($newcm);
296         $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
297         if (!$newcm) {
298             return false;
299         }
300         $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
301         if (!$section) {
302             return false;
303         }
305         $mod = new stdClass();
306         $mod->course = $newcm->course;
307         $mod->section = $section->section;
308         $mod->coursemodule = $newcm->id;
309         $mod->id = $newcm->id;
310         $newcm->section = add_mod_to_section($mod, $cm);
312         // make sure visibility is set correctly (in particular in calendar)
313         // note: allow them to set it even without moodle/course:activityvisibility
314         set_coursemodule_visible($newcm->id, $newcm->visible);
316         return $newcm;
317     }
319     /**
320      * This function deletes the old assignment course module after
321      * it has been upgraded. This code is adapted from "course/mod.php".
322      *
323      * @param stdClass $cm The course module to delete.
324      * @return bool
325      */
326     private function delete_course_module($cm) {
327         global $CFG, $USER, $DB, $OUTPUT;
328         $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
330         $coursecontext = context_course::instance($course->id);
331         $modcontext = context_module::instance($cm->id);
333         $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
335         if (file_exists($modlib)) {
336             require_once($modlib);
337         } else {
338             print_error('modulemissingcode', '', '', $modlib);
339         }
341         $deleteinstancefunction = $cm->modname."_delete_instance";
343         if (!$deleteinstancefunction($cm->instance)) {
344             echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
345         }
347         // remove all module files in case modules forget to do that
348         $fs = get_file_storage();
349         $fs->delete_area_files($modcontext->id);
351         if (!delete_course_module($cm->id)) {
352             echo $OUTPUT->notification("Could not delete the $cm->modname (coursemodule)");
353         }
354         if (!delete_mod_from_section($cm->id, $cm->section)) {
355             echo $OUTPUT->notification("Could not delete the $cm->modname from that section");
356         }
358         // Trigger a mod_deleted event with information about this module.
359         $eventdata = new stdClass();
360         $eventdata->modulename = $cm->modname;
361         $eventdata->cmid       = $cm->id;
362         $eventdata->courseid   = $course->id;
363         $eventdata->userid     = $USER->id;
364         events_trigger('mod_deleted', $eventdata);
366         add_to_log($course->id, 'course', "delete mod",
367                    "view.php?id=$cm->course",
368                    "$cm->modname $cm->instance", $cm->id);
370         return true;
371     }
373     /**
374      * This function copies the grades from the old assignment module to this one.
375      *
376      * @param stdClass $oldassignment old assignment data record
377      * @param assign $newassignment the new assign class
378      * @return bool true or false
379      */
380     public function copy_grades_for_upgrade($oldassignment, $newassignment) {
381         global $CFG;
383         require_once($CFG->libdir.'/gradelib.php');
385         // get the old and new grade items
386         $oldgradeitems = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>'assignment', 'iteminstance'=>$oldassignment->id));
387         if (!$oldgradeitems) {
388             return false;
389         }
390         $oldgradeitem = array_pop($oldgradeitems);
391         if (!$oldgradeitem) {
392             return false;
393         }
394         $newgradeitems = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>'assign', 'iteminstance'=>$newassignment->get_instance()->id));
395         if (!$newgradeitems) {
396             return false;
397         }
398         $newgradeitem = array_pop($newgradeitems);
399         if (!$newgradeitem) {
400             return false;
401         }
403         $gradegrades = grade_grade::fetch_all(array('itemid'=>$oldgradeitem->id));
404         if ($gradegrades) {
405             foreach ($gradegrades as $gradeid=>$grade) {
406                 $grade->itemid = $newgradeitem->id;
407                 grade_update('mod/assign', $newassignment->get_course()->id, 'mod', 'assign', $newassignment->get_instance()->id, 0, $grade, NULL);
408             }
409         }
410         return true;
411     }