MDL-37082 core_course: create new course_delete_module function that handles the...
[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');
29 require_once($CFG->dirroot.'/course/lib.php');
31 /*
32  * The maximum amount of time to spend upgrading a single assignment.
33  * This is intentionally generous (5 mins) as the effect of a timeout
34  * for a legitimate upgrade would be quite harsh (roll back code will not run)
35  */
36 define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
38 /**
39  * Class to manage upgrades from mod_assignment to mod_assign
40  *
41  * @package   mod_assign
42  * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
43  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44  */
45 class assign_upgrade_manager {
47     /**
48      * This function converts all of the base settings for an instance of
49      * the old assignment to the new format. Then it calls each of the plugins
50      * to see if they can help upgrade this assignment.
51      * @param int $oldassignmentid (don't rely on the old assignment type even being installed)
52      * @param string $log This string gets appended to during the conversion process
53      * @return bool true or false
54      */
55     public function upgrade_assignment($oldassignmentid, & $log) {
56         global $DB, $CFG, $USER;
57         // Steps to upgrade an assignment.
59         // Is the user the admin? admin check goes here.
60         if (!is_siteadmin($USER->id)) {
61               return false;
62         }
64         @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
66         // Get the module details.
67         $oldmodule = $DB->get_record('modules', array('name'=>'assignment'), '*', MUST_EXIST);
68         $params = array('module'=>$oldmodule->id, 'instance'=>$oldassignmentid);
69         $oldcoursemodule = $DB->get_record('course_modules',
70                                            $params,
71                                            '*',
72                                            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->sendlatenotifications = $oldassignment->emailteachers;
88         $data->duedate = $oldassignment->timedue;
89         $data->allowsubmissionsfromdate = $oldassignment->timeavailable;
90         $data->grade = $oldassignment->grade;
91         $data->submissiondrafts = $oldassignment->resubmit;
92         $data->requiresubmissionstatement = 0;
93         $data->cutoffdate = 0;
94         // New way to specify no late submissions.
95         if ($oldassignment->preventlate) {
96             $data->cutoffdate = $data->duedate;
97         }
98         $data->teamsubmission = 0;
99         $data->requireallteammemberssubmit = 0;
100         $data->teamsubmissiongroupingid = 0;
101         $data->blindmarking = 0;
103         $newassignment = new assign(null, null, null);
105         if (!$newassignment->add_instance($data, false)) {
106             $log = get_string('couldnotcreatenewassignmentinstance', 'mod_assign');
107             return false;
108         }
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,
113                                                           $newmodule->id,
114                                                           $newassignment->get_instance()->id);
115         if (!$newcoursemodule) {
116             $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
117             return false;
118         }
120         // Convert the base database tables (assignment, submission, grade).
122         // These are used to store information in case a rollback is required.
123         $gradingarea = null;
124         $gradingdefinitions = null;
125         $gradeidmap = array();
126         $completiondone = false;
127         $gradesdone = false;
129         // From this point we want to rollback on failure.
130         $rollback = false;
131         try {
132             $newassignment->set_context(context_module::instance($newcoursemodule->id));
134             // The course module has now been created - time to update the core tables.
136             // Copy intro files.
137             $newassignment->copy_area_files_for_upgrade($oldcontext->id, 'mod_assignment', 'intro', 0,
138                                             $newassignment->get_context()->id, 'mod_assign', 'intro', 0);
140             // Get the plugins to do their bit.
141             foreach ($newassignment->get_submission_plugins() as $plugin) {
142                 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
143                     $plugin->enable();
144                     if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
145                         $rollback = true;
146                     }
147                 } else {
148                     $plugin->disable();
149                 }
150             }
151             foreach ($newassignment->get_feedback_plugins() as $plugin) {
152                 if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
153                     $plugin->enable();
154                     if (!$plugin->upgrade_settings($oldcontext, $oldassignment, $log)) {
155                         $rollback = true;
156                     }
157                 } else {
158                     $plugin->disable();
159                 }
160             }
162             // See if there is advanced grading upgrades required.
163             $gradingarea = $DB->get_record('grading_areas',
164                                            array('contextid'=>$oldcontext->id, 'areaname'=>'submission'),
165                                            '*',
166                                            IGNORE_MISSING);
167             if ($gradingarea) {
168                 $params = array('id'=>$gradingarea->id,
169                                 'contextid'=>$newassignment->get_context()->id,
170                                 'component'=>'mod_assign',
171                                 'areaname'=>'submissions');
172                 $DB->update_record('grading_areas', $params);
173                 $gradingdefinitions = $DB->get_records('grading_definitions',
174                                                        array('areaid'=>$gradingarea->id));
175             }
177             // Upgrade completion data.
178             $DB->set_field('course_modules_completion',
179                            'coursemoduleid',
180                            $newcoursemodule->id,
181                            array('coursemoduleid'=>$oldcoursemodule->id));
182             $allcriteria = $DB->get_records('course_completion_criteria',
183                                             array('moduleinstance'=>$oldcoursemodule->id));
184             foreach ($allcriteria as $criteria) {
185                 $criteria->module = 'assign';
186                 $criteria->moduleinstance = $newcoursemodule->id;
187                 $DB->update_record('course_completion_criteria', $criteria);
188             }
189             $completiondone = true;
191             // Migrate log entries so we don't lose them.
192             $logparams = array('cmid' => $oldcoursemodule->id, 'course' => $oldcoursemodule->course);
193             $DB->set_field('log', 'module', 'assign', $logparams);
194             $DB->set_field('log', 'cmid', $newcoursemodule->id, $logparams);
196             // Copy all the submission data (and get plugins to do their bit).
197             $oldsubmissions = $DB->get_records('assignment_submissions',
198                                                array('assignment'=>$oldassignmentid));
200             foreach ($oldsubmissions as $oldsubmission) {
201                 $submission = new stdClass();
202                 $submission->assignment = $newassignment->get_instance()->id;
203                 $submission->userid = $oldsubmission->userid;
204                 $submission->timecreated = $oldsubmission->timecreated;
205                 $submission->timemodified = $oldsubmission->timemodified;
206                 $submission->status = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
207                 $submission->id = $DB->insert_record('assign_submission', $submission);
208                 if (!$submission->id) {
209                     $log .= get_string('couldnotinsertsubmission', 'mod_assign', $submission->userid);
210                     $rollback = true;
211                 }
212                 foreach ($newassignment->get_submission_plugins() as $plugin) {
213                     if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
214                         if (!$plugin->upgrade($oldcontext,
215                                               $oldassignment,
216                                               $oldsubmission,
217                                               $submission,
218                                               $log)) {
219                             $rollback = true;
220                         }
221                     }
222                 }
223                 if ($oldsubmission->timemarked) {
224                     // Submission has been graded - create a grade record.
225                     $grade = new stdClass();
226                     $grade->assignment = $newassignment->get_instance()->id;
227                     $grade->userid = $oldsubmission->userid;
228                     $grade->grader = $oldsubmission->teacher;
229                     $grade->timemodified = $oldsubmission->timemarked;
230                     $grade->timecreated = $oldsubmission->timecreated;
231                     $grade->grade = $oldsubmission->grade;
232                     $grade->mailed = $oldsubmission->mailed;
233                     $grade->id = $DB->insert_record('assign_grades', $grade);
234                     if (!$grade->id) {
235                         $log .= get_string('couldnotinsertgrade', 'mod_assign', $grade->userid);
236                         $rollback = true;
237                     }
239                     // Copy any grading instances.
240                     if ($gradingarea) {
242                         $gradeidmap[$grade->id] = $oldsubmission->id;
244                         foreach ($gradingdefinitions as $definition) {
245                             $params = array('definitionid'=>$definition->id,
246                                             'itemid'=>$oldsubmission->id);
247                             $DB->set_field('grading_instances', 'itemid', $grade->id, $params);
248                         }
250                     }
251                     foreach ($newassignment->get_feedback_plugins() as $plugin) {
252                         if ($plugin->can_upgrade($oldassignment->assignmenttype, $oldversion)) {
253                             if (!$plugin->upgrade($oldcontext,
254                                                   $oldassignment,
255                                                   $oldsubmission,
256                                                   $grade,
257                                                   $log)) {
258                                 $rollback = true;
259                             }
260                         }
261                     }
262                 }
263             }
265             $newassignment->update_calendar($newcoursemodule->id);
267             // Reassociate grade_items from the old assignment instance to the new assign instance.
268             // This includes outcome linked grade_items.
269             $params = array('assign', $newassignment->get_instance()->id, 'assignment', $oldassignment->id);
270             $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
271             $DB->execute($sql, $params);
273             $gradesdone = true;
275         } catch (Exception $exception) {
276             $rollback = true;
277             $log .= get_string('conversionexception', 'mod_assign', $exception->error);
278         }
280         if ($rollback) {
281             // Roll back the grades changes.
282             if ($gradesdone) {
283                 // Reassociate grade_items from the new assign instance to the old assignment instance.
284                 $params = array('assignment', $oldassignment->id, 'assign', $newassignment->get_instance()->id);
285                 $sql = 'UPDATE {grade_items} SET itemmodule = ?, iteminstance = ? WHERE itemmodule = ? AND iteminstance = ?';
286                 $DB->execute($sql, $params);
287             }
288             // Roll back the completion changes.
289             if ($completiondone) {
290                 $DB->set_field('course_modules_completion',
291                                'coursemoduleid',
292                                $oldcoursemodule->id,
293                                array('coursemoduleid'=>$newcoursemodule->id));
295                 $allcriteria = $DB->get_records('course_completion_criteria',
296                                                 array('moduleinstance'=>$newcoursemodule->id));
297                 foreach ($allcriteria as $criteria) {
298                     $criteria->module = 'assignment';
299                     $criteria->moduleinstance = $oldcoursemodule->id;
300                     $DB->update_record('course_completion_criteria', $criteria);
301                 }
302             }
303             // Roll back the log changes.
304             $logparams = array('cmid' => $newcoursemodule->id, 'course' => $newcoursemodule->course);
305             $DB->set_field('log', 'module', 'assignment', $logparams);
306             $DB->set_field('log', 'cmid', $oldcoursemodule->id, $logparams);
307             // Roll back the advanced grading update.
308             if ($gradingarea) {
309                 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
310                     foreach ($gradingdefinitions as $definition) {
311                         $DB->set_field('grading_instances',
312                                        'itemid',
313                                        $oldsubmissionid,
314                                        array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
315                     }
316                 }
317                 $params = array('id'=>$gradingarea->id,
318                                 'contextid'=>$oldcontext->id,
319                                 'component'=>'mod_assignment',
320                                 'areaname'=>'submission');
321                 $DB->update_record('grading_areas', $params);
322             }
323             $newassignment->delete_instance();
325             return false;
326         }
327         // Delete the old assignment (use object delete).
328         $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
329         if ($cm) {
330             course_delete_module($cm->id);
331         }
332         rebuild_course_cache($oldcoursemodule->course);
333         return true;
334     }
337     /**
338      * Create a duplicate course module record so we can create the upgraded
339      * assign module alongside the old assignment module.
340      *
341      * @param stdClass $cm The old course module record
342      * @param int $moduleid The id of the new assign module
343      * @param int $newinstanceid The id of the new instance of the assign module
344      * @return mixed stdClass|bool The new course module record or FALSE
345      */
346     private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
347         global $DB, $CFG;
349         $newcm = new stdClass();
350         $newcm->course           = $cm->course;
351         $newcm->module           = $moduleid;
352         $newcm->instance         = $newinstanceid;
353         $newcm->visible          = $cm->visible;
354         $newcm->section          = $cm->section;
355         $newcm->score            = $cm->score;
356         $newcm->indent           = $cm->indent;
357         $newcm->groupmode        = $cm->groupmode;
358         $newcm->groupingid       = $cm->groupingid;
359         $newcm->groupmembersonly = $cm->groupmembersonly;
360         $newcm->completion                = $cm->completion;
361         $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
362         $newcm->completionview            = $cm->completionview;
363         $newcm->completionexpected        = $cm->completionexpected;
364         if (!empty($CFG->enableavailability)) {
365             $newcm->availablefrom             = $cm->availablefrom;
366             $newcm->availableuntil            = $cm->availableuntil;
367             $newcm->showavailability          = $cm->showavailability;
368         }
369         $newcm->showdescription = $cm->showdescription;
371         $newcmid = add_course_module($newcm);
372         $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
373         if (!$newcm) {
374             return false;
375         }
376         $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
377         if (!$section) {
378             return false;
379         }
381         $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
383         // Make sure visibility is set correctly (in particular in calendar).
384         // Note: Allow them to set it even without moodle/course:activityvisibility.
385         set_coursemodule_visible($newcm->id, $newcm->visible);
387         return $newcm;
388     }