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 function define_execution() {
54 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
55 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
56 if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
57 backup_helper::delete_backup_dir($this->get_backupid()); // Empty backup dir
63 * Create the directory where all the task (activity/block...) information will be stored
65 class create_taskbasepath_directory extends backup_execution_step {
67 protected function define_execution() {
69 $basepath = $this->task->get_taskbasepath();
70 if (!check_dir_exists($basepath, true, true)) {
71 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
77 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
78 * activity structure definition within the main <activity ...> tag. Also provides
79 * subplugin support for activities (that must be properly declared)
81 abstract class backup_activity_structure_step extends backup_structure_step {
84 * Add subplugin structure to any element in the activity backup tree
86 * @param string $subplugintype type of subplugin as defined in activity db/subplugins.php
87 * @param backup_nested_element $element element in the activity backup tree that
88 * we are going to add subplugin information to
89 * @param bool $multiple to define if multiple subplugins can produce information
90 * for each instance of $element (true) or no (false)
92 protected function add_subplugin_structure($subplugintype, $element, $multiple) {
96 // Check the requested subplugintype is a valid one
97 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
98 if (!file_exists($subpluginsfile)) {
99 throw new backup_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
101 include($subpluginsfile);
102 if (!array_key_exists($subplugintype, $subplugins)) {
103 throw new backup_step_exception('incorrect_subplugin_type', $subplugintype);
106 // Arrived here, subplugin is correct, let's create the optigroup
107 $optigroupname = $subplugintype . '_' . $element->get_name() . '_subplugin';
108 $optigroup = new backup_optigroup($optigroupname, null, $multiple);
109 $element->add_child($optigroup); // Add optigroup to stay connected since beginning
111 // Get all the optigroup_elements, looking across all the subplugin dirs
113 $subpluginsdirs = get_plugin_list($subplugintype);
114 foreach ($subpluginsdirs as $name => $subpluginsdir) {
115 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
116 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
117 if (file_exists($backupfile)) {
118 require_once($backupfile);
119 $backupsubplugin = new $classname($subplugintype, $name, $optigroup);
120 // Add subplugin returned structure to optigroup
121 $backupsubplugin->define_subplugin_structure($element->get_name());
127 * Wraps any activity backup structure within the common 'activity' element
128 * that will include common to all activities information like id, context...
130 protected function prepare_activity_structure($activitystructure) {
132 // Create the wrap element
133 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
136 $activity->add_child($activitystructure);
139 $activityarr = array((object)array(
140 'id' => $this->task->get_activityid(),
141 'moduleid' => $this->task->get_moduleid(),
142 'modulename' => $this->task->get_modulename(),
143 'contextid' => $this->task->get_contextid()));
145 $activity->set_source_array($activityarr);
147 // Return the root element (activity)
153 * Abstract structure step, parent of all the block structure steps. Used to wrap the
154 * block structure definition within the main <block ...> tag
156 abstract class backup_block_structure_step extends backup_structure_step {
158 protected function prepare_block_structure($blockstructure) {
160 // Create the wrap element
161 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
164 $block->add_child($blockstructure);
167 $blockarr = array((object)array(
168 'id' => $this->task->get_blockid(),
169 'blockname' => $this->task->get_blockname(),
170 'contextid' => $this->task->get_contextid()));
172 $block->set_source_array($blockarr);
174 // Return the root element (block)
180 * structure step that will generate the module.xml file for the activity,
181 * accumulating various information about the activity, annotating groupings
182 * and completion/avail conf
184 class backup_module_structure_step extends backup_structure_step {
186 protected function define_structure() {
188 // Define each element separated
190 $module = new backup_nested_element('module', array('id', 'version'), array(
191 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
192 'added', 'score', 'indent', 'visible',
193 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
194 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
195 'availablefrom', 'availableuntil', 'showavailability'));
197 $availinfo = new backup_nested_element('availability_info');
198 $availability = new backup_nested_element('availability', array('id'), array(
199 'sourcecmid', 'requiredcompletion', 'gradeitemid', 'grademin', 'grademax'));
202 $module->add_child($availinfo);
203 $availinfo->add_child($availability);
207 $module->set_source_sql('
208 SELECT cm.*, m.version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
209 FROM {course_modules} cm
210 JOIN {modules} m ON m.id = cm.module
211 JOIN {course_sections} s ON s.id = cm.section
212 WHERE cm.id = ?', array(backup::VAR_MODID));
214 $availability->set_source_table('course_modules_availability', array('coursemoduleid' => backup::VAR_MODID));
216 // Define annotations
217 $module->annotate_ids('grouping', 'groupingid');
219 // Return the root element ($module)
225 * structure step that will generate the section.xml file for the section
228 class backup_section_structure_step extends backup_structure_step {
230 protected function define_structure() {
232 // Define each element separated
234 $section = new backup_nested_element('section', array('id'), array(
235 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible'));
239 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
242 $section->set_source_alias('section', 'number');
245 $section->annotate_files('course', 'section', 'id');
252 * structure step that will generate the course.xml file for the course, including
253 * course category reference, tags, modules restriction information
254 * and some annotations (files & groupings)
256 class backup_course_structure_step extends backup_structure_step {
258 protected function define_structure() {
261 // Define each element separated
263 $course = new backup_nested_element('course', array('id', 'contextid'), array(
264 'shortname', 'fullname', 'idnumber',
265 'summary', 'summaryformat', 'format', 'showgrades',
266 'newsitems', 'startdate',
267 'numsections', 'marker', 'maxbytes', 'showreports',
268 'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
269 'defaultgroupingid', 'lang', 'theme',
270 'timecreated', 'timemodified',
271 'requested', 'restrictmodules',
272 'enablecompletion'));
274 $category = new backup_nested_element('category', array('id'), array(
275 'name', 'description'));
277 $tags = new backup_nested_element('tags');
279 $tag = new backup_nested_element('tag', array('id'), array(
282 $allowedmodules = new backup_nested_element('allowed_modules');
284 $module = new backup_nested_element('module', array('modulename'));
288 $course->add_child($category);
290 $course->add_child($tags);
291 $tags->add_child($tag);
293 $course->add_child($allowedmodules);
294 $allowedmodules->add_child($module);
298 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
299 $courserec->contextid = $this->task->get_contextid();
301 $course->set_source_array(array($courserec));
303 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
305 $category->set_source_array(array($categoryrec));
307 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
309 JOIN {tag_instance} ti ON ti.tagid = t.id
310 WHERE ti.itemtype = ?
311 AND ti.itemid = ?', array(
312 backup_helper::is_sqlparam('course'),
313 backup::VAR_PARENTID));
315 $module->set_source_sql('SELECT m.name AS modulename
317 JOIN {course_allowed_modules} cam ON m.id = cam.module
318 WHERE course = ?', array(backup::VAR_COURSEID));
322 $course->annotate_ids('grouping', 'defaultgroupingid');
324 $course->annotate_files('course', 'summary', null);
325 $course->annotate_files('course', 'legacy', null);
327 // Return root element ($course)
334 * structure step that will generate the enrolments.xml file for the given course
336 class backup_enrolments_structure_step extends backup_structure_step {
338 protected function define_structure() {
340 // To know if we are including users
341 $users = $this->get_setting_value('users');
343 // Define each element separated
345 $enrolments = new backup_nested_element('enrolments');
347 $enrols = new backup_nested_element('enrols');
349 $enrol = new backup_nested_element('enrol', array('id'), array(
350 'enrol', 'status', 'sortorder', 'name', 'enrolperiod', 'enrolstartdate',
351 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
352 'password', 'cost', 'currency', 'roleid', 'customint1', 'customint2', 'customint3',
353 'customint4', 'customchar1', 'customchar2', 'customdec1', 'customdec2',
354 'customtext1', 'customtext2', 'timecreated', 'timemodified'));
356 $userenrolments = new backup_nested_element('user_enrolments');
358 $enrolment = new backup_nested_element('enrolment', array('id'), array(
359 'status', 'userid', 'timestart', 'timeend', 'modifierid',
363 $enrolments->add_child($enrols);
364 $enrols->add_child($enrol);
365 $enrol->add_child($userenrolments);
366 $userenrolments->add_child($enrolment);
370 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID));
372 // User enrolments only added only if users included
374 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
375 $enrolment->annotate_ids('user', 'userid');
378 $enrol->annotate_ids('role', 'roleid');
380 //TODO: let plugins annotate custom fields too and add more children
387 * structure step that will generate the roles.xml file for the given context, observing
388 * the role_assignments setting to know if that part needs to be included
390 class backup_roles_structure_step extends backup_structure_step {
392 protected function define_structure() {
394 // To know if we are including role assignments
395 $roleassignments = $this->get_setting_value('role_assignments');
397 // Define each element separated
399 $roles = new backup_nested_element('roles');
401 $overrides = new backup_nested_element('role_overrides');
403 $override = new backup_nested_element('override', array('id'), array(
404 'roleid', 'capability', 'permission', 'timemodified',
407 $assignments = new backup_nested_element('role_assignments');
409 $assignment = new backup_nested_element('assignment', array('id'), array(
410 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
414 $roles->add_child($overrides);
415 $roles->add_child($assignments);
417 $overrides->add_child($override);
418 $assignments->add_child($assignment);
422 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
424 // Assignments only added if specified
425 if ($roleassignments) {
426 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
429 // Define id annotations
430 $override->annotate_ids('role', 'roleid');
432 $assignment->annotate_ids('role', 'roleid');
434 $assignment->annotate_ids('user', 'userid');
436 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
443 * structure step that will generate the roles.xml containing the
444 * list of roles used along the whole backup process. Just raw
445 * list of used roles from role table
447 class backup_final_roles_structure_step extends backup_structure_step {
449 protected function define_structure() {
453 $rolesdef = new backup_nested_element('roles_definition');
455 $role = new backup_nested_element('role', array('id'), array(
456 'name', 'shortname', 'nameincourse', 'description',
457 'sortorder', 'archetype'));
461 $rolesdef->add_child($role);
465 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
467 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
468 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
469 WHERE bi.backupid = ?
470 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
472 // Return main element (rolesdef)
478 * structure step that will generate the scales.xml containing the
479 * list of scales used along the whole backup process.
481 class backup_final_scales_structure_step extends backup_structure_step {
483 protected function define_structure() {
487 $scalesdef = new backup_nested_element('scales_definition');
489 $scale = new backup_nested_element('scale', array('id'), array(
490 'courseid', 'userid', 'name', 'scale',
491 'description', 'descriptionformat', 'timemodified'));
495 $scalesdef->add_child($scale);
499 $scale->set_source_sql("SELECT s.*
501 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
502 WHERE bi.backupid = ?
503 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
505 // Annotate scale files (they store files in system context, so pass it instead of default one)
506 $scale->annotate_files('grade', 'scale', 'id', get_context_instance(CONTEXT_SYSTEM)->id);
508 // Return main element (scalesdef)
514 * structure step that will generate the outcomes.xml containing the
515 * list of outcomes used along the whole backup process.
517 class backup_final_outcomes_structure_step extends backup_structure_step {
519 protected function define_structure() {
523 $outcomesdef = new backup_nested_element('outcomes_definition');
525 $outcome = new backup_nested_element('outcome', array('id'), array(
526 'courseid', 'userid', 'shortname', 'fullname',
527 'scaleid', 'description', 'descriptionformat', 'timecreated',
528 'timemodified','usermodified'));
532 $outcomesdef->add_child($outcome);
536 $outcome->set_source_sql("SELECT o.*
537 FROM {grade_outcomes} o
538 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
539 WHERE bi.backupid = ?
540 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
542 // Return main element (outcomesdef)
548 * structure step in charge of constructing the filters.xml file for all the filters found
551 class backup_filters_structure_step extends backup_structure_step {
553 protected function define_structure() {
555 // Define each element separated
557 $filters = new backup_nested_element('filters');
559 $actives = new backup_nested_element('filter_actives');
561 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
563 $configs = new backup_nested_element('filter_configs');
565 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
569 $filters->add_child($actives);
570 $filters->add_child($configs);
572 $actives->add_child($active);
573 $configs->add_child($config);
577 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
579 $active->set_source_array($activearr);
580 $config->set_source_array($configarr);
582 // Return the root element (filters)
588 * structure step in charge of constructing the comments.xml file for all the comments found
591 class backup_comments_structure_step extends backup_structure_step {
593 protected function define_structure() {
595 // Define each element separated
597 $comments = new backup_nested_element('comments');
599 $comment = new backup_nested_element('comment', array('id'), array(
600 'commentarea', 'itemid', 'content', 'format',
601 'userid', 'timecreated'));
605 $comments->add_child($comment);
609 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
611 // Define id annotations
613 $comment->annotate_ids('user', 'userid');
615 // Return the root element (comments)
621 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
622 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
624 class backup_gradebook_structure_step extends backup_structure_step {
627 * We need to decide conditionally, based on dynamic information
628 * about the execution of this step. Only will be executed if all
629 * the module gradeitems have been already included in backup
631 protected function execute_condition() {
632 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
635 protected function define_structure() {
637 // are we including user info?
638 $userinfo = $this->get_setting_value('users');
640 $gradebook = new backup_nested_element('gradebook');
642 //grade_letters are done in backup_activity_grades_structure_step()
644 //calculated grade items
645 $grade_items = new backup_nested_element('grade_items');
646 $grade_item = new backup_nested_element('grade_item', array('id'), array(
647 'categoryid', 'itemname', 'itemtype', 'itemmodule',
648 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
649 'calculation', 'gradetype', 'grademax', 'grademin',
650 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
651 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
652 'decimals', 'hidden', 'locked', 'locktime',
653 'needsupdate', 'timecreated', 'timemodified'));
655 $grade_grades = new backup_nested_element('grade_grades');
656 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
657 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
658 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
659 'locked', 'locktime', 'exported', 'overridden',
660 'excluded', 'feedback', 'feedbackformat', 'information',
661 'informationformat', 'timecreated', 'timemodified'));
664 $grade_categories = new backup_nested_element('grade_categories');
665 $grade_category = new backup_nested_element('grade_category', null, array('courseid',
666 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
667 'dropload', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
668 'timecreated', 'timemodified'));
670 $letters = new backup_nested_element('grade_letters');
671 $letter = new backup_nested_element('grade_letter', 'id', array(
672 'lowerboundary', 'letter'));
677 $gradebook->add_child($grade_items);
678 $grade_items->add_child($grade_item);
679 $grade_item->add_child($grade_grades);
680 $grade_grades->add_child($grade_grade);
682 //$grade_item->add_child($grade_scale);
684 $gradebook->add_child($grade_categories);
685 $grade_categories->add_child($grade_category);
687 $gradebook->add_child($letters);
688 $letters->add_child($letter);
692 //Include manual, category and the course grade item
693 $grade_items_sql ="SELECT * FROM {grade_items}
694 WHERE courseid = :courseid
695 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
696 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
697 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
700 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
703 $grade_category_sql = "SELECT gc.*, gi.sortorder
704 FROM {grade_categories} gc
705 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
706 WHERE gc.courseid = :courseid
707 AND (gi.itemtype='course' OR gi.itemtype='category')
708 ORDER BY gc.parent ASC";//need parent categories before their children
709 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
710 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
712 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
714 // Annotations (both as final as far as they are going to be exported in next steps)
715 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
716 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
718 // Return the root element
724 * structure step in charge if constructing the completion.xml file for all the users completion
725 * information in a given activity
727 class backup_userscompletion_structure_step extends backup_structure_step {
729 protected function define_structure() {
731 // Define each element separated
733 $completions = new backup_nested_element('completions');
735 $completion = new backup_nested_element('completion', array('id'), array(
736 'userid', 'completionstate', 'viewed', 'timemodified'));
740 $completions->add_child($completion);
744 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
746 // Define id annotations
748 $completion->annotate_ids('user', 'userid');
750 // Return the root element (completions)
756 * structure step in charge of constructing the main groups.xml file for all the groups and
757 * groupings information already annotated
759 class backup_groups_structure_step extends backup_structure_step {
761 protected function define_structure() {
763 // To know if we are including users
764 $users = $this->get_setting_value('users');
766 // Define each element separated
768 $groups = new backup_nested_element('groups');
770 $group = new backup_nested_element('group', array('id'), array(
771 'name', 'description', 'descriptionformat', 'enrolmentkey',
772 'picture', 'hidepicture', 'timecreated', 'timemodified'));
774 $members = new backup_nested_element('group_members');
776 $member = new backup_nested_element('group_member', array('id'), array(
777 'userid', 'timeadded'));
779 $groupings = new backup_nested_element('groupings');
781 $grouping = new backup_nested_element('grouping', 'id', array(
782 'name', 'description', 'descriptionformat', 'configdata',
783 'timecreated', 'timemodified'));
785 $groupinggroups = new backup_nested_element('grouping_groups');
787 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
788 'groupid', 'timeadded'));
792 $groups->add_child($group);
793 $groups->add_child($groupings);
795 $group->add_child($members);
796 $members->add_child($member);
798 $groupings->add_child($grouping);
799 $grouping->add_child($groupinggroups);
800 $groupinggroups->add_child($groupinggroup);
804 $group->set_source_sql("
807 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
808 WHERE bi.backupid = ?
809 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
811 // This only happens if we are including users
813 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
816 $grouping->set_source_sql("
819 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
820 WHERE bi.backupid = ?
821 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
823 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
825 // Define id annotations (as final)
827 $member->annotate_ids('userfinal', 'userid');
829 // Define file annotations
831 $group->annotate_files('group', 'description', 'id');
832 $group->annotate_files('group', 'icon', 'id');
833 $grouping->annotate_files('grouping', 'description', 'id');
835 // Return the root element (groups)
841 * structure step in charge of constructing the main users.xml file for all the users already
842 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
845 class backup_users_structure_step extends backup_structure_step {
847 protected function define_structure() {
850 // To know if we are anonymizing users
851 $anonymize = $this->get_setting_value('anonymize');
852 // To know if we are including role assignments
853 $roleassignments = $this->get_setting_value('role_assignments');
855 // Define each element separated
857 $users = new backup_nested_element('users');
859 // Create the array of user fields by hand, as far as we have various bits to control
860 // anonymize option, password backup, mnethostid...
862 // First, the fields not needing anonymization nor special handling
863 $normalfields = array(
864 'confirmed', 'policyagreed', 'deleted',
865 'lang', 'theme', 'timezone', 'firstaccess',
866 'lastaccess', 'lastlogin', 'currentlogin',
867 'mailformat', 'maildigest', 'maildisplay', 'htmleditor',
868 'ajax', 'autosubscribe', 'trackforums', 'timecreated',
869 'timemodified', 'trustbitmask', 'screenreader');
871 // Then, the fields potentially needing anonymization
873 'username', 'idnumber', 'firstname', 'lastname',
874 'email', 'emailstop', 'icq', 'skype',
875 'yahoo', 'aim', 'msn', 'phone1',
876 'phone2', 'institution', 'department', 'address',
877 'city', 'country', 'lastip', 'picture',
878 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
880 // Add anonymized fields to $userfields with custom final element
881 foreach ($anonfields as $field) {
883 $userfields[] = new anonymizer_final_element($field);
885 $userfields[] = $field; // No anonymization, normally added
889 // mnethosturl requires special handling (custom final element)
890 $userfields[] = new mnethosturl_final_element('mnethosturl');
892 // password added conditionally
893 if (!empty($CFG->includeuserpasswordsinbackup)) {
894 $userfields[] = 'password';
897 // Merge all the fields
898 $userfields = array_merge($userfields, $normalfields);
900 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
902 $customfields = new backup_nested_element('custom_fields');
904 $customfield = new backup_nested_element('custom_field', array('id'), array(
905 'field_name', 'field_type', 'field_data'));
907 $tags = new backup_nested_element('tags');
909 $tag = new backup_nested_element('tag', array('id'), array(
912 $preferences = new backup_nested_element('preferences');
914 $preference = new backup_nested_element('preference', array('id'), array(
917 $roles = new backup_nested_element('roles');
919 $overrides = new backup_nested_element('role_overrides');
921 $override = new backup_nested_element('override', array('id'), array(
922 'roleid', 'capability', 'permission', 'timemodified',
925 $assignments = new backup_nested_element('role_assignments');
927 $assignment = new backup_nested_element('assignment', array('id'), array(
928 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
933 $users->add_child($user);
935 $user->add_child($customfields);
936 $customfields->add_child($customfield);
938 $user->add_child($tags);
939 $tags->add_child($tag);
941 $user->add_child($preferences);
942 $preferences->add_child($preference);
944 $user->add_child($roles);
946 $roles->add_child($overrides);
947 $roles->add_child($assignments);
949 $overrides->add_child($override);
950 $assignments->add_child($assignment);
954 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
956 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
957 JOIN {context} c ON c.instanceid = u.id
958 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
959 WHERE bi.backupid = ?
961 AND c.contextlevel = ?', array(
962 backup_helper::is_sqlparam($this->get_backupid()),
963 backup_helper::is_sqlparam('userfinal'),
964 backup_helper::is_sqlparam(CONTEXT_USER)));
966 // All the rest on information is only added if we arent
967 // in an anonymized backup
969 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
970 FROM {user_info_field} f
971 JOIN {user_info_data} d ON d.fieldid = f.id
972 WHERE d.userid = ?', array(backup::VAR_PARENTID));
974 $customfield->set_source_alias('shortname', 'field_name');
975 $customfield->set_source_alias('datatype', 'field_type');
976 $customfield->set_source_alias('data', 'field_data');
978 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
980 JOIN {tag_instance} ti ON ti.tagid = t.id
981 WHERE ti.itemtype = ?
982 AND ti.itemid = ?', array(
983 backup_helper::is_sqlparam('user'),
984 backup::VAR_PARENTID));
986 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
988 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
990 // Assignments only added if specified
991 if ($roleassignments) {
992 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
995 // Define id annotations (as final)
996 $override->annotate_ids('rolefinal', 'roleid');
999 // Return root element (users)
1005 * structure step in charge of constructing the block.xml file for one
1006 * given block (instance and positions). If the block has custom DB structure
1007 * that will go to a separate file (different step defined in block class)
1009 class backup_block_instance_structure_step extends backup_structure_step {
1011 protected function define_structure() {
1014 // Define each element separated
1016 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1017 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1018 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1020 $positions = new backup_nested_element('block_positions', null, array(
1021 'contextid', 'pagetype', 'subpage', 'visible',
1022 'region', 'weight'));
1026 $block->add_child($positions);
1028 // Transform configdata information if needed (process links and friends)
1029 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1030 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1031 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1032 foreach ($configdata as $attribute => $value) {
1033 if (in_array($attribute, $attrstotransform)) {
1034 $configdata[$attribute] = $this->contenttransformer->process($value);
1037 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1039 $blockrec->contextid = $this->task->get_contextid();
1040 // Get the version of the block
1041 $blockrec->version = $DB->get_field('block', 'version', array('name' => $this->task->get_blockname()));
1045 $block->set_source_array(array($blockrec));
1047 $positions->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1049 // Return the root element (block)
1055 * structure step in charge of constructing the logs.xml file for all the log records found
1058 class backup_activity_logs_structure_step extends backup_structure_step {
1060 protected function define_structure() {
1062 // Define each element separated
1064 $logs = new backup_nested_element('logs');
1066 $log = new backup_nested_element('log', array('id'), array(
1067 'time', 'userid', 'ip', 'module',
1068 'action', 'url', 'info'));
1072 $logs->add_child($log);
1076 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1079 // NOTE: We don't annotate users from logs as far as they MUST be
1080 // always annotated by the activity.
1082 // Return the root element (logs)
1089 * structure in charge of constructing the inforef.xml file for all the items we want
1090 * to have referenced there (users, roles, files...)
1092 class backup_inforef_structure_step extends backup_structure_step {
1094 protected function define_structure() {
1096 // Items we want to include in the inforef file.
1097 $items = backup_helper::get_inforef_itemnames();
1101 $inforef = new backup_nested_element('inforef');
1103 // For each item, conditionally, if there are already records, build element
1104 foreach ($items as $itemname) {
1105 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1106 $elementroot = new backup_nested_element($itemname . 'ref');
1107 $element = new backup_nested_element($itemname, array(), array('id'));
1108 $inforef->add_child($elementroot);
1109 $elementroot->add_child($element);
1110 $element->set_source_sql("
1112 FROM {backup_ids_temp}
1115 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1119 // We don't annotate anything there, but rely in the next step
1120 // (move_inforef_annotations_to_final) that will change all the
1121 // already saved 'inforref' entries to their 'final' annotations.
1127 * This step will get all the annotations already processed to inforef.xml file and
1128 * transform them into 'final' annotations.
1130 class move_inforef_annotations_to_final extends backup_execution_step {
1132 protected function define_execution() {
1134 // Items we want to include in the inforef file
1135 $items = backup_helper::get_inforef_itemnames();
1136 foreach ($items as $itemname) {
1137 // Delegate to dbops
1138 backup_structure_dbops::move_annotations_to_final($this->get_backupid(), $itemname);
1144 * structure in charge of constructing the files.xml file with all the
1145 * annotated (final) files along the process. At, the same time, and
1146 * using one specialised nested_element, will copy them form moodle storage
1149 class backup_final_files_structure_step extends backup_structure_step {
1151 protected function define_structure() {
1155 $files = new backup_nested_element('files');
1157 $file = new file_nested_element('file', array('id'), array(
1158 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1159 'filepath', 'filename', 'userid', 'filesize',
1160 'mimetype', 'status', 'timecreated', 'timemodified',
1161 'source', 'author', 'license', 'sortorder'));
1165 $files->add_child($file);
1169 $file->set_source_sql("SELECT f.*
1171 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1172 WHERE bi.backupid = ?
1173 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1180 * Structure step in charge of creating the main moodle_backup.xml file
1181 * where all the information related to the backup, settings, license and
1182 * other information needed on restore is added*/
1183 class backup_main_structure_step extends backup_structure_step {
1185 protected function define_structure() {
1191 $info['name'] = $this->get_setting_value('filename');
1192 $info['moodle_version'] = $CFG->version;
1193 $info['moodle_release'] = $CFG->release;
1194 $info['backup_version'] = $CFG->backup_version;
1195 $info['backup_release'] = $CFG->backup_release;
1196 $info['backup_date'] = time();
1197 $info['backup_uniqueid']= $this->get_backupid();
1198 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1199 $info['original_wwwroot']=$CFG->wwwroot;
1200 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1201 $info['original_course_id'] = $this->get_courseid();
1202 $info['original_course_contextid'] = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
1203 $info['original_system_contextid'] = get_context_instance(CONTEXT_SYSTEM)->id;
1205 // Get more information from controller
1206 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid());
1210 $moodle_backup = new backup_nested_element('moodle_backup');
1212 $information = new backup_nested_element('information', null, array(
1213 'name', 'moodle_version', 'moodle_release', 'backup_version',
1214 'backup_release', 'backup_date', 'mnet_remoteusers', 'original_wwwroot',
1215 'original_site_identifier_hash', 'original_course_id', 'original_course_contextid', 'original_system_contextid'));
1217 $details = new backup_nested_element('details');
1219 $detail = new backup_nested_element('detail', array('backup_id'), array(
1220 'type', 'format', 'interactive', 'mode',
1221 'execution', 'executiontime'));
1223 $contents = new backup_nested_element('contents');
1225 $activities = new backup_nested_element('activities');
1227 $activity = new backup_nested_element('activity', null, array(
1228 'moduleid', 'sectionid', 'modulename', 'title',
1231 $sections = new backup_nested_element('sections');
1233 $section = new backup_nested_element('section', null, array(
1234 'sectionid', 'title', 'directory'));
1236 $course = new backup_nested_element('course', null, array(
1237 'courseid', 'title', 'directory'));
1239 $settings = new backup_nested_element('settings');
1241 $setting = new backup_nested_element('setting', null, array(
1242 'level', 'section', 'activity', 'name', 'value'));
1246 $moodle_backup->add_child($information);
1248 $information->add_child($details);
1249 $details->add_child($detail);
1251 $information->add_child($contents);
1252 if (!empty($cinfo['activities'])) {
1253 $contents->add_child($activities);
1254 $activities->add_child($activity);
1256 if (!empty($cinfo['sections'])) {
1257 $contents->add_child($sections);
1258 $sections->add_child($section);
1260 if (!empty($cinfo['course'])) {
1261 $contents->add_child($course);
1264 $information->add_child($settings);
1265 $settings->add_child($setting);
1270 $information->set_source_array(array((object)$info));
1272 $detail->set_source_array($dinfo);
1274 $activity->set_source_array($cinfo['activities']);
1276 $section->set_source_array($cinfo['sections']);
1278 $course->set_source_array($cinfo['course']);
1280 $setting->set_source_array($sinfo);
1282 // Prepare some information to be sent to main moodle_backup.xml file
1283 return $moodle_backup;
1289 * Execution step that will generate the final zip file with all the contents
1291 class backup_zip_contents extends backup_execution_step {
1293 protected function define_execution() {
1296 $basepath = $this->get_basepath();
1298 // Get the list of files in directory
1299 $filestemp = get_directory_list($basepath, '', false, true, true);
1301 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1302 $files[$file] = $basepath . '/' . $file;
1305 // Add the log file if exists
1306 $logfilepath = $basepath . '.log';
1307 if (file_exists($logfilepath)) {
1308 $files['moodle_backup.log'] = $logfilepath;
1311 // Calculate the zip fullpath (in OS temp area it's always backup.zip)
1312 $zipfile = $basepath . '/backup.zip';
1314 // Get the zip packer
1315 $zippacker = get_file_packer('application/zip');
1318 $zippacker->archive_to_pathname($files, $zipfile);
1323 * This step will send the generated backup file to its final destination
1325 class backup_store_backup_file extends backup_execution_step {
1327 protected function define_execution() {
1330 $basepath = $this->get_basepath();
1332 // Calculate the zip fullpath (in OS temp area it's always backup.zip)
1333 $zipfile = $basepath . '/backup.zip';
1335 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1336 return array('backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile));
1342 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1343 * and put them to the backup_ids tables, to be used later as base to backup them
1345 class backup_activity_grade_items_to_ids extends backup_execution_step {
1347 protected function define_execution() {
1349 // Fetch all activity grade items
1350 if ($items = grade_item::fetch_all(array(
1351 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1352 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1353 // Annotate them in backup_ids
1354 foreach ($items as $item) {
1355 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1362 * This step will annotate all the groups belonging to already annotated groupings
1364 class backup_annotate_groups_from_groupings extends backup_execution_step {
1366 protected function define_execution() {
1369 // Fetch all the annotated groupings
1370 if ($groupings = $DB->get_records('backup_ids_temp', array(
1371 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1372 foreach ($groupings as $grouping) {
1373 if ($groups = $DB->get_records('groupings_groups', array(
1374 'groupingid' => $grouping->itemid))) {
1375 foreach ($groups as $group) {
1376 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1385 * This step will annotate all the scales belonging to already annotated outcomes
1387 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1389 protected function define_execution() {
1392 // Fetch all the annotated outcomes
1393 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1394 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1395 foreach ($outcomes as $outcome) {
1396 if ($scale = $DB->get_record('grade_outcomes', array(
1397 'id' => $outcome->itemid))) {
1398 // Annotate as scalefinal because it's > 0
1399 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1407 * This step will generate all the file annotations for the already
1408 * annotated (final) users. Need to do this here because each user
1409 * has its own context and structure tasks only are able to handle
1410 * one context. Also, this step will guarantee that every user has
1411 * its context created (req for other steps)
1413 class backup_annotate_all_user_files extends backup_execution_step {
1415 protected function define_execution() {
1418 // List of fileareas we are going to annotate
1419 $fileareas = array('profile', 'icon');
1421 if ($this->get_setting_value('user_files')) { // private files only if enabled in settings
1422 $fileareas[] = 'private';
1425 // Fetch all annotated (final) users
1426 $rs = $DB->get_recordset('backup_ids_temp', array(
1427 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1428 foreach ($rs as $record) {
1429 $userid = $record->itemid;
1430 $userctxid = get_context_instance(CONTEXT_USER, $userid)->id;
1431 // Proceed with every user filearea
1432 foreach ($fileareas as $filearea) {
1433 // We don't need to specify itemid ($userid - 5th param) as far as by
1434 // context we can get all the associated files. See MDL-22092
1435 backup_structure_dbops::annotate_files($this->get_backupid(), $userctxid, 'user', $filearea, null);
1443 * structure step in charge of constructing the grades.xml file for all the grade items
1444 * and letters related to one activity
1446 class backup_activity_grades_structure_step extends backup_structure_step {
1448 protected function define_structure() {
1450 // To know if we are including userinfo
1451 $userinfo = $this->get_setting_value('userinfo');
1453 // Define each element separated
1455 $book = new backup_nested_element('activity_gradebook');
1457 $items = new backup_nested_element('grade_items');
1459 $item = new backup_nested_element('grade_item', array('id'), array(
1460 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1461 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1462 'calculation', 'gradetype', 'grademax', 'grademin',
1463 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1464 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
1465 'decimals', 'hidden', 'locked', 'locktime',
1466 'needsupdate', 'timecreated', 'timemodified'));
1468 $grades = new backup_nested_element('grade_grades');
1470 $grade = new backup_nested_element('grade_grade', array('id'), array(
1471 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1472 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1473 'locked', 'locktime', 'exported', 'overridden',
1474 'excluded', 'feedback', 'feedbackformat', 'information',
1475 'informationformat', 'timecreated', 'timemodified'));
1477 $letters = new backup_nested_element('grade_letters');
1479 $letter = new backup_nested_element('grade_letter', 'id', array(
1480 'lowerboundary', 'letter'));
1484 $book->add_child($items);
1485 $items->add_child($item);
1487 $item->add_child($grades);
1488 $grades->add_child($grade);
1490 $book->add_child($letters);
1491 $letters->add_child($letter);
1495 $item->set_source_sql("SELECT gi.*
1496 FROM {grade_items} gi
1497 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
1498 WHERE bi.backupid = ?
1499 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
1501 // This only happens if we are including user info
1503 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1506 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1510 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1511 $item->annotate_ids('outcome', 'outcomeid');
1513 $grade->annotate_ids('user', 'userid');
1514 $grade->annotate_ids('user', 'usermodified');
1516 // Return the root element (book)