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 and create temp ids table.
33 class create_and_clean_temp_stuff
extends backup_execution_step
{
35 protected function define_execution() {
36 $progress = $this->task
->get_progress();
37 $progress->start_progress('Deleting backup directories');
38 backup_helper
::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
39 backup_helper
::clear_backup_dir($this->get_backupid(), $progress); // Empty temp dir, just in case
40 backup_controller_dbops
::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
41 backup_controller_dbops
::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
42 $progress->end_progress();
47 * Delete the temp dir used by backup/restore (conditionally) and drop temp ids table.
48 * Note we delete the directory but not the corresponding log file that will be
49 * there until cron cleans it up.
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 // Delete temp dir conditionally:
60 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
61 // 2) If backup temp dir deletion has been marked to be avoided
62 if (empty($CFG->keeptempdirectoriesonbackup
) && !$this->skipcleaningtempdir
) {
63 $progress = $this->task
->get_progress();
64 $progress->start_progress('Deleting backup dir');
65 backup_helper
::delete_backup_dir($this->get_backupid(), $progress); // Empty backup dir
66 $progress->end_progress();
70 public function skip_cleaning_temp_dir($skip) {
71 $this->skipcleaningtempdir
= $skip;
76 * Create the directory where all the task (activity/block...) information will be stored
78 class create_taskbasepath_directory
extends backup_execution_step
{
80 protected function define_execution() {
82 $basepath = $this->task
->get_taskbasepath();
83 if (!check_dir_exists($basepath, true, true)) {
84 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
90 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
91 * activity structure definition within the main <activity ...> tag.
93 abstract class backup_activity_structure_step
extends backup_structure_step
{
96 * Wraps any activity backup structure within the common 'activity' element
97 * that will include common to all activities information like id, context...
99 * @param backup_nested_element $activitystructure the element to wrap
100 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
102 protected function prepare_activity_structure($activitystructure) {
104 // Create the wrap element
105 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
108 $activity->add_child($activitystructure);
111 $activityarr = array((object)array(
112 'id' => $this->task
->get_activityid(),
113 'moduleid' => $this->task
->get_moduleid(),
114 'modulename' => $this->task
->get_modulename(),
115 'contextid' => $this->task
->get_contextid()));
117 $activity->set_source_array($activityarr);
119 // Return the root element (activity)
125 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
127 trait backup_questions_attempt_data_trait
{
130 * Attach to $element (usually attempts) the needed backup structures
131 * for question_usages and all the associated data.
133 * @param backup_nested_element $element the element that will contain all the question_usages data.
134 * @param string $usageidname the name of the element that holds the usageid.
135 * This must be child of $element, and must be a final element.
136 * @param string $nameprefix this prefix is added to all the element names we create.
137 * Element names in the XML must be unique, so if you are using usages in
138 * two different ways, you must give a prefix to at least one of them. If
139 * you only use one sort of usage, then you can just use the default empty prefix.
140 * This should include a trailing underscore. For example "myprefix_"
142 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
144 require_once($CFG->dirroot
. '/question/engine/lib.php');
146 // Check $element is one nested_backup_element
147 if (! $element instanceof backup_nested_element
) {
148 throw new backup_step_exception('question_states_bad_parent_element', $element);
150 if (! $element->get_final_element($usageidname)) {
151 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
154 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
155 array('component', 'preferredbehaviour'));
157 $qas = new backup_nested_element($nameprefix . 'question_attempts');
158 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
159 'slot', 'behaviour', 'questionid', 'variant', 'maxmark', 'minfraction', 'maxfraction',
160 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
163 $steps = new backup_nested_element($nameprefix . 'steps');
164 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
165 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
167 $response = new backup_nested_element($nameprefix . 'response');
168 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
171 $element->add_child($quba);
172 $quba->add_child($qas);
173 $qas->add_child($qa);
174 $qa->add_child($steps);
175 $steps->add_child($step);
176 $step->add_child($response);
177 $response->add_child($variable);
180 $quba->set_source_table('question_usages',
181 array('id' => '../' . $usageidname));
182 $qa->set_source_table('question_attempts', array('questionusageid' => backup
::VAR_PARENTID
), 'slot ASC');
183 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup
::VAR_PARENTID
), 'sequencenumber ASC');
184 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup
::VAR_PARENTID
));
187 $qa->annotate_ids('question', 'questionid');
188 $step->annotate_ids('user', 'userid');
191 $fileareas = question_engine
::get_all_response_file_areas();
192 foreach ($fileareas as $filearea) {
193 $step->annotate_files('question', $filearea, 'id');
200 * Abstract structure step to help activities that store question attempt data.
202 * @copyright 2011 The Open University
203 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
205 abstract class backup_questions_activity_structure_step
extends backup_activity_structure_step
{
206 use backup_questions_attempt_data_trait
;
211 * backup structure step in charge of calculating the categories to be
212 * included in backup, based in the context being backuped (module/course)
213 * and the already annotated questions present in backup_ids_temp
215 class backup_calculate_question_categories
extends backup_execution_step
{
217 protected function define_execution() {
218 backup_question_dbops
::calculate_question_categories($this->get_backupid(), $this->task
->get_contextid());
223 * backup structure step in charge of deleting all the questions annotated
224 * in the backup_ids_temp table
226 class backup_delete_temp_questions
extends backup_execution_step
{
228 protected function define_execution() {
229 backup_question_dbops
::delete_temp_questions($this->get_backupid());
234 * Abstract structure step, parent of all the block structure steps. Used to wrap the
235 * block structure definition within the main <block ...> tag
237 abstract class backup_block_structure_step
extends backup_structure_step
{
239 protected function prepare_block_structure($blockstructure) {
241 // Create the wrap element
242 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
245 $block->add_child($blockstructure);
248 $blockarr = array((object)array(
249 'id' => $this->task
->get_blockid(),
250 'blockname' => $this->task
->get_blockname(),
251 'contextid' => $this->task
->get_contextid()));
253 $block->set_source_array($blockarr);
255 // Return the root element (block)
261 * structure step that will generate the module.xml file for the activity,
262 * accumulating various information about the activity, annotating groupings
263 * and completion/avail conf
265 class backup_module_structure_step
extends backup_structure_step
{
267 protected function define_structure() {
270 // Define each element separated
272 $module = new backup_nested_element('module', array('id', 'version'), array(
273 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
274 'added', 'score', 'indent', 'visible', 'visibleoncoursepage',
275 'visibleold', 'groupmode', 'groupingid',
276 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
277 'availability', 'showdescription'));
279 $tags = new backup_nested_element('tags');
280 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
282 // attach format plugin structure to $module element, only one allowed
283 $this->add_plugin_structure('format', $module, false);
285 // Attach report plugin structure to $module element, multiple allowed.
286 $this->add_plugin_structure('report', $module, true);
288 // attach plagiarism plugin structure to $module element, there can be potentially
289 // many plagiarism plugins storing information about this course
290 $this->add_plugin_structure('plagiarism', $module, true);
292 // attach local plugin structure to $module, multiple allowed
293 $this->add_plugin_structure('local', $module, true);
295 // Attach admin tools plugin structure to $module.
296 $this->add_plugin_structure('tool', $module, true);
298 $module->add_child($tags);
299 $tags->add_child($tag);
302 $concat = $DB->sql_concat("'mod_'", 'm.name');
303 $module->set_source_sql("
304 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
305 FROM {course_modules} cm
306 JOIN {modules} m ON m.id = cm.module
307 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
308 JOIN {course_sections} s ON s.id = cm.section
309 WHERE cm.id = ?", array(backup
::VAR_MODID
));
311 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
313 JOIN {tag_instance} ti ON ti.tagid = t.id
314 WHERE ti.itemtype = 'course_modules'
315 AND ti.component = 'core'
316 AND ti.itemid = ?", array(backup
::VAR_MODID
));
318 // Define annotations
319 $module->annotate_ids('grouping', 'groupingid');
321 // Return the root element ($module)
327 * structure step that will generate the section.xml file for the section
330 class backup_section_structure_step
extends backup_structure_step
{
332 protected function define_structure() {
334 // Define each element separated
336 $section = new backup_nested_element('section', array('id'), array(
337 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
338 'availabilityjson', 'timemodified'));
340 // attach format plugin structure to $section element, only one allowed
341 $this->add_plugin_structure('format', $section, false);
343 // attach local plugin structure to $section element, multiple allowed
344 $this->add_plugin_structure('local', $section, true);
346 // Add nested elements for course_format_options table
347 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
348 'format', 'name', 'value'));
349 $section->add_child($formatoptions);
352 $section->set_source_table('course_sections', array('id' => backup
::VAR_SECTIONID
));
353 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
355 JOIN {course_format_options} cfo
356 ON cfo.courseid = c.id AND cfo.format = c.format
357 WHERE c.id = ? AND cfo.sectionid = ?',
358 array(backup
::VAR_COURSEID
, backup
::VAR_SECTIONID
));
361 $section->set_source_alias('section', 'number');
362 // The 'availability' field needs to be renamed because it clashes with
363 // the old nested element structure for availability data.
364 $section->set_source_alias('availability', 'availabilityjson');
367 $section->annotate_files('course', 'section', 'id');
374 * structure step that will generate the course.xml file for the course, including
375 * course category reference, tags, modules restriction information
376 * and some annotations (files & groupings)
378 class backup_course_structure_step
extends backup_structure_step
{
380 protected function define_structure() {
383 // Define each element separated
385 $course = new backup_nested_element('course', array('id', 'contextid'), array(
386 'shortname', 'fullname', 'idnumber',
387 'summary', 'summaryformat', 'format', 'showgrades',
388 'newsitems', 'startdate', 'enddate',
389 'marker', 'maxbytes', 'legacyfiles', 'showreports',
390 'visible', 'groupmode', 'groupmodeforce',
391 'defaultgroupingid', 'lang', 'theme',
392 'timecreated', 'timemodified',
395 'showcompletionconditions',
396 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
398 $category = new backup_nested_element('category', array('id'), array(
399 'name', 'description'));
401 $tags = new backup_nested_element('tags');
403 $tag = new backup_nested_element('tag', array('id'), array(
406 $customfields = new backup_nested_element('customfields');
407 $customfield = new backup_nested_element('customfield', array('id'), array(
408 'shortname', 'type', 'value', 'valueformat'
411 // attach format plugin structure to $course element, only one allowed
412 $this->add_plugin_structure('format', $course, false);
414 // attach theme plugin structure to $course element; multiple themes can
415 // save course data (in case of user theme, legacy theme, etc)
416 $this->add_plugin_structure('theme', $course, true);
418 // attach general report plugin structure to $course element; multiple
419 // reports can save course data if required
420 $this->add_plugin_structure('report', $course, true);
422 // attach course report plugin structure to $course element; multiple
423 // course reports can save course data if required
424 $this->add_plugin_structure('coursereport', $course, true);
426 // attach plagiarism plugin structure to $course element, there can be potentially
427 // many plagiarism plugins storing information about this course
428 $this->add_plugin_structure('plagiarism', $course, true);
430 // attach local plugin structure to $course element; multiple local plugins
431 // can save course data if required
432 $this->add_plugin_structure('local', $course, true);
434 // Attach admin tools plugin structure to $course element; multiple plugins
435 // can save course data if required.
436 $this->add_plugin_structure('tool', $course, true);
440 $course->add_child($category);
442 $course->add_child($tags);
443 $tags->add_child($tag);
445 $course->add_child($customfields);
446 $customfields->add_child($customfield);
450 $courserec = $DB->get_record('course', array('id' => $this->task
->get_courseid()));
451 $courserec->contextid
= $this->task
->get_contextid();
453 $formatoptions = course_get_format($courserec)->get_format_options();
454 $course->add_final_elements(array_keys($formatoptions));
455 foreach ($formatoptions as $key => $value) {
456 $courserec->$key = $value;
459 // Add 'numsections' in order to be able to restore in previous versions of Moodle.
460 // Even though Moodle does not officially support restore into older verions of Moodle from the
461 // version where backup was made, without 'numsections' restoring will go very wrong.
462 if (!property_exists($courserec, 'numsections') && course_get_format($courserec)->uses_sections()) {
463 $courserec->numsections
= course_get_format($courserec)->get_last_section_number();
466 $course->set_source_array(array($courserec));
468 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category
));
470 $category->set_source_array(array($categoryrec));
472 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
474 JOIN {tag_instance} ti ON ti.tagid = t.id
475 WHERE ti.itemtype = ?
476 AND ti.itemid = ?', array(
477 backup_helper
::is_sqlparam('course'),
478 backup
::VAR_PARENTID
));
480 $handler = core_course\customfield\course_handler
::create();
481 $fieldsforbackup = $handler->get_instance_data_for_backup($this->task
->get_courseid());
482 $customfield->set_source_array($fieldsforbackup);
486 $course->annotate_ids('grouping', 'defaultgroupingid');
488 $course->annotate_files('course', 'summary', null);
489 $course->annotate_files('course', 'overviewfiles', null);
491 if ($this->get_setting_value('legacyfiles')) {
492 $course->annotate_files('course', 'legacy', null);
495 // Return root element ($course)
502 * structure step that will generate the enrolments.xml file for the given course
504 class backup_enrolments_structure_step
extends backup_structure_step
{
507 * Skip enrolments on the front page.
510 protected function execute_condition() {
511 return ($this->get_courseid() != SITEID
);
514 protected function define_structure() {
517 // To know if we are including users
518 $users = $this->get_setting_value('users');
519 $keptroles = $this->task
->get_kept_roles();
521 // Define each element separated
523 $enrolments = new backup_nested_element('enrolments');
525 $enrols = new backup_nested_element('enrols');
527 $enrol = new backup_nested_element('enrol', array('id'), array(
528 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
529 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
530 'password', 'cost', 'currency', 'roleid',
531 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
532 'customchar1', 'customchar2', 'customchar3',
533 'customdec1', 'customdec2',
534 'customtext1', 'customtext2', 'customtext3', 'customtext4',
535 'timecreated', 'timemodified'));
537 $userenrolments = new backup_nested_element('user_enrolments');
539 $enrolment = new backup_nested_element('enrolment', array('id'), array(
540 'status', 'userid', 'timestart', 'timeend', 'modifierid',
544 $enrolments->add_child($enrols);
545 $enrols->add_child($enrol);
546 $enrol->add_child($userenrolments);
547 $userenrolments->add_child($enrolment);
549 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
550 $enrol->set_source_table('enrol', array('courseid' => backup
::VAR_COURSEID
), 'sortorder ASC');
552 // User enrolments only added only if users included.
553 if (empty($keptroles) && $users) {
554 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup
::VAR_PARENTID
));
555 $enrolment->annotate_ids('user', 'userid');
556 } else if (!empty($keptroles)) {
557 list($insql, $inparams) = $DB->get_in_or_equal($keptroles);
559 backup
::VAR_CONTEXTID
,
562 foreach ($inparams as $inparam) {
563 $params[] = backup_helper
::is_sqlparam($inparam);
565 $enrolment->set_source_sql(
567 FROM {user_enrolments} ue
568 INNER JOIN {role_assignments} ra ON ue.userid = ra.userid
569 WHERE ra.contextid = ?
571 AND ra.roleid $insql",
573 $enrolment->annotate_ids('user', 'userid');
576 $enrol->annotate_ids('role', 'roleid');
578 // Add enrol plugin structure.
579 $this->add_plugin_structure('enrol', $enrol, true);
586 * structure step that will generate the roles.xml file for the given context, observing
587 * the role_assignments setting to know if that part needs to be included
589 class backup_roles_structure_step
extends backup_structure_step
{
591 protected function define_structure() {
593 // To know if we are including role assignments
594 $roleassignments = $this->get_setting_value('role_assignments');
596 // Define each element separated
598 $roles = new backup_nested_element('roles');
600 $overrides = new backup_nested_element('role_overrides');
602 $override = new backup_nested_element('override', array('id'), array(
603 'roleid', 'capability', 'permission', 'timemodified',
606 $assignments = new backup_nested_element('role_assignments');
608 $assignment = new backup_nested_element('assignment', array('id'), array(
609 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
613 $roles->add_child($overrides);
614 $roles->add_child($assignments);
616 $overrides->add_child($override);
617 $assignments->add_child($assignment);
621 $override->set_source_table('role_capabilities', array('contextid' => backup
::VAR_CONTEXTID
));
623 // Assignments only added if specified
624 if ($roleassignments) {
625 $assignment->set_source_table('role_assignments', array('contextid' => backup
::VAR_CONTEXTID
));
628 // Define id annotations
629 $override->annotate_ids('role', 'roleid');
631 $assignment->annotate_ids('role', 'roleid');
633 $assignment->annotate_ids('user', 'userid');
635 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
642 * structure step that will generate the roles.xml containing the
643 * list of roles used along the whole backup process. Just raw
644 * list of used roles from role table
646 class backup_final_roles_structure_step
extends backup_structure_step
{
648 protected function define_structure() {
652 $rolesdef = new backup_nested_element('roles_definition');
654 $role = new backup_nested_element('role', array('id'), array(
655 'name', 'shortname', 'nameincourse', 'description',
656 'sortorder', 'archetype'));
660 $rolesdef->add_child($role);
664 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
666 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
667 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
668 WHERE bi.backupid = ?
669 AND bi.itemname = 'rolefinal'", array(backup
::VAR_CONTEXTID
, backup
::VAR_BACKUPID
));
671 // Return main element (rolesdef)
677 * structure step that will generate the scales.xml containing the
678 * list of scales used along the whole backup process.
680 class backup_final_scales_structure_step
extends backup_structure_step
{
682 protected function define_structure() {
686 $scalesdef = new backup_nested_element('scales_definition');
688 $scale = new backup_nested_element('scale', array('id'), array(
689 'courseid', 'userid', 'name', 'scale',
690 'description', 'descriptionformat', 'timemodified'));
694 $scalesdef->add_child($scale);
698 $scale->set_source_sql("SELECT s.*
700 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
701 WHERE bi.backupid = ?
702 AND bi.itemname = 'scalefinal'", array(backup
::VAR_BACKUPID
));
704 // Annotate scale files (they store files in system context, so pass it instead of default one)
705 $scale->annotate_files('grade', 'scale', 'id', context_system
::instance()->id
);
707 // Return main element (scalesdef)
713 * structure step that will generate the outcomes.xml containing the
714 * list of outcomes used along the whole backup process.
716 class backup_final_outcomes_structure_step
extends backup_structure_step
{
718 protected function define_structure() {
722 $outcomesdef = new backup_nested_element('outcomes_definition');
724 $outcome = new backup_nested_element('outcome', array('id'), array(
725 'courseid', 'userid', 'shortname', 'fullname',
726 'scaleid', 'description', 'descriptionformat', 'timecreated',
727 'timemodified','usermodified'));
731 $outcomesdef->add_child($outcome);
735 $outcome->set_source_sql("SELECT o.*
736 FROM {grade_outcomes} o
737 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
738 WHERE bi.backupid = ?
739 AND bi.itemname = 'outcomefinal'", array(backup
::VAR_BACKUPID
));
741 // Annotate outcome files (they store files in system context, so pass it instead of default one)
742 $outcome->annotate_files('grade', 'outcome', 'id', context_system
::instance()->id
);
744 // Return main element (outcomesdef)
750 * structure step in charge of constructing the filters.xml file for all the filters found
753 class backup_filters_structure_step
extends backup_structure_step
{
755 protected function define_structure() {
757 // Define each element separated
759 $filters = new backup_nested_element('filters');
761 $actives = new backup_nested_element('filter_actives');
763 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
765 $configs = new backup_nested_element('filter_configs');
767 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
771 $filters->add_child($actives);
772 $filters->add_child($configs);
774 $actives->add_child($active);
775 $configs->add_child($config);
779 list($activearr, $configarr) = filter_get_all_local_settings($this->task
->get_contextid());
781 $active->set_source_array($activearr);
782 $config->set_source_array($configarr);
784 // Return the root element (filters)
790 * structure step in charge of constructing the comments.xml file for all the comments found
793 class backup_comments_structure_step
extends backup_structure_step
{
795 protected function define_structure() {
797 // Define each element separated
799 $comments = new backup_nested_element('comments');
801 $comment = new backup_nested_element('comment', array('id'), array(
802 'commentarea', 'itemid', 'content', 'format',
803 'userid', 'timecreated'));
807 $comments->add_child($comment);
811 $comment->set_source_table('comments', array('contextid' => backup
::VAR_CONTEXTID
));
813 // Define id annotations
815 $comment->annotate_ids('user', 'userid');
817 // Return the root element (comments)
823 * structure step in charge of constructing the badges.xml file for all the badges found
826 class backup_badges_structure_step
extends backup_structure_step
{
828 protected function execute_condition() {
829 // Check that all activities have been included.
830 if ($this->task
->is_excluding_activities()) {
836 protected function define_structure() {
839 require_once($CFG->libdir
. '/badgeslib.php');
840 // Define each element separated.
842 $badges = new backup_nested_element('badges');
843 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
844 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
845 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
846 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron',
847 'version', 'language', 'imageauthorname', 'imageauthoremail', 'imageauthorurl',
850 $criteria = new backup_nested_element('criteria');
851 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
852 'criteriatype', 'method', 'description', 'descriptionformat'));
854 $endorsement = new backup_nested_element('endorsement', array('id'), array('badgeid',
855 'issuername', 'issuerurl', 'issueremail', 'claimid', 'claimcomment', 'dateissued'));
857 $alignments = new backup_nested_element('alignments');
858 $alignment = new backup_nested_element('alignment', array('id'), array('badgeid',
859 'targetname', 'targeturl', 'targetdescription', 'targetframework', 'targetcode'));
861 $relatedbadges = new backup_nested_element('relatedbadges');
862 $relatedbadge = new backup_nested_element('relatedbadge', array('id'), array('badgeid',
865 $parameters = new backup_nested_element('parameters');
866 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
867 'name', 'value', 'criteriatype'));
869 $manual_awards = new backup_nested_element('manual_awards');
870 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
871 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
875 $badges->add_child($badge);
876 $badge->add_child($criteria);
877 $criteria->add_child($criterion);
878 $criterion->add_child($parameters);
879 $parameters->add_child($parameter);
880 $badge->add_child($endorsement);
881 $badge->add_child($alignments);
882 $alignments->add_child($alignment);
883 $badge->add_child($relatedbadges);
884 $relatedbadges->add_child($relatedbadge);
885 $badge->add_child($manual_awards);
886 $manual_awards->add_child($manual_award);
893 WHERE courseid = :courseid
894 AND status != ' . BADGE_STATUS_ARCHIVED
;
896 'courseid' => backup
::VAR_COURSEID
898 $badge->set_source_sql($parametersql, $parameterparams);
899 $criterion->set_source_table('badge_criteria', array('badgeid' => backup
::VAR_PARENTID
));
900 $endorsement->set_source_table('badge_endorsement', array('badgeid' => backup
::VAR_PARENTID
));
902 $alignment->set_source_table('badge_alignment', array('badgeid' => backup
::VAR_PARENTID
));
903 $relatedbadge->set_source_table('badge_related', array('badgeid' => backup
::VAR_PARENTID
));
905 $parametersql = 'SELECT cp.*, c.criteriatype
906 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
908 WHERE critid = :critid';
909 $parameterparams = array('critid' => backup
::VAR_PARENTID
);
910 $parameter->set_source_sql($parametersql, $parameterparams);
912 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup
::VAR_PARENTID
));
914 // Define id annotations.
916 $badge->annotate_ids('user', 'usercreated');
917 $badge->annotate_ids('user', 'usermodified');
918 $criterion->annotate_ids('badge', 'badgeid');
919 $parameter->annotate_ids('criterion', 'critid');
920 $endorsement->annotate_ids('badge', 'badgeid');
921 $alignment->annotate_ids('badge', 'badgeid');
922 $relatedbadge->annotate_ids('badge', 'badgeid');
923 $relatedbadge->annotate_ids('badge', 'relatedbadgeid');
924 $badge->annotate_files('badges', 'badgeimage', 'id');
925 $manual_award->annotate_ids('badge', 'badgeid');
926 $manual_award->annotate_ids('user', 'recipientid');
927 $manual_award->annotate_ids('user', 'issuerid');
928 $manual_award->annotate_ids('role', 'issuerrole');
930 // Return the root element ($badges).
936 * structure step in charge of constructing the calender.xml file for all the events found
939 class backup_calendarevents_structure_step
extends backup_structure_step
{
941 protected function define_structure() {
943 // Define each element separated
945 $events = new backup_nested_element('events');
947 $event = new backup_nested_element('event', array('id'), array(
948 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
949 'repeatid', 'modulename', 'instance', 'type', 'eventtype', 'timestart',
950 'timeduration', 'timesort', 'visible', 'uuid', 'sequence', 'timemodified',
951 'priority', 'location'));
954 $events->add_child($event);
957 if ($this->name
== 'course_calendar') {
958 $calendar_items_sql ="SELECT * FROM {event}
959 WHERE courseid = :courseid
960 AND (eventtype = 'course' OR eventtype = 'group')";
961 $calendar_items_params = array('courseid'=>backup
::VAR_COURSEID
);
962 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
963 } else if ($this->name
== 'activity_calendar') {
964 // We don't backup action events.
965 $params = array('instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
,
966 'type' => array('sqlparam' => CALENDAR_EVENT_TYPE_ACTION
));
967 // If we don't want to include the userinfo in the backup then setting the courseid
968 // will filter out all of the user override events (which have a course id of zero).
970 if (!$this->get_setting_value('userinfo')) {
971 $params['courseid'] = backup
::VAR_COURSEID
;
972 $coursewhere = " AND courseid = :courseid";
974 $calendarsql = "SELECT * FROM {event}
975 WHERE instance = :instance
977 AND modulename = :modulename";
978 $calendarsql = $calendarsql . $coursewhere;
979 $event->set_source_sql($calendarsql, $params);
981 $event->set_source_table('event', array('courseid' => backup
::VAR_COURSEID
, 'instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
));
984 // Define id annotations
986 $event->annotate_ids('user', 'userid');
987 $event->annotate_ids('group', 'groupid');
988 $event->annotate_files('calendar', 'event_description', 'id');
990 // Return the root element (events)
996 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
997 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
999 class backup_gradebook_structure_step
extends backup_structure_step
{
1002 * We need to decide conditionally, based on dynamic information
1003 * about the execution of this step. Only will be executed if all
1004 * the module gradeitems have been already included in backup
1006 protected function execute_condition() {
1007 $courseid = $this->get_courseid();
1008 if ($courseid == SITEID
) {
1012 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1015 protected function define_structure() {
1018 // are we including user info?
1019 $userinfo = $this->get_setting_value('users');
1021 $gradebook = new backup_nested_element('gradebook');
1023 //grade_letters are done in backup_activity_grades_structure_step()
1025 //calculated grade items
1026 $grade_items = new backup_nested_element('grade_items');
1027 $grade_item = new backup_nested_element('grade_item', array('id'), array(
1028 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1029 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1030 'calculation', 'gradetype', 'grademax', 'grademin',
1031 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1032 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
1033 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
1034 'needsupdate', 'timecreated', 'timemodified'));
1036 $this->add_plugin_structure('local', $grade_item, true);
1038 $grade_grades = new backup_nested_element('grade_grades');
1039 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
1040 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1041 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1042 'locked', 'locktime', 'exported', 'overridden',
1043 'excluded', 'feedback', 'feedbackformat', 'information',
1044 'informationformat', 'timecreated', 'timemodified',
1045 'aggregationstatus', 'aggregationweight'));
1048 $grade_categories = new backup_nested_element('grade_categories');
1049 $grade_category = new backup_nested_element('grade_category', array('id'), array(
1051 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
1052 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
1053 'timecreated', 'timemodified', 'hidden'));
1055 $letters = new backup_nested_element('grade_letters');
1056 $letter = new backup_nested_element('grade_letter', 'id', array(
1057 'lowerboundary', 'letter'));
1059 $grade_settings = new backup_nested_element('grade_settings');
1060 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
1063 $gradebook_attributes = new backup_nested_element('attributes', null, array('calculations_freeze'));
1066 $gradebook->add_child($gradebook_attributes);
1068 $gradebook->add_child($grade_categories);
1069 $grade_categories->add_child($grade_category);
1071 $gradebook->add_child($grade_items);
1072 $grade_items->add_child($grade_item);
1073 $grade_item->add_child($grade_grades);
1074 $grade_grades->add_child($grade_grade);
1076 $gradebook->add_child($letters);
1077 $letters->add_child($letter);
1079 $gradebook->add_child($grade_settings);
1080 $grade_settings->add_child($grade_setting);
1084 // Add attribute with gradebook calculation freeze date if needed.
1085 $attributes = new stdClass();
1086 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
1087 if ($gradebookcalculationfreeze) {
1088 $attributes->calculations_freeze
= $gradebookcalculationfreeze;
1090 $gradebook_attributes->set_source_array([$attributes]);
1092 //Include manual, category and the course grade item
1093 $grade_items_sql ="SELECT * FROM {grade_items}
1094 WHERE courseid = :courseid
1095 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1096 $grade_items_params = array('courseid'=>backup
::VAR_COURSEID
);
1097 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1100 $grade_grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
1103 $grade_category_sql = "SELECT gc.*, gi.sortorder
1104 FROM {grade_categories} gc
1105 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1106 WHERE gc.courseid = :courseid
1107 AND (gi.itemtype='course' OR gi.itemtype='category')
1108 ORDER BY gc.parent ASC";//need parent categories before their children
1109 $grade_category_params = array('courseid'=>backup
::VAR_COURSEID
);
1110 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1112 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
1114 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1115 $settings = array();
1116 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1117 foreach ($rs as $record) {
1118 $settings[$record->name
] = $record;
1121 if (!isset($settings['minmaxtouse'])) {
1122 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse
);
1124 $grade_setting->set_source_array($settings);
1127 // Annotations (both as final as far as they are going to be exported in next steps)
1128 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1129 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1131 //just in case there are any users not already annotated by the activities
1132 $grade_grade->annotate_ids('userfinal', 'userid');
1134 // Return the root element
1140 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1142 class backup_grade_history_structure_step
extends backup_structure_step
{
1145 * Limit the execution.
1147 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1148 * because we do not want to save the history of items which are not backed up. At least for now.
1150 protected function execute_condition() {
1151 $courseid = $this->get_courseid();
1152 if ($courseid == SITEID
) {
1156 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1159 protected function define_structure() {
1162 $userinfo = $this->get_setting_value('users');
1163 $history = $this->get_setting_value('grade_histories');
1165 // Create the nested elements.
1166 $bookhistory = new backup_nested_element('grade_history');
1167 $grades = new backup_nested_element('grade_grades');
1168 $grade = new backup_nested_element('grade_grade', array('id'), array(
1169 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1170 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1171 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1172 'excluded', 'feedback', 'feedbackformat', 'information',
1173 'informationformat', 'timemodified'));
1176 $bookhistory->add_child($grades);
1177 $grades->add_child($grade);
1179 // This only happens if we are including user info and history.
1180 if ($userinfo && $history) {
1181 // Only keep the history of grades related to items which have been backed up, The query is
1182 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1183 $gradesql = "SELECT ggh.*
1184 FROM {grade_grades_history} ggh
1185 JOIN {grade_items} gi ON ggh.itemid = gi.id
1186 WHERE gi.courseid = :courseid
1187 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1188 $grade->set_source_sql($gradesql, array('courseid' => backup
::VAR_COURSEID
));
1191 // Annotations. (Final annotations as this step is part of the final task).
1192 $grade->annotate_ids('scalefinal', 'rawscaleid');
1193 $grade->annotate_ids('userfinal', 'loggeduser');
1194 $grade->annotate_ids('userfinal', 'userid');
1195 $grade->annotate_ids('userfinal', 'usermodified');
1197 // Return the root element.
1198 return $bookhistory;
1204 * structure step in charge if constructing the completion.xml file for all the users completion
1205 * information in a given activity
1207 class backup_userscompletion_structure_step
extends backup_structure_step
{
1210 * Skip completion on the front page.
1213 protected function execute_condition() {
1214 return ($this->get_courseid() != SITEID
);
1217 protected function define_structure() {
1219 // Define each element separated
1221 $completions = new backup_nested_element('completions');
1223 $completion = new backup_nested_element('completion', array('id'), array(
1224 'userid', 'completionstate', 'viewed', 'timemodified'));
1228 $completions->add_child($completion);
1232 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup
::VAR_MODID
));
1234 // Define id annotations
1236 $completion->annotate_ids('user', 'userid');
1238 // Return the root element (completions)
1239 return $completions;
1244 * structure step in charge of constructing the main groups.xml file for all the groups and
1245 * groupings information already annotated
1247 class backup_groups_structure_step
extends backup_structure_step
{
1249 protected function define_structure() {
1251 // To know if we are including users.
1252 $userinfo = $this->get_setting_value('users');
1253 // To know if we are including groups and groupings.
1254 $groupinfo = $this->get_setting_value('groups');
1256 // Define each element separated
1258 $groups = new backup_nested_element('groups');
1260 $group = new backup_nested_element('group', array('id'), array(
1261 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1262 'picture', 'timecreated', 'timemodified'));
1264 $members = new backup_nested_element('group_members');
1266 $member = new backup_nested_element('group_member', array('id'), array(
1267 'userid', 'timeadded', 'component', 'itemid'));
1269 $groupings = new backup_nested_element('groupings');
1271 $grouping = new backup_nested_element('grouping', 'id', array(
1272 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1273 'timecreated', 'timemodified'));
1275 $groupinggroups = new backup_nested_element('grouping_groups');
1277 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1278 'groupid', 'timeadded'));
1282 $groups->add_child($group);
1283 $groups->add_child($groupings);
1285 $group->add_child($members);
1286 $members->add_child($member);
1288 $groupings->add_child($grouping);
1289 $grouping->add_child($groupinggroups);
1290 $groupinggroups->add_child($groupinggroup);
1294 // This only happens if we are including groups/groupings.
1296 $group->set_source_sql("
1299 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1300 WHERE bi.backupid = ?
1301 AND bi.itemname = 'groupfinal'", array(backup
::VAR_BACKUPID
));
1303 $grouping->set_source_sql("
1306 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1307 WHERE bi.backupid = ?
1308 AND bi.itemname = 'groupingfinal'", array(backup
::VAR_BACKUPID
));
1309 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup
::VAR_PARENTID
));
1311 // This only happens if we are including users.
1313 $member->set_source_table('groups_members', array('groupid' => backup
::VAR_PARENTID
));
1317 // Define id annotations (as final)
1319 $member->annotate_ids('userfinal', 'userid');
1321 // Define file annotations
1323 $group->annotate_files('group', 'description', 'id');
1324 $group->annotate_files('group', 'icon', 'id');
1325 $grouping->annotate_files('grouping', 'description', 'id');
1327 // Return the root element (groups)
1333 * structure step in charge of constructing the main users.xml file for all the users already
1334 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1337 class backup_users_structure_step
extends backup_structure_step
{
1339 protected function define_structure() {
1342 // To know if we are anonymizing users
1343 $anonymize = $this->get_setting_value('anonymize');
1344 // To know if we are including role assignments
1345 $roleassignments = $this->get_setting_value('role_assignments');
1347 // Define each element separate.
1349 $users = new backup_nested_element('users');
1351 // Create the array of user fields by hand, as far as we have various bits to control
1352 // anonymize option, password backup, mnethostid...
1354 // First, the fields not needing anonymization nor special handling
1355 $normalfields = array(
1356 'confirmed', 'policyagreed', 'deleted',
1357 'lang', 'theme', 'timezone', 'firstaccess',
1358 'lastaccess', 'lastlogin', 'currentlogin',
1359 'mailformat', 'maildigest', 'maildisplay',
1360 'autosubscribe', 'trackforums', 'timecreated',
1361 'timemodified', 'trustbitmask');
1363 // Then, the fields potentially needing anonymization
1364 $anonfields = array(
1365 'username', 'idnumber', 'email', 'phone1',
1366 'phone2', 'institution', 'department', 'address',
1367 'city', 'country', 'lastip', 'picture',
1368 'description', 'descriptionformat', 'imagealt', 'auth');
1369 $anonfields = array_merge($anonfields, \core_user\fields
::get_name_fields());
1371 // Add anonymized fields to $userfields with custom final element
1372 foreach ($anonfields as $field) {
1374 $userfields[] = new anonymizer_final_element($field);
1376 $userfields[] = $field; // No anonymization, normally added
1380 // mnethosturl requires special handling (custom final element)
1381 $userfields[] = new mnethosturl_final_element('mnethosturl');
1383 // password added conditionally
1384 if (!empty($CFG->includeuserpasswordsinbackup
)) {
1385 $userfields[] = 'password';
1388 // Merge all the fields
1389 $userfields = array_merge($userfields, $normalfields);
1391 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1393 $customfields = new backup_nested_element('custom_fields');
1395 $customfield = new backup_nested_element('custom_field', array('id'), array(
1396 'field_name', 'field_type', 'field_data'));
1398 $tags = new backup_nested_element('tags');
1400 $tag = new backup_nested_element('tag', array('id'), array(
1401 'name', 'rawname'));
1403 $preferences = new backup_nested_element('preferences');
1405 $preference = new backup_nested_element('preference', array('id'), array(
1408 $roles = new backup_nested_element('roles');
1410 $overrides = new backup_nested_element('role_overrides');
1412 $override = new backup_nested_element('override', array('id'), array(
1413 'roleid', 'capability', 'permission', 'timemodified',
1416 $assignments = new backup_nested_element('role_assignments');
1418 $assignment = new backup_nested_element('assignment', array('id'), array(
1419 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1424 $users->add_child($user);
1426 $user->add_child($customfields);
1427 $customfields->add_child($customfield);
1429 $user->add_child($tags);
1430 $tags->add_child($tag);
1432 $user->add_child($preferences);
1433 $preferences->add_child($preference);
1435 $user->add_child($roles);
1437 $roles->add_child($overrides);
1438 $roles->add_child($assignments);
1440 $overrides->add_child($override);
1441 $assignments->add_child($assignment);
1445 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1447 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1448 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER
. '
1449 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1450 WHERE bi.backupid = ?
1451 AND bi.itemname = ?', array(
1452 backup_helper
::is_sqlparam($this->get_backupid()),
1453 backup_helper
::is_sqlparam('userfinal')));
1455 // All the rest on information is only added if we arent
1456 // in an anonymized backup
1458 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1459 FROM {user_info_field} f
1460 JOIN {user_info_data} d ON d.fieldid = f.id
1461 WHERE d.userid = ?', array(backup
::VAR_PARENTID
));
1463 $customfield->set_source_alias('shortname', 'field_name');
1464 $customfield->set_source_alias('datatype', 'field_type');
1465 $customfield->set_source_alias('data', 'field_data');
1467 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1469 JOIN {tag_instance} ti ON ti.tagid = t.id
1470 WHERE ti.itemtype = ?
1471 AND ti.itemid = ?', array(
1472 backup_helper
::is_sqlparam('user'),
1473 backup
::VAR_PARENTID
));
1475 $preference->set_source_table('user_preferences', array('userid' => backup
::VAR_PARENTID
));
1477 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1479 // Assignments only added if specified
1480 if ($roleassignments) {
1481 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1484 // Define id annotations (as final)
1485 $override->annotate_ids('rolefinal', 'roleid');
1487 // Return root element (users)
1493 * structure step in charge of constructing the block.xml file for one
1494 * given block (instance and positions). If the block has custom DB structure
1495 * that will go to a separate file (different step defined in block class)
1497 class backup_block_instance_structure_step
extends backup_structure_step
{
1499 protected function define_structure() {
1502 // Define each element separated
1504 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1505 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1506 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata',
1507 'timecreated', 'timemodified'));
1509 $positions = new backup_nested_element('block_positions');
1511 $position = new backup_nested_element('block_position', array('id'), array(
1512 'contextid', 'pagetype', 'subpage', 'visible',
1513 'region', 'weight'));
1517 $block->add_child($positions);
1518 $positions->add_child($position);
1520 // Transform configdata information if needed (process links and friends)
1521 $blockrec = $DB->get_record('block_instances', array('id' => $this->task
->get_blockid()));
1522 if ($attrstotransform = $this->task
->get_configdata_encoded_attributes()) {
1523 $configdata = (array)unserialize(base64_decode($blockrec->configdata
));
1524 foreach ($configdata as $attribute => $value) {
1525 if (in_array($attribute, $attrstotransform)) {
1526 $configdata[$attribute] = $this->contenttransformer
->process($value);
1529 $blockrec->configdata
= base64_encode(serialize((object)$configdata));
1531 $blockrec->contextid
= $this->task
->get_contextid();
1532 // Get the version of the block
1533 $blockrec->version
= get_config('block_'.$this->task
->get_blockname(), 'version');
1537 $block->set_source_array(array($blockrec));
1539 $position->set_source_table('block_positions', array('blockinstanceid' => backup
::VAR_PARENTID
));
1541 // File anotations (for fileareas specified on each block)
1542 foreach ($this->task
->get_fileareas() as $filearea) {
1543 $block->annotate_files('block_' . $this->task
->get_blockname(), $filearea, null);
1546 // Return the root element (block)
1552 * structure step in charge of constructing the logs.xml file for all the log records found
1553 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1554 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1555 * that just in case they become restored some day in the future
1557 class backup_course_logs_structure_step
extends backup_structure_step
{
1559 protected function define_structure() {
1561 // Define each element separated
1563 $logs = new backup_nested_element('logs');
1565 $log = new backup_nested_element('log', array('id'), array(
1566 'time', 'userid', 'ip', 'module',
1567 'action', 'url', 'info'));
1571 $logs->add_child($log);
1573 // Define sources (all the records belonging to the course, having cmid = 0)
1575 $log->set_source_table('log', array('course' => backup
::VAR_COURSEID
, 'cmid' => backup_helper
::is_sqlparam(0)));
1578 // NOTE: We don't annotate users from logs as far as they MUST be
1579 // always annotated by the course (enrol, ras... whatever)
1581 // Return the root element (logs)
1588 * structure step in charge of constructing the logs.xml file for all the log records found
1591 class backup_activity_logs_structure_step
extends backup_structure_step
{
1593 protected function define_structure() {
1595 // Define each element separated
1597 $logs = new backup_nested_element('logs');
1599 $log = new backup_nested_element('log', array('id'), array(
1600 'time', 'userid', 'ip', 'module',
1601 'action', 'url', 'info'));
1605 $logs->add_child($log);
1609 $log->set_source_table('log', array('cmid' => backup
::VAR_MODID
));
1612 // NOTE: We don't annotate users from logs as far as they MUST be
1613 // always annotated by the activity (true participants).
1615 // Return the root element (logs)
1622 * Structure step in charge of constructing the logstores.xml file for the course logs.
1624 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1625 * it, for logs belonging to the course level.
1627 class backup_course_logstores_structure_step
extends backup_structure_step
{
1629 protected function define_structure() {
1631 // Define the structure of logstores container.
1632 $logstores = new backup_nested_element('logstores');
1633 $logstore = new backup_nested_element('logstore');
1634 $logstores->add_child($logstore);
1636 // Add the tool_log logstore subplugins information to the logstore element.
1637 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1644 * Structure step in charge of constructing the loglastaccess.xml file for the course logs.
1646 * This backup step will backup the logs of the user_lastaccess table.
1648 class backup_course_loglastaccess_structure_step
extends backup_structure_step
{
1651 * This function creates the structures for the loglastaccess.xml file.
1652 * Expected structure would look like this.
1654 * <loglastaccess id=2>
1655 * <userid>5</userid>
1656 * <timeaccess>1616887341</timeaccess>
1658 * </loglastaccesses>
1660 * @return backup_nested_element
1662 protected function define_structure() {
1664 // To know if we are including userinfo.
1665 $userinfo = $this->get_setting_value('users');
1667 // Define the structure of logstores container.
1668 $lastaccesses = new backup_nested_element('lastaccesses');
1669 $lastaccess = new backup_nested_element('lastaccess', array('id'), array('userid', 'timeaccess'));
1671 // Define build tree.
1672 $lastaccesses->add_child($lastaccess);
1674 // This element should only happen if we are including user info.
1677 $lastaccess->set_source_sql('
1678 SELECT id, userid, timeaccess
1679 FROM {user_lastaccess}
1680 WHERE courseid = ?',
1681 array(backup
::VAR_COURSEID
));
1683 // Define userid annotation to user.
1684 $lastaccess->annotate_ids('user', 'userid');
1687 // Return the root element (lastaccessess).
1688 return $lastaccesses;
1693 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1695 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1697 class backup_activity_logstores_structure_step
extends backup_course_logstores_structure_step
{
1701 * Course competencies backup structure step.
1703 class backup_course_competencies_structure_step
extends backup_structure_step
{
1705 protected function define_structure() {
1706 $userinfo = $this->get_setting_value('users');
1708 $wrapper = new backup_nested_element('course_competencies');
1710 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1711 $wrapper->add_child($settings);
1713 $sql = 'SELECT s.pushratingstouserplans
1714 FROM {' . \core_competency\course_competency_settings
::TABLE
. '} s
1715 WHERE s.courseid = :courseid';
1716 $settings->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1718 $competencies = new backup_nested_element('competencies');
1719 $wrapper->add_child($competencies);
1721 $competency = new backup_nested_element('competency', null, array('id', 'idnumber', 'ruleoutcome',
1722 'sortorder', 'frameworkid', 'frameworkidnumber'));
1723 $competencies->add_child($competency);
1725 $sql = 'SELECT c.id, c.idnumber, cc.ruleoutcome, cc.sortorder, f.id AS frameworkid, f.idnumber AS frameworkidnumber
1726 FROM {' . \core_competency\course_competency
::TABLE
. '} cc
1727 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cc.competencyid
1728 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1729 WHERE cc.courseid = :courseid
1730 ORDER BY cc.sortorder';
1731 $competency->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1733 $usercomps = new backup_nested_element('user_competencies');
1734 $wrapper->add_child($usercomps);
1736 $usercomp = new backup_nested_element('user_competency', null, array('userid', 'competencyid',
1737 'proficiency', 'grade'));
1738 $usercomps->add_child($usercomp);
1740 $sql = 'SELECT ucc.userid, ucc.competencyid, ucc.proficiency, ucc.grade
1741 FROM {' . \core_competency\user_competency_course
::TABLE
. '} ucc
1742 WHERE ucc.courseid = :courseid
1743 AND ucc.grade IS NOT NULL';
1744 $usercomp->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1745 $usercomp->annotate_ids('user', 'userid');
1752 * Execute conditions.
1756 protected function execute_condition() {
1758 // Do not execute if competencies are not included.
1759 if (!$this->get_setting_value('competencies')) {
1768 * Activity competencies backup structure step.
1770 class backup_activity_competencies_structure_step
extends backup_structure_step
{
1772 protected function define_structure() {
1773 $wrapper = new backup_nested_element('course_module_competencies');
1775 $competencies = new backup_nested_element('competencies');
1776 $wrapper->add_child($competencies);
1778 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1779 'sortorder', 'frameworkidnumber'));
1780 $competencies->add_child($competency);
1782 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.sortorder, f.idnumber AS frameworkidnumber
1783 FROM {' . \core_competency\course_module_competency
::TABLE
. '} cmc
1784 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cmc.competencyid
1785 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1786 WHERE cmc.cmid = :coursemoduleid
1787 ORDER BY cmc.sortorder';
1788 $competency->set_source_sql($sql, array('coursemoduleid' => backup
::VAR_MODID
));
1794 * Execute conditions.
1798 protected function execute_condition() {
1800 // Do not execute if competencies are not included.
1801 if (!$this->get_setting_value('competencies')) {
1810 * structure in charge of constructing the inforef.xml file for all the items we want
1811 * to have referenced there (users, roles, files...)
1813 class backup_inforef_structure_step
extends backup_structure_step
{
1815 protected function define_structure() {
1817 // Items we want to include in the inforef file.
1818 $items = backup_helper
::get_inforef_itemnames();
1822 $inforef = new backup_nested_element('inforef');
1824 // For each item, conditionally, if there are already records, build element
1825 foreach ($items as $itemname) {
1826 if (backup_structure_dbops
::annotations_exist($this->get_backupid(), $itemname)) {
1827 $elementroot = new backup_nested_element($itemname . 'ref');
1828 $element = new backup_nested_element($itemname, array(), array('id'));
1829 $inforef->add_child($elementroot);
1830 $elementroot->add_child($element);
1831 $element->set_source_sql("
1833 FROM {backup_ids_temp}
1836 array(backup
::VAR_BACKUPID
, backup_helper
::is_sqlparam($itemname)));
1840 // We don't annotate anything there, but rely in the next step
1841 // (move_inforef_annotations_to_final) that will change all the
1842 // already saved 'inforref' entries to their 'final' annotations.
1848 * This step will get all the annotations already processed to inforef.xml file and
1849 * transform them into 'final' annotations.
1851 class move_inforef_annotations_to_final
extends backup_execution_step
{
1853 protected function define_execution() {
1855 // Items we want to include in the inforef file
1856 $items = backup_helper
::get_inforef_itemnames();
1857 $progress = $this->task
->get_progress();
1858 $progress->start_progress($this->get_name(), count($items));
1860 foreach ($items as $itemname) {
1861 // Delegate to dbops
1862 backup_structure_dbops
::move_annotations_to_final($this->get_backupid(),
1863 $itemname, $progress);
1864 $progress->progress($done++
);
1866 $progress->end_progress();
1871 * structure in charge of constructing the files.xml file with all the
1872 * annotated (final) files along the process. At, the same time, and
1873 * using one specialised nested_element, will copy them form moodle storage
1876 class backup_final_files_structure_step
extends backup_structure_step
{
1878 protected function define_structure() {
1882 $files = new backup_nested_element('files');
1884 $file = new file_nested_element('file', array('id'), array(
1885 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1886 'filepath', 'filename', 'userid', 'filesize',
1887 'mimetype', 'status', 'timecreated', 'timemodified',
1888 'source', 'author', 'license', 'sortorder',
1889 'repositorytype', 'repositoryid', 'reference'));
1893 $files->add_child($file);
1897 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1899 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1900 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1901 LEFT JOIN {repository} r ON r.id = ri.typeid
1902 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1903 WHERE bi.backupid = ?
1904 AND bi.itemname = 'filefinal'", array(backup
::VAR_BACKUPID
));
1911 * Structure step in charge of creating the main moodle_backup.xml file
1912 * where all the information related to the backup, settings, license and
1913 * other information needed on restore is added*/
1914 class backup_main_structure_step
extends backup_structure_step
{
1916 protected function define_structure() {
1922 $info['name'] = $this->get_setting_value('filename');
1923 $info['moodle_version'] = $CFG->version
;
1924 $info['moodle_release'] = $CFG->release
;
1925 $info['backup_version'] = $CFG->backup_version
;
1926 $info['backup_release'] = $CFG->backup_release
;
1927 $info['backup_date'] = time();
1928 $info['backup_uniqueid']= $this->get_backupid();
1929 $info['mnet_remoteusers']=backup_controller_dbops
::backup_includes_mnet_remote_users($this->get_backupid());
1930 $info['include_files'] = backup_controller_dbops
::backup_includes_files($this->get_backupid());
1931 $info['include_file_references_to_external_content'] =
1932 backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
1933 $info['original_wwwroot']=$CFG->wwwroot
;
1934 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1935 $info['original_course_id'] = $this->get_courseid();
1936 $originalcourseinfo = backup_controller_dbops
::backup_get_original_course_info($this->get_courseid());
1937 $info['original_course_format'] = $originalcourseinfo->format
;
1938 $info['original_course_fullname'] = $originalcourseinfo->fullname
;
1939 $info['original_course_shortname'] = $originalcourseinfo->shortname
;
1940 $info['original_course_startdate'] = $originalcourseinfo->startdate
;
1941 $info['original_course_enddate'] = $originalcourseinfo->enddate
;
1942 $info['original_course_contextid'] = context_course
::instance($this->get_courseid())->id
;
1943 $info['original_system_contextid'] = context_system
::instance()->id
;
1945 // Get more information from controller
1946 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops
::get_moodle_backup_information(
1947 $this->get_backupid(), $this->get_task()->get_progress());
1951 $moodle_backup = new backup_nested_element('moodle_backup');
1953 $information = new backup_nested_element('information', null, array(
1954 'name', 'moodle_version', 'moodle_release', 'backup_version',
1955 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1956 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
1957 'original_course_fullname', 'original_course_shortname', 'original_course_startdate', 'original_course_enddate',
1958 'original_course_contextid', 'original_system_contextid'));
1960 $details = new backup_nested_element('details');
1962 $detail = new backup_nested_element('detail', array('backup_id'), array(
1963 'type', 'format', 'interactive', 'mode',
1964 'execution', 'executiontime'));
1966 $contents = new backup_nested_element('contents');
1968 $activities = new backup_nested_element('activities');
1970 $activity = new backup_nested_element('activity', null, array(
1971 'moduleid', 'sectionid', 'modulename', 'title',
1974 $sections = new backup_nested_element('sections');
1976 $section = new backup_nested_element('section', null, array(
1977 'sectionid', 'title', 'directory'));
1979 $course = new backup_nested_element('course', null, array(
1980 'courseid', 'title', 'directory'));
1982 $settings = new backup_nested_element('settings');
1984 $setting = new backup_nested_element('setting', null, array(
1985 'level', 'section', 'activity', 'name', 'value'));
1989 $moodle_backup->add_child($information);
1991 $information->add_child($details);
1992 $details->add_child($detail);
1994 $information->add_child($contents);
1995 if (!empty($cinfo['activities'])) {
1996 $contents->add_child($activities);
1997 $activities->add_child($activity);
1999 if (!empty($cinfo['sections'])) {
2000 $contents->add_child($sections);
2001 $sections->add_child($section);
2003 if (!empty($cinfo['course'])) {
2004 $contents->add_child($course);
2007 $information->add_child($settings);
2008 $settings->add_child($setting);
2013 $information->set_source_array(array((object)$info));
2015 $detail->set_source_array($dinfo);
2017 $activity->set_source_array($cinfo['activities']);
2019 $section->set_source_array($cinfo['sections']);
2021 $course->set_source_array($cinfo['course']);
2023 $setting->set_source_array($sinfo);
2025 // Prepare some information to be sent to main moodle_backup.xml file
2026 return $moodle_backup;
2032 * Execution step that will generate the final zip (.mbz) file with all the contents
2034 class backup_zip_contents
extends backup_execution_step
implements file_progress
{
2036 * @var bool True if we have started tracking progress
2038 protected $startedprogress;
2040 protected function define_execution() {
2043 $basepath = $this->get_basepath();
2045 // Get the list of files in directory
2046 $filestemp = get_directory_list($basepath, '', false, true, true);
2048 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
2049 $files[$file] = $basepath . '/' . $file;
2052 // Add the log file if exists
2053 $logfilepath = $basepath . '.log';
2054 if (file_exists($logfilepath)) {
2055 $files['moodle_backup.log'] = $logfilepath;
2058 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2059 $zipfile = $basepath . '/backup.mbz';
2061 // Get the zip packer
2062 $zippacker = get_file_packer('application/vnd.moodle.backup');
2064 // Track overall progress for the 2 long-running steps (archive to
2065 // pathname, get backup information).
2066 $reporter = $this->task
->get_progress();
2067 $reporter->start_progress('backup_zip_contents', 2);
2070 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
2072 // If any sub-progress happened, end it.
2073 if ($this->startedprogress
) {
2074 $this->task
->get_progress()->end_progress();
2075 $this->startedprogress
= false;
2077 // No progress was reported, manually move it on to the next overall task.
2078 $reporter->progress(1);
2081 // Something went wrong.
2082 if ($result === false) {
2084 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
2086 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
2088 backup_general_helper
::get_backup_information_from_mbz($zipfile, $this);
2089 } catch (backup_helper_exception
$e) {
2091 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo
);
2094 // If any sub-progress happened, end it.
2095 if ($this->startedprogress
) {
2096 $this->task
->get_progress()->end_progress();
2097 $this->startedprogress
= false;
2099 $reporter->progress(2);
2101 $reporter->end_progress();
2105 * Implementation for file_progress interface to display unzip progress.
2107 * @param int $progress Current progress
2108 * @param int $max Max value
2110 public function progress($progress = file_progress
::INDETERMINATE
, $max = file_progress
::INDETERMINATE
) {
2111 $reporter = $this->task
->get_progress();
2113 // Start tracking progress if necessary.
2114 if (!$this->startedprogress
) {
2115 $reporter->start_progress('extract_file_to_dir', ($max == file_progress
::INDETERMINATE
)
2116 ? \core\progress\base
::INDETERMINATE
: $max);
2117 $this->startedprogress
= true;
2120 // Pass progress through to whatever handles it.
2121 $reporter->progress(($progress == file_progress
::INDETERMINATE
)
2122 ? \core\progress\base
::INDETERMINATE
: $progress);
2127 * This step will send the generated backup file to its final destination
2129 class backup_store_backup_file
extends backup_execution_step
{
2131 protected function define_execution() {
2134 $basepath = $this->get_basepath();
2136 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2137 $zipfile = $basepath . '/backup.mbz';
2139 $has_file_references = backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
2140 // Perform storage and return it (TODO: shouldn't be array but proper result object)
2142 'backup_destination' => backup_helper
::store_backup_file($this->get_backupid(), $zipfile,
2143 $this->task
->get_progress()),
2144 'include_file_references_to_external_content' => $has_file_references
2151 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
2152 * and put them to the backup_ids tables, to be used later as base to backup them
2154 class backup_activity_grade_items_to_ids
extends backup_execution_step
{
2156 protected function define_execution() {
2158 // Fetch all activity grade items
2159 if ($items = grade_item
::fetch_all(array(
2160 'itemtype' => 'mod', 'itemmodule' => $this->task
->get_modulename(),
2161 'iteminstance' => $this->task
->get_activityid(), 'courseid' => $this->task
->get_courseid()))) {
2162 // Annotate them in backup_ids
2163 foreach ($items as $item) {
2164 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id
);
2172 * This step allows enrol plugins to annotate custom fields.
2174 * @package core_backup
2175 * @copyright 2014 University of Wisconsin
2176 * @author Matt Petro
2177 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2179 class backup_enrolments_execution_step
extends backup_execution_step
{
2182 * Function that will contain all the code to be executed.
2184 protected function define_execution() {
2187 $plugins = enrol_get_plugins(true);
2188 $enrols = $DB->get_records('enrol', array(
2189 'courseid' => $this->task
->get_courseid()));
2191 // Allow each enrol plugin to add annotations.
2192 foreach ($enrols as $enrol) {
2193 if (isset($plugins[$enrol->enrol
])) {
2194 $plugins[$enrol->enrol
]->backup_annotate_custom_fields($this, $enrol);
2200 * Annotate a single name/id pair.
2201 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
2203 * @param string $itemname
2204 * @param int $itemid
2206 public function annotate_id($itemname, $itemid) {
2207 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2212 * This step will annotate all the groups and groupings belonging to the course
2214 class backup_annotate_course_groups_and_groupings
extends backup_execution_step
{
2216 protected function define_execution() {
2219 // Get all the course groups
2220 if ($groups = $DB->get_records('groups', array(
2221 'courseid' => $this->task
->get_courseid()))) {
2222 foreach ($groups as $group) {
2223 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->id
);
2227 // Get all the course groupings
2228 if ($groupings = $DB->get_records('groupings', array(
2229 'courseid' => $this->task
->get_courseid()))) {
2230 foreach ($groupings as $grouping) {
2231 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id
);
2238 * This step will annotate all the groups belonging to already annotated groupings
2240 class backup_annotate_groups_from_groupings
extends backup_execution_step
{
2242 protected function define_execution() {
2245 // Fetch all the annotated groupings
2246 if ($groupings = $DB->get_records('backup_ids_temp', array(
2247 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2248 foreach ($groupings as $grouping) {
2249 if ($groups = $DB->get_records('groupings_groups', array(
2250 'groupingid' => $grouping->itemid
))) {
2251 foreach ($groups as $group) {
2252 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid
);
2261 * This step will annotate all the scales belonging to already annotated outcomes
2263 class backup_annotate_scales_from_outcomes
extends backup_execution_step
{
2265 protected function define_execution() {
2268 // Fetch all the annotated outcomes
2269 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2270 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2271 foreach ($outcomes as $outcome) {
2272 if ($scale = $DB->get_record('grade_outcomes', array(
2273 'id' => $outcome->itemid
))) {
2274 // Annotate as scalefinal because it's > 0
2275 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid
);
2283 * This step will generate all the file annotations for the already
2284 * annotated (final) question_categories. It calculates the different
2285 * contexts that are being backup and, annotates all the files
2286 * on every context belonging to the "question" component. As far as
2287 * we are always including *complete* question banks it is safe and
2288 * optimal to do that in this (one pass) way
2290 class backup_annotate_all_question_files
extends backup_execution_step
{
2292 protected function define_execution() {
2295 // Get all the different contexts for the final question_categories
2296 // annotated along the whole backup
2297 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2298 FROM {question_categories} qc
2299 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2300 WHERE bi.backupid = ?
2301 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2302 // To know about qtype specific components/fileareas
2303 $components = backup_qtype_plugin
::get_components_and_fileareas();
2305 foreach($rs as $record) {
2306 // Backup all the file areas the are managed by the core question component.
2307 // That is, by the question_type base class. In particular, we don't want
2308 // to include files belonging to responses here.
2309 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'questiontext', null);
2310 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'generalfeedback', null);
2311 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answer', null);
2312 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answerfeedback', null);
2313 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'hint', null);
2314 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'correctfeedback', null);
2315 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'partiallycorrectfeedback', null);
2316 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'incorrectfeedback', null);
2318 // For files belonging to question types, we make the leap of faith that
2319 // all the files belonging to the question type are part of the question definition,
2320 // so we can just backup all the files in bulk, without specifying each
2321 // file area name separately.
2322 foreach ($components as $component => $fileareas) {
2323 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, $component, null, null);
2331 * structure step in charge of constructing the questions.xml file for all the
2332 * question categories and questions required by the backup
2333 * and letters related to one activity
2335 class backup_questions_structure_step
extends backup_structure_step
{
2337 protected function define_structure() {
2339 // Define each element separated
2341 $qcategories = new backup_nested_element('question_categories');
2343 $qcategory = new backup_nested_element('question_category', array('id'), array(
2344 'name', 'contextid', 'contextlevel', 'contextinstanceid',
2345 'info', 'infoformat', 'stamp', 'parent',
2346 'sortorder', 'idnumber'));
2348 $questions = new backup_nested_element('questions');
2350 $question = new backup_nested_element('question', array('id'), array(
2351 'parent', 'name', 'questiontext', 'questiontextformat',
2352 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
2353 'qtype', 'length', 'stamp', 'version',
2354 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby', 'idnumber'));
2356 // attach qtype plugin structure to $question element, only one allowed
2357 $this->add_plugin_structure('qtype', $question, false);
2359 // attach local plugin stucture to $question element, multiple allowed
2360 $this->add_plugin_structure('local', $question, true);
2362 $qhints = new backup_nested_element('question_hints');
2364 $qhint = new backup_nested_element('question_hint', array('id'), array(
2365 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
2367 $tags = new backup_nested_element('tags');
2369 $tag = new backup_nested_element('tag', array('id', 'contextid'), array('name', 'rawname'));
2373 $qcategories->add_child($qcategory);
2374 $qcategory->add_child($questions);
2375 $questions->add_child($question);
2376 $question->add_child($qhints);
2377 $qhints->add_child($qhint);
2379 $question->add_child($tags);
2380 $tags->add_child($tag);
2382 // Define the sources
2384 $qcategory->set_source_sql("
2385 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
2386 FROM {question_categories} gc
2387 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2388 JOIN {context} co ON co.id = gc.contextid
2389 WHERE bi.backupid = ?
2390 AND bi.itemname = 'question_categoryfinal'", array(backup
::VAR_BACKUPID
));
2392 $question->set_source_table('question', array('category' => backup
::VAR_PARENTID
));
2394 $qhint->set_source_sql('
2396 FROM {question_hints}
2397 WHERE questionid = :questionid
2399 array('questionid' => backup
::VAR_PARENTID
));
2401 $tag->set_source_sql("SELECT t.id, ti.contextid, t.name, t.rawname
2403 JOIN {tag_instance} ti ON ti.tagid = t.id
2405 AND ti.itemtype = 'question'
2406 AND ti.component = 'core_question'",
2408 backup
::VAR_PARENTID
2411 // don't need to annotate ids nor files
2412 // (already done by {@link backup_annotate_all_question_files}
2414 return $qcategories;
2421 * This step will generate all the file annotations for the already
2422 * annotated (final) users. Need to do this here because each user
2423 * has its own context and structure tasks only are able to handle
2424 * one context. Also, this step will guarantee that every user has
2425 * its context created (req for other steps)
2427 class backup_annotate_all_user_files
extends backup_execution_step
{
2429 protected function define_execution() {
2432 // List of fileareas we are going to annotate
2433 $fileareas = array('profile', 'icon');
2435 // Fetch all annotated (final) users
2436 $rs = $DB->get_recordset('backup_ids_temp', array(
2437 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2438 $progress = $this->task
->get_progress();
2439 $progress->start_progress($this->get_name());
2440 foreach ($rs as $record) {
2441 $userid = $record->itemid
;
2442 $userctx = context_user
::instance($userid, IGNORE_MISSING
);
2444 continue; // User has not context, sure it's a deleted user, so cannot have files
2446 // Proceed with every user filearea
2447 foreach ($fileareas as $filearea) {
2448 // We don't need to specify itemid ($userid - 5th param) as far as by
2449 // context we can get all the associated files. See MDL-22092
2450 backup_structure_dbops
::annotate_files($this->get_backupid(), $userctx->id
, 'user', $filearea, null);
2451 $progress->progress();
2454 $progress->end_progress();
2461 * Defines the backup step for advanced grading methods attached to the activity module
2463 class backup_activity_grading_structure_step
extends backup_structure_step
{
2466 * Include the grading.xml only if the module supports advanced grading
2468 protected function execute_condition() {
2470 // No grades on the front page.
2471 if ($this->get_courseid() == SITEID
) {
2475 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING
, false);
2479 * Declares the gradable areas structures and data sources
2481 protected function define_structure() {
2483 // To know if we are including userinfo
2484 $userinfo = $this->get_setting_value('userinfo');
2486 // Define the elements
2488 $areas = new backup_nested_element('areas');
2490 $area = new backup_nested_element('area', array('id'), array(
2491 'areaname', 'activemethod'));
2493 $definitions = new backup_nested_element('definitions');
2495 $definition = new backup_nested_element('definition', array('id'), array(
2496 'method', 'name', 'description', 'descriptionformat', 'status',
2497 'timecreated', 'timemodified', 'options'));
2499 $instances = new backup_nested_element('instances');
2501 $instance = new backup_nested_element('instance', array('id'), array(
2502 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2503 'feedbackformat', 'timemodified'));
2505 // Build the tree including the method specific structures
2506 // (beware - the order of how gradingform plugins structures are attached is important)
2507 $areas->add_child($area);
2508 // attach local plugin stucture to $area element, multiple allowed
2509 $this->add_plugin_structure('local', $area, true);
2510 $area->add_child($definitions);
2511 $definitions->add_child($definition);
2512 $this->add_plugin_structure('gradingform', $definition, true);
2513 // attach local plugin stucture to $definition element, multiple allowed
2514 $this->add_plugin_structure('local', $definition, true);
2515 $definition->add_child($instances);
2516 $instances->add_child($instance);
2517 $this->add_plugin_structure('gradingform', $instance, false);
2518 // attach local plugin stucture to $instance element, multiple allowed
2519 $this->add_plugin_structure('local', $instance, true);
2521 // Define data sources
2523 $area->set_source_table('grading_areas', array('contextid' => backup
::VAR_CONTEXTID
,
2524 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2526 $definition->set_source_table('grading_definitions', array('areaid' => backup
::VAR_PARENTID
));
2529 $instance->set_source_table('grading_instances', array('definitionid' => backup
::VAR_PARENTID
));
2532 // Annotate references
2533 $definition->annotate_files('grading', 'description', 'id');
2534 $instance->annotate_ids('user', 'raterid');
2536 // Return the root element
2543 * structure step in charge of constructing the grades.xml file for all the grade items
2544 * and letters related to one activity
2546 class backup_activity_grades_structure_step
extends backup_structure_step
{
2549 * No grades on the front page.
2552 protected function execute_condition() {
2553 return ($this->get_courseid() != SITEID
);
2556 protected function define_structure() {
2559 require_once($CFG->libdir
. '/grade/constants.php');
2561 // To know if we are including userinfo
2562 $userinfo = $this->get_setting_value('userinfo');
2564 // Define each element separated
2566 $book = new backup_nested_element('activity_gradebook');
2568 $items = new backup_nested_element('grade_items');
2570 $item = new backup_nested_element('grade_item', array('id'), array(
2571 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2572 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2573 'calculation', 'gradetype', 'grademax', 'grademin',
2574 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2575 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2576 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2577 'needsupdate', 'timecreated', 'timemodified'));
2579 $grades = new backup_nested_element('grade_grades');
2581 $grade = new backup_nested_element('grade_grade', array('id'), array(
2582 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2583 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2584 'locked', 'locktime', 'exported', 'overridden',
2585 'excluded', 'feedback', 'feedbackformat', 'information',
2586 'informationformat', 'timecreated', 'timemodified',
2587 'aggregationstatus', 'aggregationweight'));
2589 $letters = new backup_nested_element('grade_letters');
2591 $letter = new backup_nested_element('grade_letter', 'id', array(
2592 'lowerboundary', 'letter'));
2596 $book->add_child($items);
2597 $items->add_child($item);
2599 $item->add_child($grades);
2600 $grades->add_child($grade);
2602 $book->add_child($letters);
2603 $letters->add_child($letter);
2607 $item->set_source_sql("SELECT gi.*
2608 FROM {grade_items} gi
2609 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2610 WHERE bi.backupid = ?
2611 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2613 // This only happens if we are including user info
2615 $grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
2616 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_FEEDBACK_FILEAREA
, 'id');
2619 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
2623 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2624 $item->annotate_ids('outcome', 'outcomeid');
2626 $grade->annotate_ids('user', 'userid');
2627 $grade->annotate_ids('user', 'usermodified');
2629 // Return the root element (book)
2636 * Structure step in charge of constructing the grade history of an activity.
2638 * This step is added to the task regardless of the setting 'grade_histories'.
2639 * The reason is to allow for a more flexible step in case the logic needs to be
2640 * split accross different settings to control the history of items and/or grades.
2642 class backup_activity_grade_history_structure_step
extends backup_structure_step
{
2645 * No grades on the front page.
2648 protected function execute_condition() {
2649 return ($this->get_courseid() != SITEID
);
2652 protected function define_structure() {
2655 require_once($CFG->libdir
. '/grade/constants.php');
2658 $userinfo = $this->get_setting_value('userinfo');
2659 $history = $this->get_setting_value('grade_histories');
2661 // Create the nested elements.
2662 $bookhistory = new backup_nested_element('grade_history');
2663 $grades = new backup_nested_element('grade_grades');
2664 $grade = new backup_nested_element('grade_grade', array('id'), array(
2665 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2666 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2667 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2668 'excluded', 'feedback', 'feedbackformat', 'information',
2669 'informationformat', 'timemodified'));
2672 $bookhistory->add_child($grades);
2673 $grades->add_child($grade);
2675 // This only happens if we are including user info and history.
2676 if ($userinfo && $history) {
2677 // Define sources. Only select the history related to existing activity items.
2678 $grade->set_source_sql("SELECT ggh.*
2679 FROM {grade_grades_history} ggh
2680 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2681 WHERE bi.backupid = ?
2682 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2683 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_HISTORY_FEEDBACK_FILEAREA
, 'id');
2687 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2688 $grade->annotate_ids('user', 'loggeduser');
2689 $grade->annotate_ids('user', 'userid');
2690 $grade->annotate_ids('user', 'usermodified');
2692 // Return the root element.
2693 return $bookhistory;
2698 * Backups up the course completion information for the course.
2700 class backup_course_completion_structure_step
extends backup_structure_step
{
2702 protected function execute_condition() {
2704 // No completion on front page.
2705 if ($this->get_courseid() == SITEID
) {
2709 // Check that all activities have been included
2710 if ($this->task
->is_excluding_activities()) {
2717 * The structure of the course completion backup
2719 * @return backup_nested_element
2721 protected function define_structure() {
2723 // To know if we are including user completion info
2724 $userinfo = $this->get_setting_value('userscompletion');
2726 $cc = new backup_nested_element('course_completion');
2728 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2729 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2730 'timeend', 'gradepass', 'role', 'roleshortname'
2733 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2735 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2736 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2739 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2740 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2743 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2744 'course','criteriatype','method','value'
2747 $cc->add_child($criteria);
2748 $criteria->add_child($criteriacompletions);
2749 $criteriacompletions->add_child($criteriacomplete);
2750 $cc->add_child($coursecompletions);
2751 $cc->add_child($aggregatemethod);
2753 // We need some extra data for the restore.
2754 // - courseinstances shortname rather than an ID.
2755 // - roleshortname in case restoring on a different site.
2756 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2757 FROM {course_completion_criteria} ccc
2758 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2759 LEFT JOIN {role} r ON r.id = ccc.role
2760 WHERE ccc.course = ?";
2761 $criteria->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2763 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup
::VAR_COURSEID
));
2766 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup
::VAR_PARENTID
));
2767 $coursecompletions->set_source_table('course_completions', array('course' => backup
::VAR_COURSEID
));
2770 $criteria->annotate_ids('role', 'role');
2771 $criteriacomplete->annotate_ids('user', 'userid');
2772 $coursecompletions->annotate_ids('user', 'userid');
2780 * Backup completion defaults for each module type.
2782 * @package core_backup
2783 * @copyright 2017 Marina Glancy
2784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2786 class backup_completion_defaults_structure_step
extends backup_structure_step
{
2789 * To conditionally decide if one step will be executed or no
2791 protected function execute_condition() {
2792 // No completion on front page.
2793 if ($this->get_courseid() == SITEID
) {
2800 * The structure of the course completion backup
2802 * @return backup_nested_element
2804 protected function define_structure() {
2806 $cc = new backup_nested_element('course_completion_defaults');
2808 $defaults = new backup_nested_element('course_completion_default', array('id'), array(
2809 'modulename', 'completion', 'completionview', 'completionusegrade', 'completionexpected', 'customrules'
2812 // Use module name instead of module id so we can insert into another site later.
2813 $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
2814 d.completionexpected, d.customrules
2815 FROM {course_completion_defaults} d join {modules} m on d.module = m.id
2816 WHERE d.course = ?";
2817 $defaults->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2819 $cc->add_child($defaults);
2826 * Structure step in charge of constructing the contentbank.xml file for all the contents found in a given context
2828 class backup_contentbankcontent_structure_step
extends backup_structure_step
{
2831 * Define structure for content bank step
2833 protected function define_structure() {
2835 // Define each element separated.
2836 $contents = new backup_nested_element('contents');
2837 $content = new backup_nested_element('content', ['id'], [
2838 'name', 'contenttype', 'instanceid', 'configdata', 'usercreated', 'usermodified', 'timecreated', 'timemodified']);
2841 $contents->add_child($content);
2844 $content->set_source_table('contentbank_content', ['contextid' => backup
::VAR_CONTEXTID
]);
2846 // Define annotations.
2847 $content->annotate_ids('user', 'usercreated');
2848 $content->annotate_ids('user', 'usermodified');
2849 $content->annotate_files('contentbank', 'public', 'id');
2851 // Return the root element (contents).