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 correspondig 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 * Abtract tructure 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);
110 // Get all the optigroup_elements, looking across al the subplugin dirs
112 $subpluginsdirs = get_plugin_list($subplugintype);
113 foreach ($subpluginsdirs as $name => $subpluginsdir) {
114 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
115 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
116 if (file_exists($backupfile)) {
117 require_once($backupfile);
118 $backupsubplugin = new $classname($subplugintype, $name);
119 // Add subplugin returned structure to optigroup (must be optigroup_element instance)
120 if ($subpluginstructure = $backupsubplugin->define_subplugin_structure($element->get_name())) {
121 $optigroup->add_child($subpluginstructure);
125 // Finished, add optigroup to element
126 $element->add_child($optigroup);
130 * Wraps any activity backup structure within the common 'activity' element
131 * that will include common to all activities information like id, context...
133 protected function prepare_activity_structure($activitystructure) {
135 // Create the wrap element
136 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
139 $activity->add_child($activitystructure);
142 $activityarr = array((object)array(
143 'id' => $this->task->get_activityid(),
144 'moduleid' => $this->task->get_moduleid(),
145 'modulename' => $this->task->get_modulename(),
146 'contextid' => $this->task->get_contextid()));
148 $activity->set_source_array($activityarr);
150 // Return the root element (activity)
156 * Abtract structure step, parent of all the block structure steps. Used to wrap the
157 * block structure definition within the main <block ...> tag
159 abstract class backup_block_structure_step extends backup_structure_step {
161 protected function prepare_block_structure($blockstructure) {
163 // Create the wrap element
164 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
167 $block->add_child($blockstructure);
170 $blockarr = array((object)array(
171 'id' => $this->task->get_blockid(),
172 'blockname' => $this->task->get_blockname(),
173 'contextid' => $this->task->get_contextid()));
175 $block->set_source_array($blockarr);
177 // Return the root element (block)
183 * structure step that will generate the module.xml file for the activity,
184 * acummulating various information about the activity, annotating groupings
185 * and completion/avail conf
187 class backup_module_structure_step extends backup_structure_step {
189 protected function define_structure() {
191 // Define each element separated
193 $module = new backup_nested_element('module', array('id', 'version'), array(
194 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
195 'added', 'score', 'indent', 'visible',
196 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
197 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
198 'availablefrom', 'availableuntil', 'showavailability'));
200 $availinfo = new backup_nested_element('availability_info');
201 $availability = new backup_nested_element('availability', array('id'), array(
202 'sourcecmid', 'requiredcompletion', 'gradeitemid', 'grademin', 'grademax'));
205 $module->add_child($availinfo);
206 $availinfo->add_child($availability);
210 $module->set_source_sql('
211 SELECT cm.*, m.version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
212 FROM {course_modules} cm
213 JOIN {modules} m ON m.id = cm.module
214 JOIN {course_sections} s ON s.id = cm.section
215 WHERE cm.id = ?', array(backup::VAR_MODID));
217 $availability->set_source_table('course_modules_availability', array('coursemoduleid' => backup::VAR_MODID));
219 // Define annotations
220 $module->annotate_ids('grouping', 'groupingid');
222 // Return the root element ($module)
228 * structure step that will genereate the section.xml file for the section
231 class backup_section_structure_step extends backup_structure_step {
233 protected function define_structure() {
235 // Define each element separated
237 $section = new backup_nested_element('section', array('id'), array(
238 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible'));
242 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
245 $section->set_source_alias('section', 'number');
248 $section->annotate_files('course', 'section', 'id');
255 * structure step that will generate the course.xml file for the course, including
256 * course category reference, tags, modules restriction information
257 * and some annotations (files & groupings)
259 class backup_course_structure_step extends backup_structure_step {
261 protected function define_structure() {
264 // Define each element separated
266 $course = new backup_nested_element('course', array('id', 'contextid'), array(
267 'shortname', 'fullname', 'idnumber',
268 'summary', 'summaryformat', 'format', 'showgrades',
269 'newsitems', 'startdate',
270 'numsections', 'marker', 'maxbytes', 'showreports',
271 'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
272 'defaultgroupingid', 'lang', 'theme',
273 'timecreated', 'timemodified',
274 'requested', 'restrictmodules',
275 'enablecompletion'));
277 $category = new backup_nested_element('category', array('id'), array(
278 'name', 'description'));
280 $tags = new backup_nested_element('tags');
282 $tag = new backup_nested_element('tag', array('id'), array(
285 $allowedmodules = new backup_nested_element('allowed_modules');
287 $module = new backup_nested_element('module', array('modulename'));
291 $course->add_child($category);
293 $course->add_child($tags);
294 $tags->add_child($tag);
296 $course->add_child($allowedmodules);
297 $allowedmodules->add_child($module);
301 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
302 $courserec->contextid = $this->task->get_contextid();
304 $course->set_source_array(array($courserec));
306 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
308 $category->set_source_array(array($categoryrec));
310 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
312 JOIN {tag_instance} ti ON ti.tagid = t.id
313 WHERE ti.itemtype = ?
314 AND ti.itemid = ?', array(
315 $this->is_sqlparam('course'),
316 backup::VAR_PARENTID));
318 $module->set_source_sql('SELECT m.name AS modulename
320 JOIN {course_allowed_modules} cam ON m.id = cam.module
321 WHERE course = ?', array(backup::VAR_COURSEID));
325 $course->annotate_ids('grouping', 'defaultgroupingid');
327 $course->annotate_files('course', 'summary', null);
328 $course->annotate_files('course', 'legacy', null);
330 // Return root element ($course)
337 * structure step that will generate the roles.xml file for the given context, observing
338 * the role_assignments setting to know if that part needs to be included
340 class backup_roles_structure_step extends backup_structure_step {
342 protected function define_structure() {
344 // To know if we are including role assignments
345 $roleassignments = $this->get_setting_value('role_assignments');
347 // Define each element separated
349 $roles = new backup_nested_element('roles');
351 $overrides = new backup_nested_element('role_overrides');
353 $override = new backup_nested_element('override', array('id'), array(
354 'roleid', 'capability', 'permission', 'timemodified',
357 $assignments = new backup_nested_element('role_assignments');
359 $assignment = new backup_nested_element('assignment', array('id'), array(
360 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
364 $roles->add_child($overrides);
365 $roles->add_child($assignments);
367 $overrides->add_child($override);
368 $assignments->add_child($assignment);
372 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
374 // Assignments only added if specified
375 if ($roleassignments) {
376 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
379 // Define id annotations
380 $override->annotate_ids('role', 'roleid');
382 $assignment->annotate_ids('role', 'roleid');
384 $assignment->annotate_ids('user', 'userid');
391 * structure step that will generate the roles.xml containing the
392 * list of roles used along the whole backup process. Just raw
393 * list of used roles from role table
395 class backup_final_roles_structure_step extends backup_structure_step {
397 protected function define_structure() {
401 $rolesdef = new backup_nested_element('roles_definition');
403 $role = new backup_nested_element('role', array('id'), array(
404 'name', 'shortname', 'nameincourse', 'description',
405 'sortorder', 'archetype'));
409 $rolesdef->add_child($role);
413 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
415 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
416 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
417 WHERE bi.backupid = ?
418 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
420 // Return main element (rolesdef)
426 * structure step that will generate the scales.xml containing the
427 * list of scales used along the whole backup process.
429 class backup_final_scales_structure_step extends backup_structure_step {
431 protected function define_structure() {
435 $scalesdef = new backup_nested_element('scales_definition');
437 $scale = new backup_nested_element('scale', array('id'), array(
438 'courseid', 'userid', 'name', 'scale',
439 'description', 'descriptionformat', 'timemodified'));
443 $scalesdef->add_child($scale);
447 $scale->set_source_sql("SELECT s.*
449 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
450 WHERE bi.backupid = ?
451 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
453 // Return main element (scalesdef)
459 * structure step that will generate the outcomes.xml containing the
460 * list of outcomes used along the whole backup process.
462 class backup_final_outcomes_structure_step extends backup_structure_step {
464 protected function define_structure() {
468 $outcomesdef = new backup_nested_element('outcomes_definition');
470 $outcome = new backup_nested_element('outcome', array('id'), array(
471 'courseid', 'userid', 'shortname', 'fullname',
472 'scaleid', 'description', 'descriptionformat', 'timecreated',
473 'timemodified','usermodified'));
477 $outcomesdef->add_child($outcome);
481 $outcome->set_source_sql("SELECT o.*
482 FROM {grade_outcomes} o
483 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
484 WHERE bi.backupid = ?
485 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
487 // Return main element (outcomesdef)
493 * structure step in charge of constructing the filters.xml file for all the filters found
496 class backup_filters_structure_step extends backup_structure_step {
498 protected function define_structure() {
500 // Define each element separated
502 $filters = new backup_nested_element('filters');
504 $actives = new backup_nested_element('filter_actives');
506 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
508 $configs = new backup_nested_element('filter_configs');
510 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
514 $filters->add_child($actives);
515 $filters->add_child($configs);
517 $actives->add_child($active);
518 $configs->add_child($config);
522 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
524 $active->set_source_array($activearr);
525 $config->set_source_array($configarr);
527 // Return the root element (filters)
533 * structure step in charge of constructing the comments.xml file for all the comments found
536 class backup_comments_structure_step extends backup_structure_step {
538 protected function define_structure() {
540 // Define each element separated
542 $comments = new backup_nested_element('comments');
544 $comment = new backup_nested_element('comment', array('id'), array(
545 'commentarea', 'itemid', 'content', 'format',
546 'userid', 'timecreated'));
550 $comments->add_child($comment);
554 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
556 // Define id annotations
558 $comment->annotate_ids('user', 'userid');
560 // Return the root element (comments)
566 * structure step in charge if constructing the completion.xml file for all the users completion
567 * information in a given activity
569 class backup_userscompletion_structure_step extends backup_structure_step {
571 protected function define_structure() {
573 // Define each element separated
575 $completions = new backup_nested_element('completions');
577 $completion = new backup_nested_element('completion', array('id'), array(
578 'userid', 'completionstate', 'viewed', 'timemodified'));
582 $completions->add_child($completion);
586 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
588 // Define id annotations
590 $completion->annotate_ids('user', 'userid');
592 // Return the root element (completions)
598 * structure step in charge of constructing the main groups.xml file for all the groups and
599 * groupings information already annotated
601 class backup_groups_structure_step extends backup_structure_step {
603 protected function define_structure() {
605 // To know if we are including users
606 $users = $this->get_setting_value('users');
608 // Define each element separated
610 $groups = new backup_nested_element('groups');
612 $group = new backup_nested_element('group', array('id'), array(
613 'name', 'description', 'descriptionformat', 'enrolmentkey',
614 'picture', 'hidepicture', 'timecreated', 'timemodified'));
616 $members = new backup_nested_element('group_members');
618 $member = new backup_nested_element('group_member', array('id'), array(
619 'userid', 'timeadded'));
621 $groupings = new backup_nested_element('groupings');
623 $grouping = new backup_nested_element('grouping', 'id', array(
624 'name', 'description', 'descriptionformat', 'configdata',
625 'timecreated', 'timemodified'));
627 $groupinggroups = new backup_nested_element('grouping_groups');
629 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
630 'groupid', 'timeadded'));
634 $groups->add_child($group);
635 $groups->add_child($groupings);
637 $group->add_child($members);
638 $members->add_child($member);
640 $groupings->add_child($grouping);
641 $grouping->add_child($groupinggroups);
642 $groupinggroups->add_child($groupinggroup);
646 $group->set_source_sql("
649 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
650 WHERE bi.backupid = ?
651 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
653 // This only happens if we are including users
655 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
658 $grouping->set_source_sql("
661 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
662 WHERE bi.backupid = ?
663 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
665 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
667 // Define id annotations (as final)
669 $member->annotate_ids('userfinal', 'userid');
671 // Define file annotations
673 //TODO: not implemented yet
674 $group->annotate_files('group', 'description', 'id');
675 $group->annotate_files('group', 'image', 'id');
677 // Return the root element (groups)
683 * structure step in charge of constructing the main users.xml file for all the users already
684 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
687 class backup_users_structure_step extends backup_structure_step {
689 protected function define_structure() {
692 // To know if we are anonymizing users
693 $anonymize = $this->get_setting_value('anonymize');
694 // To know if we are including role assignments
695 $roleassignments = $this->get_setting_value('role_assignments');
697 // Define each element separated
699 $users = new backup_nested_element('users');
701 // Create the array of user fields by hand, as far as we have various bits to control
702 // anonymize option, password backup, mnethostid...
704 // First, the fields not needing anonymization nor special handling
705 $normalfields = array(
706 'confirmed', 'policyagreed', 'deleted',
707 'lang', 'theme', 'timezone', 'firstaccess',
708 'lastaccess', 'lastlogin', 'currentlogin', 'secret',
709 'mailformat', 'maildigest', 'maildisplay', 'htmleditor',
710 'ajax', 'autosubscribe', 'trackforums', 'timecreated',
711 'timemodified', 'trustbitmask', 'screenreader');
713 // Then, the fields potentially needing anonymization
715 'username', 'idnumber', 'firstname', 'lastname',
716 'email', 'emailstop', 'lastip', 'picture',
717 'url', 'description', 'description_format', 'imagealt', 'auth');
719 // Add anonymized fields to $userfields with custom final element
720 foreach ($anonfields as $field) {
722 $userfields[] = new anonymizer_final_element($field);
724 $userfields[] = $field; // No anonymization, normally added
728 // mnethosturl requires special handling (custom final element)
729 $userfields[] = new mnethosturl_final_element('mnethosturl');
731 // password added conditionally
732 if (!empty($CFG->includeuserpasswordsinbackup)) {
733 $userfields[] = 'password';
736 // Merge all the fields
737 $userfields = array_merge($userfields, $normalfields);
739 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
741 $customfields = new backup_nested_element('custom_fields');
743 $customfield = new backup_nested_element('custom_field', array('id'), array(
744 'field_name', 'field_type', 'field_data'));
746 $tags = new backup_nested_element('tags');
748 $tag = new backup_nested_element('tag', array('id'), array(
751 $preferences = new backup_nested_element('preferences');
753 $preference = new backup_nested_element('preference', array('id'), array(
756 $roles = new backup_nested_element('roles');
758 $overrides = new backup_nested_element('role_overrides');
760 $override = new backup_nested_element('override', array('id'), array(
761 'roleid', 'capability', 'permission', 'timemodified',
764 $assignments = new backup_nested_element('role_assignments');
766 $assignment = new backup_nested_element('assignment', array('id'), array(
767 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
772 $users->add_child($user);
774 $user->add_child($customfields);
775 $customfields->add_child($customfield);
777 $user->add_child($tags);
778 $tags->add_child($tag);
780 $user->add_child($preferences);
781 $preferences->add_child($preference);
783 $user->add_child($roles);
785 $roles->add_child($overrides);
786 $roles->add_child($assignments);
788 $overrides->add_child($override);
789 $assignments->add_child($assignment);
793 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
795 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
796 JOIN {context} c ON c.instanceid = u.id
797 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
798 WHERE bi.backupid = ?
800 AND c.contextlevel = ?', array(
801 $this->is_sqlparam($this->get_backupid()),
802 $this->is_sqlparam('userfinal'),
803 $this->is_sqlparam(CONTEXT_USER)));
805 // All the rest on information is only added if we arent
806 // in an anonymized backup
808 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
809 FROM {user_info_field} f
810 JOIN {user_info_data} d ON d.fieldid = f.id
811 WHERE d.userid = ?', array(backup::VAR_PARENTID));
813 $customfield->set_source_alias('shortname', 'field_name');
814 $customfield->set_source_alias('datatype', 'field_type');
815 $customfield->set_source_alias('data', 'field_data');
817 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
819 JOIN {tag_instance} ti ON ti.tagid = t.id
820 WHERE ti.itemtype = ?
821 AND ti.itemid = ?', array(
822 $this->is_sqlparam('user'),
823 backup::VAR_PARENTID));
825 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
827 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
829 // Assignments only added if specified
830 if ($roleassignments) {
831 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
834 // Define id annotations (as final)
835 $override->annotate_ids('rolefinal', 'roleid');
838 // Return root element (users)
844 * structure step in charge of constructing the block.xml file for one
845 * given block (intance and positions). If the block has custom DB structure
846 * that will go to a separate file (different step defined in block class)
848 class backup_block_instance_structure_step extends backup_structure_step {
850 protected function define_structure() {
853 // Define each element separated
855 $block = new backup_nested_element('block', array('id', 'version'), array(
856 'blockname', 'showinsubcontexts', 'pagetypepattern', 'subpagepattern',
857 'defaultregion', 'defaultweight', 'configdata'));
859 $positions = new backup_nested_element('block_positions', null, array(
860 'contextid', 'pagetype', 'subpage', 'visible',
861 'region', 'weight'));
865 $block->add_child($positions);
867 // Transform configdata information if needed (process links and friends)
868 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
869 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
870 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
871 foreach ($configdata as $attribute => $value) {
872 if (in_array($attribute, $attrstotransform)) {
873 $configdata[$attribute] = $this->contenttransformer->process($value);
876 $blockrec->configdata = base64_encode(serialize((object)$configdata));
878 // Get the version of the block
879 $blockrec->version = $DB->get_field('block', 'version', array('name' => $this->task->get_blockname()));
883 $block->set_source_array(array($blockrec));
885 $positions->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
887 // Return the root element (block)
893 * structure step in charge of constructing the logs.xml file for all the log records found
896 class backup_activity_logs_structure_step extends backup_structure_step {
898 protected function define_structure() {
900 // Define each element separated
902 $logs = new backup_nested_element('logs');
904 $log = new backup_nested_element('log', array('id'), array(
905 'time', 'userid', 'ip', 'module',
906 'action', 'url', 'info'));
910 $logs->add_child($log);
914 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
917 // NOTE: We don't annotate users from logs as far as they MUST be
918 // always annotated by the activity.
920 // Return the root element (logs)
927 * structure in charge of constructing the inforef.xml file for all the items we want
928 * to have referenced there (users, roles, files...)
930 class backup_inforef_structure_step extends backup_structure_step {
932 protected function define_structure() {
934 // Items we want to include in the inforef file. NOTE: Important to keep this
935 // list 100% sync with the one in next step! Until we get better place for it (backup:CONST)
936 $items = array('user', 'grouping', 'group', 'role', 'file', 'scale', 'outcome', 'grade_item');
940 $inforef = new backup_nested_element('inforef');
942 // For each item, conditionally, if there are already records, build element
943 foreach ($items as $itemname) {
944 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
945 $elementroot = new backup_nested_element($itemname . 'ref');
946 $element = new backup_nested_element($itemname, array('id'));
947 $inforef->add_child($elementroot);
948 $elementroot->add_child($element);
949 $element->set_source_sql("
951 FROM {backup_ids_temp}
954 array(backup::VAR_BACKUPID, $this->is_sqlparam($itemname)));
958 // We don't annotate anything there, but rely in the next step
959 // (move_inforef_annotations_to_final) that will change all the
960 // already saved 'inforref' entries to their 'final' annotations.
966 * This step will get all the annotations already processed to inforef.xml file and
967 * transform them into 'final' annotations.
969 class move_inforef_annotations_to_final extends backup_execution_step {
971 protected function define_execution() {
973 // Items we want to include in the inforef file. NOTE: Important to keep this
974 // list 100% sync with the one in prev step! Until we get better place for it (backup:CONST)
975 $items = array('user', 'grouping', 'group', 'role', 'file', 'scale', 'outcome', 'grade_item');
976 foreach ($items as $itemname) {
978 backup_structure_dbops::move_annotations_to_final($this->get_backupid(), $itemname);
984 * structure in charge of constructing the files.xml file with all the
985 * annotated (final) files along the process. At, the same time, and
986 * using one specialised nested_element, will copy them form moodle storage
989 class backup_final_files_structure_step extends backup_structure_step {
991 protected function define_structure() {
995 $files = new backup_nested_element('files');
997 $file = new file_nested_element('file', array('id'), array(
998 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
999 'filepath', 'filename', 'userid', 'filesize',
1000 'mimetype', 'status', 'timecreated', 'timemodified',
1001 'source', 'author', 'license', 'sortorder'));
1005 $files->add_child($file);
1009 $file->set_source_sql("SELECT f.*
1011 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1012 WHERE bi.backupid = ?
1013 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1020 * Structure step in charge of creating the main moodle_backup.xml file
1021 * where all the information related to the backup, settings, license and
1022 * other information needed on restore is added*/
1023 class backup_main_structure_step extends backup_structure_step {
1025 protected function define_structure() {
1031 $info['name'] = $this->get_setting_value('filename');
1032 $info['moodle_version'] = $CFG->version;
1033 $info['moodle_release'] = $CFG->release;
1034 $info['backup_version'] = $CFG->backup_version;
1035 $info['backup_release'] = $CFG->backup_release;
1036 $info['backup_date'] = time();
1037 $info['backup_uniqueid']= $this->get_backupid();
1038 $info['original_wwwroot']=$CFG->wwwroot;
1039 $info['original_site_identifier'] = get_site_identifier();
1040 $info['original_course_id'] = $this->get_courseid();
1042 // Get more information from controller
1043 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid());
1047 $moodle_backup = new backup_nested_element('moodle_backup');
1049 $information = new backup_nested_element('information', null, array(
1050 'name', 'moodle_version', 'moodle_release', 'backup_version',
1051 'backup_release', 'backup_date', 'original_wwwroot',
1052 'original_site_identifier', 'original_course_id'));
1054 $details = new backup_nested_element('details');
1056 $detail = new backup_nested_element('detail', array('backup_id'), array(
1057 'type', 'format', 'interactive', 'mode',
1058 'execution', 'executiontime'));
1060 $contents = new backup_nested_element('contents');
1062 $activities = new backup_nested_element('activities');
1064 $activity = new backup_nested_element('activity', null, array(
1065 'moduleid', 'sectionid', 'modulename', 'title',
1068 $sections = new backup_nested_element('sections');
1070 $section = new backup_nested_element('section', null, array(
1071 'sectionid', 'title', 'directory'));
1073 $course = new backup_nested_element('course', null, array(
1074 'courseid', 'title', 'directory'));
1076 $settings = new backup_nested_element('settings');
1078 $setting = new backup_nested_element('setting', null, array(
1079 'level', 'activity', 'name', 'value'));
1083 $moodle_backup->add_child($information);
1085 $information->add_child($details);
1086 $details->add_child($detail);
1088 $information->add_child($contents);
1089 if (!empty($cinfo['activities'])) {
1090 $contents->add_child($activities);
1091 $activities->add_child($activity);
1093 if (!empty($cinfo['sections'])) {
1094 $contents->add_child($sections);
1095 $sections->add_child($section);
1097 if (!empty($cinfo['course'])) {
1098 $contents->add_child($course);
1101 $information->add_child($settings);
1102 $settings->add_child($setting);
1107 $information->set_source_array(array((object)$info));
1109 $detail->set_source_array($dinfo);
1111 $activity->set_source_array($cinfo['activities']);
1113 $section->set_source_array($cinfo['sections']);
1115 $course->set_source_array($cinfo['course']);
1117 $setting->set_source_array($sinfo);
1119 // Prepare some information to be sent to main moodle_backup.xml file
1120 return $moodle_backup;
1126 * Execution step that will generate the final zip file with all the contents
1128 class backup_zip_contents extends backup_execution_step {
1130 protected function define_execution() {
1133 $basepath = $this->get_basepath();
1135 // Get the list of files in directory
1136 $filestemp = get_directory_list($basepath, '', false, true, true);
1138 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1139 $files[$file] = $basepath . '/' . $file;
1142 // Add the log file if exists
1143 $logfilepath = $basepath . '.log';
1144 if (file_exists($logfilepath)) {
1145 $files['moodle_backup.log'] = $logfilepath;
1148 // Calculate the zip fullpath (in OS temp area it's always backup.zip)
1149 $zipfile = $basepath . '/backup.zip';
1151 // Get the zip packer
1152 $zippacker = get_file_packer('application/zip');
1155 $zippacker->archive_to_pathname($files, $zipfile);
1160 * This step will send the generated backup file to its final destination
1162 class backup_store_backup_file extends backup_execution_step {
1164 protected function define_execution() {
1167 $basepath = $this->get_basepath();
1169 // Calculate the zip fullpath (in OS temp area it's always backup.zip)
1170 $zipfile = $basepath . '/backup.zip';
1172 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1173 return array('backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile));
1179 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1180 * and put them to the backup_ids tables, to be used later as base to backup them
1182 class backup_activity_grade_items_to_ids extends backup_execution_step {
1184 protected function define_execution() {
1186 // Fetch all activity grade items
1187 if ($items = grade_item::fetch_all(array(
1188 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1189 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1190 // Annotate them in backup_ids
1191 foreach ($items as $item) {
1192 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1199 * This step will annotate all the groups belonging to already annotated groupings
1201 class backup_annotate_groups_from_groupings extends backup_execution_step {
1203 protected function define_execution() {
1206 // Fetch all the annotated groupings
1207 if ($groupings = $DB->get_records('backup_ids_temp', array(
1208 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1209 foreach ($groupings as $grouping) {
1210 if ($groups = $DB->get_records('groupings_groups', array(
1211 'groupingid' => $grouping->itemid))) {
1212 foreach ($groups as $group) {
1213 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1222 * This step will annotate all the scales belonging to already annotated outcomes
1224 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1226 protected function define_execution() {
1229 // Fetch all the annotated outcomes
1230 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1231 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1232 foreach ($outcomes as $outcome) {
1233 if ($scale = $DB->get_record('grade_outcomes', array(
1234 'id' => $outcome->itemid))) {
1235 // Annotate as scalefinal because it's > 0
1236 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1244 * This step will generate all the user annotations for the already
1245 * annottated (final) users. Need to do this here because each user
1246 * has its own context and structure tasks only are able to handle
1247 * one context. Also, this step will guarantee that every user has
1248 * its context created (req for other steps)
1250 class backup_annotate_all_user_files extends backup_execution_step {
1252 protected function define_execution() {
1255 // List of fileareas we are going to annotate
1256 // TODO: user image not implemented yet
1257 $fileareas = array('private', 'profile', 'image');
1259 // Fetch all annotated (final) users
1260 $rs = $DB->get_recordset('backup_ids_temp', array(
1261 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1262 foreach ($rs as $record) {
1263 $userid = $record->itemid;
1264 $userctxid = get_context_instance(CONTEXT_USER, $userid)->id;
1265 // Proceed with every user filearea
1266 foreach ($fileareas as $filearea) {
1267 // We don't need to specify itemid ($userid - 4th param) as far as by
1268 // context we can get all the associated files. See MDL-22092
1269 backup_structure_dbops::annotate_files($this->get_backupid(), $userctxid, 'user', $filearea, null);
1277 * structure step in charge of constructing the grades.xml file for all the grade items
1278 * and letters related to one activity
1280 class backup_activity_grades_structure_step extends backup_structure_step {
1282 protected function define_structure() {
1284 // To know if we are including userinfo
1285 $userinfo = $this->get_setting_value('userinfo');
1287 // Define each element separated
1289 $book = new backup_nested_element('activity_gradebook');
1291 $items = new backup_nested_element('grade_items');
1293 $item = new backup_nested_element('grade_item', array('id'), array(
1294 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1295 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1296 'calculation', 'gradetype', 'grademax', 'grademin',
1297 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1298 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
1299 'decimals', 'hidden', 'locked', 'locktime',
1300 'needsupdate', 'timecreated', 'timemodified'));
1302 $grades = new backup_nested_element('grade_grades');
1304 $grade = new backup_nested_element('grade_grade', array('id'), array(
1305 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1306 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1307 'locked', 'locktime', 'exported', 'overridden',
1308 'excluded', 'feedback', 'feedbackformat', 'information',
1309 'informationformat', 'timecreated', 'timemodified'));
1311 $letters = new backup_nested_element('grade_letters');
1313 $letter = new backup_nested_element('grade_letter', 'id', array(
1314 'lowerboundary', 'letter'));
1318 $book->add_child($items);
1319 $items->add_child($item);
1321 $item->add_child($grades);
1322 $grades->add_child($grade);
1324 $book->add_child($letters);
1325 $letters->add_child($letter);
1329 $item->set_source_sql("
1331 FROM {grade_items} gi
1332 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
1333 WHERE bi.backupid = ?
1334 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
1336 // This only happens if we are including user info
1338 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1341 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1345 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1346 $item->annotate_ids('outcome', 'outcomeid');
1348 $grade->annotate_ids('user', 'userid');
1349 $grade->annotate_ids('user', 'usermodified');
1351 // Return the root element (book)