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 course report plugin structure to $course element; multiple
422 // course reports can save course data if required
423 $this->add_plugin_structure('coursereport', $course, true);
425 // attach plagiarism plugin structure to $course element, there can be potentially
426 // many plagiarism plugins storing information about this course
427 $this->add_plugin_structure('plagiarism', $course, true);
431 $course->add_child($category);
433 $course->add_child($tags);
434 $tags->add_child($tag);
436 $course->add_child($allowedmodules);
437 $allowedmodules->add_child($module);
441 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
442 $courserec->contextid = $this->task->get_contextid();
444 $course->set_source_array(array($courserec));
446 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
448 $category->set_source_array(array($categoryrec));
450 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
452 JOIN {tag_instance} ti ON ti.tagid = t.id
453 WHERE ti.itemtype = ?
454 AND ti.itemid = ?', array(
455 backup_helper::is_sqlparam('course'),
456 backup::VAR_PARENTID));
458 $module->set_source_sql('SELECT m.name AS modulename
460 JOIN {course_allowed_modules} cam ON m.id = cam.module
461 WHERE course = ?', array(backup::VAR_COURSEID));
465 $course->annotate_ids('grouping', 'defaultgroupingid');
467 $course->annotate_files('course', 'summary', null);
468 $course->annotate_files('course', 'legacy', null);
470 // Return root element ($course)
477 * structure step that will generate the enrolments.xml file for the given course
479 class backup_enrolments_structure_step extends backup_structure_step {
481 protected function define_structure() {
483 // To know if we are including users
484 $users = $this->get_setting_value('users');
486 // Define each element separated
488 $enrolments = new backup_nested_element('enrolments');
490 $enrols = new backup_nested_element('enrols');
492 $enrol = new backup_nested_element('enrol', array('id'), array(
493 'enrol', 'status', 'sortorder', 'name', 'enrolperiod', 'enrolstartdate',
494 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
495 'password', 'cost', 'currency', 'roleid', 'customint1', 'customint2', 'customint3',
496 'customint4', 'customchar1', 'customchar2', 'customdec1', 'customdec2',
497 'customtext1', 'customtext2', 'timecreated', 'timemodified'));
499 $userenrolments = new backup_nested_element('user_enrolments');
501 $enrolment = new backup_nested_element('enrolment', array('id'), array(
502 'status', 'userid', 'timestart', 'timeend', 'modifierid',
506 $enrolments->add_child($enrols);
507 $enrols->add_child($enrol);
508 $enrol->add_child($userenrolments);
509 $userenrolments->add_child($enrolment);
513 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID));
515 // User enrolments only added only if users included
517 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
518 $enrolment->annotate_ids('user', 'userid');
521 $enrol->annotate_ids('role', 'roleid');
523 //TODO: let plugins annotate custom fields too and add more children
530 * structure step that will generate the roles.xml file for the given context, observing
531 * the role_assignments setting to know if that part needs to be included
533 class backup_roles_structure_step extends backup_structure_step {
535 protected function define_structure() {
537 // To know if we are including role assignments
538 $roleassignments = $this->get_setting_value('role_assignments');
540 // Define each element separated
542 $roles = new backup_nested_element('roles');
544 $overrides = new backup_nested_element('role_overrides');
546 $override = new backup_nested_element('override', array('id'), array(
547 'roleid', 'capability', 'permission', 'timemodified',
550 $assignments = new backup_nested_element('role_assignments');
552 $assignment = new backup_nested_element('assignment', array('id'), array(
553 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
557 $roles->add_child($overrides);
558 $roles->add_child($assignments);
560 $overrides->add_child($override);
561 $assignments->add_child($assignment);
565 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
567 // Assignments only added if specified
568 if ($roleassignments) {
569 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
572 // Define id annotations
573 $override->annotate_ids('role', 'roleid');
575 $assignment->annotate_ids('role', 'roleid');
577 $assignment->annotate_ids('user', 'userid');
579 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
586 * structure step that will generate the roles.xml containing the
587 * list of roles used along the whole backup process. Just raw
588 * list of used roles from role table
590 class backup_final_roles_structure_step extends backup_structure_step {
592 protected function define_structure() {
596 $rolesdef = new backup_nested_element('roles_definition');
598 $role = new backup_nested_element('role', array('id'), array(
599 'name', 'shortname', 'nameincourse', 'description',
600 'sortorder', 'archetype'));
604 $rolesdef->add_child($role);
608 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
610 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
611 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
612 WHERE bi.backupid = ?
613 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
615 // Return main element (rolesdef)
621 * structure step that will generate the scales.xml containing the
622 * list of scales used along the whole backup process.
624 class backup_final_scales_structure_step extends backup_structure_step {
626 protected function define_structure() {
630 $scalesdef = new backup_nested_element('scales_definition');
632 $scale = new backup_nested_element('scale', array('id'), array(
633 'courseid', 'userid', 'name', 'scale',
634 'description', 'descriptionformat', 'timemodified'));
638 $scalesdef->add_child($scale);
642 $scale->set_source_sql("SELECT s.*
644 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
645 WHERE bi.backupid = ?
646 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
648 // Annotate scale files (they store files in system context, so pass it instead of default one)
649 $scale->annotate_files('grade', 'scale', 'id', get_context_instance(CONTEXT_SYSTEM)->id);
651 // Return main element (scalesdef)
657 * structure step that will generate the outcomes.xml containing the
658 * list of outcomes used along the whole backup process.
660 class backup_final_outcomes_structure_step extends backup_structure_step {
662 protected function define_structure() {
666 $outcomesdef = new backup_nested_element('outcomes_definition');
668 $outcome = new backup_nested_element('outcome', array('id'), array(
669 'courseid', 'userid', 'shortname', 'fullname',
670 'scaleid', 'description', 'descriptionformat', 'timecreated',
671 'timemodified','usermodified'));
675 $outcomesdef->add_child($outcome);
679 $outcome->set_source_sql("SELECT o.*
680 FROM {grade_outcomes} o
681 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
682 WHERE bi.backupid = ?
683 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
685 // Annotate outcome files (they store files in system context, so pass it instead of default one)
686 $outcome->annotate_files('grade', 'outcome', 'id', get_context_instance(CONTEXT_SYSTEM)->id);
688 // Return main element (outcomesdef)
694 * structure step in charge of constructing the filters.xml file for all the filters found
697 class backup_filters_structure_step extends backup_structure_step {
699 protected function define_structure() {
701 // Define each element separated
703 $filters = new backup_nested_element('filters');
705 $actives = new backup_nested_element('filter_actives');
707 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
709 $configs = new backup_nested_element('filter_configs');
711 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
715 $filters->add_child($actives);
716 $filters->add_child($configs);
718 $actives->add_child($active);
719 $configs->add_child($config);
723 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
725 $active->set_source_array($activearr);
726 $config->set_source_array($configarr);
728 // Return the root element (filters)
734 * structure step in charge of constructing the comments.xml file for all the comments found
737 class backup_comments_structure_step extends backup_structure_step {
739 protected function define_structure() {
741 // Define each element separated
743 $comments = new backup_nested_element('comments');
745 $comment = new backup_nested_element('comment', array('id'), array(
746 'commentarea', 'itemid', 'content', 'format',
747 'userid', 'timecreated'));
751 $comments->add_child($comment);
755 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
757 // Define id annotations
759 $comment->annotate_ids('user', 'userid');
761 // Return the root element (comments)
767 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
768 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
770 class backup_gradebook_structure_step extends backup_structure_step {
773 * We need to decide conditionally, based on dynamic information
774 * about the execution of this step. Only will be executed if all
775 * the module gradeitems have been already included in backup
777 protected function execute_condition() {
778 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
781 protected function define_structure() {
783 // are we including user info?
784 $userinfo = $this->get_setting_value('users');
786 $gradebook = new backup_nested_element('gradebook');
788 //grade_letters are done in backup_activity_grades_structure_step()
790 //calculated grade items
791 $grade_items = new backup_nested_element('grade_items');
792 $grade_item = new backup_nested_element('grade_item', array('id'), array(
793 'categoryid', 'itemname', 'itemtype', 'itemmodule',
794 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
795 'calculation', 'gradetype', 'grademax', 'grademin',
796 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
797 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
798 'decimals', 'hidden', 'locked', 'locktime',
799 'needsupdate', 'timecreated', 'timemodified'));
801 $grade_grades = new backup_nested_element('grade_grades');
802 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
803 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
804 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
805 'locked', 'locktime', 'exported', 'overridden',
806 'excluded', 'feedback', 'feedbackformat', 'information',
807 'informationformat', 'timecreated', 'timemodified'));
810 $grade_categories = new backup_nested_element('grade_categories');
811 $grade_category = new backup_nested_element('grade_category', array('id'), array(
813 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
814 'dropload', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
815 'timecreated', 'timemodified', 'hidden'));
817 $letters = new backup_nested_element('grade_letters');
818 $letter = new backup_nested_element('grade_letter', 'id', array(
819 'lowerboundary', 'letter'));
821 $grade_settings = new backup_nested_element('grade_settings');
822 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
827 $gradebook->add_child($grade_categories);
828 $grade_categories->add_child($grade_category);
830 $gradebook->add_child($grade_items);
831 $grade_items->add_child($grade_item);
832 $grade_item->add_child($grade_grades);
833 $grade_grades->add_child($grade_grade);
835 $gradebook->add_child($letters);
836 $letters->add_child($letter);
838 $gradebook->add_child($grade_settings);
839 $grade_settings->add_child($grade_setting);
843 //Include manual, category and the course grade item
844 $grade_items_sql ="SELECT * FROM {grade_items}
845 WHERE courseid = :courseid
846 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
847 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
848 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
851 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
854 $grade_category_sql = "SELECT gc.*, gi.sortorder
855 FROM {grade_categories} gc
856 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
857 WHERE gc.courseid = :courseid
858 AND (gi.itemtype='course' OR gi.itemtype='category')
859 ORDER BY gc.parent ASC";//need parent categories before their children
860 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
861 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
863 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
865 $grade_setting->set_source_table('grade_settings', array('courseid' => backup::VAR_COURSEID));
867 // Annotations (both as final as far as they are going to be exported in next steps)
868 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
869 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
871 //just in case there are any users not already annotated by the activities
872 $grade_grade->annotate_ids('userfinal', 'userid');
874 // Return the root element
880 * structure step in charge if constructing the completion.xml file for all the users completion
881 * information in a given activity
883 class backup_userscompletion_structure_step extends backup_structure_step {
885 protected function define_structure() {
887 // Define each element separated
889 $completions = new backup_nested_element('completions');
891 $completion = new backup_nested_element('completion', array('id'), array(
892 'userid', 'completionstate', 'viewed', 'timemodified'));
896 $completions->add_child($completion);
900 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
902 // Define id annotations
904 $completion->annotate_ids('user', 'userid');
906 // Return the root element (completions)
912 * structure step in charge of constructing the main groups.xml file for all the groups and
913 * groupings information already annotated
915 class backup_groups_structure_step extends backup_structure_step {
917 protected function define_structure() {
919 // To know if we are including users
920 $users = $this->get_setting_value('users');
922 // Define each element separated
924 $groups = new backup_nested_element('groups');
926 $group = new backup_nested_element('group', array('id'), array(
927 'name', 'description', 'descriptionformat', 'enrolmentkey',
928 'picture', 'hidepicture', 'timecreated', 'timemodified'));
930 $members = new backup_nested_element('group_members');
932 $member = new backup_nested_element('group_member', array('id'), array(
933 'userid', 'timeadded'));
935 $groupings = new backup_nested_element('groupings');
937 $grouping = new backup_nested_element('grouping', 'id', array(
938 'name', 'description', 'descriptionformat', 'configdata',
939 'timecreated', 'timemodified'));
941 $groupinggroups = new backup_nested_element('grouping_groups');
943 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
944 'groupid', 'timeadded'));
948 $groups->add_child($group);
949 $groups->add_child($groupings);
951 $group->add_child($members);
952 $members->add_child($member);
954 $groupings->add_child($grouping);
955 $grouping->add_child($groupinggroups);
956 $groupinggroups->add_child($groupinggroup);
960 $group->set_source_sql("
963 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
964 WHERE bi.backupid = ?
965 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
967 // This only happens if we are including users
969 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
972 $grouping->set_source_sql("
975 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
976 WHERE bi.backupid = ?
977 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
979 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
981 // Define id annotations (as final)
983 $member->annotate_ids('userfinal', 'userid');
985 // Define file annotations
987 $group->annotate_files('group', 'description', 'id');
988 $group->annotate_files('group', 'icon', 'id');
989 $grouping->annotate_files('grouping', 'description', 'id');
991 // Return the root element (groups)
997 * structure step in charge of constructing the main users.xml file for all the users already
998 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1001 class backup_users_structure_step extends backup_structure_step {
1003 protected function define_structure() {
1006 // To know if we are anonymizing users
1007 $anonymize = $this->get_setting_value('anonymize');
1008 // To know if we are including role assignments
1009 $roleassignments = $this->get_setting_value('role_assignments');
1011 // Define each element separated
1013 $users = new backup_nested_element('users');
1015 // Create the array of user fields by hand, as far as we have various bits to control
1016 // anonymize option, password backup, mnethostid...
1018 // First, the fields not needing anonymization nor special handling
1019 $normalfields = array(
1020 'confirmed', 'policyagreed', 'deleted',
1021 'lang', 'theme', 'timezone', 'firstaccess',
1022 'lastaccess', 'lastlogin', 'currentlogin',
1023 'mailformat', 'maildigest', 'maildisplay', 'htmleditor',
1024 'ajax', 'autosubscribe', 'trackforums', 'timecreated',
1025 'timemodified', 'trustbitmask', 'screenreader');
1027 // Then, the fields potentially needing anonymization
1028 $anonfields = array(
1029 'username', 'idnumber', 'firstname', 'lastname',
1030 'email', 'icq', 'skype',
1031 'yahoo', 'aim', 'msn', 'phone1',
1032 'phone2', 'institution', 'department', 'address',
1033 'city', 'country', 'lastip', 'picture',
1034 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1036 // Add anonymized fields to $userfields with custom final element
1037 foreach ($anonfields as $field) {
1039 $userfields[] = new anonymizer_final_element($field);
1041 $userfields[] = $field; // No anonymization, normally added
1045 // mnethosturl requires special handling (custom final element)
1046 $userfields[] = new mnethosturl_final_element('mnethosturl');
1048 // password added conditionally
1049 if (!empty($CFG->includeuserpasswordsinbackup)) {
1050 $userfields[] = 'password';
1053 // Merge all the fields
1054 $userfields = array_merge($userfields, $normalfields);
1056 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1058 $customfields = new backup_nested_element('custom_fields');
1060 $customfield = new backup_nested_element('custom_field', array('id'), array(
1061 'field_name', 'field_type', 'field_data'));
1063 $tags = new backup_nested_element('tags');
1065 $tag = new backup_nested_element('tag', array('id'), array(
1066 'name', 'rawname'));
1068 $preferences = new backup_nested_element('preferences');
1070 $preference = new backup_nested_element('preference', array('id'), array(
1073 $roles = new backup_nested_element('roles');
1075 $overrides = new backup_nested_element('role_overrides');
1077 $override = new backup_nested_element('override', array('id'), array(
1078 'roleid', 'capability', 'permission', 'timemodified',
1081 $assignments = new backup_nested_element('role_assignments');
1083 $assignment = new backup_nested_element('assignment', array('id'), array(
1084 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1089 $users->add_child($user);
1091 $user->add_child($customfields);
1092 $customfields->add_child($customfield);
1094 $user->add_child($tags);
1095 $tags->add_child($tag);
1097 $user->add_child($preferences);
1098 $preferences->add_child($preference);
1100 $user->add_child($roles);
1102 $roles->add_child($overrides);
1103 $roles->add_child($assignments);
1105 $overrides->add_child($override);
1106 $assignments->add_child($assignment);
1110 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1112 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1113 JOIN {context} c ON c.instanceid = u.id
1114 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1115 WHERE bi.backupid = ?
1117 AND c.contextlevel = ?', array(
1118 backup_helper::is_sqlparam($this->get_backupid()),
1119 backup_helper::is_sqlparam('userfinal'),
1120 backup_helper::is_sqlparam(CONTEXT_USER)));
1122 // All the rest on information is only added if we arent
1123 // in an anonymized backup
1125 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1126 FROM {user_info_field} f
1127 JOIN {user_info_data} d ON d.fieldid = f.id
1128 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1130 $customfield->set_source_alias('shortname', 'field_name');
1131 $customfield->set_source_alias('datatype', 'field_type');
1132 $customfield->set_source_alias('data', 'field_data');
1134 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1136 JOIN {tag_instance} ti ON ti.tagid = t.id
1137 WHERE ti.itemtype = ?
1138 AND ti.itemid = ?', array(
1139 backup_helper::is_sqlparam('user'),
1140 backup::VAR_PARENTID));
1142 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1144 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1146 // Assignments only added if specified
1147 if ($roleassignments) {
1148 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1151 // Define id annotations (as final)
1152 $override->annotate_ids('rolefinal', 'roleid');
1155 // Return root element (users)
1161 * structure step in charge of constructing the block.xml file for one
1162 * given block (instance and positions). If the block has custom DB structure
1163 * that will go to a separate file (different step defined in block class)
1165 class backup_block_instance_structure_step extends backup_structure_step {
1167 protected function define_structure() {
1170 // Define each element separated
1172 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1173 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1174 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1176 $positions = new backup_nested_element('block_positions');
1178 $position = new backup_nested_element('block_position', array('id'), array(
1179 'contextid', 'pagetype', 'subpage', 'visible',
1180 'region', 'weight'));
1184 $block->add_child($positions);
1185 $positions->add_child($position);
1187 // Transform configdata information if needed (process links and friends)
1188 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1189 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1190 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1191 foreach ($configdata as $attribute => $value) {
1192 if (in_array($attribute, $attrstotransform)) {
1193 $configdata[$attribute] = $this->contenttransformer->process($value);
1196 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1198 $blockrec->contextid = $this->task->get_contextid();
1199 // Get the version of the block
1200 $blockrec->version = $DB->get_field('block', 'version', array('name' => $this->task->get_blockname()));
1204 $block->set_source_array(array($blockrec));
1206 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1208 // File anotations (for fileareas specified on each block)
1209 foreach ($this->task->get_fileareas() as $filearea) {
1210 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1213 // Return the root element (block)
1219 * structure step in charge of constructing the logs.xml file for all the log records found
1220 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1221 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1222 * that just in case they become restored some day in the future
1224 class backup_course_logs_structure_step extends backup_structure_step {
1226 protected function define_structure() {
1228 // Define each element separated
1230 $logs = new backup_nested_element('logs');
1232 $log = new backup_nested_element('log', array('id'), array(
1233 'time', 'userid', 'ip', 'module',
1234 'action', 'url', 'info'));
1238 $logs->add_child($log);
1240 // Define sources (all the records belonging to the course, having cmid = 0)
1242 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1245 // NOTE: We don't annotate users from logs as far as they MUST be
1246 // always annotated by the course (enrol, ras... whatever)
1248 // Return the root element (logs)
1255 * structure step in charge of constructing the logs.xml file for all the log records found
1258 class backup_activity_logs_structure_step extends backup_structure_step {
1260 protected function define_structure() {
1262 // Define each element separated
1264 $logs = new backup_nested_element('logs');
1266 $log = new backup_nested_element('log', array('id'), array(
1267 'time', 'userid', 'ip', 'module',
1268 'action', 'url', 'info'));
1272 $logs->add_child($log);
1276 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1279 // NOTE: We don't annotate users from logs as far as they MUST be
1280 // always annotated by the activity (true participants).
1282 // Return the root element (logs)
1289 * structure in charge of constructing the inforef.xml file for all the items we want
1290 * to have referenced there (users, roles, files...)
1292 class backup_inforef_structure_step extends backup_structure_step {
1294 protected function define_structure() {
1296 // Items we want to include in the inforef file.
1297 $items = backup_helper::get_inforef_itemnames();
1301 $inforef = new backup_nested_element('inforef');
1303 // For each item, conditionally, if there are already records, build element
1304 foreach ($items as $itemname) {
1305 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1306 $elementroot = new backup_nested_element($itemname . 'ref');
1307 $element = new backup_nested_element($itemname, array(), array('id'));
1308 $inforef->add_child($elementroot);
1309 $elementroot->add_child($element);
1310 $element->set_source_sql("
1312 FROM {backup_ids_temp}
1315 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1319 // We don't annotate anything there, but rely in the next step
1320 // (move_inforef_annotations_to_final) that will change all the
1321 // already saved 'inforref' entries to their 'final' annotations.
1327 * This step will get all the annotations already processed to inforef.xml file and
1328 * transform them into 'final' annotations.
1330 class move_inforef_annotations_to_final extends backup_execution_step {
1332 protected function define_execution() {
1334 // Items we want to include in the inforef file
1335 $items = backup_helper::get_inforef_itemnames();
1336 foreach ($items as $itemname) {
1337 // Delegate to dbops
1338 backup_structure_dbops::move_annotations_to_final($this->get_backupid(), $itemname);
1344 * structure in charge of constructing the files.xml file with all the
1345 * annotated (final) files along the process. At, the same time, and
1346 * using one specialised nested_element, will copy them form moodle storage
1349 class backup_final_files_structure_step extends backup_structure_step {
1351 protected function define_structure() {
1355 $files = new backup_nested_element('files');
1357 $file = new file_nested_element('file', array('id'), array(
1358 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1359 'filepath', 'filename', 'userid', 'filesize',
1360 'mimetype', 'status', 'timecreated', 'timemodified',
1361 'source', 'author', 'license', 'sortorder'));
1365 $files->add_child($file);
1369 $file->set_source_sql("SELECT f.*
1371 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1372 WHERE bi.backupid = ?
1373 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1380 * Structure step in charge of creating the main moodle_backup.xml file
1381 * where all the information related to the backup, settings, license and
1382 * other information needed on restore is added*/
1383 class backup_main_structure_step extends backup_structure_step {
1385 protected function define_structure() {
1391 $info['name'] = $this->get_setting_value('filename');
1392 $info['moodle_version'] = $CFG->version;
1393 $info['moodle_release'] = $CFG->release;
1394 $info['backup_version'] = $CFG->backup_version;
1395 $info['backup_release'] = $CFG->backup_release;
1396 $info['backup_date'] = time();
1397 $info['backup_uniqueid']= $this->get_backupid();
1398 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1399 $info['original_wwwroot']=$CFG->wwwroot;
1400 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1401 $info['original_course_id'] = $this->get_courseid();
1402 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1403 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1404 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1405 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1406 $info['original_course_contextid'] = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
1407 $info['original_system_contextid'] = get_context_instance(CONTEXT_SYSTEM)->id;
1409 // Get more information from controller
1410 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid());
1414 $moodle_backup = new backup_nested_element('moodle_backup');
1416 $information = new backup_nested_element('information', null, array(
1417 'name', 'moodle_version', 'moodle_release', 'backup_version',
1418 'backup_release', 'backup_date', 'mnet_remoteusers', 'original_wwwroot',
1419 'original_site_identifier_hash', 'original_course_id',
1420 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1421 'original_course_contextid', 'original_system_contextid'));
1423 $details = new backup_nested_element('details');
1425 $detail = new backup_nested_element('detail', array('backup_id'), array(
1426 'type', 'format', 'interactive', 'mode',
1427 'execution', 'executiontime'));
1429 $contents = new backup_nested_element('contents');
1431 $activities = new backup_nested_element('activities');
1433 $activity = new backup_nested_element('activity', null, array(
1434 'moduleid', 'sectionid', 'modulename', 'title',
1437 $sections = new backup_nested_element('sections');
1439 $section = new backup_nested_element('section', null, array(
1440 'sectionid', 'title', 'directory'));
1442 $course = new backup_nested_element('course', null, array(
1443 'courseid', 'title', 'directory'));
1445 $settings = new backup_nested_element('settings');
1447 $setting = new backup_nested_element('setting', null, array(
1448 'level', 'section', 'activity', 'name', 'value'));
1452 $moodle_backup->add_child($information);
1454 $information->add_child($details);
1455 $details->add_child($detail);
1457 $information->add_child($contents);
1458 if (!empty($cinfo['activities'])) {
1459 $contents->add_child($activities);
1460 $activities->add_child($activity);
1462 if (!empty($cinfo['sections'])) {
1463 $contents->add_child($sections);
1464 $sections->add_child($section);
1466 if (!empty($cinfo['course'])) {
1467 $contents->add_child($course);
1470 $information->add_child($settings);
1471 $settings->add_child($setting);
1476 $information->set_source_array(array((object)$info));
1478 $detail->set_source_array($dinfo);
1480 $activity->set_source_array($cinfo['activities']);
1482 $section->set_source_array($cinfo['sections']);
1484 $course->set_source_array($cinfo['course']);
1486 $setting->set_source_array($sinfo);
1488 // Prepare some information to be sent to main moodle_backup.xml file
1489 return $moodle_backup;
1495 * Execution step that will generate the final zip (.mbz) file with all the contents
1497 class backup_zip_contents extends backup_execution_step {
1499 protected function define_execution() {
1502 $basepath = $this->get_basepath();
1504 // Get the list of files in directory
1505 $filestemp = get_directory_list($basepath, '', false, true, true);
1507 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1508 $files[$file] = $basepath . '/' . $file;
1511 // Add the log file if exists
1512 $logfilepath = $basepath . '.log';
1513 if (file_exists($logfilepath)) {
1514 $files['moodle_backup.log'] = $logfilepath;
1517 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1518 $zipfile = $basepath . '/backup.mbz';
1520 // Get the zip packer
1521 $zippacker = get_file_packer('application/zip');
1524 $zippacker->archive_to_pathname($files, $zipfile);
1529 * This step will send the generated backup file to its final destination
1531 class backup_store_backup_file extends backup_execution_step {
1533 protected function define_execution() {
1536 $basepath = $this->get_basepath();
1538 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1539 $zipfile = $basepath . '/backup.mbz';
1541 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1542 return array('backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile));
1548 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1549 * and put them to the backup_ids tables, to be used later as base to backup them
1551 class backup_activity_grade_items_to_ids extends backup_execution_step {
1553 protected function define_execution() {
1555 // Fetch all activity grade items
1556 if ($items = grade_item::fetch_all(array(
1557 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1558 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1559 // Annotate them in backup_ids
1560 foreach ($items as $item) {
1561 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1568 * This step will annotate all the groups and groupings belonging to the course
1570 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1572 protected function define_execution() {
1575 // Get all the course groups
1576 if ($groups = $DB->get_records('groups', array(
1577 'courseid' => $this->task->get_courseid()))) {
1578 foreach ($groups as $group) {
1579 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1583 // Get all the course groupings
1584 if ($groupings = $DB->get_records('groupings', array(
1585 'courseid' => $this->task->get_courseid()))) {
1586 foreach ($groupings as $grouping) {
1587 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1594 * This step will annotate all the groups belonging to already annotated groupings
1596 class backup_annotate_groups_from_groupings extends backup_execution_step {
1598 protected function define_execution() {
1601 // Fetch all the annotated groupings
1602 if ($groupings = $DB->get_records('backup_ids_temp', array(
1603 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1604 foreach ($groupings as $grouping) {
1605 if ($groups = $DB->get_records('groupings_groups', array(
1606 'groupingid' => $grouping->itemid))) {
1607 foreach ($groups as $group) {
1608 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1617 * This step will annotate all the scales belonging to already annotated outcomes
1619 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1621 protected function define_execution() {
1624 // Fetch all the annotated outcomes
1625 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1626 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1627 foreach ($outcomes as $outcome) {
1628 if ($scale = $DB->get_record('grade_outcomes', array(
1629 'id' => $outcome->itemid))) {
1630 // Annotate as scalefinal because it's > 0
1631 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1639 * This step will generate all the file annotations for the already
1640 * annotated (final) question_categories. It calculates the different
1641 * contexts that are being backup and, annotates all the files
1642 * on every context belonging to the "question" component. As far as
1643 * we are always including *complete* question banks it is safe and
1644 * optimal to do that in this (one pass) way
1646 class backup_annotate_all_question_files extends backup_execution_step {
1648 protected function define_execution() {
1651 // Get all the different contexts for the final question_categories
1652 // annotated along the whole backup
1653 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1654 FROM {question_categories} qc
1655 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
1656 WHERE bi.backupid = ?
1657 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
1658 // To know about qtype specific components/fileareas
1659 $components = backup_qtype_plugin::get_components_and_fileareas();
1661 foreach($rs as $record) {
1662 // We don't need to specify filearea nor itemid as far as by
1663 // component and context it's enough to annotate the whole bank files
1664 // This backups "questiontext", "generalfeedback" and "answerfeedback" fileareas (all them
1665 // belonging to the "question" component
1666 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', null, null);
1667 // Again, it is enough to pick files only by context and component
1668 // Do it for qtype specific components
1669 foreach ($components as $component => $fileareas) {
1670 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
1678 * structure step in charge of constructing the questions.xml file for all the
1679 * question categories and questions required by the backup
1680 * and letters related to one activity
1682 class backup_questions_structure_step extends backup_structure_step {
1684 protected function define_structure() {
1686 // Define each element separated
1688 $qcategories = new backup_nested_element('question_categories');
1690 $qcategory = new backup_nested_element('question_category', array('id'), array(
1691 'name', 'contextid', 'contextlevel', 'contextinstanceid',
1692 'info', 'infoformat', 'stamp', 'parent',
1695 $questions = new backup_nested_element('questions');
1697 $question = new backup_nested_element('question', array('id'), array(
1698 'parent', 'name', 'questiontext', 'questiontextformat',
1699 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
1700 'qtype', 'length', 'stamp', 'version',
1701 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
1703 // attach qtype plugin structure to $question element, only one allowed
1704 $this->add_plugin_structure('qtype', $question, false);
1706 $qhints = new backup_nested_element('question_hints');
1708 $qhint = new backup_nested_element('question_hint', array('id'), array(
1709 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
1713 $qcategories->add_child($qcategory);
1714 $qcategory->add_child($questions);
1715 $questions->add_child($question);
1716 $question->add_child($qhints);
1717 $qhints->add_child($qhint);
1719 // Define the sources
1721 $qcategory->set_source_sql("
1722 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
1723 FROM {question_categories} gc
1724 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
1725 JOIN {context} co ON co.id = gc.contextid
1726 WHERE bi.backupid = ?
1727 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
1729 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
1731 $qhint->set_source_sql('
1733 FROM {question_hints}
1734 WHERE questionid = :questionid
1736 array('questionid' => backup::VAR_PARENTID));
1738 // don't need to annotate ids nor files
1739 // (already done by {@link backup_annotate_all_question_files}
1741 return $qcategories;
1748 * This step will generate all the file annotations for the already
1749 * annotated (final) users. Need to do this here because each user
1750 * has its own context and structure tasks only are able to handle
1751 * one context. Also, this step will guarantee that every user has
1752 * its context created (req for other steps)
1754 class backup_annotate_all_user_files extends backup_execution_step {
1756 protected function define_execution() {
1759 // List of fileareas we are going to annotate
1760 $fileareas = array('profile', 'icon');
1762 if ($this->get_setting_value('user_files')) { // private files only if enabled in settings
1763 $fileareas[] = 'private';
1766 // Fetch all annotated (final) users
1767 $rs = $DB->get_recordset('backup_ids_temp', array(
1768 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1769 foreach ($rs as $record) {
1770 $userid = $record->itemid;
1771 $userctxid = get_context_instance(CONTEXT_USER, $userid)->id;
1772 // Proceed with every user filearea
1773 foreach ($fileareas as $filearea) {
1774 // We don't need to specify itemid ($userid - 5th param) as far as by
1775 // context we can get all the associated files. See MDL-22092
1776 backup_structure_dbops::annotate_files($this->get_backupid(), $userctxid, 'user', $filearea, null);
1784 * structure step in charge of constructing the grades.xml file for all the grade items
1785 * and letters related to one activity
1787 class backup_activity_grades_structure_step extends backup_structure_step {
1789 protected function define_structure() {
1791 // To know if we are including userinfo
1792 $userinfo = $this->get_setting_value('userinfo');
1794 // Define each element separated
1796 $book = new backup_nested_element('activity_gradebook');
1798 $items = new backup_nested_element('grade_items');
1800 $item = new backup_nested_element('grade_item', array('id'), array(
1801 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1802 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1803 'calculation', 'gradetype', 'grademax', 'grademin',
1804 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1805 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
1806 'decimals', 'hidden', 'locked', 'locktime',
1807 'needsupdate', 'timecreated', 'timemodified'));
1809 $grades = new backup_nested_element('grade_grades');
1811 $grade = new backup_nested_element('grade_grade', array('id'), array(
1812 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1813 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1814 'locked', 'locktime', 'exported', 'overridden',
1815 'excluded', 'feedback', 'feedbackformat', 'information',
1816 'informationformat', 'timecreated', 'timemodified'));
1818 $letters = new backup_nested_element('grade_letters');
1820 $letter = new backup_nested_element('grade_letter', 'id', array(
1821 'lowerboundary', 'letter'));
1825 $book->add_child($items);
1826 $items->add_child($item);
1828 $item->add_child($grades);
1829 $grades->add_child($grade);
1831 $book->add_child($letters);
1832 $letters->add_child($letter);
1836 $item->set_source_sql("SELECT gi.*
1837 FROM {grade_items} gi
1838 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
1839 WHERE bi.backupid = ?
1840 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
1842 // This only happens if we are including user info
1844 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1847 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1851 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1852 $item->annotate_ids('outcome', 'outcomeid');
1854 $grade->annotate_ids('user', 'userid');
1855 $grade->annotate_ids('user', 'usermodified');
1857 // Return the root element (book)
1864 * Backups up the course completion information for the course.
1866 class backup_course_completion_structure_step extends backup_structure_step {
1868 protected function execute_condition() {
1869 // Check that all activities have been included
1870 if ($this->task->is_excluding_activities()) {
1877 * The structure of the course completion backup
1879 * @return backup_nested_element
1881 protected function define_structure() {
1883 // To know if we are including user completion info
1884 $userinfo = $this->get_setting_value('userscompletion');
1886 $cc = new backup_nested_element('course_completion');
1888 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
1889 'course','criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod', 'timeend', 'gradepass', 'role'
1892 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
1894 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
1895 'criteriaid', 'userid','gradefinal','unenrolled','deleted','timecompleted'
1898 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
1899 'userid', 'course', 'deleted', 'timenotified', 'timeenrolled','timestarted','timecompleted','reaggregate'
1902 $notify = new backup_nested_element('course_completion_notify', array('id'), array(
1903 'course','role','message','timesent'
1906 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
1907 'course','criteriatype','method','value'
1910 $cc->add_child($criteria);
1911 $criteria->add_child($criteriacompletions);
1912 $criteriacompletions->add_child($criteriacomplete);
1913 $cc->add_child($coursecompletions);
1914 $cc->add_child($notify);
1915 $cc->add_child($aggregatemethod);
1917 // We need to get the courseinstances shortname rather than an ID for restore
1918 $criteria->set_source_sql("SELECT ccc.*, c.shortname AS courseinstanceshortname
1919 FROM {course_completion_criteria} ccc
1920 LEFT JOIN {course} c ON c.id = ccc.courseinstance
1921 WHERE ccc.course = ?", array(backup::VAR_COURSEID));
1924 $notify->set_source_table('course_completion_notify', array('course' => backup::VAR_COURSEID));
1925 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
1928 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
1929 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
1932 $criteria->annotate_ids('role', 'role');
1933 $criteriacomplete->annotate_ids('user', 'userid');
1934 $coursecompletions->annotate_ids('user', 'userid');
1935 $notify->annotate_ids('role', 'role');