MDL-34052 assignment - Disable submission and feedback plugins based on assign type...
[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 /** Include locallib.php */
28 require_once($CFG->dirroot.'/mod/assign/locallib.php');
29 /** Include accesslib.php */
30 require_once($CFG->libdir.'/accesslib.php');
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  */
37 define('ASSIGN_MAX_UPGRADE_TIME_SECS', 300);
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  */
46 class assign_upgrade_manager {
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) {
57         // steps to upgrade an assignment
58         global $DB, $CFG, $USER;
59         // steps to upgrade an assignment
61         // is the user the admin? admin check goes here
62         if (!is_siteadmin($USER->id)) {
63               return false;
64         }
66         // should we use a shutdown handler to rollback on timeout?
67         @set_time_limit(ASSIGN_MAX_UPGRADE_TIME_SECS);
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);
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, $newmodule->id, $newassignment->get_instance()->id);
113         if (!$newcoursemodule) {
114             $log = get_string('couldnotcreatenewcoursemodule', 'mod_assign');
115             return false;
116         }
118         // convert the base database tables (assignment, submission, grade)
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;
125         $gradesdone = false;
127         // from this point we want to rollback on failure
128         $rollback = false;
129         try {
130             $newassignment->set_context(context_module::instance($newcoursemodule->id));
132             // the course module has now been created - time to update the core tables
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);
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', 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             }
168             // upgrade completion data
169             $DB->set_field('course_modules_completion', 'coursemoduleid', $newcoursemodule->id, array('coursemoduleid'=>$oldcoursemodule->id));
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             }
176             $completiondone = true;
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);
184             // copy all the submission data (and get plugins to do their bit)
185             $oldsubmissions = $DB->get_records('assignment_submissions', array('assignment'=>$oldassignmentid));
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                     }
223                     // copy any grading instances
224                     if ($gradingarea) {
226                         $gradeidmap[$grade->id] = $oldsubmission->id;
228                         foreach ($gradingdefinitions as $definition) {
229                             $DB->set_field('grading_instances', 'itemid', $grade->id, array('definitionid'=>$definition->id, 'itemid'=>$oldsubmission->id));
230                         }
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             }
243             $newassignment->update_calendar($newcoursemodule->id);
245             // copy the grades from the old assignment to the new one
247             $gradeitem = $DB->get_record('grade_items', array('iteminstance'=>$oldassignment->id, 'itemmodule'=>'assignment'), 'id', IGNORE_MISSING);
248             if ($gradeitem) {
249                 $gradeitem->iteminstance = $newassignment->get_instance()->id;
250                 $gradeitem->itemmodule = 'assign';
251                 $DB->update_record('grade_items', $gradeitem);
252             }
253             $gradesdone = true;
255         } catch (Exception $exception) {
256             $rollback = true;
257             $log .= get_string('conversionexception', 'mod_assign', $exception->error);
258         }
260         if ($rollback) {
261             // roll back the grades changes
262             if ($gradesdone) {
263                 // copy the grades from the old assignment to the new one
264                 $gradeitem = $DB->get_record('grade_items', array('iteminstance'=>$newassignment->get_instance()->id, 'itemmodule'=>'assign'), 'id', IGNORE_MISSING);
265                 if ($gradeitem) {
266                     $gradeitem->iteminstance = $oldassignment->id;
267                     $gradeitem->itemmodule = 'assignment';
268                     $DB->update_record('grade_items', $gradeitem);
269                 }
270             }
271             // roll back the completion changes
272             if ($completiondone) {
273                 $DB->set_field('course_modules_completion', 'coursemoduleid', $oldcoursemodule->id, array('coursemoduleid'=>$newcoursemodule->id));
274                 $allcriteria = $DB->get_records('course_completion_criteria', array('moduleinstance'=>$newcoursemodule->id));
275                 foreach ($allcriteria as $criteria) {
276                     $criteria->module = 'assignment';
277                     $criteria->moduleinstance = $oldcoursemodule->id;
278                     $DB->update_record('course_completion_criteria', $criteria);
279                 }
280             }
281             // Roll back the log changes
282             $logparams = array('cmid' => $newcoursemodule->id, 'course' => $newcoursemodule->course);
283             $DB->set_field('log', 'module', 'assignment', $logparams);
284             $DB->set_field('log', 'cmid', $oldcoursemodule->id, $logparams);
285             // roll back the advanced grading update
286             if ($gradingarea) {
287                 foreach ($gradeidmap as $newgradeid => $oldsubmissionid) {
288                     foreach ($gradingdefinitions as $definition) {
289                         $DB->set_field('grading_instances', 'itemid', $oldsubmissionid, array('definitionid'=>$definition->id, 'itemid'=>$newgradeid));
290                     }
291                 }
292                 $DB->update_record('grading_areas', array('id'=>$gradingarea->id, 'contextid'=>$oldcontext->id, 'component'=>'mod_assignment', 'areaname'=>'submission'));
293             }
294             $newassignment->delete_instance();
296             return false;
297         }
298         // all is well,
299         // delete the old assignment (use object delete)
300         $cm = get_coursemodule_from_id('', $oldcoursemodule->id, $oldcoursemodule->course);
301         if ($cm) {
302             $this->delete_course_module($cm);
303         }
304         rebuild_course_cache($oldcoursemodule->course);
305         return true;
306     }
309     /**
310      * Create a duplicate course module record so we can create the upgraded
311      * assign module alongside the old assignment module.
312      *
313      * @param stdClass $cm The old course module record
314      * @param int $moduleid The id of the new assign module
315      * @param int $newinstanceid The id of the new instance of the assign module
316      * @return mixed stdClass|bool The new course module record or FALSE
317      */
318     private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) {
319         global $DB, $CFG;
321         $newcm = new stdClass();
322         $newcm->course           = $cm->course;
323         $newcm->module           = $moduleid;
324         $newcm->instance         = $newinstanceid;
325         $newcm->visible          = $cm->visible;
326         $newcm->section          = $cm->section;
327         $newcm->score            = $cm->score;
328         $newcm->indent           = $cm->indent;
329         $newcm->groupmode        = $cm->groupmode;
330         $newcm->groupingid       = $cm->groupingid;
331         $newcm->groupmembersonly = $cm->groupmembersonly;
332         $newcm->completion                = $cm->completion;
333         $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
334         $newcm->completionview            = $cm->completionview;
335         $newcm->completionexpected        = $cm->completionexpected;
336         if(!empty($CFG->enableavailability)) {
337             $newcm->availablefrom             = $cm->availablefrom;
338             $newcm->availableuntil            = $cm->availableuntil;
339             $newcm->showavailability          = $cm->showavailability;
340         }
341         $newcm->showdescription = $cm->showdescription;
343         $newcmid = add_course_module($newcm);
344         $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
345         if (!$newcm) {
346             return false;
347         }
348         $section = $DB->get_record("course_sections", array("id"=>$newcm->section));
349         if (!$section) {
350             return false;
351         }
353         $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section);
355         // make sure visibility is set correctly (in particular in calendar)
356         // note: allow them to set it even without moodle/course:activityvisibility
357         set_coursemodule_visible($newcm->id, $newcm->visible);
359         return $newcm;
360     }
362     /**
363      * This function deletes the old assignment course module after
364      * it has been upgraded. This code is adapted from "course/mod.php".
365      *
366      * @param stdClass $cm The course module to delete.
367      * @return bool
368      */
369     private function delete_course_module($cm) {
370         global $CFG, $USER, $DB, $OUTPUT;
371         $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
373         $coursecontext = context_course::instance($course->id);
374         $modcontext = context_module::instance($cm->id);
376         $modlib = "$CFG->dirroot/mod/$cm->modname/lib.php";
378         if (file_exists($modlib)) {
379             require_once($modlib);
380         } else {
381             print_error('modulemissingcode', '', '', $modlib);
382         }
384         $deleteinstancefunction = $cm->modname."_delete_instance";
386         if (!$deleteinstancefunction($cm->instance)) {
387             echo $OUTPUT->notification("Could not delete the $cm->modname (instance)");
388         }
390         // remove all module files in case modules forget to do that
391         $fs = get_file_storage();
392         $fs->delete_area_files($modcontext->id);
394         if (!delete_course_module($cm->id)) {
395             echo $OUTPUT->notification("Could not delete the $cm->modname (coursemodule)");
396         }
397         if (!delete_mod_from_section($cm->id, $cm->section)) {
398             echo $OUTPUT->notification("Could not delete the $cm->modname from that section");
399         }
401         // Trigger a mod_deleted event with information about this module.
402         $eventdata = new stdClass();
403         $eventdata->modulename = $cm->modname;
404         $eventdata->cmid       = $cm->id;
405         $eventdata->courseid   = $course->id;
406         $eventdata->userid     = $USER->id;
407         events_trigger('mod_deleted', $eventdata);
409         add_to_log($course->id, 'course', "delete mod",
410                    "view.php?id=$cm->course",
411                    "$cm->modname $cm->instance", $cm->id);
413         return true;
414     }