MDL-37085 bug fix in link for module subtypes. Thanks to Andrew Nicols
[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
bbd0e548 27require_once($CFG->dirroot.'/mod/assign/locallib.php');
bbd0e548
DW
28require_once($CFG->libdir.'/accesslib.php');
29
e5403f8c 30/*
5b121144
DW
31 * The maximum amount of time to spend upgrading a single assignment.
32 * This is intentionally generous (5 mins) as the effect of a timeout
33 * for a legitimate upgrade would be quite harsh (roll back code will not run)
34 */
35define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
bbd0e548
DW
36
37/**
38 * Class to manage upgrades from mod_assignment to mod_assign
39 *
40 * @package mod_assign
41 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44class assign_upgrade_manager {
45
46 /**
47 * This function converts all of the base settings for an instance of
48 * the old assignment to the new format. Then it calls each of the plugins
49 * to see if they can help upgrade this assignment.
50 * @param int $oldassignmentid (don't rely on the old assignment type even being installed)
51 * @param string $log This string gets appended to during the conversion process
52 * @return bool true or false
53 */
54 public function upgrade_assignment($oldassignmentid, & $log) {
bbd0e548 55 global $DB, $CFG, $USER;
e5403f8c 56 // Steps to upgrade an assignment.
bbd0e548 57
e5403f8c 58 // Is the user the admin? admin check goes here.
bbd0e548
DW
59 if (!is_siteadmin($USER->id)) {
60 return false;
61 }
62
5b121144
DW
63 @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
64
e5403f8c 65 // Get the module details.
bbd0e548 66 $oldmodule = $DB->get_record('modules', array('name'=>'assignment'), '*', MUST_EXIST);
e5403f8c
DW
67 $params = array('module'=>$oldmodule->id, 'instance'=>$oldassignmentid);
68 $oldcoursemodule = $DB->get_record('course_modules',
69 $params,
70 '*',
71 MUST_EXIST);
bbd0e548
DW
72 $oldcontext = context_module::instance($oldcoursemodule->id);
73
e5403f8c 74 // First insert an assign instance to get the id.
bbd0e548
DW
75 $oldassignment = $DB->get_record('assignment', array('id'=>$oldassignmentid), '*', MUST_EXIST);
76
77 $oldversion = get_config('assignment_' . $oldassignment->assignmenttype, 'version');
78
79 $data = new stdClass();
80 $data->course = $oldassignment->course;
81 $data->name = $oldassignment->name;
82 $data->intro = $oldassignment->intro;
83 $data->introformat = $oldassignment->introformat;
84 $data->alwaysshowdescription = 1;
85 $data->sendnotifications = $oldassignment->emailteachers;
56ff1300 86 $data->sendlatenotifications = $oldassignment->emailteachers;
bbd0e548
DW
87 $data->duedate = $oldassignment->timedue;
88 $data->allowsubmissionsfromdate = $oldassignment->timeavailable;
89 $data->grade = $oldassignment->grade;
90 $data->submissiondrafts = $oldassignment->resubmit;
94f26900 91 $data->requiresubmissionstatement = 0;
9e795179
DW
92 $data->cutoffdate = 0;
93 // New way to specify no late submissions.
94 if ($oldassignment->preventlate) {
95 $data->cutoffdate = $data->duedate;
96 }
7c7bc2ee
DW
97 $data->teamsubmission = 0;
98 $data->requireallteammemberssubmit = 0;
99 $data->teamsubmissiongroupingid = 0;
100 $data->blindmarking = 0;
bbd0e548
DW
101
102 $newassignment = new assign(null, null, null);
103
104 if (!$newassignment->add_instance($data, false)) {
105 $log = get_string('couldnotcreatenewassignmentinstance', 'mod_assign');
106 return false;
107 }
108
e5403f8c 109 // Now create a new coursemodule from the old one.
bbd0e548 110 $newmodule = $DB->get_record('modules', array('name'=>'assign'), '*', MUST_EXIST);
e5403f8c
DW
111 $newcoursemodule = $this->duplicate_course_module($oldcoursemodule,
112 $newmodule->id,
113 $newassignment->get_instance()->id);
bbd0e548
DW
114 if (!$newcoursemodule) {
115 $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
116 return false;
117 }
118
e5403f8c 119 // Convert the base database tables (assignment, submission, grade).
bbd0e548 120
e5403f8c 121 // These are used to store information in case a rollback is required.
bbd0e548
DW
122 $gradingarea = null;
123 $gradingdefinitions = null;
124 $gradeidmap = array();
125 $completiondone = false;
c45261df 126 $gradesdone = false;
bbd0e548 127
e5403f8c 128 // From this point we want to rollback on failure.
bbd0e548
DW
129 $rollback = false;
130 try {
131 $newassignment->set_context(context_module::instance($newcoursemodule->id));
132
e5403f8c 133 // The course module has now been created - time to update the core tables.
bbd0e548 134
e5403f8c 135 // Copy intro files.
bbd0e548
DW
136 $newassignment->copy_area_files_for_upgrade($oldcontext->id, 'mod_assignment', 'intro', 0,
137 $newassignment->get_context()->id, 'mod_assign', 'intro', 0);
138
e5403f8c 139 // Get the plugins to do their bit.
bbd0e548
DW
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
e5403f8c
DW
161 // See if there is advanced grading upgrades required.
162 $gradingarea = $DB->get_record('grading_areas',
163 array('contextid'=>$oldcontext->id, 'areaname'=>'submission'),
164 '*',
165 IGNORE_MISSING);
bbd0e548 166 if ($gradingarea) {
e5403f8c
DW
167 $params = array('id'=>$gradingarea->id,
168 'contextid'=>$newassignment->get_context()->id,
169 'component'=>'mod_assign',
170 'areaname'=>'submissions');
171 $DB->update_record('grading_areas', $params);
172 $gradingdefinitions = $DB->get_records('grading_definitions',
173 array('areaid'=>$gradingarea->id));
bbd0e548
DW
174 }
175
e5403f8c
DW
176 // Upgrade completion data.
177 $DB->set_field('course_modules_completion',
178 'coursemoduleid',
179 $newcoursemodule->id,
180 array('coursemoduleid'=>$oldcoursemodule->id));
181 $allcriteria = $DB->get_records('course_completion_criteria',
182 array('moduleinstance'=>$oldcoursemodule->id));
1f417de8
DW
183 foreach ($allcriteria as $criteria) {
184 $criteria->module = 'assign';
185 $criteria->moduleinstance = $newcoursemodule->id;
186 $DB->update_record('course_completion_criteria', $criteria);
187 }
bbd0e548
DW
188 $completiondone = true;
189
ac9ac1fe
AO
190 // Migrate log entries so we don't lose them.
191 $logparams = array('cmid' => $oldcoursemodule->id, 'course' => $oldcoursemodule->course);
192 $DB->set_field('log', 'module', 'assign', $logparams);
193 $DB->set_field('log', 'cmid', $newcoursemodule->id, $logparams);
194
e5403f8c
DW
195 // Copy all the submission data (and get plugins to do their bit).
196 $oldsubmissions = $DB->get_records('assignment_submissions',
197 array('assignment'=>$oldassignmentid));
bbd0e548
DW
198
199 foreach ($oldsubmissions as $oldsubmission) {
200 $submission = new stdClass();
201 $submission->assignment = $newassignment->get_instance()->id;
202 $submission->userid = $oldsubmission->userid;
203 $submission->timecreated = $oldsubmission->timecreated;
204 $submission->timemodified = $oldsubmission->timemodified;
205 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
206 $submission->id = $DB->insert_record('assign_submission', $submission);
207 if (!$submission->id) {
208 $log .= get_string('couldnotinsertsubmission', 'mod_assign', $submission->userid);
209 $rollback = true;
210 }
211 foreach ($newassignment->get_submission_plugins() as $plugin) {
212 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
e5403f8c
DW
213 if (!$plugin->upgrade($oldcontext,
214 $oldassignment,
215 $oldsubmission,
216 $submission,
217 $log)) {
bbd0e548
DW
218 $rollback = true;
219 }
220 }
221 }
222 if ($oldsubmission->timemarked) {
e5403f8c 223 // Submission has been graded - create a grade record.
bbd0e548
DW
224 $grade = new stdClass();
225 $grade->assignment = $newassignment->get_instance()->id;
226 $grade->userid = $oldsubmission->userid;
227 $grade->grader = $oldsubmission->teacher;
228 $grade->timemodified = $oldsubmission->timemarked;
229 $grade->timecreated = $oldsubmission->timecreated;
bbd0e548
DW
230 $grade->grade = $oldsubmission->grade;
231 $grade->mailed = $oldsubmission->mailed;
232 $grade->id = $DB->insert_record('assign_grades', $grade);
233 if (!$grade->id) {
234 $log .= get_string('couldnotinsertgrade', 'mod_assign', $grade->userid);
235 $rollback = true;
236 }
237
e5403f8c 238 // Copy any grading instances.
bbd0e548
DW
239 if ($gradingarea) {
240
241 $gradeidmap[$grade->id] = $oldsubmission->id;
242
243 foreach ($gradingdefinitions as $definition) {
e5403f8c
DW
244 $params = array('definitionid'=>$definition->id,
245 'itemid'=>$oldsubmission->id);
246 $DB->set_field('grading_instances', 'itemid', $grade->id, $params);
bbd0e548
DW
247 }
248
249 }
250 foreach ($newassignment->get_feedback_plugins() as $plugin) {
251 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
e5403f8c
DW
252 if (!$plugin->upgrade($oldcontext,
253 $oldassignment,
254 $oldsubmission,
255 $grade,
256 $log)) {
bbd0e548
DW
257 $rollback = true;
258 }
259 }
260 }
261 }
262 }
263
264 $newassignment->update_calendar($newcoursemodule->id);
bbd0e548 265
f264499f
DW
266 // Reassociate grade_items from the old assignment instance to the new assign instance.
267 // This includes outcome linked grade_items.
268 $params = array('assign', $newassignment->get_instance()->id, 'assignment', $oldassignment->id);
269 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
270 $DB->execute($sql, $params);
1f417de8 271
c45261df 272 $gradesdone = true;
bbd0e548
DW
273
274 } catch (Exception $exception) {
275 $rollback = true;
5b121144 276 $log .= get_string('conversionexception', 'mod_assign', $exception->error);
bbd0e548
DW
277 }
278
279 if ($rollback) {
e5403f8c 280 // Roll back the grades changes.
c45261df 281 if ($gradesdone) {
f264499f
DW
282 // Reassociate grade_items from the new assign instance to the old assignment instance.
283 $params = array('assignment', $oldassignment->id, 'assign', $newassignment->get_instance()->id);
284 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
285 $DB->execute($sql, $params);
c45261df 286 }
e5403f8c 287 // Roll back the completion changes.
bbd0e548 288 if ($completiondone) {
e5403f8c
DW
289 $DB->set_field('course_modules_completion',
290 'coursemoduleid',
291 $oldcoursemodule->id,
292 array('coursemoduleid'=>$newcoursemodule->id));
293
294 $allcriteria = $DB->get_records('course_completion_criteria',
295 array('moduleinstance'=>$newcoursemodule->id));
1f417de8
DW
296 foreach ($allcriteria as $criteria) {
297 $criteria->module = 'assignment';
298 $criteria->moduleinstance = $oldcoursemodule->id;
299 $DB->update_record('course_completion_criteria', $criteria);
300 }
bbd0e548 301 }
e5403f8c 302 // Roll back the log changes.
ac9ac1fe
AO
303 $logparams = array('cmid' => $newcoursemodule->id, 'course' => $newcoursemodule->course);
304 $DB->set_field('log', 'module', 'assignment', $logparams);
305 $DB->set_field('log', 'cmid', $oldcoursemodule->id, $logparams);
e5403f8c 306 // Roll back the advanced grading update.
bbd0e548
DW
307 if ($gradingarea) {
308 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
309 foreach ($gradingdefinitions as $definition) {
e5403f8c
DW
310 $DB->set_field('grading_instances',
311 'itemid',
312 $oldsubmissionid,
313 array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
bbd0e548
DW
314 }
315 }
e5403f8c
DW
316 $params = array('id'=>$gradingarea->id,
317 'contextid'=>$oldcontext->id,
318 'component'=>'mod_assignment',
319 'areaname'=>'submission');
320 $DB->update_record('grading_areas', $params);
bbd0e548
DW
321 }
322 $newassignment->delete_instance();
323
324 return false;
325 }
e5403f8c 326 // Delete the old assignment (use object delete).
bbd0e548
DW
327 $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
328 if ($cm) {
329 $this->delete_course_module($cm);
330 }
331 rebuild_course_cache($oldcoursemodule->course);
332 return true;
333 }
334
335
336 /**
337 * Create a duplicate course module record so we can create the upgraded
338 * assign module alongside the old assignment module.
339 *
340 * @param stdClass $cm The old course module record
341 * @param int $moduleid The id of the new assign module
342 * @param int $newinstanceid The id of the new instance of the assign module
343 * @return mixed stdClass|bool The new course module record or FALSE
344 */
345 private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
346 global $DB, $CFG;
347
348 $newcm = new stdClass();
349 $newcm->course = $cm->course;
350 $newcm->module = $moduleid;
351 $newcm->instance = $newinstanceid;
352 $newcm->visible = $cm->visible;
353 $newcm->section = $cm->section;
354 $newcm->score = $cm->score;
355 $newcm->indent = $cm->indent;
356 $newcm->groupmode = $cm->groupmode;
357 $newcm->groupingid = $cm->groupingid;
358 $newcm->groupmembersonly = $cm->groupmembersonly;
359 $newcm->completion = $cm->completion;
360 $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
361 $newcm->completionview = $cm->completionview;
362 $newcm->completionexpected = $cm->completionexpected;
e5403f8c 363 if (!empty($CFG->enableavailability)) {
bbd0e548
DW
364 $newcm->availablefrom = $cm->availablefrom;
365 $newcm->availableuntil = $cm->availableuntil;
366 $newcm->showavailability = $cm->showavailability;
367 }
368 $newcm->showdescription = $cm->showdescription;
369
370 $newcmid = add_course_module($newcm);
371 $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
372 if (!$newcm) {
373 return false;
374 }
375 $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
376 if (!$section) {
377 return false;
378 }
379
722e6ba9 380 $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
bbd0e548 381
e5403f8c
DW
382 // Make sure visibility is set correctly (in particular in calendar).
383 // Note: Allow them to set it even without moodle/course:activityvisibility.
bbd0e548
DW
384 set_coursemodule_visible($newcm->id, $newcm->visible);
385
386 return $newcm;
387 }
388
389 /**
390 * This function deletes the old assignment course module after
391 * it has been upgraded. This code is adapted from "course/mod.php".
392 *
393 * @param stdClass $cm The course module to delete.
394 * @return bool
395 */
396 private function delete_course_module($cm) {
397 global $CFG, $USER, $DB, $OUTPUT;
398 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
399
400 $coursecontext = context_course::instance($course->id);
401 $modcontext = context_module::instance($cm->id);
402
403 $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
404
405 if (file_exists($modlib)) {
406 require_once($modlib);
407 } else {
408 print_error('modulemissingcode', '', '', $modlib);
409 }
410
411 $deleteinstancefunction = $cm->modname."_delete_instance";
412
413 if (!$deleteinstancefunction($cm->instance)) {
414 echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
415 }
416
e5403f8c 417 // Remove all module files in case modules forget to do that.
bbd0e548
DW
418 $fs = get_file_storage();
419 $fs->delete_area_files($modcontext->id);
420
421 if (!delete_course_module($cm->id)) {
422 echo $OUTPUT->notification("Could not delete the $cm->modname (coursemodule)");
423 }
424 if (!delete_mod_from_section($cm->id, $cm->section)) {
425 echo $OUTPUT->notification("Could not delete the $cm->modname from that section");
426 }
427
428 // Trigger a mod_deleted event with information about this module.
429 $eventdata = new stdClass();
430 $eventdata->modulename = $cm->modname;
431 $eventdata->cmid = $cm->id;
432 $eventdata->courseid = $course->id;
433 $eventdata->userid = $USER->id;
434 events_trigger('mod_deleted', $eventdata);
435
436 add_to_log($course->id, 'course', "delete mod",
437 "view.php?id=$cm->course",
438 "$cm->modname $cm->instance", $cm->id);
439
440 return true;
441 }
442
bbd0e548 443}