MDL-37563 Assignment upgrade: Upgrade conditional activity settings.
[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 require_once($CFG->dirroot.'/mod/assign/locallib.php');
28 require_once($CFG->libdir.'/accesslib.php');
30 /*
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  */
35 define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
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  */
44 class assign_upgrade_manager {
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) {
55         global $DB, $CFG, $USER;
56         // Steps to upgrade an assignment.
58         // Is the user the admin? admin check goes here.
59         if (!is_siteadmin($USER->id)) {
60               return false;
61         }
63         @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
65         // Get the module details.
66         $oldmodule = $DB->get_record('modules', array('name'=>'assignment'), '*', MUST_EXIST);
67         $params = array('module'=>$oldmodule->id, 'instance'=>$oldassignmentid);
68         $oldcoursemodule = $DB->get_record('course_modules',
69                                            $params,
70                                            '*',
71                                            MUST_EXIST);
72         $oldcontext = context_module::instance($oldcoursemodule->id);
74         // First insert an assign instance to get the id.
75         $oldassignment = $DB->get_record('assignment', array('id'=>$oldassignmentid), '*', MUST_EXIST);
77         $oldversion = get_config('assignment_' . $oldassignment->assignmenttype, 'version');
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;
86         $data->sendlatenotifications = $oldassignment->emailteachers;
87         $data->duedate = $oldassignment->timedue;
88         $data->allowsubmissionsfromdate = $oldassignment->timeavailable;
89         $data->grade = $oldassignment->grade;
90         $data->submissiondrafts = $oldassignment->resubmit;
91         $data->requiresubmissionstatement = 0;
92         $data->cutoffdate = 0;
93         // New way to specify no late submissions.
94         if ($oldassignment->preventlate) {
95             $data->cutoffdate = $data->duedate;
96         }
97         $data->teamsubmission = 0;
98         $data->requireallteammemberssubmit = 0;
99         $data->teamsubmissiongroupingid = 0;
100         $data->blindmarking = 0;
102         $newassignment = new assign(null, null, null);
104         if (!$newassignment->add_instance($data, false)) {
105             $log = get_string('couldnotcreatenewassignmentinstance', 'mod_assign');
106             return false;
107         }
109         // Now create a new coursemodule from the old one.
110         $newmodule = $DB->get_record('modules', array('name'=>'assign'), '*', MUST_EXIST);
111         $newcoursemodule = $this->duplicate_course_module($oldcoursemodule,
112                                                           $newmodule->id,
113                                                           $newassignment->get_instance()->id);
114         if (!$newcoursemodule) {
115             $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
116             return false;
117         }
119         // Convert the base database tables (assignment, submission, grade).
121         // These are used to store information in case a rollback is required.
122         $gradingarea = null;
123         $gradingdefinitions = null;
124         $gradeidmap = array();
125         $completiondone = false;
126         $gradesdone = false;
128         // From this point we want to rollback on failure.
129         $rollback = false;
130         try {
131             $newassignment->set_context(context_module::instance($newcoursemodule->id));
133             // The course module has now been created - time to update the core tables.
135             // Copy intro files.
136             $newassignment->copy_area_files_for_upgrade($oldcontext->id, 'mod_assignment', 'intro', 0,
137                                             $newassignment->get_context()->id, 'mod_assign', 'intro', 0);
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                     }
146                 } else {
147                     $plugin->disable();
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                     }
156                 } else {
157                     $plugin->disable();
158                 }
159             }
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);
166             if ($gradingarea) {
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));
174             }
176             // Upgrade availability data.
177             $DB->set_field('course_modules_avail_fields',
178                            'coursemoduleid',
179                            $newcoursemodule->id,
180                            array('coursemoduleid'=>$oldcoursemodule->id));
181             $DB->set_field('course_modules_availability',
182                            'coursemoduleid',
183                            $newcoursemodule->id,
184                            array('coursemoduleid'=>$oldcoursemodule->id));
185             $DB->set_field('course_modules_availability',
186                            'sourcecmid',
187                            $newcoursemodule->id,
188                            array('sourcecmid'=>$oldcoursemodule->id));
189             $DB->set_field('course_sections_availability',
190                            'sourcecmid',
191                            $newcoursemodule->id,
192                            array('sourcecmid'=>$oldcoursemodule->id));
194             // Upgrade completion data.
195             $DB->set_field('course_modules_completion',
196                            'coursemoduleid',
197                            $newcoursemodule->id,
198                            array('coursemoduleid'=>$oldcoursemodule->id));
199             $allcriteria = $DB->get_records('course_completion_criteria',
200                                             array('moduleinstance'=>$oldcoursemodule->id));
201             foreach ($allcriteria as $criteria) {
202                 $criteria->module = 'assign';
203                 $criteria->moduleinstance = $newcoursemodule->id;
204                 $DB->update_record('course_completion_criteria', $criteria);
205             }
206             $completiondone = true;
208             // Migrate log entries so we don't lose them.
209             $logparams = array('cmid' => $oldcoursemodule->id, 'course' => $oldcoursemodule->course);
210             $DB->set_field('log', 'module', 'assign', $logparams);
211             $DB->set_field('log', 'cmid', $newcoursemodule->id, $logparams);
213             // Copy all the submission data (and get plugins to do their bit).
214             $oldsubmissions = $DB->get_records('assignment_submissions',
215                                                array('assignment'=>$oldassignmentid));
217             foreach ($oldsubmissions as $oldsubmission) {
218                 $submission = new stdClass();
219                 $submission->assignment = $newassignment->get_instance()->id;
220                 $submission->userid = $oldsubmission->userid;
221                 $submission->timecreated = $oldsubmission->timecreated;
222                 $submission->timemodified = $oldsubmission->timemodified;
223                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
224                 $submission->id = $DB->insert_record('assign_submission', $submission);
225                 if (!$submission->id) {
226                     $log .= get_string('couldnotinsertsubmission', 'mod_assign', $submission->userid);
227                     $rollback = true;
228                 }
229                 foreach ($newassignment->get_submission_plugins() as $plugin) {
230                     if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
231                         if (!$plugin->upgrade($oldcontext,
232                                               $oldassignment,
233                                               $oldsubmission,
234                                               $submission,
235                                               $log)) {
236                             $rollback = true;
237                         }
238                     }
239                 }
240                 if ($oldsubmission->timemarked) {
241                     // Submission has been graded - create a grade record.
242                     $grade = new stdClass();
243                     $grade->assignment = $newassignment->get_instance()->id;
244                     $grade->userid = $oldsubmission->userid;
245                     $grade->grader = $oldsubmission->teacher;
246                     $grade->timemodified = $oldsubmission->timemarked;
247                     $grade->timecreated = $oldsubmission->timecreated;
248                     $grade->grade = $oldsubmission->grade;
249                     $grade->mailed = $oldsubmission->mailed;
250                     $grade->id = $DB->insert_record('assign_grades', $grade);
251                     if (!$grade->id) {
252                         $log .= get_string('couldnotinsertgrade', 'mod_assign', $grade->userid);
253                         $rollback = true;
254                     }
256                     // Copy any grading instances.
257                     if ($gradingarea) {
259                         $gradeidmap[$grade->id] = $oldsubmission->id;
261                         foreach ($gradingdefinitions as $definition) {
262                             $params = array('definitionid'=>$definition->id,
263                                             'itemid'=>$oldsubmission->id);
264                             $DB->set_field('grading_instances', 'itemid', $grade->id, $params);
265                         }
267                     }
268                     foreach ($newassignment->get_feedback_plugins() as $plugin) {
269                         if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
270                             if (!$plugin->upgrade($oldcontext,
271                                                   $oldassignment,
272                                                   $oldsubmission,
273                                                   $grade,
274                                                   $log)) {
275                                 $rollback = true;
276                             }
277                         }
278                     }
279                 }
280             }
282             $newassignment->update_calendar($newcoursemodule->id);
284             // Reassociate grade_items from the old assignment instance to the new assign instance.
285             // This includes outcome linked grade_items.
286             $params = array('assign', $newassignment->get_instance()->id, 'assignment', $oldassignment->id);
287             $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
288             $DB->execute($sql, $params);
290             $gradesdone = true;
292         } catch (Exception $exception) {
293             $rollback = true;
294             $log .= get_string('conversionexception', 'mod_assign', $exception->error);
295         }
297         if ($rollback) {
298             // Roll back the grades changes.
299             if ($gradesdone) {
300                 // Reassociate grade_items from the new assign instance to the old assignment instance.
301                 $params = array('assignment', $oldassignment->id, 'assign', $newassignment->get_instance()->id);
302                 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
303                 $DB->execute($sql, $params);
304             }
305             // Roll back the completion changes.
306             if ($completiondone) {
307                 $DB->set_field('course_modules_completion',
308                                'coursemoduleid',
309                                $oldcoursemodule->id,
310                                array('coursemoduleid'=>$newcoursemodule->id));
312                 $allcriteria = $DB->get_records('course_completion_criteria',
313                                                 array('moduleinstance'=>$newcoursemodule->id));
314                 foreach ($allcriteria as $criteria) {
315                     $criteria->module = 'assignment';
316                     $criteria->moduleinstance = $oldcoursemodule->id;
317                     $DB->update_record('course_completion_criteria', $criteria);
318                 }
319             }
320             // Roll back the log changes.
321             $logparams = array('cmid' => $newcoursemodule->id, 'course' => $newcoursemodule->course);
322             $DB->set_field('log', 'module', 'assignment', $logparams);
323             $DB->set_field('log', 'cmid', $oldcoursemodule->id, $logparams);
324             // Roll back the advanced grading update.
325             if ($gradingarea) {
326                 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
327                     foreach ($gradingdefinitions as $definition) {
328                         $DB->set_field('grading_instances',
329                                        'itemid',
330                                        $oldsubmissionid,
331                                        array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
332                     }
333                 }
334                 $params = array('id'=>$gradingarea->id,
335                                 'contextid'=>$oldcontext->id,
336                                 'component'=>'mod_assignment',
337                                 'areaname'=>'submission');
338                 $DB->update_record('grading_areas', $params);
339             }
340             $newassignment->delete_instance();
342             return false;
343         }
344         // Delete the old assignment (use object delete).
345         $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
346         if ($cm) {
347             $this->delete_course_module($cm);
348         }
349         rebuild_course_cache($oldcoursemodule->course);
350         return true;
351     }
354     /**
355      * Create a duplicate course module record so we can create the upgraded
356      * assign module alongside the old assignment module.
357      *
358      * @param stdClass $cm The old course module record
359      * @param int $moduleid The id of the new assign module
360      * @param int $newinstanceid The id of the new instance of the assign module
361      * @return mixed stdClass|bool The new course module record or FALSE
362      */
363     private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
364         global $DB, $CFG;
366         $newcm = new stdClass();
367         $newcm->course           = $cm->course;
368         $newcm->module           = $moduleid;
369         $newcm->instance         = $newinstanceid;
370         $newcm->visible          = $cm->visible;
371         $newcm->section          = $cm->section;
372         $newcm->score            = $cm->score;
373         $newcm->indent           = $cm->indent;
374         $newcm->groupmode        = $cm->groupmode;
375         $newcm->groupingid       = $cm->groupingid;
376         $newcm->groupmembersonly = $cm->groupmembersonly;
377         $newcm->completion                = $cm->completion;
378         $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
379         $newcm->completionview            = $cm->completionview;
380         $newcm->completionexpected        = $cm->completionexpected;
381         if (!empty($CFG->enableavailability)) {
382             $newcm->availablefrom             = $cm->availablefrom;
383             $newcm->availableuntil            = $cm->availableuntil;
384             $newcm->showavailability          = $cm->showavailability;
385         }
386         $newcm->showdescription = $cm->showdescription;
388         $newcmid = add_course_module($newcm);
389         $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
390         if (!$newcm) {
391             return false;
392         }
393         $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
394         if (!$section) {
395             return false;
396         }
398         $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
400         // Make sure visibility is set correctly (in particular in calendar).
401         // Note: Allow them to set it even without moodle/course:activityvisibility.
402         set_coursemodule_visible($newcm->id, $newcm->visible);
404         return $newcm;
405     }
407     /**
408      * This function deletes the old assignment course module after
409      * it has been upgraded. This code is adapted from "course/mod.php".
410      *
411      * @param stdClass $cm The course module to delete.
412      * @return bool
413      */
414     private function delete_course_module($cm) {
415         global $CFG, $USER, $DB, $OUTPUT;
416         $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
418         $coursecontext = context_course::instance($course->id);
419         $modcontext = context_module::instance($cm->id);
421         $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
423         if (file_exists($modlib)) {
424             require_once($modlib);
425         } else {
426             print_error('modulemissingcode', '', '', $modlib);
427         }
429         $deleteinstancefunction = $cm->modname."_delete_instance";
431         if (!$deleteinstancefunction($cm->instance)) {
432             echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
433         }
435         // Remove all module files in case modules forget to do that.
436         $fs = get_file_storage();
437         $fs->delete_area_files($modcontext->id);
439         if (!delete_course_module($cm->id)) {
440             echo $OUTPUT->notification("Could not delete the $cm->modname (coursemodule)");
441         }
442         if (!delete_mod_from_section($cm->id, $cm->section)) {
443             echo $OUTPUT->notification("Could not delete the $cm->modname from that section");
444         }
446         // Trigger a mod_deleted event with information about this module.
447         $eventdata = new stdClass();
448         $eventdata->modulename = $cm->modname;
449         $eventdata->cmid       = $cm->id;
450         $eventdata->courseid   = $course->id;
451         $eventdata->userid     = $USER->id;
452         events_trigger('mod_deleted', $eventdata);
454         add_to_log($course->id, 'course', "delete mod",
455                    "view.php?id=$cm->course",
456                    "$cm->modname $cm->instance", $cm->id);
458         return true;
459     }