055457bef2c12610e79bf70416b596a2b9d45e3b
[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 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));
183             foreach ($allcriteria as $criteria) {
184                 $criteria->module = 'assign';
185                 $criteria->moduleinstance = $newcoursemodule->id;
186                 $DB->update_record('course_completion_criteria', $criteria);
187             }
188             $completiondone = true;
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);
195             // Copy all the submission data (and get plugins to do their bit).
196             $oldsubmissions = $DB->get_records('assignment_submissions',
197                                                array('assignment'=>$oldassignmentid));
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)) {
213                         if (!$plugin->upgrade($oldcontext,
214                                               $oldassignment,
215                                               $oldsubmission,
216                                               $submission,
217                                               $log)) {
218                             $rollback = true;
219                         }
220                     }
221                 }
222                 if ($oldsubmission->timemarked) {
223                     // Submission has been graded - create a grade record.
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;
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                     }
238                     // Copy any grading instances.
239                     if ($gradingarea) {
241                         $gradeidmap[$grade->id] = $oldsubmission->id;
243                         foreach ($gradingdefinitions as $definition) {
244                             $params = array('definitionid'=>$definition->id,
245                                             'itemid'=>$oldsubmission->id);
246                             $DB->set_field('grading_instances', 'itemid', $grade->id, $params);
247                         }
249                     }
250                     foreach ($newassignment->get_feedback_plugins() as $plugin) {
251                         if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
252                             if (!$plugin->upgrade($oldcontext,
253                                                   $oldassignment,
254                                                   $oldsubmission,
255                                                   $grade,
256                                                   $log)) {
257                                 $rollback = true;
258                             }
259                         }
260                     }
261                 }
262             }
264             $newassignment->update_calendar($newcoursemodule->id);
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);
272             $gradesdone = true;
274         } catch (Exception $exception) {
275             $rollback = true;
276             $log .= get_string('conversionexception', 'mod_assign', $exception->error);
277         }
279         if ($rollback) {
280             // Roll back the grades changes.
281             if ($gradesdone) {
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);
286             }
287             // Roll back the completion changes.
288             if ($completiondone) {
289                 $DB->set_field('course_modules_completion',
290                                'coursemoduleid',
291                                $oldcoursemodule->id,
292                                array('coursemoduleid'=>$newcoursemodule->id));
294                 $allcriteria = $DB->get_records('course_completion_criteria',
295                                                 array('moduleinstance'=>$newcoursemodule->id));
296                 foreach ($allcriteria as $criteria) {
297                     $criteria->module = 'assignment';
298                     $criteria->moduleinstance = $oldcoursemodule->id;
299                     $DB->update_record('course_completion_criteria', $criteria);
300                 }
301             }
302             // Roll back the log changes.
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);
306             // Roll back the advanced grading update.
307             if ($gradingarea) {
308                 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
309                     foreach ($gradingdefinitions as $definition) {
310                         $DB->set_field('grading_instances',
311                                        'itemid',
312                                        $oldsubmissionid,
313                                        array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
314                     }
315                 }
316                 $params = array('id'=>$gradingarea->id,
317                                 'contextid'=>$oldcontext->id,
318                                 'component'=>'mod_assignment',
319                                 'areaname'=>'submission');
320                 $DB->update_record('grading_areas', $params);
321             }
322             $newassignment->delete_instance();
324             return false;
325         }
326         // Delete the old assignment (use object delete).
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     }
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;
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;
363         if (!empty($CFG->enableavailability)) {
364             $newcm->availablefrom             = $cm->availablefrom;
365             $newcm->availableuntil            = $cm->availableuntil;
366             $newcm->showavailability          = $cm->showavailability;
367         }
368         $newcm->showdescription = $cm->showdescription;
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         }
380         $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
382         // Make sure visibility is set correctly (in particular in calendar).
383         // Note: Allow them to set it even without moodle/course:activityvisibility.
384         set_coursemodule_visible($newcm->id, $newcm->visible);
386         return $newcm;
387     }
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);
400         $coursecontext = context_course::instance($course->id);
401         $modcontext = context_module::instance($cm->id);
403         $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
405         if (file_exists($modlib)) {
406             require_once($modlib);
407         } else {
408             print_error('modulemissingcode', '', '', $modlib);
409         }
411         $deleteinstancefunction = $cm->modname."_delete_instance";
413         if (!$deleteinstancefunction($cm->instance)) {
414             echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
415         }
417         // Remove all module files in case modules forget to do that.
418         $fs = get_file_storage();
419         $fs->delete_area_files($modcontext->id);
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         }
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);
436         add_to_log($course->id, 'course', "delete mod",
437                    "view.php?id=$cm->course",
438                    "$cm->modname $cm->instance", $cm->id);
440         return true;
441     }