3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @subpackage backup-moodle2
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Define all the backup steps that will be used by common tasks in backup
30 * create the temp dir where backup/restore will happen,
31 * delete old directories and create temp ids table
33 class create_and_clean_temp_stuff extends backup_execution_step {
35 protected function define_execution() {
36 backup_helper::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
37 backup_helper::clear_backup_dir($this->get_backupid()); // Empty temp dir, just in case
38 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
39 backup_controller_dbops::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
44 * delete the temp dir used by backup/restore (conditionally),
45 * delete old directories and drop tem ids table. Note we delete
46 * the directory but not the corresponding log file that will be
47 * there for, at least, 4 hours - only delete_old_backup_dirs()
48 * deletes log files (for easier access to them)
50 class drop_and_clean_temp_stuff extends backup_execution_step {
52 protected $skipcleaningtempdir = false;
54 protected function define_execution() {
57 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
58 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
59 // Delete temp dir conditionally:
60 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
61 // 2) If backup temp dir deletion has been marked to be avoided
62 if (empty($CFG->keeptempdirectoriesonbackup) && !$this->skipcleaningtempdir) {
63 backup_helper::delete_backup_dir($this->get_backupid()); // Empty backup dir
67 public function skip_cleaning_temp_dir($skip) {
68 $this->skipcleaningtempdir = $skip;
73 * Create the directory where all the task (activity/block...) information will be stored
75 class create_taskbasepath_directory extends backup_execution_step {
77 protected function define_execution() {
79 $basepath = $this->task->get_taskbasepath();
80 if (!check_dir_exists($basepath, true, true)) {
81 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
87 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
88 * activity structure definition within the main <activity ...> tag. Also provides
89 * subplugin support for activities (that must be properly declared)
91 abstract class backup_activity_structure_step extends backup_structure_step {
94 * Add subplugin structure to any element in the activity backup tree
96 * @param string $subplugintype type of subplugin as defined in activity db/subplugins.php
97 * @param backup_nested_element $element element in the activity backup tree that
98 * we are going to add subplugin information to
99 * @param bool $multiple to define if multiple subplugins can produce information
100 * for each instance of $element (true) or no (false)
102 protected function add_subplugin_structure($subplugintype, $element, $multiple) {
106 // Check the requested subplugintype is a valid one
107 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
108 if (!file_exists($subpluginsfile)) {
109 throw new backup_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
111 include($subpluginsfile);
112 if (!array_key_exists($subplugintype, $subplugins)) {
113 throw new backup_step_exception('incorrect_subplugin_type', $subplugintype);
116 // Arrived here, subplugin is correct, let's create the optigroup
117 $optigroupname = $subplugintype . '_' . $element->get_name() . '_subplugin';
118 $optigroup = new backup_optigroup($optigroupname, null, $multiple);
119 $element->add_child($optigroup); // Add optigroup to stay connected since beginning
121 // Get all the optigroup_elements, looking across all the subplugin dirs
122 $subpluginsdirs = get_plugin_list($subplugintype);
123 foreach ($subpluginsdirs as $name => $subpluginsdir) {
124 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
125 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
126 if (file_exists($backupfile)) {
127 require_once($backupfile);
128 $backupsubplugin = new $classname($subplugintype, $name, $optigroup, $this);
129 // Add subplugin returned structure to optigroup
130 $backupsubplugin->define_subplugin_structure($element->get_name());
136 * As far as activity backup steps are implementing backup_subplugin stuff, they need to
137 * have the parent task available for wrapping purposes (get course/context....)
139 public function get_task() {
144 * Wraps any activity backup structure within the common 'activity' element
145 * that will include common to all activities information like id, context...
147 protected function prepare_activity_structure($activitystructure) {
149 // Create the wrap element
150 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
153 $activity->add_child($activitystructure);
156 $activityarr = array((object)array(
157 'id' => $this->task->get_activityid(),
158 'moduleid' => $this->task->get_moduleid(),
159 'modulename' => $this->task->get_modulename(),
160 'contextid' => $this->task->get_contextid()));
162 $activity->set_source_array($activityarr);
164 // Return the root element (activity)
170 * Abstract structure step, to be used by all the activities using core questions stuff
171 * (namely quiz module), supporting question plugins, states and sessions
173 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
176 * Attach to $element (usually attempts) the needed backup structures
177 * for question_usages and all the associated data.
179 protected function add_question_usages($element, $usageidname) {
181 require_once($CFG->dirroot . '/question/engine/lib.php');
183 // Check $element is one nested_backup_element
184 if (! $element instanceof backup_nested_element) {
185 throw new backup_step_exception('question_states_bad_parent_element', $element);
187 if (! $element->get_final_element($usageidname)) {
188 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
191 $quba = new backup_nested_element('question_usage', array('id'),
192 array('component', 'preferredbehaviour'));
194 $qas = new backup_nested_element('question_attempts');
195 $qa = new backup_nested_element('question_attempt', array('id'), array(
196 'slot', 'behaviour', 'questionid', 'maxmark', 'minfraction',
197 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
200 $steps = new backup_nested_element('steps');
201 $step = new backup_nested_element('step', array('id'), array(
202 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
204 $response = new backup_nested_element('response');
205 $variable = new backup_nested_element('variable', null, array('name', 'value'));
208 $element->add_child($quba);
209 $quba->add_child($qas);
210 $qas->add_child($qa);
211 $qa->add_child($steps);
212 $steps->add_child($step);
213 $step->add_child($response);
214 $response->add_child($variable);
217 $quba->set_source_table('question_usages',
218 array('id' => '../' . $usageidname));
219 $qa->set_source_sql('
221 FROM {question_attempts}
222 WHERE questionusageid = :questionusageid
224 array('questionusageid' => backup::VAR_PARENTID));
225 $step->set_source_sql('
227 FROM {question_attempt_steps}
228 WHERE questionattemptid = :questionattemptid
229 ORDER BY sequencenumber',
230 array('questionattemptid' => backup::VAR_PARENTID));
231 $variable->set_source_table('question_attempt_step_data',
232 array('attemptstepid' => backup::VAR_PARENTID));
235 $qa->annotate_ids('question', 'questionid');
236 $step->annotate_ids('user', 'userid');
239 $fileareas = question_engine::get_all_response_file_areas();
240 foreach ($fileareas as $filearea) {
241 $step->annotate_files('question', $filearea, 'id');
248 * backup structure step in charge of calculating the categories to be
249 * included in backup, based in the context being backuped (module/course)
250 * and the already annotated questions present in backup_ids_temp
252 class backup_calculate_question_categories extends backup_execution_step {
254 protected function define_execution() {
255 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
260 * backup structure step in charge of deleting all the questions annotated
261 * in the backup_ids_temp table
263 class backup_delete_temp_questions extends backup_execution_step {
265 protected function define_execution() {
266 backup_question_dbops::delete_temp_questions($this->get_backupid());
271 * Abstract structure step, parent of all the block structure steps. Used to wrap the
272 * block structure definition within the main <block ...> tag
274 abstract class backup_block_structure_step extends backup_structure_step {
276 protected function prepare_block_structure($blockstructure) {
278 // Create the wrap element
279 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
282 $block->add_child($blockstructure);
285 $blockarr = array((object)array(
286 'id' => $this->task->get_blockid(),
287 'blockname' => $this->task->get_blockname(),
288 'contextid' => $this->task->get_contextid()));
290 $block->set_source_array($blockarr);
292 // Return the root element (block)
298 * structure step that will generate the module.xml file for the activity,
299 * accumulating various information about the activity, annotating groupings
300 * and completion/avail conf
302 class backup_module_structure_step extends backup_structure_step {
304 protected function define_structure() {
306 // Define each element separated
308 $module = new backup_nested_element('module', array('id', 'version'), array(
309 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
310 'added', 'score', 'indent', 'visible',
311 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
312 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
313 'availablefrom', 'availableuntil', 'showavailability', 'showdescription'));
315 $availinfo = new backup_nested_element('availability_info');
316 $availability = new backup_nested_element('availability', array('id'), array(
317 'sourcecmid', 'requiredcompletion', 'gradeitemid', 'grademin', 'grademax'));
319 // attach format plugin structure to $module element, only one allowed
320 $this->add_plugin_structure('format', $module, false);
322 // attach plagiarism plugin structure to $module element, there can be potentially
323 // many plagiarism plugins storing information about this course
324 $this->add_plugin_structure('plagiarism', $module, true);
327 $module->add_child($availinfo);
328 $availinfo->add_child($availability);
332 $module->set_source_sql('
333 SELECT cm.*, m.version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
334 FROM {course_modules} cm
335 JOIN {modules} m ON m.id = cm.module
336 JOIN {course_sections} s ON s.id = cm.section
337 WHERE cm.id = ?', array(backup::VAR_MODID));
339 $availability->set_source_table('course_modules_availability', array('coursemoduleid' => backup::VAR_MODID));
341 // Define annotations
342 $module->annotate_ids('grouping', 'groupingid');
344 // Return the root element ($module)
350 * structure step that will generate the section.xml file for the section
353 class backup_section_structure_step extends backup_structure_step {
355 protected function define_structure() {
357 // Define each element separated
359 $section = new backup_nested_element('section', array('id'), array(
360 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible'));
362 // attach format plugin structure to $section element, only one allowed
363 $this->add_plugin_structure('format', $section, false);
367 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
370 $section->set_source_alias('section', 'number');
373 $section->annotate_files('course', 'section', 'id');
380 * structure step that will generate the course.xml file for the course, including
381 * course category reference, tags, modules restriction information
382 * and some annotations (files & groupings)
384 class backup_course_structure_step extends backup_structure_step {
386 protected function define_structure() {
389 // Define each element separated
391 $course = new backup_nested_element('course', array('id', 'contextid'), array(
392 'shortname', 'fullname', 'idnumber',
393 'summary', 'summaryformat', 'format', 'showgrades',
394 'newsitems', 'startdate', 'numsections',
395 'marker', 'maxbytes', 'legacyfiles', 'showreports',
396 'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
397 'defaultgroupingid', 'lang', 'theme',
398 'timecreated', 'timemodified',
399 'requested', 'restrictmodules',
400 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
402 $category = new backup_nested_element('category', array('id'), array(
403 'name', 'description'));
405 $tags = new backup_nested_element('tags');
407 $tag = new backup_nested_element('tag', array('id'), array(
410 $allowedmodules = new backup_nested_element('allowed_modules');
412 $module = new backup_nested_element('module', array(), array('modulename'));
414 // attach format plugin structure to $course element, only one allowed
415 $this->add_plugin_structure('format', $course, false);
417 // attach theme plugin structure to $course element; multiple themes can
418 // save course data (in case of user theme, legacy theme, etc)
419 $this->add_plugin_structure('theme', $course, true);
421 // attach general report plugin structure to $course element; multiple
422 // reports can save course data if required
423 $this->add_plugin_structure('report', $course, true);
425 // attach course report plugin structure to $course element; multiple
426 // course reports can save course data if required
427 $this->add_plugin_structure('coursereport', $course, true);
429 // attach plagiarism plugin structure to $course element, there can be potentially
430 // many plagiarism plugins storing information about this course
431 $this->add_plugin_structure('plagiarism', $course, true);
435 $course->add_child($category);
437 $course->add_child($tags);
438 $tags->add_child($tag);
440 $course->add_child($allowedmodules);
441 $allowedmodules->add_child($module);
445 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
446 $courserec->contextid = $this->task->get_contextid();
448 $course->set_source_array(array($courserec));
450 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
452 $category->set_source_array(array($categoryrec));
454 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
456 JOIN {tag_instance} ti ON ti.tagid = t.id
457 WHERE ti.itemtype = ?
458 AND ti.itemid = ?', array(
459 backup_helper::is_sqlparam('course'),
460 backup::VAR_PARENTID));
462 $module->set_source_sql('SELECT m.name AS modulename
464 JOIN {course_allowed_modules} cam ON m.id = cam.module
465 WHERE course = ?', array(backup::VAR_COURSEID));
469 $course->annotate_ids('grouping', 'defaultgroupingid');
471 $course->annotate_files('course', 'summary', null);
472 $course->annotate_files('course', 'legacy', null);
474 // Return root element ($course)
481 * structure step that will generate the enrolments.xml file for the given course
483 class backup_enrolments_structure_step extends backup_structure_step {
485 protected function define_structure() {
487 // To know if we are including users
488 $users = $this->get_setting_value('users');
490 // Define each element separated
492 $enrolments = new backup_nested_element('enrolments');
494 $enrols = new backup_nested_element('enrols');
496 $enrol = new backup_nested_element('enrol', array('id'), array(
497 'enrol', 'status', 'sortorder', 'name', 'enrolperiod', 'enrolstartdate',
498 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
499 'password', 'cost', 'currency', 'roleid', 'customint1', 'customint2', 'customint3',
500 'customint4', 'customchar1', 'customchar2', 'customdec1', 'customdec2',
501 'customtext1', 'customtext2', 'timecreated', 'timemodified'));
503 $userenrolments = new backup_nested_element('user_enrolments');
505 $enrolment = new backup_nested_element('enrolment', array('id'), array(
506 'status', 'userid', 'timestart', 'timeend', 'modifierid',
510 $enrolments->add_child($enrols);
511 $enrols->add_child($enrol);
512 $enrol->add_child($userenrolments);
513 $userenrolments->add_child($enrolment);
517 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID));
519 // User enrolments only added only if users included
521 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
522 $enrolment->annotate_ids('user', 'userid');
525 $enrol->annotate_ids('role', 'roleid');
527 //TODO: let plugins annotate custom fields too and add more children
534 * structure step that will generate the roles.xml file for the given context, observing
535 * the role_assignments setting to know if that part needs to be included
537 class backup_roles_structure_step extends backup_structure_step {
539 protected function define_structure() {
541 // To know if we are including role assignments
542 $roleassignments = $this->get_setting_value('role_assignments');
544 // Define each element separated
546 $roles = new backup_nested_element('roles');
548 $overrides = new backup_nested_element('role_overrides');
550 $override = new backup_nested_element('override', array('id'), array(
551 'roleid', 'capability', 'permission', 'timemodified',
554 $assignments = new backup_nested_element('role_assignments');
556 $assignment = new backup_nested_element('assignment', array('id'), array(
557 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
561 $roles->add_child($overrides);
562 $roles->add_child($assignments);
564 $overrides->add_child($override);
565 $assignments->add_child($assignment);
569 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
571 // Assignments only added if specified
572 if ($roleassignments) {
573 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
576 // Define id annotations
577 $override->annotate_ids('role', 'roleid');
579 $assignment->annotate_ids('role', 'roleid');
581 $assignment->annotate_ids('user', 'userid');
583 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
590 * structure step that will generate the roles.xml containing the
591 * list of roles used along the whole backup process. Just raw
592 * list of used roles from role table
594 class backup_final_roles_structure_step extends backup_structure_step {
596 protected function define_structure() {
600 $rolesdef = new backup_nested_element('roles_definition');
602 $role = new backup_nested_element('role', array('id'), array(
603 'name', 'shortname', 'nameincourse', 'description',
604 'sortorder', 'archetype'));
608 $rolesdef->add_child($role);
612 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
614 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
615 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
616 WHERE bi.backupid = ?
617 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
619 // Return main element (rolesdef)
625 * structure step that will generate the scales.xml containing the
626 * list of scales used along the whole backup process.
628 class backup_final_scales_structure_step extends backup_structure_step {
630 protected function define_structure() {
634 $scalesdef = new backup_nested_element('scales_definition');
636 $scale = new backup_nested_element('scale', array('id'), array(
637 'courseid', 'userid', 'name', 'scale',
638 'description', 'descriptionformat', 'timemodified'));
642 $scalesdef->add_child($scale);
646 $scale->set_source_sql("SELECT s.*
648 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
649 WHERE bi.backupid = ?
650 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
652 // Annotate scale files (they store files in system context, so pass it instead of default one)
653 $scale->annotate_files('grade', 'scale', 'id', get_context_instance(CONTEXT_SYSTEM)->id);
655 // Return main element (scalesdef)
661 * structure step that will generate the outcomes.xml containing the
662 * list of outcomes used along the whole backup process.
664 class backup_final_outcomes_structure_step extends backup_structure_step {
666 protected function define_structure() {
670 $outcomesdef = new backup_nested_element('outcomes_definition');
672 $outcome = new backup_nested_element('outcome', array('id'), array(
673 'courseid', 'userid', 'shortname', 'fullname',
674 'scaleid', 'description', 'descriptionformat', 'timecreated',
675 'timemodified','usermodified'));
679 $outcomesdef->add_child($outcome);
683 $outcome->set_source_sql("SELECT o.*
684 FROM {grade_outcomes} o
685 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
686 WHERE bi.backupid = ?
687 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
689 // Annotate outcome files (they store files in system context, so pass it instead of default one)
690 $outcome->annotate_files('grade', 'outcome', 'id', get_context_instance(CONTEXT_SYSTEM)->id);
692 // Return main element (outcomesdef)
698 * structure step in charge of constructing the filters.xml file for all the filters found
701 class backup_filters_structure_step extends backup_structure_step {
703 protected function define_structure() {
705 // Define each element separated
707 $filters = new backup_nested_element('filters');
709 $actives = new backup_nested_element('filter_actives');
711 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
713 $configs = new backup_nested_element('filter_configs');
715 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
719 $filters->add_child($actives);
720 $filters->add_child($configs);
722 $actives->add_child($active);
723 $configs->add_child($config);
727 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
729 $active->set_source_array($activearr);
730 $config->set_source_array($configarr);
732 // Return the root element (filters)
738 * structure step in charge of constructing the comments.xml file for all the comments found
741 class backup_comments_structure_step extends backup_structure_step {
743 protected function define_structure() {
745 // Define each element separated
747 $comments = new backup_nested_element('comments');
749 $comment = new backup_nested_element('comment', array('id'), array(
750 'commentarea', 'itemid', 'content', 'format',
751 'userid', 'timecreated'));
755 $comments->add_child($comment);
759 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
761 // Define id annotations
763 $comment->annotate_ids('user', 'userid');
765 // Return the root element (comments)
771 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
772 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
774 class backup_gradebook_structure_step extends backup_structure_step {
777 * We need to decide conditionally, based on dynamic information
778 * about the execution of this step. Only will be executed if all
779 * the module gradeitems have been already included in backup
781 protected function execute_condition() {
782 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
785 protected function define_structure() {
787 // are we including user info?
788 $userinfo = $this->get_setting_value('users');
790 $gradebook = new backup_nested_element('gradebook');
792 //grade_letters are done in backup_activity_grades_structure_step()
794 //calculated grade items
795 $grade_items = new backup_nested_element('grade_items');
796 $grade_item = new backup_nested_element('grade_item', array('id'), array(
797 'categoryid', 'itemname', 'itemtype', 'itemmodule',
798 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
799 'calculation', 'gradetype', 'grademax', 'grademin',
800 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
801 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
802 'decimals', 'hidden', 'locked', 'locktime',
803 'needsupdate', 'timecreated', 'timemodified'));
805 $grade_grades = new backup_nested_element('grade_grades');
806 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
807 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
808 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
809 'locked', 'locktime', 'exported', 'overridden',
810 'excluded', 'feedback', 'feedbackformat', 'information',
811 'informationformat', 'timecreated', 'timemodified'));
814 $grade_categories = new backup_nested_element('grade_categories');
815 $grade_category = new backup_nested_element('grade_category', array('id'), array(
817 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
818 'dropload', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
819 'timecreated', 'timemodified', 'hidden'));
821 $letters = new backup_nested_element('grade_letters');
822 $letter = new backup_nested_element('grade_letter', 'id', array(
823 'lowerboundary', 'letter'));
825 $grade_settings = new backup_nested_element('grade_settings');
826 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
831 $gradebook->add_child($grade_categories);
832 $grade_categories->add_child($grade_category);
834 $gradebook->add_child($grade_items);
835 $grade_items->add_child($grade_item);
836 $grade_item->add_child($grade_grades);
837 $grade_grades->add_child($grade_grade);
839 $gradebook->add_child($letters);
840 $letters->add_child($letter);
842 $gradebook->add_child($grade_settings);
843 $grade_settings->add_child($grade_setting);
847 //Include manual, category and the course grade item
848 $grade_items_sql ="SELECT * FROM {grade_items}
849 WHERE courseid = :courseid
850 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
851 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
852 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
855 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
858 $grade_category_sql = "SELECT gc.*, gi.sortorder
859 FROM {grade_categories} gc
860 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
861 WHERE gc.courseid = :courseid
862 AND (gi.itemtype='course' OR gi.itemtype='category')
863 ORDER BY gc.parent ASC";//need parent categories before their children
864 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
865 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
867 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
869 $grade_setting->set_source_table('grade_settings', array('courseid' => backup::VAR_COURSEID));
871 // Annotations (both as final as far as they are going to be exported in next steps)
872 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
873 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
875 //just in case there are any users not already annotated by the activities
876 $grade_grade->annotate_ids('userfinal', 'userid');
878 // Return the root element
884 * structure step in charge if constructing the completion.xml file for all the users completion
885 * information in a given activity
887 class backup_userscompletion_structure_step extends backup_structure_step {
889 protected function define_structure() {
891 // Define each element separated
893 $completions = new backup_nested_element('completions');
895 $completion = new backup_nested_element('completion', array('id'), array(
896 'userid', 'completionstate', 'viewed', 'timemodified'));
900 $completions->add_child($completion);
904 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
906 // Define id annotations
908 $completion->annotate_ids('user', 'userid');
910 // Return the root element (completions)
916 * structure step in charge of constructing the main groups.xml file for all the groups and
917 * groupings information already annotated
919 class backup_groups_structure_step extends backup_structure_step {
921 protected function define_structure() {
923 // To know if we are including users
924 $users = $this->get_setting_value('users');
926 // Define each element separated
928 $groups = new backup_nested_element('groups');
930 $group = new backup_nested_element('group', array('id'), array(
931 'name', 'description', 'descriptionformat', 'enrolmentkey',
932 'picture', 'hidepicture', 'timecreated', 'timemodified'));
934 $members = new backup_nested_element('group_members');
936 $member = new backup_nested_element('group_member', array('id'), array(
937 'userid', 'timeadded'));
939 $groupings = new backup_nested_element('groupings');
941 $grouping = new backup_nested_element('grouping', 'id', array(
942 'name', 'description', 'descriptionformat', 'configdata',
943 'timecreated', 'timemodified'));
945 $groupinggroups = new backup_nested_element('grouping_groups');
947 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
948 'groupid', 'timeadded'));
952 $groups->add_child($group);
953 $groups->add_child($groupings);
955 $group->add_child($members);
956 $members->add_child($member);
958 $groupings->add_child($grouping);
959 $grouping->add_child($groupinggroups);
960 $groupinggroups->add_child($groupinggroup);
964 $group->set_source_sql("
967 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
968 WHERE bi.backupid = ?
969 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
971 // This only happens if we are including users
973 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
976 $grouping->set_source_sql("
979 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
980 WHERE bi.backupid = ?
981 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
983 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
985 // Define id annotations (as final)
987 $member->annotate_ids('userfinal', 'userid');
989 // Define file annotations
991 $group->annotate_files('group', 'description', 'id');
992 $group->annotate_files('group', 'icon', 'id');
993 $grouping->annotate_files('grouping', 'description', 'id');
995 // Return the root element (groups)
1001 * structure step in charge of constructing the main users.xml file for all the users already
1002 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1005 class backup_users_structure_step extends backup_structure_step {
1007 protected function define_structure() {
1010 // To know if we are anonymizing users
1011 $anonymize = $this->get_setting_value('anonymize');
1012 // To know if we are including role assignments
1013 $roleassignments = $this->get_setting_value('role_assignments');
1015 // Define each element separated
1017 $users = new backup_nested_element('users');
1019 // Create the array of user fields by hand, as far as we have various bits to control
1020 // anonymize option, password backup, mnethostid...
1022 // First, the fields not needing anonymization nor special handling
1023 $normalfields = array(
1024 'confirmed', 'policyagreed', 'deleted',
1025 'lang', 'theme', 'timezone', 'firstaccess',
1026 'lastaccess', 'lastlogin', 'currentlogin',
1027 'mailformat', 'maildigest', 'maildisplay', 'htmleditor',
1028 'ajax', 'autosubscribe', 'trackforums', 'timecreated',
1029 'timemodified', 'trustbitmask', 'screenreader');
1031 // Then, the fields potentially needing anonymization
1032 $anonfields = array(
1033 'username', 'idnumber', 'firstname', 'lastname',
1034 'email', 'icq', 'skype',
1035 'yahoo', 'aim', 'msn', 'phone1',
1036 'phone2', 'institution', 'department', 'address',
1037 'city', 'country', 'lastip', 'picture',
1038 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1040 // Add anonymized fields to $userfields with custom final element
1041 foreach ($anonfields as $field) {
1043 $userfields[] = new anonymizer_final_element($field);
1045 $userfields[] = $field; // No anonymization, normally added
1049 // mnethosturl requires special handling (custom final element)
1050 $userfields[] = new mnethosturl_final_element('mnethosturl');
1052 // password added conditionally
1053 if (!empty($CFG->includeuserpasswordsinbackup)) {
1054 $userfields[] = 'password';
1057 // Merge all the fields
1058 $userfields = array_merge($userfields, $normalfields);
1060 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1062 $customfields = new backup_nested_element('custom_fields');
1064 $customfield = new backup_nested_element('custom_field', array('id'), array(
1065 'field_name', 'field_type', 'field_data'));
1067 $tags = new backup_nested_element('tags');
1069 $tag = new backup_nested_element('tag', array('id'), array(
1070 'name', 'rawname'));
1072 $preferences = new backup_nested_element('preferences');
1074 $preference = new backup_nested_element('preference', array('id'), array(
1077 $roles = new backup_nested_element('roles');
1079 $overrides = new backup_nested_element('role_overrides');
1081 $override = new backup_nested_element('override', array('id'), array(
1082 'roleid', 'capability', 'permission', 'timemodified',
1085 $assignments = new backup_nested_element('role_assignments');
1087 $assignment = new backup_nested_element('assignment', array('id'), array(
1088 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1093 $users->add_child($user);
1095 $user->add_child($customfields);
1096 $customfields->add_child($customfield);
1098 $user->add_child($tags);
1099 $tags->add_child($tag);
1101 $user->add_child($preferences);
1102 $preferences->add_child($preference);
1104 $user->add_child($roles);
1106 $roles->add_child($overrides);
1107 $roles->add_child($assignments);
1109 $overrides->add_child($override);
1110 $assignments->add_child($assignment);
1114 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1116 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1117 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1118 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1119 WHERE bi.backupid = ?
1120 AND bi.itemname = ?', array(
1121 backup_helper::is_sqlparam($this->get_backupid()),
1122 backup_helper::is_sqlparam('userfinal')));
1124 // All the rest on information is only added if we arent
1125 // in an anonymized backup
1127 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1128 FROM {user_info_field} f
1129 JOIN {user_info_data} d ON d.fieldid = f.id
1130 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1132 $customfield->set_source_alias('shortname', 'field_name');
1133 $customfield->set_source_alias('datatype', 'field_type');
1134 $customfield->set_source_alias('data', 'field_data');
1136 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1138 JOIN {tag_instance} ti ON ti.tagid = t.id
1139 WHERE ti.itemtype = ?
1140 AND ti.itemid = ?', array(
1141 backup_helper::is_sqlparam('user'),
1142 backup::VAR_PARENTID));
1144 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1146 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1148 // Assignments only added if specified
1149 if ($roleassignments) {
1150 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1153 // Define id annotations (as final)
1154 $override->annotate_ids('rolefinal', 'roleid');
1157 // Return root element (users)
1163 * structure step in charge of constructing the block.xml file for one
1164 * given block (instance and positions). If the block has custom DB structure
1165 * that will go to a separate file (different step defined in block class)
1167 class backup_block_instance_structure_step extends backup_structure_step {
1169 protected function define_structure() {
1172 // Define each element separated
1174 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1175 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1176 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1178 $positions = new backup_nested_element('block_positions');
1180 $position = new backup_nested_element('block_position', array('id'), array(
1181 'contextid', 'pagetype', 'subpage', 'visible',
1182 'region', 'weight'));
1186 $block->add_child($positions);
1187 $positions->add_child($position);
1189 // Transform configdata information if needed (process links and friends)
1190 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1191 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1192 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1193 foreach ($configdata as $attribute => $value) {
1194 if (in_array($attribute, $attrstotransform)) {
1195 $configdata[$attribute] = $this->contenttransformer->process($value);
1198 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1200 $blockrec->contextid = $this->task->get_contextid();
1201 // Get the version of the block
1202 $blockrec->version = $DB->get_field('block', 'version', array('name' => $this->task->get_blockname()));
1206 $block->set_source_array(array($blockrec));
1208 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1210 // File anotations (for fileareas specified on each block)
1211 foreach ($this->task->get_fileareas() as $filearea) {
1212 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1215 // Return the root element (block)
1221 * structure step in charge of constructing the logs.xml file for all the log records found
1222 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1223 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1224 * that just in case they become restored some day in the future
1226 class backup_course_logs_structure_step extends backup_structure_step {
1228 protected function define_structure() {
1230 // Define each element separated
1232 $logs = new backup_nested_element('logs');
1234 $log = new backup_nested_element('log', array('id'), array(
1235 'time', 'userid', 'ip', 'module',
1236 'action', 'url', 'info'));
1240 $logs->add_child($log);
1242 // Define sources (all the records belonging to the course, having cmid = 0)
1244 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1247 // NOTE: We don't annotate users from logs as far as they MUST be
1248 // always annotated by the course (enrol, ras... whatever)
1250 // Return the root element (logs)
1257 * structure step in charge of constructing the logs.xml file for all the log records found
1260 class backup_activity_logs_structure_step extends backup_structure_step {
1262 protected function define_structure() {
1264 // Define each element separated
1266 $logs = new backup_nested_element('logs');
1268 $log = new backup_nested_element('log', array('id'), array(
1269 'time', 'userid', 'ip', 'module',
1270 'action', 'url', 'info'));
1274 $logs->add_child($log);
1278 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1281 // NOTE: We don't annotate users from logs as far as they MUST be
1282 // always annotated by the activity (true participants).
1284 // Return the root element (logs)
1291 * structure in charge of constructing the inforef.xml file for all the items we want
1292 * to have referenced there (users, roles, files...)
1294 class backup_inforef_structure_step extends backup_structure_step {
1296 protected function define_structure() {
1298 // Items we want to include in the inforef file.
1299 $items = backup_helper::get_inforef_itemnames();
1303 $inforef = new backup_nested_element('inforef');
1305 // For each item, conditionally, if there are already records, build element
1306 foreach ($items as $itemname) {
1307 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1308 $elementroot = new backup_nested_element($itemname . 'ref');
1309 $element = new backup_nested_element($itemname, array(), array('id'));
1310 $inforef->add_child($elementroot);
1311 $elementroot->add_child($element);
1312 $element->set_source_sql("
1314 FROM {backup_ids_temp}
1317 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1321 // We don't annotate anything there, but rely in the next step
1322 // (move_inforef_annotations_to_final) that will change all the
1323 // already saved 'inforref' entries to their 'final' annotations.
1329 * This step will get all the annotations already processed to inforef.xml file and
1330 * transform them into 'final' annotations.
1332 class move_inforef_annotations_to_final extends backup_execution_step {
1334 protected function define_execution() {
1336 // Items we want to include in the inforef file
1337 $items = backup_helper::get_inforef_itemnames();
1338 foreach ($items as $itemname) {
1339 // Delegate to dbops
1340 backup_structure_dbops::move_annotations_to_final($this->get_backupid(), $itemname);
1346 * structure in charge of constructing the files.xml file with all the
1347 * annotated (final) files along the process. At, the same time, and
1348 * using one specialised nested_element, will copy them form moodle storage
1351 class backup_final_files_structure_step extends backup_structure_step {
1353 protected function define_structure() {
1357 $files = new backup_nested_element('files');
1359 $file = new file_nested_element('file', array('id'), array(
1360 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1361 'filepath', 'filename', 'userid', 'filesize',
1362 'mimetype', 'status', 'timecreated', 'timemodified',
1363 'source', 'author', 'license', 'sortorder'));
1367 $files->add_child($file);
1371 $file->set_source_sql("SELECT f.*
1373 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1374 WHERE bi.backupid = ?
1375 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1382 * Structure step in charge of creating the main moodle_backup.xml file
1383 * where all the information related to the backup, settings, license and
1384 * other information needed on restore is added*/
1385 class backup_main_structure_step extends backup_structure_step {
1387 protected function define_structure() {
1393 $info['name'] = $this->get_setting_value('filename');
1394 $info['moodle_version'] = $CFG->version;
1395 $info['moodle_release'] = $CFG->release;
1396 $info['backup_version'] = $CFG->backup_version;
1397 $info['backup_release'] = $CFG->backup_release;
1398 $info['backup_date'] = time();
1399 $info['backup_uniqueid']= $this->get_backupid();
1400 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1401 $info['original_wwwroot']=$CFG->wwwroot;
1402 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1403 $info['original_course_id'] = $this->get_courseid();
1404 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1405 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1406 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1407 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1408 $info['original_course_contextid'] = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
1409 $info['original_system_contextid'] = get_context_instance(CONTEXT_SYSTEM)->id;
1411 // Get more information from controller
1412 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid());
1416 $moodle_backup = new backup_nested_element('moodle_backup');
1418 $information = new backup_nested_element('information', null, array(
1419 'name', 'moodle_version', 'moodle_release', 'backup_version',
1420 'backup_release', 'backup_date', 'mnet_remoteusers', 'original_wwwroot',
1421 'original_site_identifier_hash', 'original_course_id',
1422 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1423 'original_course_contextid', 'original_system_contextid'));
1425 $details = new backup_nested_element('details');
1427 $detail = new backup_nested_element('detail', array('backup_id'), array(
1428 'type', 'format', 'interactive', 'mode',
1429 'execution', 'executiontime'));
1431 $contents = new backup_nested_element('contents');
1433 $activities = new backup_nested_element('activities');
1435 $activity = new backup_nested_element('activity', null, array(
1436 'moduleid', 'sectionid', 'modulename', 'title',
1439 $sections = new backup_nested_element('sections');
1441 $section = new backup_nested_element('section', null, array(
1442 'sectionid', 'title', 'directory'));
1444 $course = new backup_nested_element('course', null, array(
1445 'courseid', 'title', 'directory'));
1447 $settings = new backup_nested_element('settings');
1449 $setting = new backup_nested_element('setting', null, array(
1450 'level', 'section', 'activity', 'name', 'value'));
1454 $moodle_backup->add_child($information);
1456 $information->add_child($details);
1457 $details->add_child($detail);
1459 $information->add_child($contents);
1460 if (!empty($cinfo['activities'])) {
1461 $contents->add_child($activities);
1462 $activities->add_child($activity);
1464 if (!empty($cinfo['sections'])) {
1465 $contents->add_child($sections);
1466 $sections->add_child($section);
1468 if (!empty($cinfo['course'])) {
1469 $contents->add_child($course);
1472 $information->add_child($settings);
1473 $settings->add_child($setting);
1478 $information->set_source_array(array((object)$info));
1480 $detail->set_source_array($dinfo);
1482 $activity->set_source_array($cinfo['activities']);
1484 $section->set_source_array($cinfo['sections']);
1486 $course->set_source_array($cinfo['course']);
1488 $setting->set_source_array($sinfo);
1490 // Prepare some information to be sent to main moodle_backup.xml file
1491 return $moodle_backup;
1497 * Execution step that will generate the final zip (.mbz) file with all the contents
1499 class backup_zip_contents extends backup_execution_step {
1501 protected function define_execution() {
1504 $basepath = $this->get_basepath();
1506 // Get the list of files in directory
1507 $filestemp = get_directory_list($basepath, '', false, true, true);
1509 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1510 $files[$file] = $basepath . '/' . $file;
1513 // Add the log file if exists
1514 $logfilepath = $basepath . '.log';
1515 if (file_exists($logfilepath)) {
1516 $files['moodle_backup.log'] = $logfilepath;
1519 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1520 $zipfile = $basepath . '/backup.mbz';
1522 // Get the zip packer
1523 $zippacker = get_file_packer('application/zip');
1526 $zippacker->archive_to_pathname($files, $zipfile);
1531 * This step will send the generated backup file to its final destination
1533 class backup_store_backup_file extends backup_execution_step {
1535 protected function define_execution() {
1538 $basepath = $this->get_basepath();
1540 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1541 $zipfile = $basepath . '/backup.mbz';
1543 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1544 return array('backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile));
1550 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1551 * and put them to the backup_ids tables, to be used later as base to backup them
1553 class backup_activity_grade_items_to_ids extends backup_execution_step {
1555 protected function define_execution() {
1557 // Fetch all activity grade items
1558 if ($items = grade_item::fetch_all(array(
1559 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1560 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1561 // Annotate them in backup_ids
1562 foreach ($items as $item) {
1563 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1570 * This step will annotate all the groups and groupings belonging to the course
1572 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1574 protected function define_execution() {
1577 // Get all the course groups
1578 if ($groups = $DB->get_records('groups', array(
1579 'courseid' => $this->task->get_courseid()))) {
1580 foreach ($groups as $group) {
1581 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1585 // Get all the course groupings
1586 if ($groupings = $DB->get_records('groupings', array(
1587 'courseid' => $this->task->get_courseid()))) {
1588 foreach ($groupings as $grouping) {
1589 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1596 * This step will annotate all the groups belonging to already annotated groupings
1598 class backup_annotate_groups_from_groupings extends backup_execution_step {
1600 protected function define_execution() {
1603 // Fetch all the annotated groupings
1604 if ($groupings = $DB->get_records('backup_ids_temp', array(
1605 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1606 foreach ($groupings as $grouping) {
1607 if ($groups = $DB->get_records('groupings_groups', array(
1608 'groupingid' => $grouping->itemid))) {
1609 foreach ($groups as $group) {
1610 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1619 * This step will annotate all the scales belonging to already annotated outcomes
1621 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1623 protected function define_execution() {
1626 // Fetch all the annotated outcomes
1627 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1628 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1629 foreach ($outcomes as $outcome) {
1630 if ($scale = $DB->get_record('grade_outcomes', array(
1631 'id' => $outcome->itemid))) {
1632 // Annotate as scalefinal because it's > 0
1633 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1641 * This step will generate all the file annotations for the already
1642 * annotated (final) question_categories. It calculates the different
1643 * contexts that are being backup and, annotates all the files
1644 * on every context belonging to the "question" component. As far as
1645 * we are always including *complete* question banks it is safe and
1646 * optimal to do that in this (one pass) way
1648 class backup_annotate_all_question_files extends backup_execution_step {
1650 protected function define_execution() {
1653 // Get all the different contexts for the final question_categories
1654 // annotated along the whole backup
1655 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1656 FROM {question_categories} qc
1657 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
1658 WHERE bi.backupid = ?
1659 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
1660 // To know about qtype specific components/fileareas
1661 $components = backup_qtype_plugin::get_components_and_fileareas();
1663 foreach($rs as $record) {
1664 // We don't need to specify filearea nor itemid as far as by
1665 // component and context it's enough to annotate the whole bank files
1666 // This backups "questiontext", "generalfeedback" and "answerfeedback" fileareas (all them
1667 // belonging to the "question" component
1668 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', null, null);
1669 // Again, it is enough to pick files only by context and component
1670 // Do it for qtype specific components
1671 foreach ($components as $component => $fileareas) {
1672 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
1680 * structure step in charge of constructing the questions.xml file for all the
1681 * question categories and questions required by the backup
1682 * and letters related to one activity
1684 class backup_questions_structure_step extends backup_structure_step {
1686 protected function define_structure() {
1688 // Define each element separated
1690 $qcategories = new backup_nested_element('question_categories');
1692 $qcategory = new backup_nested_element('question_category', array('id'), array(
1693 'name', 'contextid', 'contextlevel', 'contextinstanceid',
1694 'info', 'infoformat', 'stamp', 'parent',
1697 $questions = new backup_nested_element('questions');
1699 $question = new backup_nested_element('question', array('id'), array(
1700 'parent', 'name', 'questiontext', 'questiontextformat',
1701 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
1702 'qtype', 'length', 'stamp', 'version',
1703 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
1705 // attach qtype plugin structure to $question element, only one allowed
1706 $this->add_plugin_structure('qtype', $question, false);
1708 $qhints = new backup_nested_element('question_hints');
1710 $qhint = new backup_nested_element('question_hint', array('id'), array(
1711 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
1715 $qcategories->add_child($qcategory);
1716 $qcategory->add_child($questions);
1717 $questions->add_child($question);
1718 $question->add_child($qhints);
1719 $qhints->add_child($qhint);
1721 // Define the sources
1723 $qcategory->set_source_sql("
1724 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
1725 FROM {question_categories} gc
1726 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
1727 JOIN {context} co ON co.id = gc.contextid
1728 WHERE bi.backupid = ?
1729 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
1731 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
1733 $qhint->set_source_sql('
1735 FROM {question_hints}
1736 WHERE questionid = :questionid
1738 array('questionid' => backup::VAR_PARENTID));
1740 // don't need to annotate ids nor files
1741 // (already done by {@link backup_annotate_all_question_files}
1743 return $qcategories;
1750 * This step will generate all the file annotations for the already
1751 * annotated (final) users. Need to do this here because each user
1752 * has its own context and structure tasks only are able to handle
1753 * one context. Also, this step will guarantee that every user has
1754 * its context created (req for other steps)
1756 class backup_annotate_all_user_files extends backup_execution_step {
1758 protected function define_execution() {
1761 // List of fileareas we are going to annotate
1762 $fileareas = array('profile', 'icon');
1764 if ($this->get_setting_value('user_files')) { // private files only if enabled in settings
1765 $fileareas[] = 'private';
1768 // Fetch all annotated (final) users
1769 $rs = $DB->get_recordset('backup_ids_temp', array(
1770 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1771 foreach ($rs as $record) {
1772 $userid = $record->itemid;
1773 $userctx = get_context_instance(CONTEXT_USER, $userid);
1775 continue; // User has not context, sure it's a deleted user, so cannot have files
1777 // Proceed with every user filearea
1778 foreach ($fileareas as $filearea) {
1779 // We don't need to specify itemid ($userid - 5th param) as far as by
1780 // context we can get all the associated files. See MDL-22092
1781 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
1790 * Defines the backup step for advanced grading methods attached to the activity module
1792 class backup_activity_grading_structure_step extends backup_structure_step {
1795 * Include the grading.xml only if the module supports advanced grading
1797 protected function execute_condition() {
1798 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
1802 * Declares the gradable areas structures and data sources
1804 protected function define_structure() {
1806 // To know if we are including userinfo
1807 $userinfo = $this->get_setting_value('userinfo');
1809 // Define the elements
1811 $areas = new backup_nested_element('areas');
1813 $area = new backup_nested_element('area', array('id'), array(
1814 'areaname', 'activemethod'));
1816 $definitions = new backup_nested_element('definitions');
1818 $definition = new backup_nested_element('definition', array('id'), array(
1819 'method', 'name', 'description', 'descriptionformat', 'status',
1820 'timecreated', 'timemodified', 'options'));
1822 $instances = new backup_nested_element('instances');
1824 $instance = new backup_nested_element('instance', array('id'), array(
1825 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
1826 'feedbackformat', 'timemodified'));
1828 // Build the tree including the method specific structures
1829 // (beware - the order of how gradingform plugins structures are attached is important)
1830 $areas->add_child($area);
1831 $area->add_child($definitions);
1832 $definitions->add_child($definition);
1833 $this->add_plugin_structure('gradingform', $definition, true);
1834 $definition->add_child($instances);
1835 $instances->add_child($instance);
1836 $this->add_plugin_structure('gradingform', $instance, false);
1838 // Define data sources
1840 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
1841 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
1843 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
1846 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
1849 // Annotate references
1850 $definition->annotate_files('grading', 'description', 'id');
1851 $instance->annotate_ids('user', 'raterid');
1853 // Return the root element
1860 * structure step in charge of constructing the grades.xml file for all the grade items
1861 * and letters related to one activity
1863 class backup_activity_grades_structure_step extends backup_structure_step {
1865 protected function define_structure() {
1867 // To know if we are including userinfo
1868 $userinfo = $this->get_setting_value('userinfo');
1870 // Define each element separated
1872 $book = new backup_nested_element('activity_gradebook');
1874 $items = new backup_nested_element('grade_items');
1876 $item = new backup_nested_element('grade_item', array('id'), array(
1877 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1878 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1879 'calculation', 'gradetype', 'grademax', 'grademin',
1880 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1881 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
1882 'decimals', 'hidden', 'locked', 'locktime',
1883 'needsupdate', 'timecreated', 'timemodified'));
1885 $grades = new backup_nested_element('grade_grades');
1887 $grade = new backup_nested_element('grade_grade', array('id'), array(
1888 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1889 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1890 'locked', 'locktime', 'exported', 'overridden',
1891 'excluded', 'feedback', 'feedbackformat', 'information',
1892 'informationformat', 'timecreated', 'timemodified'));
1894 $letters = new backup_nested_element('grade_letters');
1896 $letter = new backup_nested_element('grade_letter', 'id', array(
1897 'lowerboundary', 'letter'));
1901 $book->add_child($items);
1902 $items->add_child($item);
1904 $item->add_child($grades);
1905 $grades->add_child($grade);
1907 $book->add_child($letters);
1908 $letters->add_child($letter);
1912 $item->set_source_sql("SELECT gi.*
1913 FROM {grade_items} gi
1914 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
1915 WHERE bi.backupid = ?
1916 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
1918 // This only happens if we are including user info
1920 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1923 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1927 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1928 $item->annotate_ids('outcome', 'outcomeid');
1930 $grade->annotate_ids('user', 'userid');
1931 $grade->annotate_ids('user', 'usermodified');
1933 // Return the root element (book)
1940 * Backups up the course completion information for the course.
1942 class backup_course_completion_structure_step extends backup_structure_step {
1944 protected function execute_condition() {
1945 // Check that all activities have been included
1946 if ($this->task->is_excluding_activities()) {
1953 * The structure of the course completion backup
1955 * @return backup_nested_element
1957 protected function define_structure() {
1959 // To know if we are including user completion info
1960 $userinfo = $this->get_setting_value('userscompletion');
1962 $cc = new backup_nested_element('course_completion');
1964 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
1965 'course','criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod', 'timeend', 'gradepass', 'role'
1968 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
1970 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
1971 'criteriaid', 'userid','gradefinal','unenrolled','deleted','timecompleted'
1974 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
1975 'userid', 'course', 'deleted', 'timenotified', 'timeenrolled','timestarted','timecompleted','reaggregate'
1978 $notify = new backup_nested_element('course_completion_notify', array('id'), array(
1979 'course','role','message','timesent'
1982 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
1983 'course','criteriatype','method','value'
1986 $cc->add_child($criteria);
1987 $criteria->add_child($criteriacompletions);
1988 $criteriacompletions->add_child($criteriacomplete);
1989 $cc->add_child($coursecompletions);
1990 $cc->add_child($notify);
1991 $cc->add_child($aggregatemethod);
1993 // We need to get the courseinstances shortname rather than an ID for restore
1994 $criteria->set_source_sql("SELECT ccc.*, c.shortname AS courseinstanceshortname
1995 FROM {course_completion_criteria} ccc
1996 LEFT JOIN {course} c ON c.id = ccc.courseinstance
1997 WHERE ccc.course = ?", array(backup::VAR_COURSEID));
2000 $notify->set_source_table('course_completion_notify', array('course' => backup::VAR_COURSEID));
2001 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2004 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2005 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2008 $criteria->annotate_ids('role', 'role');
2009 $criteriacomplete->annotate_ids('user', 'userid');
2010 $coursecompletions->annotate_ids('user', 'userid');
2011 $notify->annotate_ids('role', 'role');