weekly on-sync release 2.5dev
[moodle.git] / mod / assign / upgradelib.php
CommitLineData
bbd0e548
DW
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/**
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 */
24
25defined('MOODLE_INTERNAL') || die();
26
27/** Include locallib.php */
28require_once($CFG->dirroot.'/mod/assign/locallib.php');
29/** Include accesslib.php */
30require_once($CFG->libdir.'/accesslib.php');
31
5b121144
DW
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 */
37define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
bbd0e548
DW
38
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 */
46class assign_upgrade_manager {
47
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) {
bbd0e548 57 // steps to upgrade an assignment
bbd0e548
DW
58 global $DB, $CFG, $USER;
59 // steps to upgrade an assignment
60
61 // is the user the admin? admin check goes here
62 if (!is_siteadmin($USER->id)) {
63 return false;
64 }
65
5b121144
DW
66 // should we use a shutdown handler to rollback on timeout?
67 @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
68
bbd0e548
DW
69
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);
74
75 // first insert an assign instance to get the id
76 $oldassignment = $DB->get_record('assignment', array('id'=>$oldassignmentid), '*', MUST_EXIST);
77
78 $oldversion = get_config('assignment_' . $oldassignment->assignmenttype, 'version');
79
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;
56ff1300 87 $data->sendlatenotifications = $oldassignment->emailteachers;
bbd0e548
DW
88 $data->duedate = $oldassignment->timedue;
89 $data->allowsubmissionsfromdate = $oldassignment->timeavailable;
90 $data->grade = $oldassignment->grade;
91 $data->submissiondrafts = $oldassignment->resubmit;
94f26900 92 $data->requiresubmissionstatement = 0;
9e795179
DW
93 $data->cutoffdate = 0;
94 // New way to specify no late submissions.
95 if ($oldassignment->preventlate) {
96 $data->cutoffdate = $data->duedate;
97 }
7c7bc2ee
DW
98 $data->teamsubmission = 0;
99 $data->requireallteammemberssubmit = 0;
100 $data->teamsubmissiongroupingid = 0;
101 $data->blindmarking = 0;
bbd0e548
DW
102
103 $newassignment = new assign(null, null, null);
104
105 if (!$newassignment->add_instance($data, false)) {
106 $log = get_string('couldnotcreatenewassignmentinstance', 'mod_assign');
107 return false;
108 }
109
110 // now create a new coursemodule from the old one
111 $newmodule = $DB->get_record('modules', array('name'=>'assign'), '*', MUST_EXIST);
112 $newcoursemodule = $this->duplicate_course_module($oldcoursemodule, $newmodule->id, $newassignment->get_instance()->id);
113 if (!$newcoursemodule) {
114 $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
115 return false;
116 }
117
118 // convert the base database tables (assignment, submission, grade)
119
120 // these are used to store information in case a rollback is required
121 $gradingarea = null;
122 $gradingdefinitions = null;
123 $gradeidmap = array();
124 $completiondone = false;
c45261df 125 $gradesdone = false;
bbd0e548
DW
126
127 // from this point we want to rollback on failure
128 $rollback = false;
129 try {
130 $newassignment->set_context(context_module::instance($newcoursemodule->id));
131
132 // the course module has now been created - time to update the core tables
133
134 // copy intro files
135 $newassignment->copy_area_files_for_upgrade($oldcontext->id, 'mod_assignment', 'intro', 0,
136 $newassignment->get_context()->id, 'mod_assign', 'intro', 0);
137
138
139 // get the plugins to do their bit
140 foreach ($newassignment->get_submission_plugins() as $plugin) {
141 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
142 $plugin->enable();
143 if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
144 $rollback = true;
145 }
fb11a702
LT
146 } else {
147 $plugin->disable();
bbd0e548
DW
148 }
149 }
150 foreach ($newassignment->get_feedback_plugins() as $plugin) {
151 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
152 $plugin->enable();
153 if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
154 $rollback = true;
155 }
fb11a702
LT
156 } else {
157 $plugin->disable();
bbd0e548
DW
158 }
159 }
160
161 // see if there is advanced grading upgrades required
162 $gradingarea = $DB->get_record('grading_areas', array('contextid'=>$oldcontext->id, 'areaname'=>'submission'), '*', IGNORE_MISSING);
163 if ($gradingarea) {
164 $DB->update_record('grading_areas', array('id'=>$gradingarea->id, 'contextid'=>$newassignment->get_context()->id, 'component'=>'mod_assign', 'areaname'=>'submissions'));
165 $gradingdefinitions = $DB->get_records('grading_definitions', array('areaid'=>$gradingarea->id));
166 }
167
168 // upgrade completion data
169 $DB->set_field('course_modules_completion', 'coursemoduleid', $newcoursemodule->id, array('coursemoduleid'=>$oldcoursemodule->id));
1f417de8
DW
170 $allcriteria = $DB->get_records('course_completion_criteria', array('moduleinstance'=>$oldcoursemodule->id));
171 foreach ($allcriteria as $criteria) {
172 $criteria->module = 'assign';
173 $criteria->moduleinstance = $newcoursemodule->id;
174 $DB->update_record('course_completion_criteria', $criteria);
175 }
bbd0e548
DW
176 $completiondone = true;
177
ac9ac1fe
AO
178 // Migrate log entries so we don't lose them.
179 $logparams = array('cmid' => $oldcoursemodule->id, 'course' => $oldcoursemodule->course);
180 $DB->set_field('log', 'module', 'assign', $logparams);
181 $DB->set_field('log', 'cmid', $newcoursemodule->id, $logparams);
182
bbd0e548
DW
183
184 // copy all the submission data (and get plugins to do their bit)
185 $oldsubmissions = $DB->get_records('assignment_submissions', array('assignment'=>$oldassignmentid));
186
187 foreach ($oldsubmissions as $oldsubmission) {
188 $submission = new stdClass();
189 $submission->assignment = $newassignment->get_instance()->id;
190 $submission->userid = $oldsubmission->userid;
191 $submission->timecreated = $oldsubmission->timecreated;
192 $submission->timemodified = $oldsubmission->timemodified;
193 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
194 $submission->id = $DB->insert_record('assign_submission', $submission);
195 if (!$submission->id) {
196 $log .= get_string('couldnotinsertsubmission', 'mod_assign', $submission->userid);
197 $rollback = true;
198 }
199 foreach ($newassignment->get_submission_plugins() as $plugin) {
200 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
201 if (!$plugin->upgrade($oldcontext, $oldassignment, $oldsubmission, $submission, $log)) {
202 $rollback = true;
203 }
204 }
205 }
206 if ($oldsubmission->timemarked) {
207 // submission has been graded - create a grade record
208 $grade = new stdClass();
209 $grade->assignment = $newassignment->get_instance()->id;
210 $grade->userid = $oldsubmission->userid;
211 $grade->grader = $oldsubmission->teacher;
212 $grade->timemodified = $oldsubmission->timemarked;
213 $grade->timecreated = $oldsubmission->timecreated;
214 // $grade->locked = $oldsubmission->locked;
215 $grade->grade = $oldsubmission->grade;
216 $grade->mailed = $oldsubmission->mailed;
217 $grade->id = $DB->insert_record('assign_grades', $grade);
218 if (!$grade->id) {
219 $log .= get_string('couldnotinsertgrade', 'mod_assign', $grade->userid);
220 $rollback = true;
221 }
222
223 // copy any grading instances
224 if ($gradingarea) {
225
226 $gradeidmap[$grade->id] = $oldsubmission->id;
227
228 foreach ($gradingdefinitions as $definition) {
229 $DB->set_field('grading_instances', 'itemid', $grade->id, array('definitionid'=>$definition->id, 'itemid'=>$oldsubmission->id));
230 }
231
232 }
233 foreach ($newassignment->get_feedback_plugins() as $plugin) {
234 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
235 if (!$plugin->upgrade($oldcontext, $oldassignment, $oldsubmission, $grade, $log)) {
236 $rollback = true;
237 }
238 }
239 }
240 }
241 }
242
243 $newassignment->update_calendar($newcoursemodule->id);
bbd0e548 244
f264499f
DW
245 // Reassociate grade_items from the old assignment instance to the new assign instance.
246 // This includes outcome linked grade_items.
247 $params = array('assign', $newassignment->get_instance()->id, 'assignment', $oldassignment->id);
248 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
249 $DB->execute($sql, $params);
1f417de8 250
c45261df 251 $gradesdone = true;
bbd0e548
DW
252
253 } catch (Exception $exception) {
254 $rollback = true;
5b121144 255 $log .= get_string('conversionexception', 'mod_assign', $exception->error);
bbd0e548
DW
256 }
257
258 if ($rollback) {
c45261df
DW
259 // roll back the grades changes
260 if ($gradesdone) {
f264499f
DW
261 // Reassociate grade_items from the new assign instance to the old assignment instance.
262 $params = array('assignment', $oldassignment->id, 'assign', $newassignment->get_instance()->id);
263 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
264 $DB->execute($sql, $params);
c45261df 265 }
bbd0e548
DW
266 // roll back the completion changes
267 if ($completiondone) {
268 $DB->set_field('course_modules_completion', 'coursemoduleid', $oldcoursemodule->id, array('coursemoduleid'=>$newcoursemodule->id));
1f417de8
DW
269 $allcriteria = $DB->get_records('course_completion_criteria', array('moduleinstance'=>$newcoursemodule->id));
270 foreach ($allcriteria as $criteria) {
271 $criteria->module = 'assignment';
272 $criteria->moduleinstance = $oldcoursemodule->id;
273 $DB->update_record('course_completion_criteria', $criteria);
274 }
bbd0e548 275 }
ac9ac1fe
AO
276 // Roll back the log changes
277 $logparams = array('cmid' => $newcoursemodule->id, 'course' => $newcoursemodule->course);
278 $DB->set_field('log', 'module', 'assignment', $logparams);
279 $DB->set_field('log', 'cmid', $oldcoursemodule->id, $logparams);
bbd0e548
DW
280 // roll back the advanced grading update
281 if ($gradingarea) {
282 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
283 foreach ($gradingdefinitions as $definition) {
284 $DB->set_field('grading_instances', 'itemid', $oldsubmissionid, array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
285 }
286 }
287 $DB->update_record('grading_areas', array('id'=>$gradingarea->id, 'contextid'=>$oldcontext->id, 'component'=>'mod_assignment', 'areaname'=>'submission'));
288 }
289 $newassignment->delete_instance();
290
291 return false;
292 }
293 // all is well,
294 // delete the old assignment (use object delete)
295 $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
296 if ($cm) {
297 $this->delete_course_module($cm);
298 }
299 rebuild_course_cache($oldcoursemodule->course);
300 return true;
301 }
302
303
304 /**
305 * Create a duplicate course module record so we can create the upgraded
306 * assign module alongside the old assignment module.
307 *
308 * @param stdClass $cm The old course module record
309 * @param int $moduleid The id of the new assign module
310 * @param int $newinstanceid The id of the new instance of the assign module
311 * @return mixed stdClass|bool The new course module record or FALSE
312 */
313 private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
314 global $DB, $CFG;
315
316 $newcm = new stdClass();
317 $newcm->course = $cm->course;
318 $newcm->module = $moduleid;
319 $newcm->instance = $newinstanceid;
320 $newcm->visible = $cm->visible;
321 $newcm->section = $cm->section;
322 $newcm->score = $cm->score;
323 $newcm->indent = $cm->indent;
324 $newcm->groupmode = $cm->groupmode;
325 $newcm->groupingid = $cm->groupingid;
326 $newcm->groupmembersonly = $cm->groupmembersonly;
327 $newcm->completion = $cm->completion;
328 $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
329 $newcm->completionview = $cm->completionview;
330 $newcm->completionexpected = $cm->completionexpected;
331 if(!empty($CFG->enableavailability)) {
332 $newcm->availablefrom = $cm->availablefrom;
333 $newcm->availableuntil = $cm->availableuntil;
334 $newcm->showavailability = $cm->showavailability;
335 }
336 $newcm->showdescription = $cm->showdescription;
337
338 $newcmid = add_course_module($newcm);
339 $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
340 if (!$newcm) {
341 return false;
342 }
343 $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
344 if (!$section) {
345 return false;
346 }
347
722e6ba9 348 $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
bbd0e548
DW
349
350 // make sure visibility is set correctly (in particular in calendar)
351 // note: allow them to set it even without moodle/course:activityvisibility
352 set_coursemodule_visible($newcm->id, $newcm->visible);
353
354 return $newcm;
355 }
356
357 /**
358 * This function deletes the old assignment course module after
359 * it has been upgraded. This code is adapted from "course/mod.php".
360 *
361 * @param stdClass $cm The course module to delete.
362 * @return bool
363 */
364 private function delete_course_module($cm) {
365 global $CFG, $USER, $DB, $OUTPUT;
366 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
367
368 $coursecontext = context_course::instance($course->id);
369 $modcontext = context_module::instance($cm->id);
370
371 $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
372
373 if (file_exists($modlib)) {
374 require_once($modlib);
375 } else {
376 print_error('modulemissingcode', '', '', $modlib);
377 }
378
379 $deleteinstancefunction = $cm->modname."_delete_instance";
380
381 if (!$deleteinstancefunction($cm->instance)) {
382 echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
383 }
384
385 // remove all module files in case modules forget to do that
386 $fs = get_file_storage();
387 $fs->delete_area_files($modcontext->id);
388
389 if (!delete_course_module($cm->id)) {
390 echo $OUTPUT->notification("Could not delete the $cm->modname (coursemodule)");
391 }
392 if (!delete_mod_from_section($cm->id, $cm->section)) {
393 echo $OUTPUT->notification("Could not delete the $cm->modname from that section");
394 }
395
396 // Trigger a mod_deleted event with information about this module.
397 $eventdata = new stdClass();
398 $eventdata->modulename = $cm->modname;
399 $eventdata->cmid = $cm->id;
400 $eventdata->courseid = $course->id;
401 $eventdata->userid = $USER->id;
402 events_trigger('mod_deleted', $eventdata);
403
404 add_to_log($course->id, 'course', "delete mod",
405 "view.php?id=$cm->course",
406 "$cm->modname $cm->instance", $cm->id);
407
408 return true;
409 }
410
bbd0e548 411}