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/>.
19 * Defines various backup steps that will be used by common tasks in backup
21 * @package core_backup
24 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
31 * create the temp dir where backup/restore will happen,
32 * delete old directories and create temp ids table
34 class create_and_clean_temp_stuff extends backup_execution_step {
36 protected function define_execution() {
37 backup_helper::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
38 backup_helper::clear_backup_dir($this->get_backupid()); // Empty temp dir, just in case
39 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
40 backup_controller_dbops::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
45 * delete the temp dir used by backup/restore (conditionally),
46 * delete old directories and drop tem ids table. Note we delete
47 * the directory but not the corresponding log file that will be
48 * there for, at least, 4 hours - only delete_old_backup_dirs()
49 * deletes log files (for easier access to them)
51 class drop_and_clean_temp_stuff extends backup_execution_step {
53 protected $skipcleaningtempdir = false;
55 protected function define_execution() {
58 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
59 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
60 // Delete temp dir conditionally:
61 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
62 // 2) If backup temp dir deletion has been marked to be avoided
63 if (empty($CFG->keeptempdirectoriesonbackup) && !$this->skipcleaningtempdir) {
64 backup_helper::delete_backup_dir($this->get_backupid()); // Empty backup dir
68 public function skip_cleaning_temp_dir($skip) {
69 $this->skipcleaningtempdir = $skip;
74 * Create the directory where all the task (activity/block...) information will be stored
76 class create_taskbasepath_directory extends backup_execution_step {
78 protected function define_execution() {
80 $basepath = $this->task->get_taskbasepath();
81 if (!check_dir_exists($basepath, true, true)) {
82 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
88 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
89 * activity structure definition within the main <activity ...> tag. Also provides
90 * subplugin support for activities (that must be properly declared)
92 abstract class backup_activity_structure_step extends backup_structure_step {
95 * Add subplugin structure to any element in the activity backup tree
97 * @param string $subplugintype type of subplugin as defined in activity db/subplugins.php
98 * @param backup_nested_element $element element in the activity backup tree that
99 * we are going to add subplugin information to
100 * @param bool $multiple to define if multiple subplugins can produce information
101 * for each instance of $element (true) or no (false)
104 protected function add_subplugin_structure($subplugintype, $element, $multiple) {
108 // Check the requested subplugintype is a valid one
109 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
110 if (!file_exists($subpluginsfile)) {
111 throw new backup_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
113 include($subpluginsfile);
114 if (!array_key_exists($subplugintype, $subplugins)) {
115 throw new backup_step_exception('incorrect_subplugin_type', $subplugintype);
118 // Arrived here, subplugin is correct, let's create the optigroup
119 $optigroupname = $subplugintype . '_' . $element->get_name() . '_subplugin';
120 $optigroup = new backup_optigroup($optigroupname, null, $multiple);
121 $element->add_child($optigroup); // Add optigroup to stay connected since beginning
123 // Get all the optigroup_elements, looking across all the subplugin dirs
124 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
125 foreach ($subpluginsdirs as $name => $subpluginsdir) {
126 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
127 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
128 if (file_exists($backupfile)) {
129 require_once($backupfile);
130 $backupsubplugin = new $classname($subplugintype, $name, $optigroup, $this);
131 // Add subplugin returned structure to optigroup
132 $backupsubplugin->define_subplugin_structure($element->get_name());
138 * As far as activity backup steps are implementing backup_subplugin stuff, they need to
139 * have the parent task available for wrapping purposes (get course/context....)
141 * @return backup_activity_task
143 public function get_task() {
148 * Wraps any activity backup structure within the common 'activity' element
149 * that will include common to all activities information like id, context...
151 * @param backup_nested_element $activitystructure the element to wrap
152 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
154 protected function prepare_activity_structure($activitystructure) {
156 // Create the wrap element
157 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
160 $activity->add_child($activitystructure);
163 $activityarr = array((object)array(
164 'id' => $this->task->get_activityid(),
165 'moduleid' => $this->task->get_moduleid(),
166 'modulename' => $this->task->get_modulename(),
167 'contextid' => $this->task->get_contextid()));
169 $activity->set_source_array($activityarr);
171 // Return the root element (activity)
177 * Abstract structure step, to be used by all the activities using core questions stuff
178 * (namely quiz module), supporting question plugins, states and sessions
180 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
183 * Attach to $element (usually attempts) the needed backup structures
184 * for question_usages and all the associated data.
186 * @param backup_nested_element $element the element that will contain all the question_usages data.
187 * @param string $usageidname the name of the element that holds the usageid.
188 * This must be child of $element, and must be a final element.
189 * @param string $nameprefix this prefix is added to all the element names we create.
190 * Element names in the XML must be unique, so if you are using usages in
191 * two different ways, you must give a prefix to at least one of them. If
192 * you only use one sort of usage, then you can just use the default empty prefix.
193 * This should include a trailing underscore. For example "myprefix_"
195 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
197 require_once($CFG->dirroot . '/question/engine/lib.php');
199 // Check $element is one nested_backup_element
200 if (! $element instanceof backup_nested_element) {
201 throw new backup_step_exception('question_states_bad_parent_element', $element);
203 if (! $element->get_final_element($usageidname)) {
204 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
207 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
208 array('component', 'preferredbehaviour'));
210 $qas = new backup_nested_element($nameprefix . 'question_attempts');
211 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
212 'slot', 'behaviour', 'questionid', 'maxmark', 'minfraction',
213 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
216 $steps = new backup_nested_element($nameprefix . 'steps');
217 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
218 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
220 $response = new backup_nested_element($nameprefix . 'response');
221 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
224 $element->add_child($quba);
225 $quba->add_child($qas);
226 $qas->add_child($qa);
227 $qa->add_child($steps);
228 $steps->add_child($step);
229 $step->add_child($response);
230 $response->add_child($variable);
233 $quba->set_source_table('question_usages',
234 array('id' => '../' . $usageidname));
235 $qa->set_source_table('question_attempts', array('questionusageid' => backup::VAR_PARENTID), 'slot ASC');
236 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup::VAR_PARENTID), 'sequencenumber ASC');
237 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup::VAR_PARENTID));
240 $qa->annotate_ids('question', 'questionid');
241 $step->annotate_ids('user', 'userid');
244 $fileareas = question_engine::get_all_response_file_areas();
245 foreach ($fileareas as $filearea) {
246 $step->annotate_files('question', $filearea, 'id');
253 * backup structure step in charge of calculating the categories to be
254 * included in backup, based in the context being backuped (module/course)
255 * and the already annotated questions present in backup_ids_temp
257 class backup_calculate_question_categories extends backup_execution_step {
259 protected function define_execution() {
260 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
265 * backup structure step in charge of deleting all the questions annotated
266 * in the backup_ids_temp table
268 class backup_delete_temp_questions extends backup_execution_step {
270 protected function define_execution() {
271 backup_question_dbops::delete_temp_questions($this->get_backupid());
276 * Abstract structure step, parent of all the block structure steps. Used to wrap the
277 * block structure definition within the main <block ...> tag
279 abstract class backup_block_structure_step extends backup_structure_step {
281 protected function prepare_block_structure($blockstructure) {
283 // Create the wrap element
284 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
287 $block->add_child($blockstructure);
290 $blockarr = array((object)array(
291 'id' => $this->task->get_blockid(),
292 'blockname' => $this->task->get_blockname(),
293 'contextid' => $this->task->get_contextid()));
295 $block->set_source_array($blockarr);
297 // Return the root element (block)
303 * structure step that will generate the module.xml file for the activity,
304 * accumulating various information about the activity, annotating groupings
305 * and completion/avail conf
307 class backup_module_structure_step extends backup_structure_step {
309 protected function define_structure() {
312 // Define each element separated
314 $module = new backup_nested_element('module', array('id', 'version'), array(
315 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
316 'added', 'score', 'indent', 'visible',
317 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
318 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
319 'availablefrom', 'availableuntil', 'showavailability', 'showdescription'));
321 $availinfo = new backup_nested_element('availability_info');
322 $availability = new backup_nested_element('availability', array('id'), array(
323 'sourcecmid', 'requiredcompletion', 'gradeitemid', 'grademin', 'grademax'));
324 $availabilityfield = new backup_nested_element('availability_field', array('id'), array(
325 'userfield', 'customfield', 'customfieldtype', 'operator', 'value'));
327 // attach format plugin structure to $module element, only one allowed
328 $this->add_plugin_structure('format', $module, false);
330 // attach plagiarism plugin structure to $module element, there can be potentially
331 // many plagiarism plugins storing information about this course
332 $this->add_plugin_structure('plagiarism', $module, true);
334 // attach local plugin structure to $module, multiple allowed
335 $this->add_plugin_structure('local', $module, true);
338 $module->add_child($availinfo);
339 $availinfo->add_child($availability);
340 $availinfo->add_child($availabilityfield);
343 $concat = $DB->sql_concat("'mod_'", 'm.name');
344 $module->set_source_sql("
345 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
346 FROM {course_modules} cm
347 JOIN {modules} m ON m.id = cm.module
348 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
349 JOIN {course_sections} s ON s.id = cm.section
350 WHERE cm.id = ?", array(backup::VAR_MODID));
352 $availability->set_source_table('course_modules_availability', array('coursemoduleid' => backup::VAR_MODID));
353 $availabilityfield->set_source_sql('
354 SELECT cmaf.*, uif.shortname AS customfield, uif.datatype AS customfieldtype
355 FROM {course_modules_avail_fields} cmaf
356 LEFT JOIN {user_info_field} uif ON uif.id = cmaf.customfieldid
357 WHERE cmaf.coursemoduleid = ?', array(backup::VAR_MODID));
359 // Define annotations
360 $module->annotate_ids('grouping', 'groupingid');
362 // Return the root element ($module)
368 * structure step that will generate the section.xml file for the section
371 class backup_section_structure_step extends backup_structure_step {
373 protected function define_structure() {
375 // Define each element separated
377 $section = new backup_nested_element('section', array('id'), array(
378 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
379 'availablefrom', 'availableuntil', 'showavailability', 'groupingid'));
381 // attach format plugin structure to $section element, only one allowed
382 $this->add_plugin_structure('format', $section, false);
384 // attach local plugin structure to $section element, multiple allowed
385 $this->add_plugin_structure('local', $section, true);
387 // Add nested elements for _availability table
388 $avail = new backup_nested_element('availability', array('id'), array(
389 'sourcecmid', 'requiredcompletion', 'gradeitemid', 'grademin', 'grademax'));
390 $availfield = new backup_nested_element('availability_field', array('id'), array(
391 'userfield', 'operator', 'value', 'customfield', 'customfieldtype'));
392 $section->add_child($avail);
393 $section->add_child($availfield);
395 // Add nested elements for course_format_options table
396 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
397 'format', 'name', 'value'));
398 $section->add_child($formatoptions);
401 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
402 $avail->set_source_table('course_sections_availability', array('coursesectionid' => backup::VAR_SECTIONID));
403 $availfield->set_source_sql('
404 SELECT csaf.*, uif.shortname AS customfield, uif.datatype AS customfieldtype
405 FROM {course_sections_avail_fields} csaf
406 LEFT JOIN {user_info_field} uif ON uif.id = csaf.customfieldid
407 WHERE csaf.coursesectionid = ?', array(backup::VAR_SECTIONID));
408 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
410 JOIN {course_format_options} cfo
411 ON cfo.courseid = c.id AND cfo.format = c.format
412 WHERE c.id = ? AND cfo.sectionid = ?',
413 array(backup::VAR_COURSEID, backup::VAR_SECTIONID));
416 $section->set_source_alias('section', 'number');
419 $section->annotate_ids('grouping', 'groupingid');
420 $section->annotate_files('course', 'section', 'id');
427 * structure step that will generate the course.xml file for the course, including
428 * course category reference, tags, modules restriction information
429 * and some annotations (files & groupings)
431 class backup_course_structure_step extends backup_structure_step {
433 protected function define_structure() {
436 // Define each element separated
438 $course = new backup_nested_element('course', array('id', 'contextid'), array(
439 'shortname', 'fullname', 'idnumber',
440 'summary', 'summaryformat', 'format', 'showgrades',
441 'newsitems', 'startdate',
442 'marker', 'maxbytes', 'legacyfiles', 'showreports',
443 'visible', 'groupmode', 'groupmodeforce',
444 'defaultgroupingid', 'lang', 'theme',
445 'timecreated', 'timemodified',
447 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
449 $category = new backup_nested_element('category', array('id'), array(
450 'name', 'description'));
452 $tags = new backup_nested_element('tags');
454 $tag = new backup_nested_element('tag', array('id'), array(
457 // attach format plugin structure to $course element, only one allowed
458 $this->add_plugin_structure('format', $course, false);
460 // attach theme plugin structure to $course element; multiple themes can
461 // save course data (in case of user theme, legacy theme, etc)
462 $this->add_plugin_structure('theme', $course, true);
464 // attach general report plugin structure to $course element; multiple
465 // reports can save course data if required
466 $this->add_plugin_structure('report', $course, true);
468 // attach course report plugin structure to $course element; multiple
469 // course reports can save course data if required
470 $this->add_plugin_structure('coursereport', $course, true);
472 // attach plagiarism plugin structure to $course element, there can be potentially
473 // many plagiarism plugins storing information about this course
474 $this->add_plugin_structure('plagiarism', $course, true);
476 // attach local plugin structure to $course element; multiple local plugins
477 // can save course data if required
478 $this->add_plugin_structure('local', $course, true);
482 $course->add_child($category);
484 $course->add_child($tags);
485 $tags->add_child($tag);
489 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
490 $courserec->contextid = $this->task->get_contextid();
492 $formatoptions = course_get_format($courserec)->get_format_options();
493 $course->add_final_elements(array_keys($formatoptions));
494 foreach ($formatoptions as $key => $value) {
495 $courserec->$key = $value;
498 $course->set_source_array(array($courserec));
500 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
502 $category->set_source_array(array($categoryrec));
504 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
506 JOIN {tag_instance} ti ON ti.tagid = t.id
507 WHERE ti.itemtype = ?
508 AND ti.itemid = ?', array(
509 backup_helper::is_sqlparam('course'),
510 backup::VAR_PARENTID));
514 $course->annotate_ids('grouping', 'defaultgroupingid');
516 $course->annotate_files('course', 'summary', null);
517 $course->annotate_files('course', 'overviewfiles', null);
518 $course->annotate_files('course', 'legacy', null);
520 // Return root element ($course)
527 * structure step that will generate the enrolments.xml file for the given course
529 class backup_enrolments_structure_step extends backup_structure_step {
531 protected function define_structure() {
533 // To know if we are including users
534 $users = $this->get_setting_value('users');
536 // Define each element separated
538 $enrolments = new backup_nested_element('enrolments');
540 $enrols = new backup_nested_element('enrols');
542 $enrol = new backup_nested_element('enrol', array('id'), array(
543 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
544 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
545 'password', 'cost', 'currency', 'roleid',
546 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
547 'customchar1', 'customchar2', 'customchar3',
548 'customdec1', 'customdec2',
549 'customtext1', 'customtext2', 'customtext3', 'customtext4',
550 'timecreated', 'timemodified'));
552 $userenrolments = new backup_nested_element('user_enrolments');
554 $enrolment = new backup_nested_element('enrolment', array('id'), array(
555 'status', 'userid', 'timestart', 'timeend', 'modifierid',
559 $enrolments->add_child($enrols);
560 $enrols->add_child($enrol);
561 $enrol->add_child($userenrolments);
562 $userenrolments->add_child($enrolment);
564 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
565 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
567 // User enrolments only added only if users included
569 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
570 $enrolment->annotate_ids('user', 'userid');
573 $enrol->annotate_ids('role', 'roleid');
575 //TODO: let plugins annotate custom fields too and add more children
582 * structure step that will generate the roles.xml file for the given context, observing
583 * the role_assignments setting to know if that part needs to be included
585 class backup_roles_structure_step extends backup_structure_step {
587 protected function define_structure() {
589 // To know if we are including role assignments
590 $roleassignments = $this->get_setting_value('role_assignments');
592 // Define each element separated
594 $roles = new backup_nested_element('roles');
596 $overrides = new backup_nested_element('role_overrides');
598 $override = new backup_nested_element('override', array('id'), array(
599 'roleid', 'capability', 'permission', 'timemodified',
602 $assignments = new backup_nested_element('role_assignments');
604 $assignment = new backup_nested_element('assignment', array('id'), array(
605 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
609 $roles->add_child($overrides);
610 $roles->add_child($assignments);
612 $overrides->add_child($override);
613 $assignments->add_child($assignment);
617 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
619 // Assignments only added if specified
620 if ($roleassignments) {
621 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
624 // Define id annotations
625 $override->annotate_ids('role', 'roleid');
627 $assignment->annotate_ids('role', 'roleid');
629 $assignment->annotate_ids('user', 'userid');
631 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
638 * structure step that will generate the roles.xml containing the
639 * list of roles used along the whole backup process. Just raw
640 * list of used roles from role table
642 class backup_final_roles_structure_step extends backup_structure_step {
644 protected function define_structure() {
648 $rolesdef = new backup_nested_element('roles_definition');
650 $role = new backup_nested_element('role', array('id'), array(
651 'name', 'shortname', 'nameincourse', 'description',
652 'sortorder', 'archetype'));
656 $rolesdef->add_child($role);
660 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
662 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
663 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
664 WHERE bi.backupid = ?
665 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
667 // Return main element (rolesdef)
673 * structure step that will generate the scales.xml containing the
674 * list of scales used along the whole backup process.
676 class backup_final_scales_structure_step extends backup_structure_step {
678 protected function define_structure() {
682 $scalesdef = new backup_nested_element('scales_definition');
684 $scale = new backup_nested_element('scale', array('id'), array(
685 'courseid', 'userid', 'name', 'scale',
686 'description', 'descriptionformat', 'timemodified'));
690 $scalesdef->add_child($scale);
694 $scale->set_source_sql("SELECT s.*
696 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
697 WHERE bi.backupid = ?
698 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
700 // Annotate scale files (they store files in system context, so pass it instead of default one)
701 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
703 // Return main element (scalesdef)
709 * structure step that will generate the outcomes.xml containing the
710 * list of outcomes used along the whole backup process.
712 class backup_final_outcomes_structure_step extends backup_structure_step {
714 protected function define_structure() {
718 $outcomesdef = new backup_nested_element('outcomes_definition');
720 $outcome = new backup_nested_element('outcome', array('id'), array(
721 'courseid', 'userid', 'shortname', 'fullname',
722 'scaleid', 'description', 'descriptionformat', 'timecreated',
723 'timemodified','usermodified'));
727 $outcomesdef->add_child($outcome);
731 $outcome->set_source_sql("SELECT o.*
732 FROM {grade_outcomes} o
733 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
734 WHERE bi.backupid = ?
735 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
737 // Annotate outcome files (they store files in system context, so pass it instead of default one)
738 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
740 // Return main element (outcomesdef)
746 * structure step in charge of constructing the filters.xml file for all the filters found
749 class backup_filters_structure_step extends backup_structure_step {
751 protected function define_structure() {
753 // Define each element separated
755 $filters = new backup_nested_element('filters');
757 $actives = new backup_nested_element('filter_actives');
759 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
761 $configs = new backup_nested_element('filter_configs');
763 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
767 $filters->add_child($actives);
768 $filters->add_child($configs);
770 $actives->add_child($active);
771 $configs->add_child($config);
775 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
777 $active->set_source_array($activearr);
778 $config->set_source_array($configarr);
780 // Return the root element (filters)
786 * structure step in charge of constructing the comments.xml file for all the comments found
789 class backup_comments_structure_step extends backup_structure_step {
791 protected function define_structure() {
793 // Define each element separated
795 $comments = new backup_nested_element('comments');
797 $comment = new backup_nested_element('comment', array('id'), array(
798 'commentarea', 'itemid', 'content', 'format',
799 'userid', 'timecreated'));
803 $comments->add_child($comment);
807 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
809 // Define id annotations
811 $comment->annotate_ids('user', 'userid');
813 // Return the root element (comments)
819 * structure step in charge of constructing the badges.xml file for all the badges found
822 class backup_badges_structure_step extends backup_structure_step {
824 protected function execute_condition() {
825 // Check that all activities have been included.
826 if ($this->task->is_excluding_activities()) {
832 protected function define_structure() {
834 // Define each element separated.
836 $badges = new backup_nested_element('badges');
837 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
838 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
839 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
840 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron'));
842 $criteria = new backup_nested_element('criteria');
843 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
844 'criteriatype', 'method'));
846 $parameters = new backup_nested_element('parameters');
847 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
848 'name', 'value', 'criteriatype'));
850 $manual_awards = new backup_nested_element('manual_awards');
851 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
852 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
856 $badges->add_child($badge);
857 $badge->add_child($criteria);
858 $criteria->add_child($criterion);
859 $criterion->add_child($parameters);
860 $parameters->add_child($parameter);
861 $badge->add_child($manual_awards);
862 $manual_awards->add_child($manual_award);
866 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
867 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
869 $parametersql = 'SELECT cp.*, c.criteriatype
870 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
872 WHERE critid = :critid';
873 $parameterparams = array('critid' => backup::VAR_PARENTID);
874 $parameter->set_source_sql($parametersql, $parameterparams);
876 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
878 // Define id annotations.
880 $badge->annotate_ids('user', 'usercreated');
881 $badge->annotate_ids('user', 'usermodified');
882 $criterion->annotate_ids('badge', 'badgeid');
883 $parameter->annotate_ids('criterion', 'critid');
884 $badge->annotate_files('badges', 'badgeimage', 'id');
885 $manual_award->annotate_ids('badge', 'badgeid');
886 $manual_award->annotate_ids('user', 'recipientid');
887 $manual_award->annotate_ids('user', 'issuerid');
888 $manual_award->annotate_ids('role', 'issuerrole');
890 // Return the root element ($badges).
896 * structure step in charge of constructing the calender.xml file for all the events found
899 class backup_calendarevents_structure_step extends backup_structure_step {
901 protected function define_structure() {
903 // Define each element separated
905 $events = new backup_nested_element('events');
907 $event = new backup_nested_element('event', array('id'), array(
908 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
909 'repeatid', 'modulename', 'instance', 'eventtype', 'timestart',
910 'timeduration', 'visible', 'uuid', 'sequence', 'timemodified'));
913 $events->add_child($event);
916 if ($this->name == 'course_calendar') {
917 $calendar_items_sql ="SELECT * FROM {event}
918 WHERE courseid = :courseid
919 AND (eventtype = 'course' OR eventtype = 'group')";
920 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
921 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
923 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
926 // Define id annotations
928 $event->annotate_ids('user', 'userid');
929 $event->annotate_ids('group', 'groupid');
930 $event->annotate_files('calendar', 'event_description', 'id');
932 // Return the root element (events)
938 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
939 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
941 class backup_gradebook_structure_step extends backup_structure_step {
944 * We need to decide conditionally, based on dynamic information
945 * about the execution of this step. Only will be executed if all
946 * the module gradeitems have been already included in backup
948 protected function execute_condition() {
949 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
952 protected function define_structure() {
954 // are we including user info?
955 $userinfo = $this->get_setting_value('users');
957 $gradebook = new backup_nested_element('gradebook');
959 //grade_letters are done in backup_activity_grades_structure_step()
961 //calculated grade items
962 $grade_items = new backup_nested_element('grade_items');
963 $grade_item = new backup_nested_element('grade_item', array('id'), array(
964 'categoryid', 'itemname', 'itemtype', 'itemmodule',
965 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
966 'calculation', 'gradetype', 'grademax', 'grademin',
967 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
968 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
969 'decimals', 'hidden', 'locked', 'locktime',
970 'needsupdate', 'timecreated', 'timemodified'));
972 $grade_grades = new backup_nested_element('grade_grades');
973 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
974 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
975 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
976 'locked', 'locktime', 'exported', 'overridden',
977 'excluded', 'feedback', 'feedbackformat', 'information',
978 'informationformat', 'timecreated', 'timemodified'));
981 $grade_categories = new backup_nested_element('grade_categories');
982 $grade_category = new backup_nested_element('grade_category', array('id'), array(
984 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
985 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
986 'timecreated', 'timemodified', 'hidden'));
988 $letters = new backup_nested_element('grade_letters');
989 $letter = new backup_nested_element('grade_letter', 'id', array(
990 'lowerboundary', 'letter'));
992 $grade_settings = new backup_nested_element('grade_settings');
993 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
998 $gradebook->add_child($grade_categories);
999 $grade_categories->add_child($grade_category);
1001 $gradebook->add_child($grade_items);
1002 $grade_items->add_child($grade_item);
1003 $grade_item->add_child($grade_grades);
1004 $grade_grades->add_child($grade_grade);
1006 $gradebook->add_child($letters);
1007 $letters->add_child($letter);
1009 $gradebook->add_child($grade_settings);
1010 $grade_settings->add_child($grade_setting);
1014 //Include manual, category and the course grade item
1015 $grade_items_sql ="SELECT * FROM {grade_items}
1016 WHERE courseid = :courseid
1017 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1018 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
1019 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1022 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1025 $grade_category_sql = "SELECT gc.*, gi.sortorder
1026 FROM {grade_categories} gc
1027 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1028 WHERE gc.courseid = :courseid
1029 AND (gi.itemtype='course' OR gi.itemtype='category')
1030 ORDER BY gc.parent ASC";//need parent categories before their children
1031 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1032 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1034 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1036 $grade_setting->set_source_table('grade_settings', array('courseid' => backup::VAR_COURSEID));
1038 // Annotations (both as final as far as they are going to be exported in next steps)
1039 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1040 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1042 //just in case there are any users not already annotated by the activities
1043 $grade_grade->annotate_ids('userfinal', 'userid');
1045 // Return the root element
1051 * structure step in charge if constructing the completion.xml file for all the users completion
1052 * information in a given activity
1054 class backup_userscompletion_structure_step extends backup_structure_step {
1056 protected function define_structure() {
1058 // Define each element separated
1060 $completions = new backup_nested_element('completions');
1062 $completion = new backup_nested_element('completion', array('id'), array(
1063 'userid', 'completionstate', 'viewed', 'timemodified'));
1067 $completions->add_child($completion);
1071 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1073 // Define id annotations
1075 $completion->annotate_ids('user', 'userid');
1077 // Return the root element (completions)
1078 return $completions;
1083 * structure step in charge of constructing the main groups.xml file for all the groups and
1084 * groupings information already annotated
1086 class backup_groups_structure_step extends backup_structure_step {
1088 protected function define_structure() {
1090 // To know if we are including users
1091 $users = $this->get_setting_value('users');
1093 // Define each element separated
1095 $groups = new backup_nested_element('groups');
1097 $group = new backup_nested_element('group', array('id'), array(
1098 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1099 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1101 $members = new backup_nested_element('group_members');
1103 $member = new backup_nested_element('group_member', array('id'), array(
1104 'userid', 'timeadded', 'component', 'itemid'));
1106 $groupings = new backup_nested_element('groupings');
1108 $grouping = new backup_nested_element('grouping', 'id', array(
1109 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1110 'timecreated', 'timemodified'));
1112 $groupinggroups = new backup_nested_element('grouping_groups');
1114 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1115 'groupid', 'timeadded'));
1119 $groups->add_child($group);
1120 $groups->add_child($groupings);
1122 $group->add_child($members);
1123 $members->add_child($member);
1125 $groupings->add_child($grouping);
1126 $grouping->add_child($groupinggroups);
1127 $groupinggroups->add_child($groupinggroup);
1131 $group->set_source_sql("
1134 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1135 WHERE bi.backupid = ?
1136 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1138 // This only happens if we are including users
1140 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1143 $grouping->set_source_sql("
1146 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1147 WHERE bi.backupid = ?
1148 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1150 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1152 // Define id annotations (as final)
1154 $member->annotate_ids('userfinal', 'userid');
1156 // Define file annotations
1158 $group->annotate_files('group', 'description', 'id');
1159 $group->annotate_files('group', 'icon', 'id');
1160 $grouping->annotate_files('grouping', 'description', 'id');
1162 // Return the root element (groups)
1168 * structure step in charge of constructing the main users.xml file for all the users already
1169 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1172 class backup_users_structure_step extends backup_structure_step {
1174 protected function define_structure() {
1177 // To know if we are anonymizing users
1178 $anonymize = $this->get_setting_value('anonymize');
1179 // To know if we are including role assignments
1180 $roleassignments = $this->get_setting_value('role_assignments');
1182 // Define each element separated
1184 $users = new backup_nested_element('users');
1186 // Create the array of user fields by hand, as far as we have various bits to control
1187 // anonymize option, password backup, mnethostid...
1189 // First, the fields not needing anonymization nor special handling
1190 $normalfields = array(
1191 'confirmed', 'policyagreed', 'deleted',
1192 'lang', 'theme', 'timezone', 'firstaccess',
1193 'lastaccess', 'lastlogin', 'currentlogin',
1194 'mailformat', 'maildigest', 'maildisplay', 'htmleditor',
1195 'autosubscribe', 'trackforums', 'timecreated',
1196 'timemodified', 'trustbitmask');
1198 // Then, the fields potentially needing anonymization
1199 $anonfields = array(
1200 'username', 'idnumber', 'email', 'icq', 'skype',
1201 'yahoo', 'aim', 'msn', 'phone1',
1202 'phone2', 'institution', 'department', 'address',
1203 'city', 'country', 'lastip', 'picture',
1204 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1205 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1207 // Add anonymized fields to $userfields with custom final element
1208 foreach ($anonfields as $field) {
1210 $userfields[] = new anonymizer_final_element($field);
1212 $userfields[] = $field; // No anonymization, normally added
1216 // mnethosturl requires special handling (custom final element)
1217 $userfields[] = new mnethosturl_final_element('mnethosturl');
1219 // password added conditionally
1220 if (!empty($CFG->includeuserpasswordsinbackup)) {
1221 $userfields[] = 'password';
1224 // Merge all the fields
1225 $userfields = array_merge($userfields, $normalfields);
1227 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1229 $customfields = new backup_nested_element('custom_fields');
1231 $customfield = new backup_nested_element('custom_field', array('id'), array(
1232 'field_name', 'field_type', 'field_data'));
1234 $tags = new backup_nested_element('tags');
1236 $tag = new backup_nested_element('tag', array('id'), array(
1237 'name', 'rawname'));
1239 $preferences = new backup_nested_element('preferences');
1241 $preference = new backup_nested_element('preference', array('id'), array(
1244 $roles = new backup_nested_element('roles');
1246 $overrides = new backup_nested_element('role_overrides');
1248 $override = new backup_nested_element('override', array('id'), array(
1249 'roleid', 'capability', 'permission', 'timemodified',
1252 $assignments = new backup_nested_element('role_assignments');
1254 $assignment = new backup_nested_element('assignment', array('id'), array(
1255 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1260 $users->add_child($user);
1262 $user->add_child($customfields);
1263 $customfields->add_child($customfield);
1265 $user->add_child($tags);
1266 $tags->add_child($tag);
1268 $user->add_child($preferences);
1269 $preferences->add_child($preference);
1271 $user->add_child($roles);
1273 $roles->add_child($overrides);
1274 $roles->add_child($assignments);
1276 $overrides->add_child($override);
1277 $assignments->add_child($assignment);
1281 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1283 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1284 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1285 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1286 WHERE bi.backupid = ?
1287 AND bi.itemname = ?', array(
1288 backup_helper::is_sqlparam($this->get_backupid()),
1289 backup_helper::is_sqlparam('userfinal')));
1291 // All the rest on information is only added if we arent
1292 // in an anonymized backup
1294 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1295 FROM {user_info_field} f
1296 JOIN {user_info_data} d ON d.fieldid = f.id
1297 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1299 $customfield->set_source_alias('shortname', 'field_name');
1300 $customfield->set_source_alias('datatype', 'field_type');
1301 $customfield->set_source_alias('data', 'field_data');
1303 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1305 JOIN {tag_instance} ti ON ti.tagid = t.id
1306 WHERE ti.itemtype = ?
1307 AND ti.itemid = ?', array(
1308 backup_helper::is_sqlparam('user'),
1309 backup::VAR_PARENTID));
1311 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1313 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1315 // Assignments only added if specified
1316 if ($roleassignments) {
1317 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1320 // Define id annotations (as final)
1321 $override->annotate_ids('rolefinal', 'roleid');
1324 // Return root element (users)
1330 * structure step in charge of constructing the block.xml file for one
1331 * given block (instance and positions). If the block has custom DB structure
1332 * that will go to a separate file (different step defined in block class)
1334 class backup_block_instance_structure_step extends backup_structure_step {
1336 protected function define_structure() {
1339 // Define each element separated
1341 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1342 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1343 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1345 $positions = new backup_nested_element('block_positions');
1347 $position = new backup_nested_element('block_position', array('id'), array(
1348 'contextid', 'pagetype', 'subpage', 'visible',
1349 'region', 'weight'));
1353 $block->add_child($positions);
1354 $positions->add_child($position);
1356 // Transform configdata information if needed (process links and friends)
1357 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1358 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1359 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1360 foreach ($configdata as $attribute => $value) {
1361 if (in_array($attribute, $attrstotransform)) {
1362 $configdata[$attribute] = $this->contenttransformer->process($value);
1365 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1367 $blockrec->contextid = $this->task->get_contextid();
1368 // Get the version of the block
1369 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1373 $block->set_source_array(array($blockrec));
1375 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1377 // File anotations (for fileareas specified on each block)
1378 foreach ($this->task->get_fileareas() as $filearea) {
1379 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1382 // Return the root element (block)
1388 * structure step in charge of constructing the logs.xml file for all the log records found
1389 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1390 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1391 * that just in case they become restored some day in the future
1393 class backup_course_logs_structure_step extends backup_structure_step {
1395 protected function define_structure() {
1397 // Define each element separated
1399 $logs = new backup_nested_element('logs');
1401 $log = new backup_nested_element('log', array('id'), array(
1402 'time', 'userid', 'ip', 'module',
1403 'action', 'url', 'info'));
1407 $logs->add_child($log);
1409 // Define sources (all the records belonging to the course, having cmid = 0)
1411 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1414 // NOTE: We don't annotate users from logs as far as they MUST be
1415 // always annotated by the course (enrol, ras... whatever)
1417 // Return the root element (logs)
1424 * structure step in charge of constructing the logs.xml file for all the log records found
1427 class backup_activity_logs_structure_step extends backup_structure_step {
1429 protected function define_structure() {
1431 // Define each element separated
1433 $logs = new backup_nested_element('logs');
1435 $log = new backup_nested_element('log', array('id'), array(
1436 'time', 'userid', 'ip', 'module',
1437 'action', 'url', 'info'));
1441 $logs->add_child($log);
1445 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1448 // NOTE: We don't annotate users from logs as far as they MUST be
1449 // always annotated by the activity (true participants).
1451 // Return the root element (logs)
1458 * structure in charge of constructing the inforef.xml file for all the items we want
1459 * to have referenced there (users, roles, files...)
1461 class backup_inforef_structure_step extends backup_structure_step {
1463 protected function define_structure() {
1465 // Items we want to include in the inforef file.
1466 $items = backup_helper::get_inforef_itemnames();
1470 $inforef = new backup_nested_element('inforef');
1472 // For each item, conditionally, if there are already records, build element
1473 foreach ($items as $itemname) {
1474 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1475 $elementroot = new backup_nested_element($itemname . 'ref');
1476 $element = new backup_nested_element($itemname, array(), array('id'));
1477 $inforef->add_child($elementroot);
1478 $elementroot->add_child($element);
1479 $element->set_source_sql("
1481 FROM {backup_ids_temp}
1484 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1488 // We don't annotate anything there, but rely in the next step
1489 // (move_inforef_annotations_to_final) that will change all the
1490 // already saved 'inforref' entries to their 'final' annotations.
1496 * This step will get all the annotations already processed to inforef.xml file and
1497 * transform them into 'final' annotations.
1499 class move_inforef_annotations_to_final extends backup_execution_step {
1501 protected function define_execution() {
1503 // Items we want to include in the inforef file
1504 $items = backup_helper::get_inforef_itemnames();
1505 $progress = $this->task->get_progress();
1506 $progress->start_progress($this->get_name(), count($items));
1508 foreach ($items as $itemname) {
1509 // Delegate to dbops
1510 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1511 $itemname, $progress);
1512 $progress->progress($done++);
1514 $progress->end_progress();
1519 * structure in charge of constructing the files.xml file with all the
1520 * annotated (final) files along the process. At, the same time, and
1521 * using one specialised nested_element, will copy them form moodle storage
1524 class backup_final_files_structure_step extends backup_structure_step {
1526 protected function define_structure() {
1530 $files = new backup_nested_element('files');
1532 $file = new file_nested_element('file', array('id'), array(
1533 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1534 'filepath', 'filename', 'userid', 'filesize',
1535 'mimetype', 'status', 'timecreated', 'timemodified',
1536 'source', 'author', 'license', 'sortorder',
1537 'repositorytype', 'repositoryid', 'reference'));
1541 $files->add_child($file);
1545 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1547 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1548 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1549 LEFT JOIN {repository} r ON r.id = ri.typeid
1550 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1551 WHERE bi.backupid = ?
1552 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1559 * Structure step in charge of creating the main moodle_backup.xml file
1560 * where all the information related to the backup, settings, license and
1561 * other information needed on restore is added*/
1562 class backup_main_structure_step extends backup_structure_step {
1564 protected function define_structure() {
1570 $info['name'] = $this->get_setting_value('filename');
1571 $info['moodle_version'] = $CFG->version;
1572 $info['moodle_release'] = $CFG->release;
1573 $info['backup_version'] = $CFG->backup_version;
1574 $info['backup_release'] = $CFG->backup_release;
1575 $info['backup_date'] = time();
1576 $info['backup_uniqueid']= $this->get_backupid();
1577 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1578 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1579 $info['include_file_references_to_external_content'] =
1580 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1581 $info['original_wwwroot']=$CFG->wwwroot;
1582 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1583 $info['original_course_id'] = $this->get_courseid();
1584 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1585 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1586 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1587 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1588 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1589 $info['original_system_contextid'] = context_system::instance()->id;
1591 // Get more information from controller
1592 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid());
1596 $moodle_backup = new backup_nested_element('moodle_backup');
1598 $information = new backup_nested_element('information', null, array(
1599 'name', 'moodle_version', 'moodle_release', 'backup_version',
1600 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1601 'original_site_identifier_hash', 'original_course_id',
1602 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1603 'original_course_contextid', 'original_system_contextid'));
1605 $details = new backup_nested_element('details');
1607 $detail = new backup_nested_element('detail', array('backup_id'), array(
1608 'type', 'format', 'interactive', 'mode',
1609 'execution', 'executiontime'));
1611 $contents = new backup_nested_element('contents');
1613 $activities = new backup_nested_element('activities');
1615 $activity = new backup_nested_element('activity', null, array(
1616 'moduleid', 'sectionid', 'modulename', 'title',
1619 $sections = new backup_nested_element('sections');
1621 $section = new backup_nested_element('section', null, array(
1622 'sectionid', 'title', 'directory'));
1624 $course = new backup_nested_element('course', null, array(
1625 'courseid', 'title', 'directory'));
1627 $settings = new backup_nested_element('settings');
1629 $setting = new backup_nested_element('setting', null, array(
1630 'level', 'section', 'activity', 'name', 'value'));
1634 $moodle_backup->add_child($information);
1636 $information->add_child($details);
1637 $details->add_child($detail);
1639 $information->add_child($contents);
1640 if (!empty($cinfo['activities'])) {
1641 $contents->add_child($activities);
1642 $activities->add_child($activity);
1644 if (!empty($cinfo['sections'])) {
1645 $contents->add_child($sections);
1646 $sections->add_child($section);
1648 if (!empty($cinfo['course'])) {
1649 $contents->add_child($course);
1652 $information->add_child($settings);
1653 $settings->add_child($setting);
1658 $information->set_source_array(array((object)$info));
1660 $detail->set_source_array($dinfo);
1662 $activity->set_source_array($cinfo['activities']);
1664 $section->set_source_array($cinfo['sections']);
1666 $course->set_source_array($cinfo['course']);
1668 $setting->set_source_array($sinfo);
1670 // Prepare some information to be sent to main moodle_backup.xml file
1671 return $moodle_backup;
1677 * Execution step that will generate the final zip (.mbz) file with all the contents
1679 class backup_zip_contents extends backup_execution_step implements file_progress {
1681 * @var bool True if we have started tracking progress
1683 protected $startedprogress;
1685 protected function define_execution() {
1688 $basepath = $this->get_basepath();
1690 // Get the list of files in directory
1691 $filestemp = get_directory_list($basepath, '', false, true, true);
1693 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1694 $files[$file] = $basepath . '/' . $file;
1697 // Add the log file if exists
1698 $logfilepath = $basepath . '.log';
1699 if (file_exists($logfilepath)) {
1700 $files['moodle_backup.log'] = $logfilepath;
1703 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1704 $zipfile = $basepath . '/backup.mbz';
1706 // Get the zip packer
1707 $zippacker = get_file_packer('application/zip');
1710 $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1712 // If any progress happened, end it.
1713 if ($this->startedprogress) {
1714 $this->task->get_progress()->end_progress();
1719 * Implementation for file_progress interface to display unzip progress.
1721 * @param int $progress Current progress
1722 * @param int $max Max value
1724 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
1725 $reporter = $this->task->get_progress();
1727 // Start tracking progress if necessary.
1728 if (!$this->startedprogress) {
1729 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
1730 ? core_backup_progress::INDETERMINATE : $max);
1731 $this->startedprogress = true;
1734 // Pass progress through to whatever handles it.
1735 $reporter->progress(($progress == file_progress::INDETERMINATE)
1736 ? core_backup_progress::INDETERMINATE : $progress);
1741 * This step will send the generated backup file to its final destination
1743 class backup_store_backup_file extends backup_execution_step {
1745 protected function define_execution() {
1748 $basepath = $this->get_basepath();
1750 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1751 $zipfile = $basepath . '/backup.mbz';
1753 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1754 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1756 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile),
1757 'include_file_references_to_external_content' => $has_file_references
1764 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1765 * and put them to the backup_ids tables, to be used later as base to backup them
1767 class backup_activity_grade_items_to_ids extends backup_execution_step {
1769 protected function define_execution() {
1771 // Fetch all activity grade items
1772 if ($items = grade_item::fetch_all(array(
1773 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1774 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1775 // Annotate them in backup_ids
1776 foreach ($items as $item) {
1777 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1784 * This step will annotate all the groups and groupings belonging to the course
1786 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1788 protected function define_execution() {
1791 // Get all the course groups
1792 if ($groups = $DB->get_records('groups', array(
1793 'courseid' => $this->task->get_courseid()))) {
1794 foreach ($groups as $group) {
1795 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1799 // Get all the course groupings
1800 if ($groupings = $DB->get_records('groupings', array(
1801 'courseid' => $this->task->get_courseid()))) {
1802 foreach ($groupings as $grouping) {
1803 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1810 * This step will annotate all the groups belonging to already annotated groupings
1812 class backup_annotate_groups_from_groupings extends backup_execution_step {
1814 protected function define_execution() {
1817 // Fetch all the annotated groupings
1818 if ($groupings = $DB->get_records('backup_ids_temp', array(
1819 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1820 foreach ($groupings as $grouping) {
1821 if ($groups = $DB->get_records('groupings_groups', array(
1822 'groupingid' => $grouping->itemid))) {
1823 foreach ($groups as $group) {
1824 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1833 * This step will annotate all the scales belonging to already annotated outcomes
1835 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1837 protected function define_execution() {
1840 // Fetch all the annotated outcomes
1841 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1842 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1843 foreach ($outcomes as $outcome) {
1844 if ($scale = $DB->get_record('grade_outcomes', array(
1845 'id' => $outcome->itemid))) {
1846 // Annotate as scalefinal because it's > 0
1847 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1855 * This step will generate all the file annotations for the already
1856 * annotated (final) question_categories. It calculates the different
1857 * contexts that are being backup and, annotates all the files
1858 * on every context belonging to the "question" component. As far as
1859 * we are always including *complete* question banks it is safe and
1860 * optimal to do that in this (one pass) way
1862 class backup_annotate_all_question_files extends backup_execution_step {
1864 protected function define_execution() {
1867 // Get all the different contexts for the final question_categories
1868 // annotated along the whole backup
1869 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1870 FROM {question_categories} qc
1871 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
1872 WHERE bi.backupid = ?
1873 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
1874 // To know about qtype specific components/fileareas
1875 $components = backup_qtype_plugin::get_components_and_fileareas();
1877 foreach($rs as $record) {
1878 // We don't need to specify filearea nor itemid as far as by
1879 // component and context it's enough to annotate the whole bank files
1880 // This backups "questiontext", "generalfeedback" and "answerfeedback" fileareas (all them
1881 // belonging to the "question" component
1882 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', null, null);
1883 // Again, it is enough to pick files only by context and component
1884 // Do it for qtype specific components
1885 foreach ($components as $component => $fileareas) {
1886 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
1894 * structure step in charge of constructing the questions.xml file for all the
1895 * question categories and questions required by the backup
1896 * and letters related to one activity
1898 class backup_questions_structure_step extends backup_structure_step {
1900 protected function define_structure() {
1902 // Define each element separated
1904 $qcategories = new backup_nested_element('question_categories');
1906 $qcategory = new backup_nested_element('question_category', array('id'), array(
1907 'name', 'contextid', 'contextlevel', 'contextinstanceid',
1908 'info', 'infoformat', 'stamp', 'parent',
1911 $questions = new backup_nested_element('questions');
1913 $question = new backup_nested_element('question', array('id'), array(
1914 'parent', 'name', 'questiontext', 'questiontextformat',
1915 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
1916 'qtype', 'length', 'stamp', 'version',
1917 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
1919 // attach qtype plugin structure to $question element, only one allowed
1920 $this->add_plugin_structure('qtype', $question, false);
1922 // attach local plugin stucture to $question element, multiple allowed
1923 $this->add_plugin_structure('local', $question, true);
1925 $qhints = new backup_nested_element('question_hints');
1927 $qhint = new backup_nested_element('question_hint', array('id'), array(
1928 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
1930 $tags = new backup_nested_element('tags');
1932 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
1936 $qcategories->add_child($qcategory);
1937 $qcategory->add_child($questions);
1938 $questions->add_child($question);
1939 $question->add_child($qhints);
1940 $qhints->add_child($qhint);
1942 $question->add_child($tags);
1943 $tags->add_child($tag);
1945 // Define the sources
1947 $qcategory->set_source_sql("
1948 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
1949 FROM {question_categories} gc
1950 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
1951 JOIN {context} co ON co.id = gc.contextid
1952 WHERE bi.backupid = ?
1953 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
1955 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
1957 $qhint->set_source_sql('
1959 FROM {question_hints}
1960 WHERE questionid = :questionid
1962 array('questionid' => backup::VAR_PARENTID));
1964 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
1966 JOIN {tag_instance} ti ON ti.tagid = t.id
1968 AND ti.itemtype = 'question'", array(backup::VAR_PARENTID));
1970 // don't need to annotate ids nor files
1971 // (already done by {@link backup_annotate_all_question_files}
1973 return $qcategories;
1980 * This step will generate all the file annotations for the already
1981 * annotated (final) users. Need to do this here because each user
1982 * has its own context and structure tasks only are able to handle
1983 * one context. Also, this step will guarantee that every user has
1984 * its context created (req for other steps)
1986 class backup_annotate_all_user_files extends backup_execution_step {
1988 protected function define_execution() {
1991 // List of fileareas we are going to annotate
1992 $fileareas = array('profile', 'icon');
1994 // Fetch all annotated (final) users
1995 $rs = $DB->get_recordset('backup_ids_temp', array(
1996 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1997 $progress = $this->task->get_progress();
1998 $progress->start_progress($this->get_name());
1999 foreach ($rs as $record) {
2000 $userid = $record->itemid;
2001 $userctx = context_user::instance($userid, IGNORE_MISSING);
2003 continue; // User has not context, sure it's a deleted user, so cannot have files
2005 // Proceed with every user filearea
2006 foreach ($fileareas as $filearea) {
2007 // We don't need to specify itemid ($userid - 5th param) as far as by
2008 // context we can get all the associated files. See MDL-22092
2009 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2010 $progress->progress();
2013 $progress->end_progress();
2020 * Defines the backup step for advanced grading methods attached to the activity module
2022 class backup_activity_grading_structure_step extends backup_structure_step {
2025 * Include the grading.xml only if the module supports advanced grading
2027 protected function execute_condition() {
2028 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2032 * Declares the gradable areas structures and data sources
2034 protected function define_structure() {
2036 // To know if we are including userinfo
2037 $userinfo = $this->get_setting_value('userinfo');
2039 // Define the elements
2041 $areas = new backup_nested_element('areas');
2043 $area = new backup_nested_element('area', array('id'), array(
2044 'areaname', 'activemethod'));
2046 $definitions = new backup_nested_element('definitions');
2048 $definition = new backup_nested_element('definition', array('id'), array(
2049 'method', 'name', 'description', 'descriptionformat', 'status',
2050 'timecreated', 'timemodified', 'options'));
2052 $instances = new backup_nested_element('instances');
2054 $instance = new backup_nested_element('instance', array('id'), array(
2055 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2056 'feedbackformat', 'timemodified'));
2058 // Build the tree including the method specific structures
2059 // (beware - the order of how gradingform plugins structures are attached is important)
2060 $areas->add_child($area);
2061 // attach local plugin stucture to $area element, multiple allowed
2062 $this->add_plugin_structure('local', $area, true);
2063 $area->add_child($definitions);
2064 $definitions->add_child($definition);
2065 $this->add_plugin_structure('gradingform', $definition, true);
2066 // attach local plugin stucture to $definition element, multiple allowed
2067 $this->add_plugin_structure('local', $definition, true);
2068 $definition->add_child($instances);
2069 $instances->add_child($instance);
2070 $this->add_plugin_structure('gradingform', $instance, false);
2071 // attach local plugin stucture to $instance element, multiple allowed
2072 $this->add_plugin_structure('local', $instance, true);
2074 // Define data sources
2076 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2077 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2079 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2082 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2085 // Annotate references
2086 $definition->annotate_files('grading', 'description', 'id');
2087 $instance->annotate_ids('user', 'raterid');
2089 // Return the root element
2096 * structure step in charge of constructing the grades.xml file for all the grade items
2097 * and letters related to one activity
2099 class backup_activity_grades_structure_step extends backup_structure_step {
2101 protected function define_structure() {
2103 // To know if we are including userinfo
2104 $userinfo = $this->get_setting_value('userinfo');
2106 // Define each element separated
2108 $book = new backup_nested_element('activity_gradebook');
2110 $items = new backup_nested_element('grade_items');
2112 $item = new backup_nested_element('grade_item', array('id'), array(
2113 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2114 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2115 'calculation', 'gradetype', 'grademax', 'grademin',
2116 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2117 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
2118 'decimals', 'hidden', 'locked', 'locktime',
2119 'needsupdate', 'timecreated', 'timemodified'));
2121 $grades = new backup_nested_element('grade_grades');
2123 $grade = new backup_nested_element('grade_grade', array('id'), array(
2124 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2125 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2126 'locked', 'locktime', 'exported', 'overridden',
2127 'excluded', 'feedback', 'feedbackformat', 'information',
2128 'informationformat', 'timecreated', 'timemodified'));
2130 $letters = new backup_nested_element('grade_letters');
2132 $letter = new backup_nested_element('grade_letter', 'id', array(
2133 'lowerboundary', 'letter'));
2137 $book->add_child($items);
2138 $items->add_child($item);
2140 $item->add_child($grades);
2141 $grades->add_child($grade);
2143 $book->add_child($letters);
2144 $letters->add_child($letter);
2148 $item->set_source_sql("SELECT gi.*
2149 FROM {grade_items} gi
2150 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2151 WHERE bi.backupid = ?
2152 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2154 // This only happens if we are including user info
2156 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2159 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2163 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2164 $item->annotate_ids('outcome', 'outcomeid');
2166 $grade->annotate_ids('user', 'userid');
2167 $grade->annotate_ids('user', 'usermodified');
2169 // Return the root element (book)
2176 * Backups up the course completion information for the course.
2178 class backup_course_completion_structure_step extends backup_structure_step {
2180 protected function execute_condition() {
2181 // Check that all activities have been included
2182 if ($this->task->is_excluding_activities()) {
2189 * The structure of the course completion backup
2191 * @return backup_nested_element
2193 protected function define_structure() {
2195 // To know if we are including user completion info
2196 $userinfo = $this->get_setting_value('userscompletion');
2198 $cc = new backup_nested_element('course_completion');
2200 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2201 'course','criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod', 'timeend', 'gradepass', 'role'
2204 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2206 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2207 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2210 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2211 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2214 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2215 'course','criteriatype','method','value'
2218 $cc->add_child($criteria);
2219 $criteria->add_child($criteriacompletions);
2220 $criteriacompletions->add_child($criteriacomplete);
2221 $cc->add_child($coursecompletions);
2222 $cc->add_child($aggregatemethod);
2224 // We need to get the courseinstances shortname rather than an ID for restore
2225 $criteria->set_source_sql("SELECT ccc.*, c.shortname AS courseinstanceshortname
2226 FROM {course_completion_criteria} ccc
2227 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2228 WHERE ccc.course = ?", array(backup::VAR_COURSEID));
2231 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2234 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2235 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2238 $criteria->annotate_ids('role', 'role');
2239 $criteriacomplete->annotate_ids('user', 'userid');
2240 $coursecompletions->annotate_ids('user', 'userid');