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');
199 * Helper to backup question reference data for an instance.
201 trait backup_question_reference_data_trait
{
204 * Backup the related data from reference table for the instance.
206 * @param backup_nested_element $element
207 * @param string $component
208 * @param string $questionarea
210 protected function add_question_references($element, $component, $questionarea) {
211 // Check $element is one nested_backup_element.
212 if (! $element instanceof backup_nested_element
) {
213 throw new backup_step_exception('question_states_bad_parent_element', $element);
216 $reference = new backup_nested_element('question_reference', ['id'],
217 ['usingcontextid', 'component', 'questionarea', 'questionbankentryid', 'version']);
219 $element->add_child($reference);
221 $reference->set_source_table('question_references', [
222 'usingcontextid' => backup
::VAR_CONTEXTID
,
223 'component' => backup_helper
::is_sqlparam($component),
224 'questionarea' => backup_helper
::is_sqlparam($questionarea),
225 'itemid' => backup
::VAR_PARENTID
231 * Helper to backup question set reference data for an instance.
233 trait backup_question_set_reference_trait
{
236 * Backup the related data from set_reference table for the instance.
238 * @param backup_nested_element $element
239 * @param string $component
240 * @param string $questionarea
242 protected function add_question_set_references($element, $component, $questionarea) {
243 // Check $element is one nested_backup_element.
244 if (! $element instanceof backup_nested_element
) {
245 throw new backup_step_exception('question_states_bad_parent_element', $element);
248 $setreference = new backup_nested_element('question_set_reference', ['id'],
249 ['usingcontextid', 'component', 'questionarea', 'questionscontextid', 'filtercondition']);
251 $element->add_child($setreference);
253 $setreference->set_source_table('question_set_references', [
254 'usingcontextid' => backup
::VAR_CONTEXTID
,
255 'component' => backup_helper
::is_sqlparam($component),
256 'questionarea' => backup_helper
::is_sqlparam($questionarea),
257 'itemid' => backup
::VAR_PARENTID
264 * Abstract structure step to help activities that store question attempt data, reference data and set reference data.
266 * @copyright 2011 The Open University
267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269 abstract class backup_questions_activity_structure_step
extends backup_activity_structure_step
{
270 use backup_questions_attempt_data_trait
;
271 use backup_question_reference_data_trait
;
272 use backup_question_set_reference_trait
;
277 * backup structure step in charge of calculating the categories to be
278 * included in backup, based in the context being backuped (module/course)
279 * and the already annotated questions present in backup_ids_temp
281 class backup_calculate_question_categories
extends backup_execution_step
{
283 protected function define_execution() {
284 backup_question_dbops
::calculate_question_categories($this->get_backupid(), $this->task
->get_contextid());
289 * backup structure step in charge of deleting all the questions annotated
290 * in the backup_ids_temp table
292 class backup_delete_temp_questions
extends backup_execution_step
{
294 protected function define_execution() {
295 backup_question_dbops
::delete_temp_questions($this->get_backupid());
300 * Abstract structure step, parent of all the block structure steps. Used to wrap the
301 * block structure definition within the main <block ...> tag
303 abstract class backup_block_structure_step
extends backup_structure_step
{
305 protected function prepare_block_structure($blockstructure) {
307 // Create the wrap element
308 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
311 $block->add_child($blockstructure);
314 $blockarr = array((object)array(
315 'id' => $this->task
->get_blockid(),
316 'blockname' => $this->task
->get_blockname(),
317 'contextid' => $this->task
->get_contextid()));
319 $block->set_source_array($blockarr);
321 // Return the root element (block)
327 * structure step that will generate the module.xml file for the activity,
328 * accumulating various information about the activity, annotating groupings
329 * and completion/avail conf
331 class backup_module_structure_step
extends backup_structure_step
{
333 protected function define_structure() {
336 // Define each element separated
338 $module = new backup_nested_element('module', array('id', 'version'), array(
339 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
340 'added', 'score', 'indent', 'visible', 'visibleoncoursepage',
341 'visibleold', 'groupmode', 'groupingid',
342 'completion', 'completiongradeitemnumber', 'completionpassgrade',
343 'completionview', 'completionexpected',
344 'availability', 'showdescription', 'downloadcontent', 'lang'));
346 $tags = new backup_nested_element('tags');
347 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
349 // attach format plugin structure to $module element, only one allowed
350 $this->add_plugin_structure('format', $module, false);
352 // Attach report plugin structure to $module element, multiple allowed.
353 $this->add_plugin_structure('report', $module, true);
355 // attach plagiarism plugin structure to $module element, there can be potentially
356 // many plagiarism plugins storing information about this course
357 $this->add_plugin_structure('plagiarism', $module, true);
359 // attach local plugin structure to $module, multiple allowed
360 $this->add_plugin_structure('local', $module, true);
362 // Attach admin tools plugin structure to $module.
363 $this->add_plugin_structure('tool', $module, true);
365 $module->add_child($tags);
366 $tags->add_child($tag);
369 $concat = $DB->sql_concat("'mod_'", 'm.name');
370 $module->set_source_sql("
371 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
372 FROM {course_modules} cm
373 JOIN {modules} m ON m.id = cm.module
374 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
375 JOIN {course_sections} s ON s.id = cm.section
376 WHERE cm.id = ?", array(backup
::VAR_MODID
));
378 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
380 JOIN {tag_instance} ti ON ti.tagid = t.id
381 WHERE ti.itemtype = 'course_modules'
382 AND ti.component = 'core'
383 AND ti.itemid = ?", array(backup
::VAR_MODID
));
385 // Define annotations
386 $module->annotate_ids('grouping', 'groupingid');
388 // Return the root element ($module)
394 * structure step that will generate the section.xml file for the section
397 class backup_section_structure_step
extends backup_structure_step
{
399 protected function define_structure() {
401 // Define each element separated
403 $section = new backup_nested_element('section', array('id'), array(
404 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
405 'availabilityjson', 'timemodified'));
407 // attach format plugin structure to $section element, only one allowed
408 $this->add_plugin_structure('format', $section, false);
410 // attach local plugin structure to $section element, multiple allowed
411 $this->add_plugin_structure('local', $section, true);
413 // Add nested elements for course_format_options table
414 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
415 'format', 'name', 'value'));
416 $section->add_child($formatoptions);
419 $section->set_source_table('course_sections', array('id' => backup
::VAR_SECTIONID
));
420 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
422 JOIN {course_format_options} cfo
423 ON cfo.courseid = c.id AND cfo.format = c.format
424 WHERE c.id = ? AND cfo.sectionid = ?',
425 array(backup
::VAR_COURSEID
, backup
::VAR_SECTIONID
));
428 $section->set_source_alias('section', 'number');
429 // The 'availability' field needs to be renamed because it clashes with
430 // the old nested element structure for availability data.
431 $section->set_source_alias('availability', 'availabilityjson');
434 $section->annotate_files('course', 'section', 'id');
441 * structure step that will generate the course.xml file for the course, including
442 * course category reference, tags, modules restriction information
443 * and some annotations (files & groupings)
445 class backup_course_structure_step
extends backup_structure_step
{
447 protected function define_structure() {
450 // Define each element separated
452 $course = new backup_nested_element('course', array('id', 'contextid'), array(
453 'shortname', 'fullname', 'idnumber',
454 'summary', 'summaryformat', 'format', 'showgrades',
455 'newsitems', 'startdate', 'enddate',
456 'marker', 'maxbytes', 'legacyfiles', 'showreports',
457 'visible', 'groupmode', 'groupmodeforce',
458 'defaultgroupingid', 'lang', 'theme',
459 'timecreated', 'timemodified',
462 'showcompletionconditions',
463 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
465 $category = new backup_nested_element('category', array('id'), array(
466 'name', 'description'));
468 $tags = new backup_nested_element('tags');
470 $tag = new backup_nested_element('tag', array('id'), array(
473 $customfields = new backup_nested_element('customfields');
474 $customfield = new backup_nested_element('customfield', array('id'), array(
475 'shortname', 'type', 'value', 'valueformat'
478 $courseformatoptions = new backup_nested_element('courseformatoptions');
479 $courseformatoption = new backup_nested_element('courseformatoption', [], [
480 'courseid', 'format', 'sectionid', 'name', 'value'
483 // attach format plugin structure to $course element, only one allowed
484 $this->add_plugin_structure('format', $course, false);
486 // attach theme plugin structure to $course element; multiple themes can
487 // save course data (in case of user theme, legacy theme, etc)
488 $this->add_plugin_structure('theme', $course, true);
490 // attach general report plugin structure to $course element; multiple
491 // reports can save course data if required
492 $this->add_plugin_structure('report', $course, true);
494 // attach course report plugin structure to $course element; multiple
495 // course reports can save course data if required
496 $this->add_plugin_structure('coursereport', $course, true);
498 // attach plagiarism plugin structure to $course element, there can be potentially
499 // many plagiarism plugins storing information about this course
500 $this->add_plugin_structure('plagiarism', $course, true);
502 // attach local plugin structure to $course element; multiple local plugins
503 // can save course data if required
504 $this->add_plugin_structure('local', $course, true);
506 // Attach admin tools plugin structure to $course element; multiple plugins
507 // can save course data if required.
508 $this->add_plugin_structure('tool', $course, true);
512 $course->add_child($category);
514 $course->add_child($tags);
515 $tags->add_child($tag);
517 $course->add_child($customfields);
518 $customfields->add_child($customfield);
520 $course->add_child($courseformatoptions);
521 $courseformatoptions->add_child($courseformatoption);
525 $courserec = $DB->get_record('course', array('id' => $this->task
->get_courseid()));
526 $courserec->contextid
= $this->task
->get_contextid();
528 // Add 'numsections' in order to be able to restore in previous versions of Moodle.
529 // Even though Moodle does not officially support restore into older verions of Moodle from the
530 // version where backup was made, without 'numsections' restoring will go very wrong.
531 if (!property_exists($courserec, 'numsections') && course_get_format($courserec)->uses_sections()) {
532 $courserec->numsections
= course_get_format($courserec)->get_last_section_number();
535 $course->set_source_array(array($courserec));
537 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category
));
539 $category->set_source_array(array($categoryrec));
541 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
543 JOIN {tag_instance} ti ON ti.tagid = t.id
544 WHERE ti.itemtype = ?
545 AND ti.itemid = ?', array(
546 backup_helper
::is_sqlparam('course'),
547 backup
::VAR_PARENTID
));
549 $courseformatoption->set_source_sql('SELECT id, format, sectionid, name, value
550 FROM {course_format_options}
551 WHERE courseid = ?', [ backup
::VAR_PARENTID
]);
553 $handler = core_course\customfield\course_handler
::create();
554 $fieldsforbackup = $handler->get_instance_data_for_backup($this->task
->get_courseid());
555 $customfield->set_source_array($fieldsforbackup);
559 $course->annotate_ids('grouping', 'defaultgroupingid');
561 $course->annotate_files('course', 'summary', null);
562 $course->annotate_files('course', 'overviewfiles', null);
564 if ($this->get_setting_value('legacyfiles')) {
565 $course->annotate_files('course', 'legacy', null);
568 // Return root element ($course)
575 * structure step that will generate the enrolments.xml file for the given course
577 class backup_enrolments_structure_step
extends backup_structure_step
{
580 * Skip enrolments on the front page.
583 protected function execute_condition() {
584 return ($this->get_courseid() != SITEID
);
587 protected function define_structure() {
590 // To know if we are including users
591 $users = $this->get_setting_value('users');
592 $keptroles = $this->task
->get_kept_roles();
594 // Define each element separated
596 $enrolments = new backup_nested_element('enrolments');
598 $enrols = new backup_nested_element('enrols');
600 $enrol = new backup_nested_element('enrol', array('id'), array(
601 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
602 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
603 'password', 'cost', 'currency', 'roleid',
604 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
605 'customchar1', 'customchar2', 'customchar3',
606 'customdec1', 'customdec2',
607 'customtext1', 'customtext2', 'customtext3', 'customtext4',
608 'timecreated', 'timemodified'));
610 $userenrolments = new backup_nested_element('user_enrolments');
612 $enrolment = new backup_nested_element('enrolment', array('id'), array(
613 'status', 'userid', 'timestart', 'timeend', 'modifierid',
617 $enrolments->add_child($enrols);
618 $enrols->add_child($enrol);
619 $enrol->add_child($userenrolments);
620 $userenrolments->add_child($enrolment);
622 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
623 $enrol->set_source_table('enrol', array('courseid' => backup
::VAR_COURSEID
), 'sortorder ASC');
625 // User enrolments only added only if users included.
626 if (empty($keptroles) && $users) {
627 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup
::VAR_PARENTID
));
628 $enrolment->annotate_ids('user', 'userid');
629 } else if (!empty($keptroles)) {
630 list($insql, $inparams) = $DB->get_in_or_equal($keptroles);
632 backup
::VAR_CONTEXTID
,
635 foreach ($inparams as $inparam) {
636 $params[] = backup_helper
::is_sqlparam($inparam);
638 $enrolment->set_source_sql(
640 FROM {user_enrolments} ue
641 INNER JOIN {role_assignments} ra ON ue.userid = ra.userid
642 WHERE ra.contextid = ?
644 AND ra.roleid $insql",
646 $enrolment->annotate_ids('user', 'userid');
649 $enrol->annotate_ids('role', 'roleid');
651 // Add enrol plugin structure.
652 $this->add_plugin_structure('enrol', $enrol, true);
659 * structure step that will generate the roles.xml file for the given context, observing
660 * the role_assignments setting to know if that part needs to be included
662 class backup_roles_structure_step
extends backup_structure_step
{
664 protected function define_structure() {
666 // To know if we are including role assignments
667 $roleassignments = $this->get_setting_value('role_assignments');
669 // Define each element separated
671 $roles = new backup_nested_element('roles');
673 $overrides = new backup_nested_element('role_overrides');
675 $override = new backup_nested_element('override', array('id'), array(
676 'roleid', 'capability', 'permission', 'timemodified',
679 $assignments = new backup_nested_element('role_assignments');
681 $assignment = new backup_nested_element('assignment', array('id'), array(
682 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
686 $roles->add_child($overrides);
687 $roles->add_child($assignments);
689 $overrides->add_child($override);
690 $assignments->add_child($assignment);
694 $override->set_source_table('role_capabilities', array('contextid' => backup
::VAR_CONTEXTID
));
696 // Assignments only added if specified
697 if ($roleassignments) {
698 $assignment->set_source_table('role_assignments', array('contextid' => backup
::VAR_CONTEXTID
));
701 // Define id annotations
702 $override->annotate_ids('role', 'roleid');
704 $assignment->annotate_ids('role', 'roleid');
706 $assignment->annotate_ids('user', 'userid');
708 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
715 * structure step that will generate the roles.xml containing the
716 * list of roles used along the whole backup process. Just raw
717 * list of used roles from role table
719 class backup_final_roles_structure_step
extends backup_structure_step
{
721 protected function define_structure() {
725 $rolesdef = new backup_nested_element('roles_definition');
727 $role = new backup_nested_element('role', array('id'), array(
728 'name', 'shortname', 'nameincourse', 'description',
729 'sortorder', 'archetype'));
733 $rolesdef->add_child($role);
737 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
739 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
740 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
741 WHERE bi.backupid = ?
742 AND bi.itemname = 'rolefinal'", array(backup
::VAR_CONTEXTID
, backup
::VAR_BACKUPID
));
744 // Return main element (rolesdef)
750 * structure step that will generate the scales.xml containing the
751 * list of scales used along the whole backup process.
753 class backup_final_scales_structure_step
extends backup_structure_step
{
755 protected function define_structure() {
759 $scalesdef = new backup_nested_element('scales_definition');
761 $scale = new backup_nested_element('scale', array('id'), array(
762 'courseid', 'userid', 'name', 'scale',
763 'description', 'descriptionformat', 'timemodified'));
767 $scalesdef->add_child($scale);
771 $scale->set_source_sql("SELECT s.*
773 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
774 WHERE bi.backupid = ?
775 AND bi.itemname = 'scalefinal'", array(backup
::VAR_BACKUPID
));
777 // Annotate scale files (they store files in system context, so pass it instead of default one)
778 $scale->annotate_files('grade', 'scale', 'id', context_system
::instance()->id
);
780 // Return main element (scalesdef)
786 * structure step that will generate the outcomes.xml containing the
787 * list of outcomes used along the whole backup process.
789 class backup_final_outcomes_structure_step
extends backup_structure_step
{
791 protected function define_structure() {
795 $outcomesdef = new backup_nested_element('outcomes_definition');
797 $outcome = new backup_nested_element('outcome', array('id'), array(
798 'courseid', 'userid', 'shortname', 'fullname',
799 'scaleid', 'description', 'descriptionformat', 'timecreated',
800 'timemodified','usermodified'));
804 $outcomesdef->add_child($outcome);
808 $outcome->set_source_sql("SELECT o.*
809 FROM {grade_outcomes} o
810 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
811 WHERE bi.backupid = ?
812 AND bi.itemname = 'outcomefinal'", array(backup
::VAR_BACKUPID
));
814 // Annotate outcome files (they store files in system context, so pass it instead of default one)
815 $outcome->annotate_files('grade', 'outcome', 'id', context_system
::instance()->id
);
817 // Return main element (outcomesdef)
823 * structure step in charge of constructing the filters.xml file for all the filters found
826 class backup_filters_structure_step
extends backup_structure_step
{
828 protected function define_structure() {
830 // Define each element separated
832 $filters = new backup_nested_element('filters');
834 $actives = new backup_nested_element('filter_actives');
836 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
838 $configs = new backup_nested_element('filter_configs');
840 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
844 $filters->add_child($actives);
845 $filters->add_child($configs);
847 $actives->add_child($active);
848 $configs->add_child($config);
852 list($activearr, $configarr) = filter_get_all_local_settings($this->task
->get_contextid());
854 $active->set_source_array($activearr);
855 $config->set_source_array($configarr);
857 // Return the root element (filters)
863 * Structure step in charge of constructing the comments.xml file for all the comments found in a given context.
865 class backup_comments_structure_step
extends backup_structure_step
{
867 protected function define_structure() {
868 // Define each element separated.
869 $comments = new backup_nested_element('comments');
871 $comment = new backup_nested_element('comment', array('id'), array(
872 'component', 'commentarea', 'itemid', 'content', 'format',
873 'userid', 'timecreated'));
876 $comments->add_child($comment);
879 $comment->set_source_table('comments', array('contextid' => backup
::VAR_CONTEXTID
));
881 // Define id annotations.
882 $comment->annotate_ids('user', 'userid');
884 // Return the root element (comments).
890 * structure step in charge of constructing the badges.xml file for all the badges found
893 class backup_badges_structure_step
extends backup_structure_step
{
895 protected function execute_condition() {
896 // Check that all activities have been included.
897 if ($this->task
->is_excluding_activities()) {
903 protected function define_structure() {
906 require_once($CFG->libdir
. '/badgeslib.php');
907 // Define each element separated.
909 $badges = new backup_nested_element('badges');
910 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
911 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
912 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
913 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron',
914 'version', 'language', 'imageauthorname', 'imageauthoremail', 'imageauthorurl',
917 $criteria = new backup_nested_element('criteria');
918 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
919 'criteriatype', 'method', 'description', 'descriptionformat'));
921 $endorsement = new backup_nested_element('endorsement', array('id'), array('badgeid',
922 'issuername', 'issuerurl', 'issueremail', 'claimid', 'claimcomment', 'dateissued'));
924 $alignments = new backup_nested_element('alignments');
925 $alignment = new backup_nested_element('alignment', array('id'), array('badgeid',
926 'targetname', 'targeturl', 'targetdescription', 'targetframework', 'targetcode'));
928 $relatedbadges = new backup_nested_element('relatedbadges');
929 $relatedbadge = new backup_nested_element('relatedbadge', array('id'), array('badgeid',
932 $parameters = new backup_nested_element('parameters');
933 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
934 'name', 'value', 'criteriatype'));
936 $manual_awards = new backup_nested_element('manual_awards');
937 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
938 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
942 $badges->add_child($badge);
943 $badge->add_child($criteria);
944 $criteria->add_child($criterion);
945 $criterion->add_child($parameters);
946 $parameters->add_child($parameter);
947 $badge->add_child($endorsement);
948 $badge->add_child($alignments);
949 $alignments->add_child($alignment);
950 $badge->add_child($relatedbadges);
951 $relatedbadges->add_child($relatedbadge);
952 $badge->add_child($manual_awards);
953 $manual_awards->add_child($manual_award);
960 WHERE courseid = :courseid
961 AND status != ' . BADGE_STATUS_ARCHIVED
;
963 'courseid' => backup
::VAR_COURSEID
965 $badge->set_source_sql($parametersql, $parameterparams);
966 $criterion->set_source_table('badge_criteria', array('badgeid' => backup
::VAR_PARENTID
));
967 $endorsement->set_source_table('badge_endorsement', array('badgeid' => backup
::VAR_PARENTID
));
969 $alignment->set_source_table('badge_alignment', array('badgeid' => backup
::VAR_PARENTID
));
970 $relatedbadge->set_source_table('badge_related', array('badgeid' => backup
::VAR_PARENTID
));
972 $parametersql = 'SELECT cp.*, c.criteriatype
973 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
975 WHERE critid = :critid';
976 $parameterparams = array('critid' => backup
::VAR_PARENTID
);
977 $parameter->set_source_sql($parametersql, $parameterparams);
979 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup
::VAR_PARENTID
));
981 // Define id annotations.
983 $badge->annotate_ids('user', 'usercreated');
984 $badge->annotate_ids('user', 'usermodified');
985 $criterion->annotate_ids('badge', 'badgeid');
986 $parameter->annotate_ids('criterion', 'critid');
987 $endorsement->annotate_ids('badge', 'badgeid');
988 $alignment->annotate_ids('badge', 'badgeid');
989 $relatedbadge->annotate_ids('badge', 'badgeid');
990 $relatedbadge->annotate_ids('badge', 'relatedbadgeid');
991 $badge->annotate_files('badges', 'badgeimage', 'id');
992 $manual_award->annotate_ids('badge', 'badgeid');
993 $manual_award->annotate_ids('user', 'recipientid');
994 $manual_award->annotate_ids('user', 'issuerid');
995 $manual_award->annotate_ids('role', 'issuerrole');
997 // Return the root element ($badges).
1003 * structure step in charge of constructing the calender.xml file for all the events found
1004 * in a given context
1006 class backup_calendarevents_structure_step
extends backup_structure_step
{
1008 protected function define_structure() {
1010 // Define each element separated
1012 $events = new backup_nested_element('events');
1014 $event = new backup_nested_element('event', array('id'), array(
1015 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
1016 'repeatid', 'modulename', 'instance', 'type', 'eventtype', 'timestart',
1017 'timeduration', 'timesort', 'visible', 'uuid', 'sequence', 'timemodified',
1018 'priority', 'location'));
1021 $events->add_child($event);
1024 if ($this->name
== 'course_calendar') {
1025 $calendar_items_sql ="SELECT * FROM {event}
1026 WHERE courseid = :courseid
1027 AND (eventtype = 'course' OR eventtype = 'group')";
1028 $calendar_items_params = array('courseid'=>backup
::VAR_COURSEID
);
1029 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
1030 } else if ($this->name
== 'activity_calendar') {
1031 // We don't backup action events.
1032 $params = array('instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
,
1033 'type' => array('sqlparam' => CALENDAR_EVENT_TYPE_ACTION
));
1034 // If we don't want to include the userinfo in the backup then setting the courseid
1035 // will filter out all of the user override events (which have a course id of zero).
1037 if (!$this->get_setting_value('userinfo')) {
1038 $params['courseid'] = backup
::VAR_COURSEID
;
1039 $coursewhere = " AND courseid = :courseid";
1041 $calendarsql = "SELECT * FROM {event}
1042 WHERE instance = :instance
1044 AND modulename = :modulename";
1045 $calendarsql = $calendarsql . $coursewhere;
1046 $event->set_source_sql($calendarsql, $params);
1048 $event->set_source_table('event', array('courseid' => backup
::VAR_COURSEID
, 'instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
));
1051 // Define id annotations
1053 $event->annotate_ids('user', 'userid');
1054 $event->annotate_ids('group', 'groupid');
1055 $event->annotate_files('calendar', 'event_description', 'id');
1057 // Return the root element (events)
1063 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
1064 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
1066 class backup_gradebook_structure_step
extends backup_structure_step
{
1069 * We need to decide conditionally, based on dynamic information
1070 * about the execution of this step. Only will be executed if all
1071 * the module gradeitems have been already included in backup
1073 protected function execute_condition() {
1074 $courseid = $this->get_courseid();
1075 if ($courseid == SITEID
) {
1079 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1082 protected function define_structure() {
1085 // are we including user info?
1086 $userinfo = $this->get_setting_value('users');
1088 $gradebook = new backup_nested_element('gradebook');
1090 //grade_letters are done in backup_activity_grades_structure_step()
1092 //calculated grade items
1093 $grade_items = new backup_nested_element('grade_items');
1094 $grade_item = new backup_nested_element('grade_item', array('id'), array(
1095 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1096 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1097 'calculation', 'gradetype', 'grademax', 'grademin',
1098 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1099 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
1100 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
1101 'needsupdate', 'timecreated', 'timemodified'));
1103 $this->add_plugin_structure('local', $grade_item, true);
1105 $grade_grades = new backup_nested_element('grade_grades');
1106 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
1107 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1108 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1109 'locked', 'locktime', 'exported', 'overridden',
1110 'excluded', 'feedback', 'feedbackformat', 'information',
1111 'informationformat', 'timecreated', 'timemodified',
1112 'aggregationstatus', 'aggregationweight'));
1115 $grade_categories = new backup_nested_element('grade_categories');
1116 $grade_category = new backup_nested_element('grade_category', array('id'), array(
1118 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
1119 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
1120 'timecreated', 'timemodified', 'hidden'));
1122 $letters = new backup_nested_element('grade_letters');
1123 $letter = new backup_nested_element('grade_letter', 'id', array(
1124 'lowerboundary', 'letter'));
1126 $grade_settings = new backup_nested_element('grade_settings');
1127 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
1130 $gradebook_attributes = new backup_nested_element('attributes', null, array('calculations_freeze'));
1133 $gradebook->add_child($gradebook_attributes);
1135 $gradebook->add_child($grade_categories);
1136 $grade_categories->add_child($grade_category);
1138 $gradebook->add_child($grade_items);
1139 $grade_items->add_child($grade_item);
1140 $grade_item->add_child($grade_grades);
1141 $grade_grades->add_child($grade_grade);
1143 $gradebook->add_child($letters);
1144 $letters->add_child($letter);
1146 $gradebook->add_child($grade_settings);
1147 $grade_settings->add_child($grade_setting);
1151 // Add attribute with gradebook calculation freeze date if needed.
1152 $attributes = new stdClass();
1153 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
1154 if ($gradebookcalculationfreeze) {
1155 $attributes->calculations_freeze
= $gradebookcalculationfreeze;
1157 $gradebook_attributes->set_source_array([$attributes]);
1159 //Include manual, category and the course grade item
1160 $grade_items_sql ="SELECT * FROM {grade_items}
1161 WHERE courseid = :courseid
1162 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1163 $grade_items_params = array('courseid'=>backup
::VAR_COURSEID
);
1164 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1167 $grade_grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
1170 $grade_category_sql = "SELECT gc.*, gi.sortorder
1171 FROM {grade_categories} gc
1172 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1173 WHERE gc.courseid = :courseid
1174 AND (gi.itemtype='course' OR gi.itemtype='category')
1175 ORDER BY gc.parent ASC";//need parent categories before their children
1176 $grade_category_params = array('courseid'=>backup
::VAR_COURSEID
);
1177 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1179 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
1181 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1182 $settings = array();
1183 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1184 foreach ($rs as $record) {
1185 $settings[$record->name
] = $record;
1188 if (!isset($settings['minmaxtouse'])) {
1189 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse
);
1191 $grade_setting->set_source_array($settings);
1194 // Annotations (both as final as far as they are going to be exported in next steps)
1195 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1196 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1198 //just in case there are any users not already annotated by the activities
1199 $grade_grade->annotate_ids('userfinal', 'userid');
1201 // Return the root element
1207 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1209 class backup_grade_history_structure_step
extends backup_structure_step
{
1212 * Limit the execution.
1214 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1215 * because we do not want to save the history of items which are not backed up. At least for now.
1217 protected function execute_condition() {
1218 $courseid = $this->get_courseid();
1219 if ($courseid == SITEID
) {
1223 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1226 protected function define_structure() {
1229 $userinfo = $this->get_setting_value('users');
1230 $history = $this->get_setting_value('grade_histories');
1232 // Create the nested elements.
1233 $bookhistory = new backup_nested_element('grade_history');
1234 $grades = new backup_nested_element('grade_grades');
1235 $grade = new backup_nested_element('grade_grade', array('id'), array(
1236 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1237 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1238 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1239 'excluded', 'feedback', 'feedbackformat', 'information',
1240 'informationformat', 'timemodified'));
1243 $bookhistory->add_child($grades);
1244 $grades->add_child($grade);
1246 // This only happens if we are including user info and history.
1247 if ($userinfo && $history) {
1248 // Only keep the history of grades related to items which have been backed up, The query is
1249 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1250 $gradesql = "SELECT ggh.*
1251 FROM {grade_grades_history} ggh
1252 JOIN {grade_items} gi ON ggh.itemid = gi.id
1253 WHERE gi.courseid = :courseid
1254 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1255 $grade->set_source_sql($gradesql, array('courseid' => backup
::VAR_COURSEID
));
1258 // Annotations. (Final annotations as this step is part of the final task).
1259 $grade->annotate_ids('scalefinal', 'rawscaleid');
1260 $grade->annotate_ids('userfinal', 'loggeduser');
1261 $grade->annotate_ids('userfinal', 'userid');
1262 $grade->annotate_ids('userfinal', 'usermodified');
1264 // Return the root element.
1265 return $bookhistory;
1271 * structure step in charge if constructing the completion.xml file for all the users completion
1272 * information in a given activity
1274 class backup_userscompletion_structure_step
extends backup_structure_step
{
1277 * Skip completion on the front page.
1280 protected function execute_condition() {
1281 return ($this->get_courseid() != SITEID
);
1284 protected function define_structure() {
1286 // Define each element separated
1287 $completions = new backup_nested_element('completions');
1289 $completion = new backup_nested_element('completion', array('id'), array(
1290 'userid', 'completionstate', 'viewed', 'timemodified'));
1294 $completions->add_child($completion);
1298 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup
::VAR_MODID
));
1300 // Define id annotations
1302 $completion->annotate_ids('user', 'userid');
1304 $completionviews = new backup_nested_element('completionviews');
1305 $completionview = new backup_nested_element('completionview', ['id'], ['userid', 'timecreated']);
1308 $completionviews->add_child($completionview);
1311 $completionview->set_source_table('course_modules_viewed', ['coursemoduleid' => backup
::VAR_MODID
]);
1313 // Define id annotations.
1314 $completionview->annotate_ids('user', 'userid');
1316 $completions->add_child($completionviews);
1317 // Return the root element (completions).
1318 return $completions;
1324 * structure step in charge of constructing the main groups.xml file for all the groups and
1325 * groupings information already annotated
1327 class backup_groups_structure_step
extends backup_structure_step
{
1329 protected function define_structure() {
1331 // To know if we are including users.
1332 $userinfo = $this->get_setting_value('users');
1333 // To know if we are including groups and groupings.
1334 $groupinfo = $this->get_setting_value('groups');
1336 // Define each element separated
1338 $groups = new backup_nested_element('groups');
1340 $group = new backup_nested_element('group', array('id'), array(
1341 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1342 'picture', 'timecreated', 'timemodified'));
1344 $members = new backup_nested_element('group_members');
1346 $member = new backup_nested_element('group_member', array('id'), array(
1347 'userid', 'timeadded', 'component', 'itemid'));
1349 $groupings = new backup_nested_element('groupings');
1351 $grouping = new backup_nested_element('grouping', 'id', array(
1352 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1353 'timecreated', 'timemodified'));
1355 $groupinggroups = new backup_nested_element('grouping_groups');
1357 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1358 'groupid', 'timeadded'));
1362 $groups->add_child($group);
1363 $groups->add_child($groupings);
1365 $group->add_child($members);
1366 $members->add_child($member);
1368 $groupings->add_child($grouping);
1369 $grouping->add_child($groupinggroups);
1370 $groupinggroups->add_child($groupinggroup);
1374 // This only happens if we are including groups/groupings.
1376 $group->set_source_sql("
1379 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1380 WHERE bi.backupid = ?
1381 AND bi.itemname = 'groupfinal'", array(backup
::VAR_BACKUPID
));
1383 $grouping->set_source_sql("
1386 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1387 WHERE bi.backupid = ?
1388 AND bi.itemname = 'groupingfinal'", array(backup
::VAR_BACKUPID
));
1389 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup
::VAR_PARENTID
));
1391 // This only happens if we are including users.
1393 $member->set_source_table('groups_members', array('groupid' => backup
::VAR_PARENTID
));
1397 // Define id annotations (as final)
1399 $member->annotate_ids('userfinal', 'userid');
1401 // Define file annotations
1403 $group->annotate_files('group', 'description', 'id');
1404 $group->annotate_files('group', 'icon', 'id');
1405 $grouping->annotate_files('grouping', 'description', 'id');
1407 // Return the root element (groups)
1413 * structure step in charge of constructing the main users.xml file for all the users already
1414 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1417 class backup_users_structure_step
extends backup_structure_step
{
1419 protected function define_structure() {
1422 // To know if we are anonymizing users
1423 $anonymize = $this->get_setting_value('anonymize');
1424 // To know if we are including role assignments
1425 $roleassignments = $this->get_setting_value('role_assignments');
1427 // Define each element separate.
1429 $users = new backup_nested_element('users');
1431 // Create the array of user fields by hand, as far as we have various bits to control
1432 // anonymize option, password backup, mnethostid...
1434 // First, the fields not needing anonymization nor special handling
1435 $normalfields = array(
1436 'confirmed', 'policyagreed', 'deleted',
1437 'lang', 'theme', 'timezone', 'firstaccess',
1438 'lastaccess', 'lastlogin', 'currentlogin',
1439 'mailformat', 'maildigest', 'maildisplay',
1440 'autosubscribe', 'trackforums', 'timecreated',
1441 'timemodified', 'trustbitmask');
1443 // Then, the fields potentially needing anonymization
1444 $anonfields = array(
1445 'username', 'idnumber', 'email', 'phone1',
1446 'phone2', 'institution', 'department', 'address',
1447 'city', 'country', 'lastip', 'picture',
1448 'description', 'descriptionformat', 'imagealt', 'auth');
1449 $anonfields = array_merge($anonfields, \core_user\fields
::get_name_fields());
1451 // Add anonymized fields to $userfields with custom final element
1452 foreach ($anonfields as $field) {
1454 $userfields[] = new anonymizer_final_element($field);
1456 $userfields[] = $field; // No anonymization, normally added
1460 // mnethosturl requires special handling (custom final element)
1461 $userfields[] = new mnethosturl_final_element('mnethosturl');
1463 // password added conditionally
1464 if (!empty($CFG->includeuserpasswordsinbackup
)) {
1465 $userfields[] = 'password';
1468 // Merge all the fields
1469 $userfields = array_merge($userfields, $normalfields);
1471 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1473 $customfields = new backup_nested_element('custom_fields');
1475 $customfield = new backup_nested_element('custom_field', array('id'), array(
1476 'field_name', 'field_type', 'field_data'));
1478 $tags = new backup_nested_element('tags');
1480 $tag = new backup_nested_element('tag', array('id'), array(
1481 'name', 'rawname'));
1483 $preferences = new backup_nested_element('preferences');
1485 $preference = new backup_nested_element('preference', array('id'), array(
1488 $roles = new backup_nested_element('roles');
1490 $overrides = new backup_nested_element('role_overrides');
1492 $override = new backup_nested_element('override', array('id'), array(
1493 'roleid', 'capability', 'permission', 'timemodified',
1496 $assignments = new backup_nested_element('role_assignments');
1498 $assignment = new backup_nested_element('assignment', array('id'), array(
1499 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1504 $users->add_child($user);
1506 $user->add_child($customfields);
1507 $customfields->add_child($customfield);
1509 $user->add_child($tags);
1510 $tags->add_child($tag);
1512 $user->add_child($preferences);
1513 $preferences->add_child($preference);
1515 $user->add_child($roles);
1517 $roles->add_child($overrides);
1518 $roles->add_child($assignments);
1520 $overrides->add_child($override);
1521 $assignments->add_child($assignment);
1525 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1527 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1528 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER
. '
1529 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1530 WHERE bi.backupid = ?
1531 AND bi.itemname = ?', array(
1532 backup_helper
::is_sqlparam($this->get_backupid()),
1533 backup_helper
::is_sqlparam('userfinal')));
1535 // All the rest on information is only added if we arent
1536 // in an anonymized backup
1538 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1539 FROM {user_info_field} f
1540 JOIN {user_info_data} d ON d.fieldid = f.id
1541 WHERE d.userid = ?', array(backup
::VAR_PARENTID
));
1543 $customfield->set_source_alias('shortname', 'field_name');
1544 $customfield->set_source_alias('datatype', 'field_type');
1545 $customfield->set_source_alias('data', 'field_data');
1547 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1549 JOIN {tag_instance} ti ON ti.tagid = t.id
1550 WHERE ti.itemtype = ?
1551 AND ti.itemid = ?', array(
1552 backup_helper
::is_sqlparam('user'),
1553 backup
::VAR_PARENTID
));
1555 $preference->set_source_table('user_preferences', array('userid' => backup
::VAR_PARENTID
));
1557 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1559 // Assignments only added if specified
1560 if ($roleassignments) {
1561 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1564 // Define id annotations (as final)
1565 $override->annotate_ids('rolefinal', 'roleid');
1567 // Return root element (users)
1573 * structure step in charge of constructing the block.xml file for one
1574 * given block (instance and positions). If the block has custom DB structure
1575 * that will go to a separate file (different step defined in block class)
1577 class backup_block_instance_structure_step
extends backup_structure_step
{
1579 protected function define_structure() {
1582 // Define each element separated
1584 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1585 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1586 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata',
1587 'timecreated', 'timemodified'));
1589 $positions = new backup_nested_element('block_positions');
1591 $position = new backup_nested_element('block_position', array('id'), array(
1592 'contextid', 'pagetype', 'subpage', 'visible',
1593 'region', 'weight'));
1597 $block->add_child($positions);
1598 $positions->add_child($position);
1600 // Transform configdata information if needed (process links and friends)
1601 $blockrec = $DB->get_record('block_instances', array('id' => $this->task
->get_blockid()));
1602 if ($attrstotransform = $this->task
->get_configdata_encoded_attributes()) {
1603 $configdata = (array)unserialize(base64_decode($blockrec->configdata
));
1604 foreach ($configdata as $attribute => $value) {
1605 if (in_array($attribute, $attrstotransform)) {
1606 $configdata[$attribute] = $this->contenttransformer
->process($value);
1609 $blockrec->configdata
= base64_encode(serialize((object)$configdata));
1611 $blockrec->contextid
= $this->task
->get_contextid();
1612 // Get the version of the block
1613 $blockrec->version
= get_config('block_'.$this->task
->get_blockname(), 'version');
1617 $block->set_source_array(array($blockrec));
1619 $position->set_source_table('block_positions', array('blockinstanceid' => backup
::VAR_PARENTID
));
1621 // File anotations (for fileareas specified on each block)
1622 foreach ($this->task
->get_fileareas() as $filearea) {
1623 $block->annotate_files('block_' . $this->task
->get_blockname(), $filearea, null);
1626 // Return the root element (block)
1632 * structure step in charge of constructing the logs.xml file for all the log records found
1633 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1634 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1635 * that just in case they become restored some day in the future
1637 class backup_course_logs_structure_step
extends backup_structure_step
{
1639 protected function define_structure() {
1641 // Define each element separated
1643 $logs = new backup_nested_element('logs');
1645 $log = new backup_nested_element('log', array('id'), array(
1646 'time', 'userid', 'ip', 'module',
1647 'action', 'url', 'info'));
1651 $logs->add_child($log);
1653 // Define sources (all the records belonging to the course, having cmid = 0)
1655 $log->set_source_table('log', array('course' => backup
::VAR_COURSEID
, 'cmid' => backup_helper
::is_sqlparam(0)));
1658 // NOTE: We don't annotate users from logs as far as they MUST be
1659 // always annotated by the course (enrol, ras... whatever)
1661 // Return the root element (logs)
1668 * structure step in charge of constructing the logs.xml file for all the log records found
1671 class backup_activity_logs_structure_step
extends backup_structure_step
{
1673 protected function define_structure() {
1675 // Define each element separated
1677 $logs = new backup_nested_element('logs');
1679 $log = new backup_nested_element('log', array('id'), array(
1680 'time', 'userid', 'ip', 'module',
1681 'action', 'url', 'info'));
1685 $logs->add_child($log);
1689 $log->set_source_table('log', array('cmid' => backup
::VAR_MODID
));
1692 // NOTE: We don't annotate users from logs as far as they MUST be
1693 // always annotated by the activity (true participants).
1695 // Return the root element (logs)
1702 * Structure step in charge of constructing the logstores.xml file for the course logs.
1704 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1705 * it, for logs belonging to the course level.
1707 class backup_course_logstores_structure_step
extends backup_structure_step
{
1709 protected function define_structure() {
1711 // Define the structure of logstores container.
1712 $logstores = new backup_nested_element('logstores');
1713 $logstore = new backup_nested_element('logstore');
1714 $logstores->add_child($logstore);
1716 // Add the tool_log logstore subplugins information to the logstore element.
1717 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1724 * Structure step in charge of constructing the loglastaccess.xml file for the course logs.
1726 * This backup step will backup the logs of the user_lastaccess table.
1728 class backup_course_loglastaccess_structure_step
extends backup_structure_step
{
1731 * This function creates the structures for the loglastaccess.xml file.
1732 * Expected structure would look like this.
1734 * <loglastaccess id=2>
1735 * <userid>5</userid>
1736 * <timeaccess>1616887341</timeaccess>
1738 * </loglastaccesses>
1740 * @return backup_nested_element
1742 protected function define_structure() {
1744 // To know if we are including userinfo.
1745 $userinfo = $this->get_setting_value('users');
1747 // Define the structure of logstores container.
1748 $lastaccesses = new backup_nested_element('lastaccesses');
1749 $lastaccess = new backup_nested_element('lastaccess', array('id'), array('userid', 'timeaccess'));
1751 // Define build tree.
1752 $lastaccesses->add_child($lastaccess);
1754 // This element should only happen if we are including user info.
1757 $lastaccess->set_source_sql('
1758 SELECT id, userid, timeaccess
1759 FROM {user_lastaccess}
1760 WHERE courseid = ?',
1761 array(backup
::VAR_COURSEID
));
1763 // Define userid annotation to user.
1764 $lastaccess->annotate_ids('user', 'userid');
1767 // Return the root element (lastaccessess).
1768 return $lastaccesses;
1773 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1775 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1777 class backup_activity_logstores_structure_step
extends backup_course_logstores_structure_step
{
1781 * Course competencies backup structure step.
1783 class backup_course_competencies_structure_step
extends backup_structure_step
{
1785 protected function define_structure() {
1786 $userinfo = $this->get_setting_value('users');
1788 $wrapper = new backup_nested_element('course_competencies');
1790 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1791 $wrapper->add_child($settings);
1793 $sql = 'SELECT s.pushratingstouserplans
1794 FROM {' . \core_competency\course_competency_settings
::TABLE
. '} s
1795 WHERE s.courseid = :courseid';
1796 $settings->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1798 $competencies = new backup_nested_element('competencies');
1799 $wrapper->add_child($competencies);
1801 $competency = new backup_nested_element('competency', null, array('id', 'idnumber', 'ruleoutcome',
1802 'sortorder', 'frameworkid', 'frameworkidnumber'));
1803 $competencies->add_child($competency);
1805 $sql = 'SELECT c.id, c.idnumber, cc.ruleoutcome, cc.sortorder, f.id AS frameworkid, f.idnumber AS frameworkidnumber
1806 FROM {' . \core_competency\course_competency
::TABLE
. '} cc
1807 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cc.competencyid
1808 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1809 WHERE cc.courseid = :courseid
1810 ORDER BY cc.sortorder';
1811 $competency->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1813 $usercomps = new backup_nested_element('user_competencies');
1814 $wrapper->add_child($usercomps);
1816 $usercomp = new backup_nested_element('user_competency', null, array('userid', 'competencyid',
1817 'proficiency', 'grade'));
1818 $usercomps->add_child($usercomp);
1820 $sql = 'SELECT ucc.userid, ucc.competencyid, ucc.proficiency, ucc.grade
1821 FROM {' . \core_competency\user_competency_course
::TABLE
. '} ucc
1822 WHERE ucc.courseid = :courseid
1823 AND ucc.grade IS NOT NULL';
1824 $usercomp->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1825 $usercomp->annotate_ids('user', 'userid');
1832 * Execute conditions.
1836 protected function execute_condition() {
1838 // Do not execute if competencies are not included.
1839 if (!$this->get_setting_value('competencies')) {
1848 * Activity competencies backup structure step.
1850 class backup_activity_competencies_structure_step
extends backup_structure_step
{
1852 protected function define_structure() {
1853 $wrapper = new backup_nested_element('course_module_competencies');
1855 $competencies = new backup_nested_element('competencies');
1856 $wrapper->add_child($competencies);
1858 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1859 'sortorder', 'frameworkidnumber', 'overridegrade'));
1860 $competencies->add_child($competency);
1862 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.overridegrade, cmc.sortorder, f.idnumber AS frameworkidnumber
1863 FROM {' . \core_competency\course_module_competency
::TABLE
. '} cmc
1864 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cmc.competencyid
1865 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1866 WHERE cmc.cmid = :coursemoduleid
1867 ORDER BY cmc.sortorder';
1868 $competency->set_source_sql($sql, array('coursemoduleid' => backup
::VAR_MODID
));
1874 * Execute conditions.
1878 protected function execute_condition() {
1880 // Do not execute if competencies are not included.
1881 if (!$this->get_setting_value('competencies')) {
1890 * structure in charge of constructing the inforef.xml file for all the items we want
1891 * to have referenced there (users, roles, files...)
1893 class backup_inforef_structure_step
extends backup_structure_step
{
1895 protected function define_structure() {
1897 // Items we want to include in the inforef file.
1898 $items = backup_helper
::get_inforef_itemnames();
1902 $inforef = new backup_nested_element('inforef');
1904 // For each item, conditionally, if there are already records, build element
1905 foreach ($items as $itemname) {
1906 if (backup_structure_dbops
::annotations_exist($this->get_backupid(), $itemname)) {
1907 $elementroot = new backup_nested_element($itemname . 'ref');
1908 $element = new backup_nested_element($itemname, array(), array('id'));
1909 $inforef->add_child($elementroot);
1910 $elementroot->add_child($element);
1911 $element->set_source_sql("
1913 FROM {backup_ids_temp}
1916 array(backup
::VAR_BACKUPID
, backup_helper
::is_sqlparam($itemname)));
1920 // We don't annotate anything there, but rely in the next step
1921 // (move_inforef_annotations_to_final) that will change all the
1922 // already saved 'inforref' entries to their 'final' annotations.
1928 * This step will get all the annotations already processed to inforef.xml file and
1929 * transform them into 'final' annotations.
1931 class move_inforef_annotations_to_final
extends backup_execution_step
{
1933 protected function define_execution() {
1935 // Items we want to include in the inforef file
1936 $items = backup_helper
::get_inforef_itemnames();
1937 $progress = $this->task
->get_progress();
1938 $progress->start_progress($this->get_name(), count($items));
1940 foreach ($items as $itemname) {
1941 // Delegate to dbops
1942 backup_structure_dbops
::move_annotations_to_final($this->get_backupid(),
1943 $itemname, $progress);
1944 $progress->progress($done++
);
1946 $progress->end_progress();
1951 * structure in charge of constructing the files.xml file with all the
1952 * annotated (final) files along the process. At, the same time, and
1953 * using one specialised nested_element, will copy them form moodle storage
1956 class backup_final_files_structure_step
extends backup_structure_step
{
1958 protected function define_structure() {
1962 $files = new backup_nested_element('files');
1964 $file = new file_nested_element('file', array('id'), array(
1965 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1966 'filepath', 'filename', 'userid', 'filesize',
1967 'mimetype', 'status', 'timecreated', 'timemodified',
1968 'source', 'author', 'license', 'sortorder',
1969 'repositorytype', 'repositoryid', 'reference'));
1973 $files->add_child($file);
1977 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1979 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1980 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1981 LEFT JOIN {repository} r ON r.id = ri.typeid
1982 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1983 WHERE bi.backupid = ?
1984 AND bi.itemname = 'filefinal'", array(backup
::VAR_BACKUPID
));
1991 * Structure step in charge of creating the main moodle_backup.xml file
1992 * where all the information related to the backup, settings, license and
1993 * other information needed on restore is added*/
1994 class backup_main_structure_step
extends backup_structure_step
{
1996 protected function define_structure() {
2002 $info['name'] = $this->get_setting_value('filename');
2003 $info['moodle_version'] = $CFG->version
;
2004 $info['moodle_release'] = $CFG->release
;
2005 $info['backup_version'] = $CFG->backup_version
;
2006 $info['backup_release'] = $CFG->backup_release
;
2007 $info['backup_date'] = time();
2008 $info['backup_uniqueid']= $this->get_backupid();
2009 $info['mnet_remoteusers']=backup_controller_dbops
::backup_includes_mnet_remote_users($this->get_backupid());
2010 $info['include_files'] = backup_controller_dbops
::backup_includes_files($this->get_backupid());
2011 $info['include_file_references_to_external_content'] =
2012 backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
2013 $info['original_wwwroot']=$CFG->wwwroot
;
2014 $info['original_site_identifier_hash'] = md5(get_site_identifier());
2015 $info['original_course_id'] = $this->get_courseid();
2016 $originalcourseinfo = backup_controller_dbops
::backup_get_original_course_info($this->get_courseid());
2017 $info['original_course_format'] = $originalcourseinfo->format
;
2018 $info['original_course_fullname'] = $originalcourseinfo->fullname
;
2019 $info['original_course_shortname'] = $originalcourseinfo->shortname
;
2020 $info['original_course_startdate'] = $originalcourseinfo->startdate
;
2021 $info['original_course_enddate'] = $originalcourseinfo->enddate
;
2022 $info['original_course_contextid'] = context_course
::instance($this->get_courseid())->id
;
2023 $info['original_system_contextid'] = context_system
::instance()->id
;
2025 // Get more information from controller
2026 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops
::get_moodle_backup_information(
2027 $this->get_backupid(), $this->get_task()->get_progress());
2031 $moodle_backup = new backup_nested_element('moodle_backup');
2033 $information = new backup_nested_element('information', null, array(
2034 'name', 'moodle_version', 'moodle_release', 'backup_version',
2035 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
2036 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
2037 'original_course_fullname', 'original_course_shortname', 'original_course_startdate', 'original_course_enddate',
2038 'original_course_contextid', 'original_system_contextid'));
2040 $details = new backup_nested_element('details');
2042 $detail = new backup_nested_element('detail', array('backup_id'), array(
2043 'type', 'format', 'interactive', 'mode',
2044 'execution', 'executiontime'));
2046 $contents = new backup_nested_element('contents');
2048 $activities = new backup_nested_element('activities');
2050 $activity = new backup_nested_element('activity', null, array(
2051 'moduleid', 'sectionid', 'modulename', 'title',
2054 $sections = new backup_nested_element('sections');
2056 $section = new backup_nested_element('section', null, array(
2057 'sectionid', 'title', 'directory'));
2059 $course = new backup_nested_element('course', null, array(
2060 'courseid', 'title', 'directory'));
2062 $settings = new backup_nested_element('settings');
2064 $setting = new backup_nested_element('setting', null, array(
2065 'level', 'section', 'activity', 'name', 'value'));
2069 $moodle_backup->add_child($information);
2071 $information->add_child($details);
2072 $details->add_child($detail);
2074 $information->add_child($contents);
2075 if (!empty($cinfo['activities'])) {
2076 $contents->add_child($activities);
2077 $activities->add_child($activity);
2079 if (!empty($cinfo['sections'])) {
2080 $contents->add_child($sections);
2081 $sections->add_child($section);
2083 if (!empty($cinfo['course'])) {
2084 $contents->add_child($course);
2087 $information->add_child($settings);
2088 $settings->add_child($setting);
2093 $information->set_source_array(array((object)$info));
2095 $detail->set_source_array($dinfo);
2097 $activity->set_source_array($cinfo['activities']);
2099 $section->set_source_array($cinfo['sections']);
2101 $course->set_source_array($cinfo['course']);
2103 $setting->set_source_array($sinfo);
2105 // Prepare some information to be sent to main moodle_backup.xml file
2106 return $moodle_backup;
2112 * Execution step that will generate the final zip (.mbz) file with all the contents
2114 class backup_zip_contents
extends backup_execution_step
implements file_progress
{
2116 * @var bool True if we have started tracking progress
2118 protected $startedprogress;
2120 protected function define_execution() {
2123 $basepath = $this->get_basepath();
2125 // Get the list of files in directory
2126 $filestemp = get_directory_list($basepath, '', false, true, true);
2128 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
2129 $files[$file] = $basepath . '/' . $file;
2132 // Add the log file if exists
2133 $logfilepath = $basepath . '.log';
2134 if (file_exists($logfilepath)) {
2135 $files['moodle_backup.log'] = $logfilepath;
2138 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2139 $zipfile = $basepath . '/backup.mbz';
2141 // Get the zip packer
2142 $zippacker = get_file_packer('application/vnd.moodle.backup');
2144 // Track overall progress for the 2 long-running steps (archive to
2145 // pathname, get backup information).
2146 $reporter = $this->task
->get_progress();
2147 $reporter->start_progress('backup_zip_contents', 2);
2150 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
2152 // If any sub-progress happened, end it.
2153 if ($this->startedprogress
) {
2154 $this->task
->get_progress()->end_progress();
2155 $this->startedprogress
= false;
2157 // No progress was reported, manually move it on to the next overall task.
2158 $reporter->progress(1);
2161 // Something went wrong.
2162 if ($result === false) {
2164 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
2166 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
2168 backup_general_helper
::get_backup_information_from_mbz($zipfile, $this);
2169 } catch (backup_helper_exception
$e) {
2171 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo
);
2174 // If any sub-progress happened, end it.
2175 if ($this->startedprogress
) {
2176 $this->task
->get_progress()->end_progress();
2177 $this->startedprogress
= false;
2179 $reporter->progress(2);
2181 $reporter->end_progress();
2185 * Implementation for file_progress interface to display unzip progress.
2187 * @param int $progress Current progress
2188 * @param int $max Max value
2190 public function progress($progress = file_progress
::INDETERMINATE
, $max = file_progress
::INDETERMINATE
) {
2191 $reporter = $this->task
->get_progress();
2193 // Start tracking progress if necessary.
2194 if (!$this->startedprogress
) {
2195 $reporter->start_progress('extract_file_to_dir', ($max == file_progress
::INDETERMINATE
)
2196 ? \core\progress\base
::INDETERMINATE
: $max);
2197 $this->startedprogress
= true;
2200 // Pass progress through to whatever handles it.
2201 $reporter->progress(($progress == file_progress
::INDETERMINATE
)
2202 ? \core\progress\base
::INDETERMINATE
: $progress);
2207 * This step will send the generated backup file to its final destination
2209 class backup_store_backup_file
extends backup_execution_step
{
2211 protected function define_execution() {
2214 $basepath = $this->get_basepath();
2216 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2217 $zipfile = $basepath . '/backup.mbz';
2219 $has_file_references = backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
2220 // Perform storage and return it (TODO: shouldn't be array but proper result object)
2222 'backup_destination' => backup_helper
::store_backup_file($this->get_backupid(), $zipfile,
2223 $this->task
->get_progress()),
2224 'include_file_references_to_external_content' => $has_file_references
2231 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
2232 * and put them to the backup_ids tables, to be used later as base to backup them
2234 class backup_activity_grade_items_to_ids
extends backup_execution_step
{
2236 protected function define_execution() {
2238 // Fetch all activity grade items
2239 if ($items = grade_item
::fetch_all(array(
2240 'itemtype' => 'mod', 'itemmodule' => $this->task
->get_modulename(),
2241 'iteminstance' => $this->task
->get_activityid(), 'courseid' => $this->task
->get_courseid()))) {
2242 // Annotate them in backup_ids
2243 foreach ($items as $item) {
2244 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id
);
2252 * This step allows enrol plugins to annotate custom fields.
2254 * @package core_backup
2255 * @copyright 2014 University of Wisconsin
2256 * @author Matt Petro
2257 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2259 class backup_enrolments_execution_step
extends backup_execution_step
{
2262 * Function that will contain all the code to be executed.
2264 protected function define_execution() {
2267 $plugins = enrol_get_plugins(true);
2268 $enrols = $DB->get_records('enrol', array(
2269 'courseid' => $this->task
->get_courseid()));
2271 // Allow each enrol plugin to add annotations.
2272 foreach ($enrols as $enrol) {
2273 if (isset($plugins[$enrol->enrol
])) {
2274 $plugins[$enrol->enrol
]->backup_annotate_custom_fields($this, $enrol);
2280 * Annotate a single name/id pair.
2281 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
2283 * @param string $itemname
2284 * @param int $itemid
2286 public function annotate_id($itemname, $itemid) {
2287 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2292 * This step will annotate all the groups and groupings belonging to the course
2294 class backup_annotate_course_groups_and_groupings
extends backup_execution_step
{
2296 protected function define_execution() {
2299 // Get all the course groups
2300 if ($groups = $DB->get_records('groups', array(
2301 'courseid' => $this->task
->get_courseid()))) {
2302 foreach ($groups as $group) {
2303 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->id
);
2307 // Get all the course groupings
2308 if ($groupings = $DB->get_records('groupings', array(
2309 'courseid' => $this->task
->get_courseid()))) {
2310 foreach ($groupings as $grouping) {
2311 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id
);
2318 * This step will annotate all the groups belonging to already annotated groupings
2320 class backup_annotate_groups_from_groupings
extends backup_execution_step
{
2322 protected function define_execution() {
2325 // Fetch all the annotated groupings
2326 if ($groupings = $DB->get_records('backup_ids_temp', array(
2327 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2328 foreach ($groupings as $grouping) {
2329 if ($groups = $DB->get_records('groupings_groups', array(
2330 'groupingid' => $grouping->itemid
))) {
2331 foreach ($groups as $group) {
2332 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid
);
2341 * This step will annotate all the scales belonging to already annotated outcomes
2343 class backup_annotate_scales_from_outcomes
extends backup_execution_step
{
2345 protected function define_execution() {
2348 // Fetch all the annotated outcomes
2349 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2350 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2351 foreach ($outcomes as $outcome) {
2352 if ($scale = $DB->get_record('grade_outcomes', array(
2353 'id' => $outcome->itemid
))) {
2354 // Annotate as scalefinal because it's > 0
2355 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid
);
2363 * This step will generate all the file annotations for the already
2364 * annotated (final) question_categories. It calculates the different
2365 * contexts that are being backup and, annotates all the files
2366 * on every context belonging to the "question" component. As far as
2367 * we are always including *complete* question banks it is safe and
2368 * optimal to do that in this (one pass) way
2370 class backup_annotate_all_question_files
extends backup_execution_step
{
2372 protected function define_execution() {
2375 // Get all the different contexts for the final question_categories
2376 // annotated along the whole backup
2377 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2378 FROM {question_categories} qc
2379 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2380 WHERE bi.backupid = ?
2381 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2382 // To know about qtype specific components/fileareas
2383 $components = backup_qtype_plugin
::get_components_and_fileareas();
2385 foreach($rs as $record) {
2386 // Backup all the file areas the are managed by the core question component.
2387 // That is, by the question_type base class. In particular, we don't want
2388 // to include files belonging to responses here.
2389 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'questiontext', null);
2390 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'generalfeedback', null);
2391 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answer', null);
2392 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answerfeedback', null);
2393 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'hint', null);
2394 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'correctfeedback', null);
2395 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'partiallycorrectfeedback', null);
2396 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'incorrectfeedback', null);
2398 // For files belonging to question types, we make the leap of faith that
2399 // all the files belonging to the question type are part of the question definition,
2400 // so we can just backup all the files in bulk, without specifying each
2401 // file area name separately.
2402 foreach ($components as $component => $fileareas) {
2403 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, $component, null, null);
2411 * structure step in charge of constructing the questions.xml file for all the
2412 * question categories and questions required by the backup
2413 * and letters related to one activity.
2415 class backup_questions_structure_step
extends backup_structure_step
{
2417 protected function define_structure() {
2419 // Define each element separately.
2420 $qcategories = new backup_nested_element('question_categories');
2422 $qcategory = new backup_nested_element('question_category', ['id'],
2427 'contextinstanceid',
2436 $questionbankentries = new backup_nested_element('question_bank_entries');
2438 $questionbankentry = new backup_nested_element('question_bank_entry', ['id'],
2440 'questioncategoryid',
2445 $questionversions = new backup_nested_element('question_version');
2447 $questionverion = new backup_nested_element('question_versions', ['id'], ['version', 'status']);
2449 $questions = new backup_nested_element('questions');
2451 $question = new backup_nested_element('question', ['id'],
2456 'questiontextformat',
2458 'generalfeedbackformat',
2470 // Attach qtype plugin structure to $question element, only one allowed.
2471 $this->add_plugin_structure('qtype', $question, false);
2473 // Attach qbank plugin stucture to $question element, multiple allowed.
2474 $this->add_plugin_structure('qbank', $question, true);
2476 // attach local plugin stucture to $question element, multiple allowed
2477 $this->add_plugin_structure('local', $question, true);
2479 $qhints = new backup_nested_element('question_hints');
2481 $qhint = new backup_nested_element('question_hint', ['id'],
2490 $tags = new backup_nested_element('tags');
2492 $tag = new backup_nested_element('tag', ['id', 'contextid'], ['name', 'rawname']);
2494 // Build the initial tree.
2495 $qcategories->add_child($qcategory);
2496 $qcategory->add_child($questionbankentries);
2497 $questionbankentries->add_child($questionbankentry);
2498 $questionbankentry->add_child($questionversions);
2499 $questionversions->add_child($questionverion);
2500 $questionverion->add_child($questions);
2501 $questions->add_child($question);
2502 $question->add_child($qhints);
2503 $qhints->add_child($qhint);
2505 // Add question tags.
2506 $question->add_child($tags);
2507 $tags->add_child($tag);
2509 $qcategory->set_source_sql("
2512 instanceid AS contextinstanceid
2513 FROM {question_categories} gc
2514 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2515 JOIN {context} co ON co.id = gc.contextid
2516 WHERE bi.backupid = ?
2517 AND bi.itemname = 'question_categoryfinal'", [backup
::VAR_BACKUPID
]);
2519 $questionbankentry->set_source_table('question_bank_entries', ['questioncategoryid' => backup
::VAR_PARENTID
]);
2521 $questionverion->set_source_table('question_versions', ['questionbankentryid' => backup
::VAR_PARENTID
]);
2523 $question->set_source_sql('
2526 JOIN {question_versions} qv ON qv.questionid = q.id
2527 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2528 WHERE qv.id = ?', [backup
::VAR_PARENTID
]);
2530 $qhint->set_source_sql('
2532 FROM {question_hints}
2533 WHERE questionid = :questionid
2534 ORDER BY id', ['questionid' => backup
::VAR_PARENTID
]);
2536 $tag->set_source_sql("SELECT t.id, ti.contextid, t.name, t.rawname
2538 JOIN {tag_instance} ti ON ti.tagid = t.id
2540 AND ti.itemtype = 'question'
2541 AND ti.component = 'core_question'", [backup
::VAR_PARENTID
]);
2543 // Don't need to annotate ids nor files.
2544 // ...(already done by {@see backup_annotate_all_question_files()}.
2546 return $qcategories;
2553 * This step will generate all the file annotations for the already
2554 * annotated (final) users. Need to do this here because each user
2555 * has its own context and structure tasks only are able to handle
2556 * one context. Also, this step will guarantee that every user has
2557 * its context created (req for other steps)
2559 class backup_annotate_all_user_files
extends backup_execution_step
{
2561 protected function define_execution() {
2564 // List of fileareas we are going to annotate
2565 $fileareas = array('profile', 'icon');
2567 // Fetch all annotated (final) users
2568 $rs = $DB->get_recordset('backup_ids_temp', array(
2569 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2570 $progress = $this->task
->get_progress();
2571 $progress->start_progress($this->get_name());
2572 foreach ($rs as $record) {
2573 $userid = $record->itemid
;
2574 $userctx = context_user
::instance($userid, IGNORE_MISSING
);
2576 continue; // User has not context, sure it's a deleted user, so cannot have files
2578 // Proceed with every user filearea
2579 foreach ($fileareas as $filearea) {
2580 // We don't need to specify itemid ($userid - 5th param) as far as by
2581 // context we can get all the associated files. See MDL-22092
2582 backup_structure_dbops
::annotate_files($this->get_backupid(), $userctx->id
, 'user', $filearea, null);
2583 $progress->progress();
2586 $progress->end_progress();
2593 * Defines the backup step for advanced grading methods attached to the activity module
2595 class backup_activity_grading_structure_step
extends backup_structure_step
{
2598 * Include the grading.xml only if the module supports advanced grading
2600 protected function execute_condition() {
2602 // No grades on the front page.
2603 if ($this->get_courseid() == SITEID
) {
2607 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING
, false);
2611 * Declares the gradable areas structures and data sources
2613 protected function define_structure() {
2615 // To know if we are including userinfo
2616 $userinfo = $this->get_setting_value('userinfo');
2618 // Define the elements
2620 $areas = new backup_nested_element('areas');
2622 $area = new backup_nested_element('area', array('id'), array(
2623 'areaname', 'activemethod'));
2625 $definitions = new backup_nested_element('definitions');
2627 $definition = new backup_nested_element('definition', array('id'), array(
2628 'method', 'name', 'description', 'descriptionformat', 'status',
2629 'timecreated', 'timemodified', 'options'));
2631 $instances = new backup_nested_element('instances');
2633 $instance = new backup_nested_element('instance', array('id'), array(
2634 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2635 'feedbackformat', 'timemodified'));
2637 // Build the tree including the method specific structures
2638 // (beware - the order of how gradingform plugins structures are attached is important)
2639 $areas->add_child($area);
2640 // attach local plugin stucture to $area element, multiple allowed
2641 $this->add_plugin_structure('local', $area, true);
2642 $area->add_child($definitions);
2643 $definitions->add_child($definition);
2644 $this->add_plugin_structure('gradingform', $definition, true);
2645 // attach local plugin stucture to $definition element, multiple allowed
2646 $this->add_plugin_structure('local', $definition, true);
2647 $definition->add_child($instances);
2648 $instances->add_child($instance);
2649 $this->add_plugin_structure('gradingform', $instance, false);
2650 // attach local plugin stucture to $instance element, multiple allowed
2651 $this->add_plugin_structure('local', $instance, true);
2653 // Define data sources
2655 $area->set_source_table('grading_areas', array('contextid' => backup
::VAR_CONTEXTID
,
2656 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2658 $definition->set_source_table('grading_definitions', array('areaid' => backup
::VAR_PARENTID
));
2661 $instance->set_source_table('grading_instances', array('definitionid' => backup
::VAR_PARENTID
));
2664 // Annotate references
2665 $definition->annotate_files('grading', 'description', 'id');
2666 $instance->annotate_ids('user', 'raterid');
2668 // Return the root element
2675 * structure step in charge of constructing the grades.xml file for all the grade items
2676 * and letters related to one activity
2678 class backup_activity_grades_structure_step
extends backup_structure_step
{
2681 * No grades on the front page.
2684 protected function execute_condition() {
2685 return ($this->get_courseid() != SITEID
);
2688 protected function define_structure() {
2691 require_once($CFG->libdir
. '/grade/constants.php');
2693 // To know if we are including userinfo
2694 $userinfo = $this->get_setting_value('userinfo');
2696 // Define each element separated
2698 $book = new backup_nested_element('activity_gradebook');
2700 $items = new backup_nested_element('grade_items');
2702 $item = new backup_nested_element('grade_item', array('id'), array(
2703 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2704 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2705 'calculation', 'gradetype', 'grademax', 'grademin',
2706 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2707 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2708 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2709 'needsupdate', 'timecreated', 'timemodified'));
2711 $grades = new backup_nested_element('grade_grades');
2713 $grade = new backup_nested_element('grade_grade', array('id'), array(
2714 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2715 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2716 'locked', 'locktime', 'exported', 'overridden',
2717 'excluded', 'feedback', 'feedbackformat', 'information',
2718 'informationformat', 'timecreated', 'timemodified',
2719 'aggregationstatus', 'aggregationweight'));
2721 $letters = new backup_nested_element('grade_letters');
2723 $letter = new backup_nested_element('grade_letter', 'id', array(
2724 'lowerboundary', 'letter'));
2728 $book->add_child($items);
2729 $items->add_child($item);
2731 $item->add_child($grades);
2732 $grades->add_child($grade);
2734 $book->add_child($letters);
2735 $letters->add_child($letter);
2739 $item->set_source_sql("SELECT gi.*
2740 FROM {grade_items} gi
2741 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2742 WHERE bi.backupid = ?
2743 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2745 // This only happens if we are including user info
2747 $grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
2748 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_FEEDBACK_FILEAREA
, 'id');
2751 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
2755 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2756 $item->annotate_ids('outcome', 'outcomeid');
2758 $grade->annotate_ids('user', 'userid');
2759 $grade->annotate_ids('user', 'usermodified');
2761 // Return the root element (book)
2768 * Structure step in charge of constructing the grade history of an activity.
2770 * This step is added to the task regardless of the setting 'grade_histories'.
2771 * The reason is to allow for a more flexible step in case the logic needs to be
2772 * split accross different settings to control the history of items and/or grades.
2774 class backup_activity_grade_history_structure_step
extends backup_structure_step
{
2777 * No grades on the front page.
2780 protected function execute_condition() {
2781 return ($this->get_courseid() != SITEID
);
2784 protected function define_structure() {
2787 require_once($CFG->libdir
. '/grade/constants.php');
2790 $userinfo = $this->get_setting_value('userinfo');
2791 $history = $this->get_setting_value('grade_histories');
2793 // Create the nested elements.
2794 $bookhistory = new backup_nested_element('grade_history');
2795 $grades = new backup_nested_element('grade_grades');
2796 $grade = new backup_nested_element('grade_grade', array('id'), array(
2797 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2798 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2799 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2800 'excluded', 'feedback', 'feedbackformat', 'information',
2801 'informationformat', 'timemodified'));
2804 $bookhistory->add_child($grades);
2805 $grades->add_child($grade);
2807 // This only happens if we are including user info and history.
2808 if ($userinfo && $history) {
2809 // Define sources. Only select the history related to existing activity items.
2810 $grade->set_source_sql("SELECT ggh.*
2811 FROM {grade_grades_history} ggh
2812 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2813 WHERE bi.backupid = ?
2814 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2815 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_HISTORY_FEEDBACK_FILEAREA
, 'id');
2819 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2820 $grade->annotate_ids('user', 'loggeduser');
2821 $grade->annotate_ids('user', 'userid');
2822 $grade->annotate_ids('user', 'usermodified');
2824 // Return the root element.
2825 return $bookhistory;
2830 * Backups up the course completion information for the course.
2832 class backup_course_completion_structure_step
extends backup_structure_step
{
2834 protected function execute_condition() {
2836 // No completion on front page.
2837 if ($this->get_courseid() == SITEID
) {
2841 // Check that all activities have been included
2842 if ($this->task
->is_excluding_activities()) {
2849 * The structure of the course completion backup
2851 * @return backup_nested_element
2853 protected function define_structure() {
2855 // To know if we are including user completion info
2856 $userinfo = $this->get_setting_value('userscompletion');
2858 $cc = new backup_nested_element('course_completion');
2860 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2861 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2862 'timeend', 'gradepass', 'role', 'roleshortname'
2865 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2867 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2868 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2871 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2872 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2875 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2876 'course','criteriatype','method','value'
2879 $cc->add_child($criteria);
2880 $criteria->add_child($criteriacompletions);
2881 $criteriacompletions->add_child($criteriacomplete);
2882 $cc->add_child($coursecompletions);
2883 $cc->add_child($aggregatemethod);
2885 // We need some extra data for the restore.
2886 // - courseinstances shortname rather than an ID.
2887 // - roleshortname in case restoring on a different site.
2888 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2889 FROM {course_completion_criteria} ccc
2890 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2891 LEFT JOIN {role} r ON r.id = ccc.role
2892 WHERE ccc.course = ?";
2893 $criteria->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2895 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup
::VAR_COURSEID
));
2898 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup
::VAR_PARENTID
));
2899 $coursecompletions->set_source_table('course_completions', array('course' => backup
::VAR_COURSEID
));
2902 $criteria->annotate_ids('role', 'role');
2903 $criteriacomplete->annotate_ids('user', 'userid');
2904 $coursecompletions->annotate_ids('user', 'userid');
2912 * Backup completion defaults for each module type.
2914 * @package core_backup
2915 * @copyright 2017 Marina Glancy
2916 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2918 class backup_completion_defaults_structure_step
extends backup_structure_step
{
2921 * To conditionally decide if one step will be executed or no
2923 protected function execute_condition() {
2924 // No completion on front page.
2925 if ($this->get_courseid() == SITEID
) {
2932 * The structure of the course completion backup
2934 * @return backup_nested_element
2936 protected function define_structure() {
2938 $cc = new backup_nested_element('course_completion_defaults');
2940 $defaults = new backup_nested_element('course_completion_default', array('id'), array(
2941 'modulename', 'completion', 'completionview', 'completionusegrade', 'completionpassgrade',
2942 'completionexpected', 'customrules'
2945 // Use module name instead of module id so we can insert into another site later.
2946 $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
2947 d.completionpassgrade, d.completionexpected, d.customrules
2948 FROM {course_completion_defaults} d join {modules} m on d.module = m.id
2949 WHERE d.course = ?";
2950 $defaults->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2952 $cc->add_child($defaults);
2959 * Structure step in charge of constructing the contentbank.xml file for all the contents found in a given context
2961 class backup_contentbankcontent_structure_step
extends backup_structure_step
{
2964 * Define structure for content bank step
2966 protected function define_structure() {
2968 // Define each element separated.
2969 $contents = new backup_nested_element('contents');
2970 $content = new backup_nested_element('content', ['id'], [
2971 'name', 'contenttype', 'instanceid', 'configdata', 'usercreated', 'usermodified', 'timecreated', 'timemodified']);
2974 $contents->add_child($content);
2977 $content->set_source_table('contentbank_content', ['contextid' => backup
::VAR_CONTEXTID
]);
2979 // Define annotations.
2980 $content->annotate_ids('user', 'usercreated');
2981 $content->annotate_ids('user', 'usermodified');
2982 $content->annotate_files('contentbank', 'public', 'id');
2984 // Return the root element (contents).