3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Defines various backup steps that will be used by common tasks in backup
21 * @package core_backup
24 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') ||
die();
31 * Create the temp dir where backup/restore will happen and create temp ids table.
33 class create_and_clean_temp_stuff
extends backup_execution_step
{
35 protected function define_execution() {
36 $progress = $this->task
->get_progress();
37 $progress->start_progress('Deleting backup directories');
38 backup_helper
::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
39 backup_helper
::clear_backup_dir($this->get_backupid(), $progress); // Empty temp dir, just in case
40 backup_controller_dbops
::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
41 backup_controller_dbops
::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
42 $progress->end_progress();
47 * Delete the temp dir used by backup/restore (conditionally) and drop temp ids table.
48 * Note we delete the directory but not the corresponding log file that will be
49 * there until cron cleans it up.
51 class drop_and_clean_temp_stuff
extends backup_execution_step
{
53 protected $skipcleaningtempdir = false;
55 protected function define_execution() {
58 backup_controller_dbops
::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
59 // Delete temp dir conditionally:
60 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
61 // 2) If backup temp dir deletion has been marked to be avoided
62 if (empty($CFG->keeptempdirectoriesonbackup
) && !$this->skipcleaningtempdir
) {
63 $progress = $this->task
->get_progress();
64 $progress->start_progress('Deleting backup dir');
65 backup_helper
::delete_backup_dir($this->get_backupid(), $progress); // Empty backup dir
66 $progress->end_progress();
70 public function skip_cleaning_temp_dir($skip) {
71 $this->skipcleaningtempdir
= $skip;
76 * Create the directory where all the task (activity/block...) information will be stored
78 class create_taskbasepath_directory
extends backup_execution_step
{
80 protected function define_execution() {
82 $basepath = $this->task
->get_taskbasepath();
83 if (!check_dir_exists($basepath, true, true)) {
84 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
90 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
91 * activity structure definition within the main <activity ...> tag.
93 abstract class backup_activity_structure_step
extends backup_structure_step
{
96 * Wraps any activity backup structure within the common 'activity' element
97 * that will include common to all activities information like id, context...
99 * @param backup_nested_element $activitystructure the element to wrap
100 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
102 protected function prepare_activity_structure($activitystructure) {
104 // Create the wrap element
105 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
108 $activity->add_child($activitystructure);
111 $activityarr = array((object)array(
112 'id' => $this->task
->get_activityid(),
113 'moduleid' => $this->task
->get_moduleid(),
114 'modulename' => $this->task
->get_modulename(),
115 'contextid' => $this->task
->get_contextid()));
117 $activity->set_source_array($activityarr);
119 // Return the root element (activity)
125 * Helper code for use by any plugin that stores question attempt data that it needs to back up.
127 trait backup_questions_attempt_data_trait
{
130 * Attach to $element (usually attempts) the needed backup structures
131 * for question_usages and all the associated data.
133 * @param backup_nested_element $element the element that will contain all the question_usages data.
134 * @param string $usageidname the name of the element that holds the usageid.
135 * This must be child of $element, and must be a final element.
136 * @param string $nameprefix this prefix is added to all the element names we create.
137 * Element names in the XML must be unique, so if you are using usages in
138 * two different ways, you must give a prefix to at least one of them. If
139 * you only use one sort of usage, then you can just use the default empty prefix.
140 * This should include a trailing underscore. For example "myprefix_"
142 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
144 require_once($CFG->dirroot
. '/question/engine/lib.php');
146 // Check $element is one nested_backup_element
147 if (! $element instanceof backup_nested_element
) {
148 throw new backup_step_exception('question_states_bad_parent_element', $element);
150 if (! $element->get_final_element($usageidname)) {
151 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
154 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
155 array('component', 'preferredbehaviour'));
157 $qas = new backup_nested_element($nameprefix . 'question_attempts');
158 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
159 'slot', 'behaviour', 'questionid', 'variant', 'maxmark', 'minfraction', 'maxfraction',
160 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
163 $steps = new backup_nested_element($nameprefix . 'steps');
164 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
165 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
167 $response = new backup_nested_element($nameprefix . 'response');
168 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
171 $element->add_child($quba);
172 $quba->add_child($qas);
173 $qas->add_child($qa);
174 $qa->add_child($steps);
175 $steps->add_child($step);
176 $step->add_child($response);
177 $response->add_child($variable);
180 $quba->set_source_table('question_usages',
181 array('id' => '../' . $usageidname));
182 $qa->set_source_table('question_attempts', array('questionusageid' => backup
::VAR_PARENTID
), 'slot ASC');
183 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup
::VAR_PARENTID
), 'sequencenumber ASC');
184 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup
::VAR_PARENTID
));
187 $qa->annotate_ids('question', 'questionid');
188 $step->annotate_ids('user', 'userid');
191 $fileareas = question_engine
::get_all_response_file_areas();
192 foreach ($fileareas as $filearea) {
193 $step->annotate_files('question', $filearea, 'id');
200 * Abstract structure step to help activities that store question attempt data.
202 * @copyright 2011 The Open University
203 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
205 abstract class backup_questions_activity_structure_step
extends backup_activity_structure_step
{
206 use backup_questions_attempt_data_trait
;
211 * backup structure step in charge of calculating the categories to be
212 * included in backup, based in the context being backuped (module/course)
213 * and the already annotated questions present in backup_ids_temp
215 class backup_calculate_question_categories
extends backup_execution_step
{
217 protected function define_execution() {
218 backup_question_dbops
::calculate_question_categories($this->get_backupid(), $this->task
->get_contextid());
223 * backup structure step in charge of deleting all the questions annotated
224 * in the backup_ids_temp table
226 class backup_delete_temp_questions
extends backup_execution_step
{
228 protected function define_execution() {
229 backup_question_dbops
::delete_temp_questions($this->get_backupid());
234 * Abstract structure step, parent of all the block structure steps. Used to wrap the
235 * block structure definition within the main <block ...> tag
237 abstract class backup_block_structure_step
extends backup_structure_step
{
239 protected function prepare_block_structure($blockstructure) {
241 // Create the wrap element
242 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
245 $block->add_child($blockstructure);
248 $blockarr = array((object)array(
249 'id' => $this->task
->get_blockid(),
250 'blockname' => $this->task
->get_blockname(),
251 'contextid' => $this->task
->get_contextid()));
253 $block->set_source_array($blockarr);
255 // Return the root element (block)
261 * structure step that will generate the module.xml file for the activity,
262 * accumulating various information about the activity, annotating groupings
263 * and completion/avail conf
265 class backup_module_structure_step
extends backup_structure_step
{
267 protected function define_structure() {
270 // Define each element separated
272 $module = new backup_nested_element('module', array('id', 'version'), array(
273 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
274 'added', 'score', 'indent', 'visible', 'visibleoncoursepage',
275 'visibleold', 'groupmode', 'groupingid',
276 'completion', 'completiongradeitemnumber', 'completionpassgrade',
277 'completionview', 'completionexpected',
278 'availability', 'showdescription', 'downloadcontent'));
280 $tags = new backup_nested_element('tags');
281 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
283 // attach format plugin structure to $module element, only one allowed
284 $this->add_plugin_structure('format', $module, false);
286 // Attach report plugin structure to $module element, multiple allowed.
287 $this->add_plugin_structure('report', $module, true);
289 // attach plagiarism plugin structure to $module element, there can be potentially
290 // many plagiarism plugins storing information about this course
291 $this->add_plugin_structure('plagiarism', $module, true);
293 // attach local plugin structure to $module, multiple allowed
294 $this->add_plugin_structure('local', $module, true);
296 // Attach admin tools plugin structure to $module.
297 $this->add_plugin_structure('tool', $module, true);
299 $module->add_child($tags);
300 $tags->add_child($tag);
303 $concat = $DB->sql_concat("'mod_'", 'm.name');
304 $module->set_source_sql("
305 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
306 FROM {course_modules} cm
307 JOIN {modules} m ON m.id = cm.module
308 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
309 JOIN {course_sections} s ON s.id = cm.section
310 WHERE cm.id = ?", array(backup
::VAR_MODID
));
312 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
314 JOIN {tag_instance} ti ON ti.tagid = t.id
315 WHERE ti.itemtype = 'course_modules'
316 AND ti.component = 'core'
317 AND ti.itemid = ?", array(backup
::VAR_MODID
));
319 // Define annotations
320 $module->annotate_ids('grouping', 'groupingid');
322 // Return the root element ($module)
328 * structure step that will generate the section.xml file for the section
331 class backup_section_structure_step
extends backup_structure_step
{
333 protected function define_structure() {
335 // Define each element separated
337 $section = new backup_nested_element('section', array('id'), array(
338 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
339 'availabilityjson', 'timemodified'));
341 // attach format plugin structure to $section element, only one allowed
342 $this->add_plugin_structure('format', $section, false);
344 // attach local plugin structure to $section element, multiple allowed
345 $this->add_plugin_structure('local', $section, true);
347 // Add nested elements for course_format_options table
348 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
349 'format', 'name', 'value'));
350 $section->add_child($formatoptions);
353 $section->set_source_table('course_sections', array('id' => backup
::VAR_SECTIONID
));
354 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
356 JOIN {course_format_options} cfo
357 ON cfo.courseid = c.id AND cfo.format = c.format
358 WHERE c.id = ? AND cfo.sectionid = ?',
359 array(backup
::VAR_COURSEID
, backup
::VAR_SECTIONID
));
362 $section->set_source_alias('section', 'number');
363 // The 'availability' field needs to be renamed because it clashes with
364 // the old nested element structure for availability data.
365 $section->set_source_alias('availability', 'availabilityjson');
368 $section->annotate_files('course', 'section', 'id');
375 * structure step that will generate the course.xml file for the course, including
376 * course category reference, tags, modules restriction information
377 * and some annotations (files & groupings)
379 class backup_course_structure_step
extends backup_structure_step
{
381 protected function define_structure() {
384 // Define each element separated
386 $course = new backup_nested_element('course', array('id', 'contextid'), array(
387 'shortname', 'fullname', 'idnumber',
388 'summary', 'summaryformat', 'format', 'showgrades',
389 'newsitems', 'startdate', 'enddate',
390 'marker', 'maxbytes', 'legacyfiles', 'showreports',
391 'visible', 'groupmode', 'groupmodeforce',
392 'defaultgroupingid', 'lang', 'theme',
393 'timecreated', 'timemodified',
396 'showcompletionconditions',
397 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
399 $category = new backup_nested_element('category', array('id'), array(
400 'name', 'description'));
402 $tags = new backup_nested_element('tags');
404 $tag = new backup_nested_element('tag', array('id'), array(
407 $customfields = new backup_nested_element('customfields');
408 $customfield = new backup_nested_element('customfield', array('id'), array(
409 'shortname', 'type', 'value', 'valueformat'
412 // attach format plugin structure to $course element, only one allowed
413 $this->add_plugin_structure('format', $course, false);
415 // attach theme plugin structure to $course element; multiple themes can
416 // save course data (in case of user theme, legacy theme, etc)
417 $this->add_plugin_structure('theme', $course, true);
419 // attach general report plugin structure to $course element; multiple
420 // reports can save course data if required
421 $this->add_plugin_structure('report', $course, true);
423 // attach course report plugin structure to $course element; multiple
424 // course reports can save course data if required
425 $this->add_plugin_structure('coursereport', $course, true);
427 // attach plagiarism plugin structure to $course element, there can be potentially
428 // many plagiarism plugins storing information about this course
429 $this->add_plugin_structure('plagiarism', $course, true);
431 // attach local plugin structure to $course element; multiple local plugins
432 // can save course data if required
433 $this->add_plugin_structure('local', $course, true);
435 // Attach admin tools plugin structure to $course element; multiple plugins
436 // can save course data if required.
437 $this->add_plugin_structure('tool', $course, true);
441 $course->add_child($category);
443 $course->add_child($tags);
444 $tags->add_child($tag);
446 $course->add_child($customfields);
447 $customfields->add_child($customfield);
451 $courserec = $DB->get_record('course', array('id' => $this->task
->get_courseid()));
452 $courserec->contextid
= $this->task
->get_contextid();
454 $formatoptions = course_get_format($courserec)->get_format_options();
455 $course->add_final_elements(array_keys($formatoptions));
456 foreach ($formatoptions as $key => $value) {
457 $courserec->$key = $value;
460 // Add 'numsections' in order to be able to restore in previous versions of Moodle.
461 // Even though Moodle does not officially support restore into older verions of Moodle from the
462 // version where backup was made, without 'numsections' restoring will go very wrong.
463 if (!property_exists($courserec, 'numsections') && course_get_format($courserec)->uses_sections()) {
464 $courserec->numsections
= course_get_format($courserec)->get_last_section_number();
467 $course->set_source_array(array($courserec));
469 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category
));
471 $category->set_source_array(array($categoryrec));
473 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
475 JOIN {tag_instance} ti ON ti.tagid = t.id
476 WHERE ti.itemtype = ?
477 AND ti.itemid = ?', array(
478 backup_helper
::is_sqlparam('course'),
479 backup
::VAR_PARENTID
));
481 $handler = core_course\customfield\course_handler
::create();
482 $fieldsforbackup = $handler->get_instance_data_for_backup($this->task
->get_courseid());
483 $customfield->set_source_array($fieldsforbackup);
487 $course->annotate_ids('grouping', 'defaultgroupingid');
489 $course->annotate_files('course', 'summary', null);
490 $course->annotate_files('course', 'overviewfiles', null);
492 if ($this->get_setting_value('legacyfiles')) {
493 $course->annotate_files('course', 'legacy', null);
496 // Return root element ($course)
503 * structure step that will generate the enrolments.xml file for the given course
505 class backup_enrolments_structure_step
extends backup_structure_step
{
508 * Skip enrolments on the front page.
511 protected function execute_condition() {
512 return ($this->get_courseid() != SITEID
);
515 protected function define_structure() {
518 // To know if we are including users
519 $users = $this->get_setting_value('users');
520 $keptroles = $this->task
->get_kept_roles();
522 // Define each element separated
524 $enrolments = new backup_nested_element('enrolments');
526 $enrols = new backup_nested_element('enrols');
528 $enrol = new backup_nested_element('enrol', array('id'), array(
529 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
530 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
531 'password', 'cost', 'currency', 'roleid',
532 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
533 'customchar1', 'customchar2', 'customchar3',
534 'customdec1', 'customdec2',
535 'customtext1', 'customtext2', 'customtext3', 'customtext4',
536 'timecreated', 'timemodified'));
538 $userenrolments = new backup_nested_element('user_enrolments');
540 $enrolment = new backup_nested_element('enrolment', array('id'), array(
541 'status', 'userid', 'timestart', 'timeend', 'modifierid',
545 $enrolments->add_child($enrols);
546 $enrols->add_child($enrol);
547 $enrol->add_child($userenrolments);
548 $userenrolments->add_child($enrolment);
550 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
551 $enrol->set_source_table('enrol', array('courseid' => backup
::VAR_COURSEID
), 'sortorder ASC');
553 // User enrolments only added only if users included.
554 if (empty($keptroles) && $users) {
555 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup
::VAR_PARENTID
));
556 $enrolment->annotate_ids('user', 'userid');
557 } else if (!empty($keptroles)) {
558 list($insql, $inparams) = $DB->get_in_or_equal($keptroles);
560 backup
::VAR_CONTEXTID
,
563 foreach ($inparams as $inparam) {
564 $params[] = backup_helper
::is_sqlparam($inparam);
566 $enrolment->set_source_sql(
568 FROM {user_enrolments} ue
569 INNER JOIN {role_assignments} ra ON ue.userid = ra.userid
570 WHERE ra.contextid = ?
572 AND ra.roleid $insql",
574 $enrolment->annotate_ids('user', 'userid');
577 $enrol->annotate_ids('role', 'roleid');
579 // Add enrol plugin structure.
580 $this->add_plugin_structure('enrol', $enrol, true);
587 * structure step that will generate the roles.xml file for the given context, observing
588 * the role_assignments setting to know if that part needs to be included
590 class backup_roles_structure_step
extends backup_structure_step
{
592 protected function define_structure() {
594 // To know if we are including role assignments
595 $roleassignments = $this->get_setting_value('role_assignments');
597 // Define each element separated
599 $roles = new backup_nested_element('roles');
601 $overrides = new backup_nested_element('role_overrides');
603 $override = new backup_nested_element('override', array('id'), array(
604 'roleid', 'capability', 'permission', 'timemodified',
607 $assignments = new backup_nested_element('role_assignments');
609 $assignment = new backup_nested_element('assignment', array('id'), array(
610 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
614 $roles->add_child($overrides);
615 $roles->add_child($assignments);
617 $overrides->add_child($override);
618 $assignments->add_child($assignment);
622 $override->set_source_table('role_capabilities', array('contextid' => backup
::VAR_CONTEXTID
));
624 // Assignments only added if specified
625 if ($roleassignments) {
626 $assignment->set_source_table('role_assignments', array('contextid' => backup
::VAR_CONTEXTID
));
629 // Define id annotations
630 $override->annotate_ids('role', 'roleid');
632 $assignment->annotate_ids('role', 'roleid');
634 $assignment->annotate_ids('user', 'userid');
636 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
643 * structure step that will generate the roles.xml containing the
644 * list of roles used along the whole backup process. Just raw
645 * list of used roles from role table
647 class backup_final_roles_structure_step
extends backup_structure_step
{
649 protected function define_structure() {
653 $rolesdef = new backup_nested_element('roles_definition');
655 $role = new backup_nested_element('role', array('id'), array(
656 'name', 'shortname', 'nameincourse', 'description',
657 'sortorder', 'archetype'));
661 $rolesdef->add_child($role);
665 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
667 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
668 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
669 WHERE bi.backupid = ?
670 AND bi.itemname = 'rolefinal'", array(backup
::VAR_CONTEXTID
, backup
::VAR_BACKUPID
));
672 // Return main element (rolesdef)
678 * structure step that will generate the scales.xml containing the
679 * list of scales used along the whole backup process.
681 class backup_final_scales_structure_step
extends backup_structure_step
{
683 protected function define_structure() {
687 $scalesdef = new backup_nested_element('scales_definition');
689 $scale = new backup_nested_element('scale', array('id'), array(
690 'courseid', 'userid', 'name', 'scale',
691 'description', 'descriptionformat', 'timemodified'));
695 $scalesdef->add_child($scale);
699 $scale->set_source_sql("SELECT s.*
701 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
702 WHERE bi.backupid = ?
703 AND bi.itemname = 'scalefinal'", array(backup
::VAR_BACKUPID
));
705 // Annotate scale files (they store files in system context, so pass it instead of default one)
706 $scale->annotate_files('grade', 'scale', 'id', context_system
::instance()->id
);
708 // Return main element (scalesdef)
714 * structure step that will generate the outcomes.xml containing the
715 * list of outcomes used along the whole backup process.
717 class backup_final_outcomes_structure_step
extends backup_structure_step
{
719 protected function define_structure() {
723 $outcomesdef = new backup_nested_element('outcomes_definition');
725 $outcome = new backup_nested_element('outcome', array('id'), array(
726 'courseid', 'userid', 'shortname', 'fullname',
727 'scaleid', 'description', 'descriptionformat', 'timecreated',
728 'timemodified','usermodified'));
732 $outcomesdef->add_child($outcome);
736 $outcome->set_source_sql("SELECT o.*
737 FROM {grade_outcomes} o
738 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
739 WHERE bi.backupid = ?
740 AND bi.itemname = 'outcomefinal'", array(backup
::VAR_BACKUPID
));
742 // Annotate outcome files (they store files in system context, so pass it instead of default one)
743 $outcome->annotate_files('grade', 'outcome', 'id', context_system
::instance()->id
);
745 // Return main element (outcomesdef)
751 * structure step in charge of constructing the filters.xml file for all the filters found
754 class backup_filters_structure_step
extends backup_structure_step
{
756 protected function define_structure() {
758 // Define each element separated
760 $filters = new backup_nested_element('filters');
762 $actives = new backup_nested_element('filter_actives');
764 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
766 $configs = new backup_nested_element('filter_configs');
768 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
772 $filters->add_child($actives);
773 $filters->add_child($configs);
775 $actives->add_child($active);
776 $configs->add_child($config);
780 list($activearr, $configarr) = filter_get_all_local_settings($this->task
->get_contextid());
782 $active->set_source_array($activearr);
783 $config->set_source_array($configarr);
785 // Return the root element (filters)
791 * Structure step in charge of constructing the comments.xml file for all the comments found in a given context.
793 class backup_comments_structure_step
extends backup_structure_step
{
795 protected function define_structure() {
796 // Define each element separated.
797 $comments = new backup_nested_element('comments');
799 $comment = new backup_nested_element('comment', array('id'), array(
800 'component', 'commentarea', 'itemid', 'content', 'format',
801 'userid', 'timecreated'));
804 $comments->add_child($comment);
807 $comment->set_source_table('comments', array('contextid' => backup
::VAR_CONTEXTID
));
809 // Define id annotations.
810 $comment->annotate_ids('user', 'userid');
812 // Return the root element (comments).
818 * structure step in charge of constructing the badges.xml file for all the badges found
821 class backup_badges_structure_step
extends backup_structure_step
{
823 protected function execute_condition() {
824 // Check that all activities have been included.
825 if ($this->task
->is_excluding_activities()) {
831 protected function define_structure() {
834 require_once($CFG->libdir
. '/badgeslib.php');
835 // Define each element separated.
837 $badges = new backup_nested_element('badges');
838 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
839 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
840 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
841 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron',
842 'version', 'language', 'imageauthorname', 'imageauthoremail', 'imageauthorurl',
845 $criteria = new backup_nested_element('criteria');
846 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
847 'criteriatype', 'method', 'description', 'descriptionformat'));
849 $endorsement = new backup_nested_element('endorsement', array('id'), array('badgeid',
850 'issuername', 'issuerurl', 'issueremail', 'claimid', 'claimcomment', 'dateissued'));
852 $alignments = new backup_nested_element('alignments');
853 $alignment = new backup_nested_element('alignment', array('id'), array('badgeid',
854 'targetname', 'targeturl', 'targetdescription', 'targetframework', 'targetcode'));
856 $relatedbadges = new backup_nested_element('relatedbadges');
857 $relatedbadge = new backup_nested_element('relatedbadge', array('id'), array('badgeid',
860 $parameters = new backup_nested_element('parameters');
861 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
862 'name', 'value', 'criteriatype'));
864 $manual_awards = new backup_nested_element('manual_awards');
865 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
866 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
870 $badges->add_child($badge);
871 $badge->add_child($criteria);
872 $criteria->add_child($criterion);
873 $criterion->add_child($parameters);
874 $parameters->add_child($parameter);
875 $badge->add_child($endorsement);
876 $badge->add_child($alignments);
877 $alignments->add_child($alignment);
878 $badge->add_child($relatedbadges);
879 $relatedbadges->add_child($relatedbadge);
880 $badge->add_child($manual_awards);
881 $manual_awards->add_child($manual_award);
888 WHERE courseid = :courseid
889 AND status != ' . BADGE_STATUS_ARCHIVED
;
891 'courseid' => backup
::VAR_COURSEID
893 $badge->set_source_sql($parametersql, $parameterparams);
894 $criterion->set_source_table('badge_criteria', array('badgeid' => backup
::VAR_PARENTID
));
895 $endorsement->set_source_table('badge_endorsement', array('badgeid' => backup
::VAR_PARENTID
));
897 $alignment->set_source_table('badge_alignment', array('badgeid' => backup
::VAR_PARENTID
));
898 $relatedbadge->set_source_table('badge_related', array('badgeid' => backup
::VAR_PARENTID
));
900 $parametersql = 'SELECT cp.*, c.criteriatype
901 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
903 WHERE critid = :critid';
904 $parameterparams = array('critid' => backup
::VAR_PARENTID
);
905 $parameter->set_source_sql($parametersql, $parameterparams);
907 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup
::VAR_PARENTID
));
909 // Define id annotations.
911 $badge->annotate_ids('user', 'usercreated');
912 $badge->annotate_ids('user', 'usermodified');
913 $criterion->annotate_ids('badge', 'badgeid');
914 $parameter->annotate_ids('criterion', 'critid');
915 $endorsement->annotate_ids('badge', 'badgeid');
916 $alignment->annotate_ids('badge', 'badgeid');
917 $relatedbadge->annotate_ids('badge', 'badgeid');
918 $relatedbadge->annotate_ids('badge', 'relatedbadgeid');
919 $badge->annotate_files('badges', 'badgeimage', 'id');
920 $manual_award->annotate_ids('badge', 'badgeid');
921 $manual_award->annotate_ids('user', 'recipientid');
922 $manual_award->annotate_ids('user', 'issuerid');
923 $manual_award->annotate_ids('role', 'issuerrole');
925 // Return the root element ($badges).
931 * structure step in charge of constructing the calender.xml file for all the events found
934 class backup_calendarevents_structure_step
extends backup_structure_step
{
936 protected function define_structure() {
938 // Define each element separated
940 $events = new backup_nested_element('events');
942 $event = new backup_nested_element('event', array('id'), array(
943 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
944 'repeatid', 'modulename', 'instance', 'type', 'eventtype', 'timestart',
945 'timeduration', 'timesort', 'visible', 'uuid', 'sequence', 'timemodified',
946 'priority', 'location'));
949 $events->add_child($event);
952 if ($this->name
== 'course_calendar') {
953 $calendar_items_sql ="SELECT * FROM {event}
954 WHERE courseid = :courseid
955 AND (eventtype = 'course' OR eventtype = 'group')";
956 $calendar_items_params = array('courseid'=>backup
::VAR_COURSEID
);
957 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
958 } else if ($this->name
== 'activity_calendar') {
959 // We don't backup action events.
960 $params = array('instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
,
961 'type' => array('sqlparam' => CALENDAR_EVENT_TYPE_ACTION
));
962 // If we don't want to include the userinfo in the backup then setting the courseid
963 // will filter out all of the user override events (which have a course id of zero).
965 if (!$this->get_setting_value('userinfo')) {
966 $params['courseid'] = backup
::VAR_COURSEID
;
967 $coursewhere = " AND courseid = :courseid";
969 $calendarsql = "SELECT * FROM {event}
970 WHERE instance = :instance
972 AND modulename = :modulename";
973 $calendarsql = $calendarsql . $coursewhere;
974 $event->set_source_sql($calendarsql, $params);
976 $event->set_source_table('event', array('courseid' => backup
::VAR_COURSEID
, 'instance' => backup
::VAR_ACTIVITYID
, 'modulename' => backup
::VAR_MODNAME
));
979 // Define id annotations
981 $event->annotate_ids('user', 'userid');
982 $event->annotate_ids('group', 'groupid');
983 $event->annotate_files('calendar', 'event_description', 'id');
985 // Return the root element (events)
991 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
992 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
994 class backup_gradebook_structure_step
extends backup_structure_step
{
997 * We need to decide conditionally, based on dynamic information
998 * about the execution of this step. Only will be executed if all
999 * the module gradeitems have been already included in backup
1001 protected function execute_condition() {
1002 $courseid = $this->get_courseid();
1003 if ($courseid == SITEID
) {
1007 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1010 protected function define_structure() {
1013 // are we including user info?
1014 $userinfo = $this->get_setting_value('users');
1016 $gradebook = new backup_nested_element('gradebook');
1018 //grade_letters are done in backup_activity_grades_structure_step()
1020 //calculated grade items
1021 $grade_items = new backup_nested_element('grade_items');
1022 $grade_item = new backup_nested_element('grade_item', array('id'), array(
1023 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1024 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1025 'calculation', 'gradetype', 'grademax', 'grademin',
1026 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1027 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
1028 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
1029 'needsupdate', 'timecreated', 'timemodified'));
1031 $this->add_plugin_structure('local', $grade_item, true);
1033 $grade_grades = new backup_nested_element('grade_grades');
1034 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
1035 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1036 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1037 'locked', 'locktime', 'exported', 'overridden',
1038 'excluded', 'feedback', 'feedbackformat', 'information',
1039 'informationformat', 'timecreated', 'timemodified',
1040 'aggregationstatus', 'aggregationweight'));
1043 $grade_categories = new backup_nested_element('grade_categories');
1044 $grade_category = new backup_nested_element('grade_category', array('id'), array(
1046 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
1047 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
1048 'timecreated', 'timemodified', 'hidden'));
1050 $letters = new backup_nested_element('grade_letters');
1051 $letter = new backup_nested_element('grade_letter', 'id', array(
1052 'lowerboundary', 'letter'));
1054 $grade_settings = new backup_nested_element('grade_settings');
1055 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
1058 $gradebook_attributes = new backup_nested_element('attributes', null, array('calculations_freeze'));
1061 $gradebook->add_child($gradebook_attributes);
1063 $gradebook->add_child($grade_categories);
1064 $grade_categories->add_child($grade_category);
1066 $gradebook->add_child($grade_items);
1067 $grade_items->add_child($grade_item);
1068 $grade_item->add_child($grade_grades);
1069 $grade_grades->add_child($grade_grade);
1071 $gradebook->add_child($letters);
1072 $letters->add_child($letter);
1074 $gradebook->add_child($grade_settings);
1075 $grade_settings->add_child($grade_setting);
1079 // Add attribute with gradebook calculation freeze date if needed.
1080 $attributes = new stdClass();
1081 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
1082 if ($gradebookcalculationfreeze) {
1083 $attributes->calculations_freeze
= $gradebookcalculationfreeze;
1085 $gradebook_attributes->set_source_array([$attributes]);
1087 //Include manual, category and the course grade item
1088 $grade_items_sql ="SELECT * FROM {grade_items}
1089 WHERE courseid = :courseid
1090 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1091 $grade_items_params = array('courseid'=>backup
::VAR_COURSEID
);
1092 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1095 $grade_grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
1098 $grade_category_sql = "SELECT gc.*, gi.sortorder
1099 FROM {grade_categories} gc
1100 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1101 WHERE gc.courseid = :courseid
1102 AND (gi.itemtype='course' OR gi.itemtype='category')
1103 ORDER BY gc.parent ASC";//need parent categories before their children
1104 $grade_category_params = array('courseid'=>backup
::VAR_COURSEID
);
1105 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1107 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
1109 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1110 $settings = array();
1111 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1112 foreach ($rs as $record) {
1113 $settings[$record->name
] = $record;
1116 if (!isset($settings['minmaxtouse'])) {
1117 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse
);
1119 $grade_setting->set_source_array($settings);
1122 // Annotations (both as final as far as they are going to be exported in next steps)
1123 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1124 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1126 //just in case there are any users not already annotated by the activities
1127 $grade_grade->annotate_ids('userfinal', 'userid');
1129 // Return the root element
1135 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1137 class backup_grade_history_structure_step
extends backup_structure_step
{
1140 * Limit the execution.
1142 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1143 * because we do not want to save the history of items which are not backed up. At least for now.
1145 protected function execute_condition() {
1146 $courseid = $this->get_courseid();
1147 if ($courseid == SITEID
) {
1151 return backup_plan_dbops
::require_gradebook_backup($courseid, $this->get_backupid());
1154 protected function define_structure() {
1157 $userinfo = $this->get_setting_value('users');
1158 $history = $this->get_setting_value('grade_histories');
1160 // Create the nested elements.
1161 $bookhistory = new backup_nested_element('grade_history');
1162 $grades = new backup_nested_element('grade_grades');
1163 $grade = new backup_nested_element('grade_grade', array('id'), array(
1164 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1165 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1166 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1167 'excluded', 'feedback', 'feedbackformat', 'information',
1168 'informationformat', 'timemodified'));
1171 $bookhistory->add_child($grades);
1172 $grades->add_child($grade);
1174 // This only happens if we are including user info and history.
1175 if ($userinfo && $history) {
1176 // Only keep the history of grades related to items which have been backed up, The query is
1177 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1178 $gradesql = "SELECT ggh.*
1179 FROM {grade_grades_history} ggh
1180 JOIN {grade_items} gi ON ggh.itemid = gi.id
1181 WHERE gi.courseid = :courseid
1182 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1183 $grade->set_source_sql($gradesql, array('courseid' => backup
::VAR_COURSEID
));
1186 // Annotations. (Final annotations as this step is part of the final task).
1187 $grade->annotate_ids('scalefinal', 'rawscaleid');
1188 $grade->annotate_ids('userfinal', 'loggeduser');
1189 $grade->annotate_ids('userfinal', 'userid');
1190 $grade->annotate_ids('userfinal', 'usermodified');
1192 // Return the root element.
1193 return $bookhistory;
1199 * structure step in charge if constructing the completion.xml file for all the users completion
1200 * information in a given activity
1202 class backup_userscompletion_structure_step
extends backup_structure_step
{
1205 * Skip completion on the front page.
1208 protected function execute_condition() {
1209 return ($this->get_courseid() != SITEID
);
1212 protected function define_structure() {
1214 // Define each element separated
1216 $completions = new backup_nested_element('completions');
1218 $completion = new backup_nested_element('completion', array('id'), array(
1219 'userid', 'completionstate', 'viewed', 'timemodified'));
1223 $completions->add_child($completion);
1227 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup
::VAR_MODID
));
1229 // Define id annotations
1231 $completion->annotate_ids('user', 'userid');
1233 // Return the root element (completions)
1234 return $completions;
1239 * structure step in charge of constructing the main groups.xml file for all the groups and
1240 * groupings information already annotated
1242 class backup_groups_structure_step
extends backup_structure_step
{
1244 protected function define_structure() {
1246 // To know if we are including users.
1247 $userinfo = $this->get_setting_value('users');
1248 // To know if we are including groups and groupings.
1249 $groupinfo = $this->get_setting_value('groups');
1251 // Define each element separated
1253 $groups = new backup_nested_element('groups');
1255 $group = new backup_nested_element('group', array('id'), array(
1256 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1257 'picture', 'timecreated', 'timemodified'));
1259 $members = new backup_nested_element('group_members');
1261 $member = new backup_nested_element('group_member', array('id'), array(
1262 'userid', 'timeadded', 'component', 'itemid'));
1264 $groupings = new backup_nested_element('groupings');
1266 $grouping = new backup_nested_element('grouping', 'id', array(
1267 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1268 'timecreated', 'timemodified'));
1270 $groupinggroups = new backup_nested_element('grouping_groups');
1272 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1273 'groupid', 'timeadded'));
1277 $groups->add_child($group);
1278 $groups->add_child($groupings);
1280 $group->add_child($members);
1281 $members->add_child($member);
1283 $groupings->add_child($grouping);
1284 $grouping->add_child($groupinggroups);
1285 $groupinggroups->add_child($groupinggroup);
1289 // This only happens if we are including groups/groupings.
1291 $group->set_source_sql("
1294 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1295 WHERE bi.backupid = ?
1296 AND bi.itemname = 'groupfinal'", array(backup
::VAR_BACKUPID
));
1298 $grouping->set_source_sql("
1301 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1302 WHERE bi.backupid = ?
1303 AND bi.itemname = 'groupingfinal'", array(backup
::VAR_BACKUPID
));
1304 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup
::VAR_PARENTID
));
1306 // This only happens if we are including users.
1308 $member->set_source_table('groups_members', array('groupid' => backup
::VAR_PARENTID
));
1312 // Define id annotations (as final)
1314 $member->annotate_ids('userfinal', 'userid');
1316 // Define file annotations
1318 $group->annotate_files('group', 'description', 'id');
1319 $group->annotate_files('group', 'icon', 'id');
1320 $grouping->annotate_files('grouping', 'description', 'id');
1322 // Return the root element (groups)
1328 * structure step in charge of constructing the main users.xml file for all the users already
1329 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1332 class backup_users_structure_step
extends backup_structure_step
{
1334 protected function define_structure() {
1337 // To know if we are anonymizing users
1338 $anonymize = $this->get_setting_value('anonymize');
1339 // To know if we are including role assignments
1340 $roleassignments = $this->get_setting_value('role_assignments');
1342 // Define each element separate.
1344 $users = new backup_nested_element('users');
1346 // Create the array of user fields by hand, as far as we have various bits to control
1347 // anonymize option, password backup, mnethostid...
1349 // First, the fields not needing anonymization nor special handling
1350 $normalfields = array(
1351 'confirmed', 'policyagreed', 'deleted',
1352 'lang', 'theme', 'timezone', 'firstaccess',
1353 'lastaccess', 'lastlogin', 'currentlogin',
1354 'mailformat', 'maildigest', 'maildisplay',
1355 'autosubscribe', 'trackforums', 'timecreated',
1356 'timemodified', 'trustbitmask');
1358 // Then, the fields potentially needing anonymization
1359 $anonfields = array(
1360 'username', 'idnumber', 'email', 'phone1',
1361 'phone2', 'institution', 'department', 'address',
1362 'city', 'country', 'lastip', 'picture',
1363 'description', 'descriptionformat', 'imagealt', 'auth');
1364 $anonfields = array_merge($anonfields, \core_user\fields
::get_name_fields());
1366 // Add anonymized fields to $userfields with custom final element
1367 foreach ($anonfields as $field) {
1369 $userfields[] = new anonymizer_final_element($field);
1371 $userfields[] = $field; // No anonymization, normally added
1375 // mnethosturl requires special handling (custom final element)
1376 $userfields[] = new mnethosturl_final_element('mnethosturl');
1378 // password added conditionally
1379 if (!empty($CFG->includeuserpasswordsinbackup
)) {
1380 $userfields[] = 'password';
1383 // Merge all the fields
1384 $userfields = array_merge($userfields, $normalfields);
1386 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1388 $customfields = new backup_nested_element('custom_fields');
1390 $customfield = new backup_nested_element('custom_field', array('id'), array(
1391 'field_name', 'field_type', 'field_data'));
1393 $tags = new backup_nested_element('tags');
1395 $tag = new backup_nested_element('tag', array('id'), array(
1396 'name', 'rawname'));
1398 $preferences = new backup_nested_element('preferences');
1400 $preference = new backup_nested_element('preference', array('id'), array(
1403 $roles = new backup_nested_element('roles');
1405 $overrides = new backup_nested_element('role_overrides');
1407 $override = new backup_nested_element('override', array('id'), array(
1408 'roleid', 'capability', 'permission', 'timemodified',
1411 $assignments = new backup_nested_element('role_assignments');
1413 $assignment = new backup_nested_element('assignment', array('id'), array(
1414 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1419 $users->add_child($user);
1421 $user->add_child($customfields);
1422 $customfields->add_child($customfield);
1424 $user->add_child($tags);
1425 $tags->add_child($tag);
1427 $user->add_child($preferences);
1428 $preferences->add_child($preference);
1430 $user->add_child($roles);
1432 $roles->add_child($overrides);
1433 $roles->add_child($assignments);
1435 $overrides->add_child($override);
1436 $assignments->add_child($assignment);
1440 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1442 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1443 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER
. '
1444 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1445 WHERE bi.backupid = ?
1446 AND bi.itemname = ?', array(
1447 backup_helper
::is_sqlparam($this->get_backupid()),
1448 backup_helper
::is_sqlparam('userfinal')));
1450 // All the rest on information is only added if we arent
1451 // in an anonymized backup
1453 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1454 FROM {user_info_field} f
1455 JOIN {user_info_data} d ON d.fieldid = f.id
1456 WHERE d.userid = ?', array(backup
::VAR_PARENTID
));
1458 $customfield->set_source_alias('shortname', 'field_name');
1459 $customfield->set_source_alias('datatype', 'field_type');
1460 $customfield->set_source_alias('data', 'field_data');
1462 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1464 JOIN {tag_instance} ti ON ti.tagid = t.id
1465 WHERE ti.itemtype = ?
1466 AND ti.itemid = ?', array(
1467 backup_helper
::is_sqlparam('user'),
1468 backup
::VAR_PARENTID
));
1470 $preference->set_source_table('user_preferences', array('userid' => backup
::VAR_PARENTID
));
1472 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1474 // Assignments only added if specified
1475 if ($roleassignments) {
1476 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1479 // Define id annotations (as final)
1480 $override->annotate_ids('rolefinal', 'roleid');
1482 // Return root element (users)
1488 * structure step in charge of constructing the block.xml file for one
1489 * given block (instance and positions). If the block has custom DB structure
1490 * that will go to a separate file (different step defined in block class)
1492 class backup_block_instance_structure_step
extends backup_structure_step
{
1494 protected function define_structure() {
1497 // Define each element separated
1499 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1500 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1501 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata',
1502 'timecreated', 'timemodified'));
1504 $positions = new backup_nested_element('block_positions');
1506 $position = new backup_nested_element('block_position', array('id'), array(
1507 'contextid', 'pagetype', 'subpage', 'visible',
1508 'region', 'weight'));
1512 $block->add_child($positions);
1513 $positions->add_child($position);
1515 // Transform configdata information if needed (process links and friends)
1516 $blockrec = $DB->get_record('block_instances', array('id' => $this->task
->get_blockid()));
1517 if ($attrstotransform = $this->task
->get_configdata_encoded_attributes()) {
1518 $configdata = (array)unserialize(base64_decode($blockrec->configdata
));
1519 foreach ($configdata as $attribute => $value) {
1520 if (in_array($attribute, $attrstotransform)) {
1521 $configdata[$attribute] = $this->contenttransformer
->process($value);
1524 $blockrec->configdata
= base64_encode(serialize((object)$configdata));
1526 $blockrec->contextid
= $this->task
->get_contextid();
1527 // Get the version of the block
1528 $blockrec->version
= get_config('block_'.$this->task
->get_blockname(), 'version');
1532 $block->set_source_array(array($blockrec));
1534 $position->set_source_table('block_positions', array('blockinstanceid' => backup
::VAR_PARENTID
));
1536 // File anotations (for fileareas specified on each block)
1537 foreach ($this->task
->get_fileareas() as $filearea) {
1538 $block->annotate_files('block_' . $this->task
->get_blockname(), $filearea, null);
1541 // Return the root element (block)
1547 * structure step in charge of constructing the logs.xml file for all the log records found
1548 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1549 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1550 * that just in case they become restored some day in the future
1552 class backup_course_logs_structure_step
extends backup_structure_step
{
1554 protected function define_structure() {
1556 // Define each element separated
1558 $logs = new backup_nested_element('logs');
1560 $log = new backup_nested_element('log', array('id'), array(
1561 'time', 'userid', 'ip', 'module',
1562 'action', 'url', 'info'));
1566 $logs->add_child($log);
1568 // Define sources (all the records belonging to the course, having cmid = 0)
1570 $log->set_source_table('log', array('course' => backup
::VAR_COURSEID
, 'cmid' => backup_helper
::is_sqlparam(0)));
1573 // NOTE: We don't annotate users from logs as far as they MUST be
1574 // always annotated by the course (enrol, ras... whatever)
1576 // Return the root element (logs)
1583 * structure step in charge of constructing the logs.xml file for all the log records found
1586 class backup_activity_logs_structure_step
extends backup_structure_step
{
1588 protected function define_structure() {
1590 // Define each element separated
1592 $logs = new backup_nested_element('logs');
1594 $log = new backup_nested_element('log', array('id'), array(
1595 'time', 'userid', 'ip', 'module',
1596 'action', 'url', 'info'));
1600 $logs->add_child($log);
1604 $log->set_source_table('log', array('cmid' => backup
::VAR_MODID
));
1607 // NOTE: We don't annotate users from logs as far as they MUST be
1608 // always annotated by the activity (true participants).
1610 // Return the root element (logs)
1617 * Structure step in charge of constructing the logstores.xml file for the course logs.
1619 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1620 * it, for logs belonging to the course level.
1622 class backup_course_logstores_structure_step
extends backup_structure_step
{
1624 protected function define_structure() {
1626 // Define the structure of logstores container.
1627 $logstores = new backup_nested_element('logstores');
1628 $logstore = new backup_nested_element('logstore');
1629 $logstores->add_child($logstore);
1631 // Add the tool_log logstore subplugins information to the logstore element.
1632 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1639 * Structure step in charge of constructing the loglastaccess.xml file for the course logs.
1641 * This backup step will backup the logs of the user_lastaccess table.
1643 class backup_course_loglastaccess_structure_step
extends backup_structure_step
{
1646 * This function creates the structures for the loglastaccess.xml file.
1647 * Expected structure would look like this.
1649 * <loglastaccess id=2>
1650 * <userid>5</userid>
1651 * <timeaccess>1616887341</timeaccess>
1653 * </loglastaccesses>
1655 * @return backup_nested_element
1657 protected function define_structure() {
1659 // To know if we are including userinfo.
1660 $userinfo = $this->get_setting_value('users');
1662 // Define the structure of logstores container.
1663 $lastaccesses = new backup_nested_element('lastaccesses');
1664 $lastaccess = new backup_nested_element('lastaccess', array('id'), array('userid', 'timeaccess'));
1666 // Define build tree.
1667 $lastaccesses->add_child($lastaccess);
1669 // This element should only happen if we are including user info.
1672 $lastaccess->set_source_sql('
1673 SELECT id, userid, timeaccess
1674 FROM {user_lastaccess}
1675 WHERE courseid = ?',
1676 array(backup
::VAR_COURSEID
));
1678 // Define userid annotation to user.
1679 $lastaccess->annotate_ids('user', 'userid');
1682 // Return the root element (lastaccessess).
1683 return $lastaccesses;
1688 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1690 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1692 class backup_activity_logstores_structure_step
extends backup_course_logstores_structure_step
{
1696 * Course competencies backup structure step.
1698 class backup_course_competencies_structure_step
extends backup_structure_step
{
1700 protected function define_structure() {
1701 $userinfo = $this->get_setting_value('users');
1703 $wrapper = new backup_nested_element('course_competencies');
1705 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1706 $wrapper->add_child($settings);
1708 $sql = 'SELECT s.pushratingstouserplans
1709 FROM {' . \core_competency\course_competency_settings
::TABLE
. '} s
1710 WHERE s.courseid = :courseid';
1711 $settings->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1713 $competencies = new backup_nested_element('competencies');
1714 $wrapper->add_child($competencies);
1716 $competency = new backup_nested_element('competency', null, array('id', 'idnumber', 'ruleoutcome',
1717 'sortorder', 'frameworkid', 'frameworkidnumber'));
1718 $competencies->add_child($competency);
1720 $sql = 'SELECT c.id, c.idnumber, cc.ruleoutcome, cc.sortorder, f.id AS frameworkid, f.idnumber AS frameworkidnumber
1721 FROM {' . \core_competency\course_competency
::TABLE
. '} cc
1722 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cc.competencyid
1723 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1724 WHERE cc.courseid = :courseid
1725 ORDER BY cc.sortorder';
1726 $competency->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1728 $usercomps = new backup_nested_element('user_competencies');
1729 $wrapper->add_child($usercomps);
1731 $usercomp = new backup_nested_element('user_competency', null, array('userid', 'competencyid',
1732 'proficiency', 'grade'));
1733 $usercomps->add_child($usercomp);
1735 $sql = 'SELECT ucc.userid, ucc.competencyid, ucc.proficiency, ucc.grade
1736 FROM {' . \core_competency\user_competency_course
::TABLE
. '} ucc
1737 WHERE ucc.courseid = :courseid
1738 AND ucc.grade IS NOT NULL';
1739 $usercomp->set_source_sql($sql, array('courseid' => backup
::VAR_COURSEID
));
1740 $usercomp->annotate_ids('user', 'userid');
1747 * Execute conditions.
1751 protected function execute_condition() {
1753 // Do not execute if competencies are not included.
1754 if (!$this->get_setting_value('competencies')) {
1763 * Activity competencies backup structure step.
1765 class backup_activity_competencies_structure_step
extends backup_structure_step
{
1767 protected function define_structure() {
1768 $wrapper = new backup_nested_element('course_module_competencies');
1770 $competencies = new backup_nested_element('competencies');
1771 $wrapper->add_child($competencies);
1773 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1774 'sortorder', 'frameworkidnumber'));
1775 $competencies->add_child($competency);
1777 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.sortorder, f.idnumber AS frameworkidnumber
1778 FROM {' . \core_competency\course_module_competency
::TABLE
. '} cmc
1779 JOIN {' . \core_competency\competency
::TABLE
. '} c ON c.id = cmc.competencyid
1780 JOIN {' . \core_competency\competency_framework
::TABLE
. '} f ON f.id = c.competencyframeworkid
1781 WHERE cmc.cmid = :coursemoduleid
1782 ORDER BY cmc.sortorder';
1783 $competency->set_source_sql($sql, array('coursemoduleid' => backup
::VAR_MODID
));
1789 * Execute conditions.
1793 protected function execute_condition() {
1795 // Do not execute if competencies are not included.
1796 if (!$this->get_setting_value('competencies')) {
1805 * structure in charge of constructing the inforef.xml file for all the items we want
1806 * to have referenced there (users, roles, files...)
1808 class backup_inforef_structure_step
extends backup_structure_step
{
1810 protected function define_structure() {
1812 // Items we want to include in the inforef file.
1813 $items = backup_helper
::get_inforef_itemnames();
1817 $inforef = new backup_nested_element('inforef');
1819 // For each item, conditionally, if there are already records, build element
1820 foreach ($items as $itemname) {
1821 if (backup_structure_dbops
::annotations_exist($this->get_backupid(), $itemname)) {
1822 $elementroot = new backup_nested_element($itemname . 'ref');
1823 $element = new backup_nested_element($itemname, array(), array('id'));
1824 $inforef->add_child($elementroot);
1825 $elementroot->add_child($element);
1826 $element->set_source_sql("
1828 FROM {backup_ids_temp}
1831 array(backup
::VAR_BACKUPID
, backup_helper
::is_sqlparam($itemname)));
1835 // We don't annotate anything there, but rely in the next step
1836 // (move_inforef_annotations_to_final) that will change all the
1837 // already saved 'inforref' entries to their 'final' annotations.
1843 * This step will get all the annotations already processed to inforef.xml file and
1844 * transform them into 'final' annotations.
1846 class move_inforef_annotations_to_final
extends backup_execution_step
{
1848 protected function define_execution() {
1850 // Items we want to include in the inforef file
1851 $items = backup_helper
::get_inforef_itemnames();
1852 $progress = $this->task
->get_progress();
1853 $progress->start_progress($this->get_name(), count($items));
1855 foreach ($items as $itemname) {
1856 // Delegate to dbops
1857 backup_structure_dbops
::move_annotations_to_final($this->get_backupid(),
1858 $itemname, $progress);
1859 $progress->progress($done++
);
1861 $progress->end_progress();
1866 * structure in charge of constructing the files.xml file with all the
1867 * annotated (final) files along the process. At, the same time, and
1868 * using one specialised nested_element, will copy them form moodle storage
1871 class backup_final_files_structure_step
extends backup_structure_step
{
1873 protected function define_structure() {
1877 $files = new backup_nested_element('files');
1879 $file = new file_nested_element('file', array('id'), array(
1880 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1881 'filepath', 'filename', 'userid', 'filesize',
1882 'mimetype', 'status', 'timecreated', 'timemodified',
1883 'source', 'author', 'license', 'sortorder',
1884 'repositorytype', 'repositoryid', 'reference'));
1888 $files->add_child($file);
1892 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1894 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1895 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1896 LEFT JOIN {repository} r ON r.id = ri.typeid
1897 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1898 WHERE bi.backupid = ?
1899 AND bi.itemname = 'filefinal'", array(backup
::VAR_BACKUPID
));
1906 * Structure step in charge of creating the main moodle_backup.xml file
1907 * where all the information related to the backup, settings, license and
1908 * other information needed on restore is added*/
1909 class backup_main_structure_step
extends backup_structure_step
{
1911 protected function define_structure() {
1917 $info['name'] = $this->get_setting_value('filename');
1918 $info['moodle_version'] = $CFG->version
;
1919 $info['moodle_release'] = $CFG->release
;
1920 $info['backup_version'] = $CFG->backup_version
;
1921 $info['backup_release'] = $CFG->backup_release
;
1922 $info['backup_date'] = time();
1923 $info['backup_uniqueid']= $this->get_backupid();
1924 $info['mnet_remoteusers']=backup_controller_dbops
::backup_includes_mnet_remote_users($this->get_backupid());
1925 $info['include_files'] = backup_controller_dbops
::backup_includes_files($this->get_backupid());
1926 $info['include_file_references_to_external_content'] =
1927 backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
1928 $info['original_wwwroot']=$CFG->wwwroot
;
1929 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1930 $info['original_course_id'] = $this->get_courseid();
1931 $originalcourseinfo = backup_controller_dbops
::backup_get_original_course_info($this->get_courseid());
1932 $info['original_course_format'] = $originalcourseinfo->format
;
1933 $info['original_course_fullname'] = $originalcourseinfo->fullname
;
1934 $info['original_course_shortname'] = $originalcourseinfo->shortname
;
1935 $info['original_course_startdate'] = $originalcourseinfo->startdate
;
1936 $info['original_course_enddate'] = $originalcourseinfo->enddate
;
1937 $info['original_course_contextid'] = context_course
::instance($this->get_courseid())->id
;
1938 $info['original_system_contextid'] = context_system
::instance()->id
;
1940 // Get more information from controller
1941 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops
::get_moodle_backup_information(
1942 $this->get_backupid(), $this->get_task()->get_progress());
1946 $moodle_backup = new backup_nested_element('moodle_backup');
1948 $information = new backup_nested_element('information', null, array(
1949 'name', 'moodle_version', 'moodle_release', 'backup_version',
1950 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1951 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
1952 'original_course_fullname', 'original_course_shortname', 'original_course_startdate', 'original_course_enddate',
1953 'original_course_contextid', 'original_system_contextid'));
1955 $details = new backup_nested_element('details');
1957 $detail = new backup_nested_element('detail', array('backup_id'), array(
1958 'type', 'format', 'interactive', 'mode',
1959 'execution', 'executiontime'));
1961 $contents = new backup_nested_element('contents');
1963 $activities = new backup_nested_element('activities');
1965 $activity = new backup_nested_element('activity', null, array(
1966 'moduleid', 'sectionid', 'modulename', 'title',
1969 $sections = new backup_nested_element('sections');
1971 $section = new backup_nested_element('section', null, array(
1972 'sectionid', 'title', 'directory'));
1974 $course = new backup_nested_element('course', null, array(
1975 'courseid', 'title', 'directory'));
1977 $settings = new backup_nested_element('settings');
1979 $setting = new backup_nested_element('setting', null, array(
1980 'level', 'section', 'activity', 'name', 'value'));
1984 $moodle_backup->add_child($information);
1986 $information->add_child($details);
1987 $details->add_child($detail);
1989 $information->add_child($contents);
1990 if (!empty($cinfo['activities'])) {
1991 $contents->add_child($activities);
1992 $activities->add_child($activity);
1994 if (!empty($cinfo['sections'])) {
1995 $contents->add_child($sections);
1996 $sections->add_child($section);
1998 if (!empty($cinfo['course'])) {
1999 $contents->add_child($course);
2002 $information->add_child($settings);
2003 $settings->add_child($setting);
2008 $information->set_source_array(array((object)$info));
2010 $detail->set_source_array($dinfo);
2012 $activity->set_source_array($cinfo['activities']);
2014 $section->set_source_array($cinfo['sections']);
2016 $course->set_source_array($cinfo['course']);
2018 $setting->set_source_array($sinfo);
2020 // Prepare some information to be sent to main moodle_backup.xml file
2021 return $moodle_backup;
2027 * Execution step that will generate the final zip (.mbz) file with all the contents
2029 class backup_zip_contents
extends backup_execution_step
implements file_progress
{
2031 * @var bool True if we have started tracking progress
2033 protected $startedprogress;
2035 protected function define_execution() {
2038 $basepath = $this->get_basepath();
2040 // Get the list of files in directory
2041 $filestemp = get_directory_list($basepath, '', false, true, true);
2043 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
2044 $files[$file] = $basepath . '/' . $file;
2047 // Add the log file if exists
2048 $logfilepath = $basepath . '.log';
2049 if (file_exists($logfilepath)) {
2050 $files['moodle_backup.log'] = $logfilepath;
2053 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2054 $zipfile = $basepath . '/backup.mbz';
2056 // Get the zip packer
2057 $zippacker = get_file_packer('application/vnd.moodle.backup');
2059 // Track overall progress for the 2 long-running steps (archive to
2060 // pathname, get backup information).
2061 $reporter = $this->task
->get_progress();
2062 $reporter->start_progress('backup_zip_contents', 2);
2065 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
2067 // If any sub-progress happened, end it.
2068 if ($this->startedprogress
) {
2069 $this->task
->get_progress()->end_progress();
2070 $this->startedprogress
= false;
2072 // No progress was reported, manually move it on to the next overall task.
2073 $reporter->progress(1);
2076 // Something went wrong.
2077 if ($result === false) {
2079 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
2081 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
2083 backup_general_helper
::get_backup_information_from_mbz($zipfile, $this);
2084 } catch (backup_helper_exception
$e) {
2086 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo
);
2089 // If any sub-progress happened, end it.
2090 if ($this->startedprogress
) {
2091 $this->task
->get_progress()->end_progress();
2092 $this->startedprogress
= false;
2094 $reporter->progress(2);
2096 $reporter->end_progress();
2100 * Implementation for file_progress interface to display unzip progress.
2102 * @param int $progress Current progress
2103 * @param int $max Max value
2105 public function progress($progress = file_progress
::INDETERMINATE
, $max = file_progress
::INDETERMINATE
) {
2106 $reporter = $this->task
->get_progress();
2108 // Start tracking progress if necessary.
2109 if (!$this->startedprogress
) {
2110 $reporter->start_progress('extract_file_to_dir', ($max == file_progress
::INDETERMINATE
)
2111 ? \core\progress\base
::INDETERMINATE
: $max);
2112 $this->startedprogress
= true;
2115 // Pass progress through to whatever handles it.
2116 $reporter->progress(($progress == file_progress
::INDETERMINATE
)
2117 ? \core\progress\base
::INDETERMINATE
: $progress);
2122 * This step will send the generated backup file to its final destination
2124 class backup_store_backup_file
extends backup_execution_step
{
2126 protected function define_execution() {
2129 $basepath = $this->get_basepath();
2131 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2132 $zipfile = $basepath . '/backup.mbz';
2134 $has_file_references = backup_controller_dbops
::backup_includes_file_references($this->get_backupid());
2135 // Perform storage and return it (TODO: shouldn't be array but proper result object)
2137 'backup_destination' => backup_helper
::store_backup_file($this->get_backupid(), $zipfile,
2138 $this->task
->get_progress()),
2139 'include_file_references_to_external_content' => $has_file_references
2146 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
2147 * and put them to the backup_ids tables, to be used later as base to backup them
2149 class backup_activity_grade_items_to_ids
extends backup_execution_step
{
2151 protected function define_execution() {
2153 // Fetch all activity grade items
2154 if ($items = grade_item
::fetch_all(array(
2155 'itemtype' => 'mod', 'itemmodule' => $this->task
->get_modulename(),
2156 'iteminstance' => $this->task
->get_activityid(), 'courseid' => $this->task
->get_courseid()))) {
2157 // Annotate them in backup_ids
2158 foreach ($items as $item) {
2159 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id
);
2167 * This step allows enrol plugins to annotate custom fields.
2169 * @package core_backup
2170 * @copyright 2014 University of Wisconsin
2171 * @author Matt Petro
2172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2174 class backup_enrolments_execution_step
extends backup_execution_step
{
2177 * Function that will contain all the code to be executed.
2179 protected function define_execution() {
2182 $plugins = enrol_get_plugins(true);
2183 $enrols = $DB->get_records('enrol', array(
2184 'courseid' => $this->task
->get_courseid()));
2186 // Allow each enrol plugin to add annotations.
2187 foreach ($enrols as $enrol) {
2188 if (isset($plugins[$enrol->enrol
])) {
2189 $plugins[$enrol->enrol
]->backup_annotate_custom_fields($this, $enrol);
2195 * Annotate a single name/id pair.
2196 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
2198 * @param string $itemname
2199 * @param int $itemid
2201 public function annotate_id($itemname, $itemid) {
2202 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2207 * This step will annotate all the groups and groupings belonging to the course
2209 class backup_annotate_course_groups_and_groupings
extends backup_execution_step
{
2211 protected function define_execution() {
2214 // Get all the course groups
2215 if ($groups = $DB->get_records('groups', array(
2216 'courseid' => $this->task
->get_courseid()))) {
2217 foreach ($groups as $group) {
2218 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->id
);
2222 // Get all the course groupings
2223 if ($groupings = $DB->get_records('groupings', array(
2224 'courseid' => $this->task
->get_courseid()))) {
2225 foreach ($groupings as $grouping) {
2226 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id
);
2233 * This step will annotate all the groups belonging to already annotated groupings
2235 class backup_annotate_groups_from_groupings
extends backup_execution_step
{
2237 protected function define_execution() {
2240 // Fetch all the annotated groupings
2241 if ($groupings = $DB->get_records('backup_ids_temp', array(
2242 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2243 foreach ($groupings as $grouping) {
2244 if ($groups = $DB->get_records('groupings_groups', array(
2245 'groupingid' => $grouping->itemid
))) {
2246 foreach ($groups as $group) {
2247 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid
);
2256 * This step will annotate all the scales belonging to already annotated outcomes
2258 class backup_annotate_scales_from_outcomes
extends backup_execution_step
{
2260 protected function define_execution() {
2263 // Fetch all the annotated outcomes
2264 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2265 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2266 foreach ($outcomes as $outcome) {
2267 if ($scale = $DB->get_record('grade_outcomes', array(
2268 'id' => $outcome->itemid
))) {
2269 // Annotate as scalefinal because it's > 0
2270 backup_structure_dbops
::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid
);
2278 * This step will generate all the file annotations for the already
2279 * annotated (final) question_categories. It calculates the different
2280 * contexts that are being backup and, annotates all the files
2281 * on every context belonging to the "question" component. As far as
2282 * we are always including *complete* question banks it is safe and
2283 * optimal to do that in this (one pass) way
2285 class backup_annotate_all_question_files
extends backup_execution_step
{
2287 protected function define_execution() {
2290 // Get all the different contexts for the final question_categories
2291 // annotated along the whole backup
2292 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2293 FROM {question_categories} qc
2294 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2295 WHERE bi.backupid = ?
2296 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2297 // To know about qtype specific components/fileareas
2298 $components = backup_qtype_plugin
::get_components_and_fileareas();
2300 foreach($rs as $record) {
2301 // Backup all the file areas the are managed by the core question component.
2302 // That is, by the question_type base class. In particular, we don't want
2303 // to include files belonging to responses here.
2304 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'questiontext', null);
2305 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'generalfeedback', null);
2306 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answer', null);
2307 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'answerfeedback', null);
2308 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'hint', null);
2309 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'correctfeedback', null);
2310 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'partiallycorrectfeedback', null);
2311 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, 'question', 'incorrectfeedback', null);
2313 // For files belonging to question types, we make the leap of faith that
2314 // all the files belonging to the question type are part of the question definition,
2315 // so we can just backup all the files in bulk, without specifying each
2316 // file area name separately.
2317 foreach ($components as $component => $fileareas) {
2318 backup_structure_dbops
::annotate_files($this->get_backupid(), $record->contextid
, $component, null, null);
2326 * structure step in charge of constructing the questions.xml file for all the
2327 * question categories and questions required by the backup
2328 * and letters related to one activity
2330 class backup_questions_structure_step
extends backup_structure_step
{
2332 protected function define_structure() {
2334 // Define each element separated
2336 $qcategories = new backup_nested_element('question_categories');
2338 $qcategory = new backup_nested_element('question_category', array('id'), array(
2339 'name', 'contextid', 'contextlevel', 'contextinstanceid',
2340 'info', 'infoformat', 'stamp', 'parent',
2341 'sortorder', 'idnumber'));
2343 $questions = new backup_nested_element('questions');
2345 $question = new backup_nested_element('question', array('id'), array(
2346 'parent', 'name', 'questiontext', 'questiontextformat',
2347 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
2348 'qtype', 'length', 'stamp', 'version',
2349 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby', 'idnumber'));
2351 // attach qtype plugin structure to $question element, only one allowed
2352 $this->add_plugin_structure('qtype', $question, false);
2354 // Attach qbank plugin stucture to $question element, multiple allowed.
2355 $this->add_plugin_structure('qbank', $question, true);
2357 // attach local plugin stucture to $question element, multiple allowed
2358 $this->add_plugin_structure('local', $question, true);
2360 $qhints = new backup_nested_element('question_hints');
2362 $qhint = new backup_nested_element('question_hint', array('id'), array(
2363 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
2365 $tags = new backup_nested_element('tags');
2367 $tag = new backup_nested_element('tag', array('id', 'contextid'), array('name', 'rawname'));
2371 $qcategories->add_child($qcategory);
2372 $qcategory->add_child($questions);
2373 $questions->add_child($question);
2374 $question->add_child($qhints);
2375 $qhints->add_child($qhint);
2377 $question->add_child($tags);
2378 $tags->add_child($tag);
2380 // Define the sources
2382 $qcategory->set_source_sql("
2383 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
2384 FROM {question_categories} gc
2385 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2386 JOIN {context} co ON co.id = gc.contextid
2387 WHERE bi.backupid = ?
2388 AND bi.itemname = 'question_categoryfinal'", array(backup
::VAR_BACKUPID
));
2390 $question->set_source_table('question', array('category' => backup
::VAR_PARENTID
));
2392 $qhint->set_source_sql('
2394 FROM {question_hints}
2395 WHERE questionid = :questionid
2397 array('questionid' => backup
::VAR_PARENTID
));
2399 $tag->set_source_sql("SELECT t.id, ti.contextid, t.name, t.rawname
2401 JOIN {tag_instance} ti ON ti.tagid = t.id
2403 AND ti.itemtype = 'question'
2404 AND ti.component = 'core_question'",
2406 backup
::VAR_PARENTID
2409 // don't need to annotate ids nor files
2410 // (already done by {@link backup_annotate_all_question_files}
2412 return $qcategories;
2419 * This step will generate all the file annotations for the already
2420 * annotated (final) users. Need to do this here because each user
2421 * has its own context and structure tasks only are able to handle
2422 * one context. Also, this step will guarantee that every user has
2423 * its context created (req for other steps)
2425 class backup_annotate_all_user_files
extends backup_execution_step
{
2427 protected function define_execution() {
2430 // List of fileareas we are going to annotate
2431 $fileareas = array('profile', 'icon');
2433 // Fetch all annotated (final) users
2434 $rs = $DB->get_recordset('backup_ids_temp', array(
2435 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2436 $progress = $this->task
->get_progress();
2437 $progress->start_progress($this->get_name());
2438 foreach ($rs as $record) {
2439 $userid = $record->itemid
;
2440 $userctx = context_user
::instance($userid, IGNORE_MISSING
);
2442 continue; // User has not context, sure it's a deleted user, so cannot have files
2444 // Proceed with every user filearea
2445 foreach ($fileareas as $filearea) {
2446 // We don't need to specify itemid ($userid - 5th param) as far as by
2447 // context we can get all the associated files. See MDL-22092
2448 backup_structure_dbops
::annotate_files($this->get_backupid(), $userctx->id
, 'user', $filearea, null);
2449 $progress->progress();
2452 $progress->end_progress();
2459 * Defines the backup step for advanced grading methods attached to the activity module
2461 class backup_activity_grading_structure_step
extends backup_structure_step
{
2464 * Include the grading.xml only if the module supports advanced grading
2466 protected function execute_condition() {
2468 // No grades on the front page.
2469 if ($this->get_courseid() == SITEID
) {
2473 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING
, false);
2477 * Declares the gradable areas structures and data sources
2479 protected function define_structure() {
2481 // To know if we are including userinfo
2482 $userinfo = $this->get_setting_value('userinfo');
2484 // Define the elements
2486 $areas = new backup_nested_element('areas');
2488 $area = new backup_nested_element('area', array('id'), array(
2489 'areaname', 'activemethod'));
2491 $definitions = new backup_nested_element('definitions');
2493 $definition = new backup_nested_element('definition', array('id'), array(
2494 'method', 'name', 'description', 'descriptionformat', 'status',
2495 'timecreated', 'timemodified', 'options'));
2497 $instances = new backup_nested_element('instances');
2499 $instance = new backup_nested_element('instance', array('id'), array(
2500 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2501 'feedbackformat', 'timemodified'));
2503 // Build the tree including the method specific structures
2504 // (beware - the order of how gradingform plugins structures are attached is important)
2505 $areas->add_child($area);
2506 // attach local plugin stucture to $area element, multiple allowed
2507 $this->add_plugin_structure('local', $area, true);
2508 $area->add_child($definitions);
2509 $definitions->add_child($definition);
2510 $this->add_plugin_structure('gradingform', $definition, true);
2511 // attach local plugin stucture to $definition element, multiple allowed
2512 $this->add_plugin_structure('local', $definition, true);
2513 $definition->add_child($instances);
2514 $instances->add_child($instance);
2515 $this->add_plugin_structure('gradingform', $instance, false);
2516 // attach local plugin stucture to $instance element, multiple allowed
2517 $this->add_plugin_structure('local', $instance, true);
2519 // Define data sources
2521 $area->set_source_table('grading_areas', array('contextid' => backup
::VAR_CONTEXTID
,
2522 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2524 $definition->set_source_table('grading_definitions', array('areaid' => backup
::VAR_PARENTID
));
2527 $instance->set_source_table('grading_instances', array('definitionid' => backup
::VAR_PARENTID
));
2530 // Annotate references
2531 $definition->annotate_files('grading', 'description', 'id');
2532 $instance->annotate_ids('user', 'raterid');
2534 // Return the root element
2541 * structure step in charge of constructing the grades.xml file for all the grade items
2542 * and letters related to one activity
2544 class backup_activity_grades_structure_step
extends backup_structure_step
{
2547 * No grades on the front page.
2550 protected function execute_condition() {
2551 return ($this->get_courseid() != SITEID
);
2554 protected function define_structure() {
2557 require_once($CFG->libdir
. '/grade/constants.php');
2559 // To know if we are including userinfo
2560 $userinfo = $this->get_setting_value('userinfo');
2562 // Define each element separated
2564 $book = new backup_nested_element('activity_gradebook');
2566 $items = new backup_nested_element('grade_items');
2568 $item = new backup_nested_element('grade_item', array('id'), array(
2569 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2570 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2571 'calculation', 'gradetype', 'grademax', 'grademin',
2572 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2573 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2574 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2575 'needsupdate', 'timecreated', 'timemodified'));
2577 $grades = new backup_nested_element('grade_grades');
2579 $grade = new backup_nested_element('grade_grade', array('id'), array(
2580 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2581 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2582 'locked', 'locktime', 'exported', 'overridden',
2583 'excluded', 'feedback', 'feedbackformat', 'information',
2584 'informationformat', 'timecreated', 'timemodified',
2585 'aggregationstatus', 'aggregationweight'));
2587 $letters = new backup_nested_element('grade_letters');
2589 $letter = new backup_nested_element('grade_letter', 'id', array(
2590 'lowerboundary', 'letter'));
2594 $book->add_child($items);
2595 $items->add_child($item);
2597 $item->add_child($grades);
2598 $grades->add_child($grade);
2600 $book->add_child($letters);
2601 $letters->add_child($letter);
2605 $item->set_source_sql("SELECT gi.*
2606 FROM {grade_items} gi
2607 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2608 WHERE bi.backupid = ?
2609 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2611 // This only happens if we are including user info
2613 $grade->set_source_table('grade_grades', array('itemid' => backup
::VAR_PARENTID
));
2614 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_FEEDBACK_FILEAREA
, 'id');
2617 $letter->set_source_table('grade_letters', array('contextid' => backup
::VAR_CONTEXTID
));
2621 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2622 $item->annotate_ids('outcome', 'outcomeid');
2624 $grade->annotate_ids('user', 'userid');
2625 $grade->annotate_ids('user', 'usermodified');
2627 // Return the root element (book)
2634 * Structure step in charge of constructing the grade history of an activity.
2636 * This step is added to the task regardless of the setting 'grade_histories'.
2637 * The reason is to allow for a more flexible step in case the logic needs to be
2638 * split accross different settings to control the history of items and/or grades.
2640 class backup_activity_grade_history_structure_step
extends backup_structure_step
{
2643 * No grades on the front page.
2646 protected function execute_condition() {
2647 return ($this->get_courseid() != SITEID
);
2650 protected function define_structure() {
2653 require_once($CFG->libdir
. '/grade/constants.php');
2656 $userinfo = $this->get_setting_value('userinfo');
2657 $history = $this->get_setting_value('grade_histories');
2659 // Create the nested elements.
2660 $bookhistory = new backup_nested_element('grade_history');
2661 $grades = new backup_nested_element('grade_grades');
2662 $grade = new backup_nested_element('grade_grade', array('id'), array(
2663 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2664 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2665 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2666 'excluded', 'feedback', 'feedbackformat', 'information',
2667 'informationformat', 'timemodified'));
2670 $bookhistory->add_child($grades);
2671 $grades->add_child($grade);
2673 // This only happens if we are including user info and history.
2674 if ($userinfo && $history) {
2675 // Define sources. Only select the history related to existing activity items.
2676 $grade->set_source_sql("SELECT ggh.*
2677 FROM {grade_grades_history} ggh
2678 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2679 WHERE bi.backupid = ?
2680 AND bi.itemname = 'grade_item'", array(backup
::VAR_BACKUPID
));
2681 $grade->annotate_files(GRADE_FILE_COMPONENT
, GRADE_HISTORY_FEEDBACK_FILEAREA
, 'id');
2685 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2686 $grade->annotate_ids('user', 'loggeduser');
2687 $grade->annotate_ids('user', 'userid');
2688 $grade->annotate_ids('user', 'usermodified');
2690 // Return the root element.
2691 return $bookhistory;
2696 * Backups up the course completion information for the course.
2698 class backup_course_completion_structure_step
extends backup_structure_step
{
2700 protected function execute_condition() {
2702 // No completion on front page.
2703 if ($this->get_courseid() == SITEID
) {
2707 // Check that all activities have been included
2708 if ($this->task
->is_excluding_activities()) {
2715 * The structure of the course completion backup
2717 * @return backup_nested_element
2719 protected function define_structure() {
2721 // To know if we are including user completion info
2722 $userinfo = $this->get_setting_value('userscompletion');
2724 $cc = new backup_nested_element('course_completion');
2726 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2727 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2728 'timeend', 'gradepass', 'role', 'roleshortname'
2731 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2733 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2734 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2737 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2738 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2741 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2742 'course','criteriatype','method','value'
2745 $cc->add_child($criteria);
2746 $criteria->add_child($criteriacompletions);
2747 $criteriacompletions->add_child($criteriacomplete);
2748 $cc->add_child($coursecompletions);
2749 $cc->add_child($aggregatemethod);
2751 // We need some extra data for the restore.
2752 // - courseinstances shortname rather than an ID.
2753 // - roleshortname in case restoring on a different site.
2754 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2755 FROM {course_completion_criteria} ccc
2756 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2757 LEFT JOIN {role} r ON r.id = ccc.role
2758 WHERE ccc.course = ?";
2759 $criteria->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2761 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup
::VAR_COURSEID
));
2764 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup
::VAR_PARENTID
));
2765 $coursecompletions->set_source_table('course_completions', array('course' => backup
::VAR_COURSEID
));
2768 $criteria->annotate_ids('role', 'role');
2769 $criteriacomplete->annotate_ids('user', 'userid');
2770 $coursecompletions->annotate_ids('user', 'userid');
2778 * Backup completion defaults for each module type.
2780 * @package core_backup
2781 * @copyright 2017 Marina Glancy
2782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2784 class backup_completion_defaults_structure_step
extends backup_structure_step
{
2787 * To conditionally decide if one step will be executed or no
2789 protected function execute_condition() {
2790 // No completion on front page.
2791 if ($this->get_courseid() == SITEID
) {
2798 * The structure of the course completion backup
2800 * @return backup_nested_element
2802 protected function define_structure() {
2804 $cc = new backup_nested_element('course_completion_defaults');
2806 $defaults = new backup_nested_element('course_completion_default', array('id'), array(
2807 'modulename', 'completion', 'completionview', 'completionusegrade', 'completionpassgrade',
2808 'completionexpected', 'customrules'
2811 // Use module name instead of module id so we can insert into another site later.
2812 $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
2813 d.completionpassgrade, d.completionexpected, d.customrules
2814 FROM {course_completion_defaults} d join {modules} m on d.module = m.id
2815 WHERE d.course = ?";
2816 $defaults->set_source_sql($sourcesql, array(backup
::VAR_COURSEID
));
2818 $cc->add_child($defaults);
2825 * Structure step in charge of constructing the contentbank.xml file for all the contents found in a given context
2827 class backup_contentbankcontent_structure_step
extends backup_structure_step
{
2830 * Define structure for content bank step
2832 protected function define_structure() {
2834 // Define each element separated.
2835 $contents = new backup_nested_element('contents');
2836 $content = new backup_nested_element('content', ['id'], [
2837 'name', 'contenttype', 'instanceid', 'configdata', 'usercreated', 'usermodified', 'timecreated', 'timemodified']);
2840 $contents->add_child($content);
2843 $content->set_source_table('contentbank_content', ['contextid' => backup
::VAR_CONTEXTID
]);
2845 // Define annotations.
2846 $content->annotate_ids('user', 'usercreated');
2847 $content->annotate_ids('user', 'usermodified');
2848 $content->annotate_files('contentbank', 'public', 'id');
2850 // Return the root element (contents).