MDL-75708 reportbuilder: consider stress tests as requiring longtest.
[moodle.git] / backup / moodle2 / backup_stepslib.php
blob2d2552dbe4b3cbb0afeb60ad49c3525cd7ca7d62
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Defines various backup steps that will be used by common tasks in backup
21 * @package core_backup
22 * @subpackage moodle2
23 * @category 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();
30 /**
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();
46 /**
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() {
56 global $CFG;
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;
75 /**
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() {
81 global $CFG;
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);
89 /**
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 {
95 /**
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);
107 // Build the tree
108 $activity->add_child($activitystructure);
110 // Set the source
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)
120 return $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 = '') {
143 global $CFG;
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',
161 'timemodified'));
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'));
170 // Build the tree
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);
179 // Set the sources
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));
186 // Annotate ids
187 $qa->annotate_ids('question', 'questionid');
188 $step->annotate_ids('user', 'userid');
190 // Annotate files
191 $fileareas = question_engine::get_all_response_file_areas();
192 foreach ($fileareas as $filearea) {
193 $step->annotate_files('question', $filearea, 'id');
199 * Helper to backup question reference data for an instance.
201 trait backup_question_reference_data_trait {
204 * Backup the related data from reference table for the instance.
206 * @param backup_nested_element $element
207 * @param string $component
208 * @param string $questionarea
210 protected function add_question_references($element, $component, $questionarea) {
211 // Check $element is one nested_backup_element.
212 if (! $element instanceof backup_nested_element) {
213 throw new backup_step_exception('question_states_bad_parent_element', $element);
216 $reference = new backup_nested_element('question_reference', ['id'],
217 ['usingcontextid', 'component', 'questionarea', 'questionbankentryid', 'version']);
219 $element->add_child($reference);
221 $reference->set_source_table('question_references', [
222 'usingcontextid' => backup::VAR_CONTEXTID,
223 'component' => backup_helper::is_sqlparam($component),
224 'questionarea' => backup_helper::is_sqlparam($questionarea),
225 'itemid' => backup::VAR_PARENTID
231 * Helper to backup question set reference data for an instance.
233 trait backup_question_set_reference_trait {
236 * Backup the related data from set_reference table for the instance.
238 * @param backup_nested_element $element
239 * @param string $component
240 * @param string $questionarea
242 protected function add_question_set_references($element, $component, $questionarea) {
243 // Check $element is one nested_backup_element.
244 if (! $element instanceof backup_nested_element) {
245 throw new backup_step_exception('question_states_bad_parent_element', $element);
248 $setreference = new backup_nested_element('question_set_reference', ['id'],
249 ['usingcontextid', 'component', 'questionarea', 'questionscontextid', 'filtercondition']);
251 $element->add_child($setreference);
253 $setreference->set_source_table('question_set_references', [
254 'usingcontextid' => backup::VAR_CONTEXTID,
255 'component' => backup_helper::is_sqlparam($component),
256 'questionarea' => backup_helper::is_sqlparam($questionarea),
257 'itemid' => backup::VAR_PARENTID
264 * Abstract structure step to help activities that store question attempt data, reference data and set reference data.
266 * @copyright 2011 The Open University
267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
270 use backup_questions_attempt_data_trait;
271 use backup_question_reference_data_trait;
272 use backup_question_set_reference_trait;
277 * backup structure step in charge of calculating the categories to be
278 * included in backup, based in the context being backuped (module/course)
279 * and the already annotated questions present in backup_ids_temp
281 class backup_calculate_question_categories extends backup_execution_step {
283 protected function define_execution() {
284 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
289 * backup structure step in charge of deleting all the questions annotated
290 * in the backup_ids_temp table
292 class backup_delete_temp_questions extends backup_execution_step {
294 protected function define_execution() {
295 backup_question_dbops::delete_temp_questions($this->get_backupid());
300 * Abstract structure step, parent of all the block structure steps. Used to wrap the
301 * block structure definition within the main <block ...> tag
303 abstract class backup_block_structure_step extends backup_structure_step {
305 protected function prepare_block_structure($blockstructure) {
307 // Create the wrap element
308 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
310 // Build the tree
311 $block->add_child($blockstructure);
313 // Set the source
314 $blockarr = array((object)array(
315 'id' => $this->task->get_blockid(),
316 'blockname' => $this->task->get_blockname(),
317 'contextid' => $this->task->get_contextid()));
319 $block->set_source_array($blockarr);
321 // Return the root element (block)
322 return $block;
327 * structure step that will generate the module.xml file for the activity,
328 * accumulating various information about the activity, annotating groupings
329 * and completion/avail conf
331 class backup_module_structure_step extends backup_structure_step {
333 protected function define_structure() {
334 global $DB;
336 // Define each element separated
338 $module = new backup_nested_element('module', array('id', 'version'), array(
339 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
340 'added', 'score', 'indent', 'visible', 'visibleoncoursepage',
341 'visibleold', 'groupmode', 'groupingid',
342 'completion', 'completiongradeitemnumber', 'completionpassgrade',
343 'completionview', 'completionexpected',
344 'availability', 'showdescription', 'downloadcontent', 'lang'));
346 $tags = new backup_nested_element('tags');
347 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
349 // attach format plugin structure to $module element, only one allowed
350 $this->add_plugin_structure('format', $module, false);
352 // Attach report plugin structure to $module element, multiple allowed.
353 $this->add_plugin_structure('report', $module, true);
355 // attach plagiarism plugin structure to $module element, there can be potentially
356 // many plagiarism plugins storing information about this course
357 $this->add_plugin_structure('plagiarism', $module, true);
359 // attach local plugin structure to $module, multiple allowed
360 $this->add_plugin_structure('local', $module, true);
362 // Attach admin tools plugin structure to $module.
363 $this->add_plugin_structure('tool', $module, true);
365 $module->add_child($tags);
366 $tags->add_child($tag);
368 // Set the sources
369 $concat = $DB->sql_concat("'mod_'", 'm.name');
370 $module->set_source_sql("
371 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
372 FROM {course_modules} cm
373 JOIN {modules} m ON m.id = cm.module
374 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
375 JOIN {course_sections} s ON s.id = cm.section
376 WHERE cm.id = ?", array(backup::VAR_MODID));
378 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
379 FROM {tag} t
380 JOIN {tag_instance} ti ON ti.tagid = t.id
381 WHERE ti.itemtype = 'course_modules'
382 AND ti.component = 'core'
383 AND ti.itemid = ?", array(backup::VAR_MODID));
385 // Define annotations
386 $module->annotate_ids('grouping', 'groupingid');
388 // Return the root element ($module)
389 return $module;
394 * structure step that will generate the section.xml file for the section
395 * annotating files
397 class backup_section_structure_step extends backup_structure_step {
399 protected function define_structure() {
401 // Define each element separated
403 $section = new backup_nested_element('section', array('id'), array(
404 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
405 'availabilityjson', 'timemodified'));
407 // attach format plugin structure to $section element, only one allowed
408 $this->add_plugin_structure('format', $section, false);
410 // attach local plugin structure to $section element, multiple allowed
411 $this->add_plugin_structure('local', $section, true);
413 // Add nested elements for course_format_options table
414 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
415 'format', 'name', 'value'));
416 $section->add_child($formatoptions);
418 // Define sources.
419 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
420 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
421 FROM {course} c
422 JOIN {course_format_options} cfo
423 ON cfo.courseid = c.id AND cfo.format = c.format
424 WHERE c.id = ? AND cfo.sectionid = ?',
425 array(backup::VAR_COURSEID, backup::VAR_SECTIONID));
427 // Aliases
428 $section->set_source_alias('section', 'number');
429 // The 'availability' field needs to be renamed because it clashes with
430 // the old nested element structure for availability data.
431 $section->set_source_alias('availability', 'availabilityjson');
433 // Set annotations
434 $section->annotate_files('course', 'section', 'id');
436 return $section;
441 * structure step that will generate the course.xml file for the course, including
442 * course category reference, tags, modules restriction information
443 * and some annotations (files & groupings)
445 class backup_course_structure_step extends backup_structure_step {
447 protected function define_structure() {
448 global $DB;
450 // Define each element separated
452 $course = new backup_nested_element('course', array('id', 'contextid'), array(
453 'shortname', 'fullname', 'idnumber',
454 'summary', 'summaryformat', 'format', 'showgrades',
455 'newsitems', 'startdate', 'enddate',
456 'marker', 'maxbytes', 'legacyfiles', 'showreports',
457 'visible', 'groupmode', 'groupmodeforce',
458 'defaultgroupingid', 'lang', 'theme',
459 'timecreated', 'timemodified',
460 'requested',
461 'showactivitydates',
462 'showcompletionconditions',
463 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
465 $category = new backup_nested_element('category', array('id'), array(
466 'name', 'description'));
468 $tags = new backup_nested_element('tags');
470 $tag = new backup_nested_element('tag', array('id'), array(
471 'name', 'rawname'));
473 $customfields = new backup_nested_element('customfields');
474 $customfield = new backup_nested_element('customfield', array('id'), array(
475 'shortname', 'type', 'value', 'valueformat'
478 $courseformatoptions = new backup_nested_element('courseformatoptions');
479 $courseformatoption = new backup_nested_element('courseformatoption', [], [
480 'courseid', 'format', 'sectionid', 'name', 'value'
483 // attach format plugin structure to $course element, only one allowed
484 $this->add_plugin_structure('format', $course, false);
486 // attach theme plugin structure to $course element; multiple themes can
487 // save course data (in case of user theme, legacy theme, etc)
488 $this->add_plugin_structure('theme', $course, true);
490 // attach general report plugin structure to $course element; multiple
491 // reports can save course data if required
492 $this->add_plugin_structure('report', $course, true);
494 // attach course report plugin structure to $course element; multiple
495 // course reports can save course data if required
496 $this->add_plugin_structure('coursereport', $course, true);
498 // attach plagiarism plugin structure to $course element, there can be potentially
499 // many plagiarism plugins storing information about this course
500 $this->add_plugin_structure('plagiarism', $course, true);
502 // attach local plugin structure to $course element; multiple local plugins
503 // can save course data if required
504 $this->add_plugin_structure('local', $course, true);
506 // Attach admin tools plugin structure to $course element; multiple plugins
507 // can save course data if required.
508 $this->add_plugin_structure('tool', $course, true);
510 // Build the tree
512 $course->add_child($category);
514 $course->add_child($tags);
515 $tags->add_child($tag);
517 $course->add_child($customfields);
518 $customfields->add_child($customfield);
520 $course->add_child($courseformatoptions);
521 $courseformatoptions->add_child($courseformatoption);
523 // Set the sources
525 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
526 $courserec->contextid = $this->task->get_contextid();
528 // Add 'numsections' in order to be able to restore in previous versions of Moodle.
529 // Even though Moodle does not officially support restore into older verions of Moodle from the
530 // version where backup was made, without 'numsections' restoring will go very wrong.
531 if (!property_exists($courserec, 'numsections') && course_get_format($courserec)->uses_sections()) {
532 $courserec->numsections = course_get_format($courserec)->get_last_section_number();
535 $course->set_source_array(array($courserec));
537 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
539 $category->set_source_array(array($categoryrec));
541 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
542 FROM {tag} t
543 JOIN {tag_instance} ti ON ti.tagid = t.id
544 WHERE ti.itemtype = ?
545 AND ti.itemid = ?', array(
546 backup_helper::is_sqlparam('course'),
547 backup::VAR_PARENTID));
549 $courseformatoption->set_source_sql('SELECT id, format, sectionid, name, value
550 FROM {course_format_options}
551 WHERE courseid = ?', [ backup::VAR_PARENTID ]);
553 $handler = core_course\customfield\course_handler::create();
554 $fieldsforbackup = $handler->get_instance_data_for_backup($this->task->get_courseid());
555 $customfield->set_source_array($fieldsforbackup);
557 // Some annotations
559 $course->annotate_ids('grouping', 'defaultgroupingid');
561 $course->annotate_files('course', 'summary', null);
562 $course->annotate_files('course', 'overviewfiles', null);
564 if ($this->get_setting_value('legacyfiles')) {
565 $course->annotate_files('course', 'legacy', null);
568 // Return root element ($course)
570 return $course;
575 * structure step that will generate the enrolments.xml file for the given course
577 class backup_enrolments_structure_step extends backup_structure_step {
580 * Skip enrolments on the front page.
581 * @return bool
583 protected function execute_condition() {
584 return ($this->get_courseid() != SITEID);
587 protected function define_structure() {
588 global $DB;
590 // To know if we are including users
591 $users = $this->get_setting_value('users');
592 $keptroles = $this->task->get_kept_roles();
594 // Define each element separated
596 $enrolments = new backup_nested_element('enrolments');
598 $enrols = new backup_nested_element('enrols');
600 $enrol = new backup_nested_element('enrol', array('id'), array(
601 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
602 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
603 'password', 'cost', 'currency', 'roleid',
604 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
605 'customchar1', 'customchar2', 'customchar3',
606 'customdec1', 'customdec2',
607 'customtext1', 'customtext2', 'customtext3', 'customtext4',
608 'timecreated', 'timemodified'));
610 $userenrolments = new backup_nested_element('user_enrolments');
612 $enrolment = new backup_nested_element('enrolment', array('id'), array(
613 'status', 'userid', 'timestart', 'timeend', 'modifierid',
614 'timemodified'));
616 // Build the tree
617 $enrolments->add_child($enrols);
618 $enrols->add_child($enrol);
619 $enrol->add_child($userenrolments);
620 $userenrolments->add_child($enrolment);
622 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
623 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
625 // User enrolments only added only if users included.
626 if (empty($keptroles) && $users) {
627 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
628 $enrolment->annotate_ids('user', 'userid');
629 } else if (!empty($keptroles)) {
630 list($insql, $inparams) = $DB->get_in_or_equal($keptroles);
631 $params = array(
632 backup::VAR_CONTEXTID,
633 backup::VAR_PARENTID
635 foreach ($inparams as $inparam) {
636 $params[] = backup_helper::is_sqlparam($inparam);
638 $enrolment->set_source_sql(
639 "SELECT ue.*
640 FROM {user_enrolments} ue
641 INNER JOIN {role_assignments} ra ON ue.userid = ra.userid
642 WHERE ra.contextid = ?
643 AND ue.enrolid = ?
644 AND ra.roleid $insql",
645 $params);
646 $enrolment->annotate_ids('user', 'userid');
649 $enrol->annotate_ids('role', 'roleid');
651 // Add enrol plugin structure.
652 $this->add_plugin_structure('enrol', $enrol, true);
654 return $enrolments;
659 * structure step that will generate the roles.xml file for the given context, observing
660 * the role_assignments setting to know if that part needs to be included
662 class backup_roles_structure_step extends backup_structure_step {
664 protected function define_structure() {
666 // To know if we are including role assignments
667 $roleassignments = $this->get_setting_value('role_assignments');
669 // Define each element separated
671 $roles = new backup_nested_element('roles');
673 $overrides = new backup_nested_element('role_overrides');
675 $override = new backup_nested_element('override', array('id'), array(
676 'roleid', 'capability', 'permission', 'timemodified',
677 'modifierid'));
679 $assignments = new backup_nested_element('role_assignments');
681 $assignment = new backup_nested_element('assignment', array('id'), array(
682 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
683 'sortorder'));
685 // Build the tree
686 $roles->add_child($overrides);
687 $roles->add_child($assignments);
689 $overrides->add_child($override);
690 $assignments->add_child($assignment);
692 // Define sources
694 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
696 // Assignments only added if specified
697 if ($roleassignments) {
698 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
701 // Define id annotations
702 $override->annotate_ids('role', 'roleid');
704 $assignment->annotate_ids('role', 'roleid');
706 $assignment->annotate_ids('user', 'userid');
708 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
710 return $roles;
715 * structure step that will generate the roles.xml containing the
716 * list of roles used along the whole backup process. Just raw
717 * list of used roles from role table
719 class backup_final_roles_structure_step extends backup_structure_step {
721 protected function define_structure() {
723 // Define elements
725 $rolesdef = new backup_nested_element('roles_definition');
727 $role = new backup_nested_element('role', array('id'), array(
728 'name', 'shortname', 'nameincourse', 'description',
729 'sortorder', 'archetype'));
731 // Build the tree
733 $rolesdef->add_child($role);
735 // Define sources
737 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
738 FROM {role} r
739 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
740 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
741 WHERE bi.backupid = ?
742 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
744 // Return main element (rolesdef)
745 return $rolesdef;
750 * structure step that will generate the scales.xml containing the
751 * list of scales used along the whole backup process.
753 class backup_final_scales_structure_step extends backup_structure_step {
755 protected function define_structure() {
757 // Define elements
759 $scalesdef = new backup_nested_element('scales_definition');
761 $scale = new backup_nested_element('scale', array('id'), array(
762 'courseid', 'userid', 'name', 'scale',
763 'description', 'descriptionformat', 'timemodified'));
765 // Build the tree
767 $scalesdef->add_child($scale);
769 // Define sources
771 $scale->set_source_sql("SELECT s.*
772 FROM {scale} s
773 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
774 WHERE bi.backupid = ?
775 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
777 // Annotate scale files (they store files in system context, so pass it instead of default one)
778 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
780 // Return main element (scalesdef)
781 return $scalesdef;
786 * structure step that will generate the outcomes.xml containing the
787 * list of outcomes used along the whole backup process.
789 class backup_final_outcomes_structure_step extends backup_structure_step {
791 protected function define_structure() {
793 // Define elements
795 $outcomesdef = new backup_nested_element('outcomes_definition');
797 $outcome = new backup_nested_element('outcome', array('id'), array(
798 'courseid', 'userid', 'shortname', 'fullname',
799 'scaleid', 'description', 'descriptionformat', 'timecreated',
800 'timemodified','usermodified'));
802 // Build the tree
804 $outcomesdef->add_child($outcome);
806 // Define sources
808 $outcome->set_source_sql("SELECT o.*
809 FROM {grade_outcomes} o
810 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
811 WHERE bi.backupid = ?
812 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
814 // Annotate outcome files (they store files in system context, so pass it instead of default one)
815 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
817 // Return main element (outcomesdef)
818 return $outcomesdef;
823 * structure step in charge of constructing the filters.xml file for all the filters found
824 * in activity
826 class backup_filters_structure_step extends backup_structure_step {
828 protected function define_structure() {
830 // Define each element separated
832 $filters = new backup_nested_element('filters');
834 $actives = new backup_nested_element('filter_actives');
836 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
838 $configs = new backup_nested_element('filter_configs');
840 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
842 // Build the tree
844 $filters->add_child($actives);
845 $filters->add_child($configs);
847 $actives->add_child($active);
848 $configs->add_child($config);
850 // Define sources
852 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
854 $active->set_source_array($activearr);
855 $config->set_source_array($configarr);
857 // Return the root element (filters)
858 return $filters;
863 * Structure step in charge of constructing the comments.xml file for all the comments found in a given context.
865 class backup_comments_structure_step extends backup_structure_step {
867 protected function define_structure() {
868 // Define each element separated.
869 $comments = new backup_nested_element('comments');
871 $comment = new backup_nested_element('comment', array('id'), array(
872 'component', 'commentarea', 'itemid', 'content', 'format',
873 'userid', 'timecreated'));
875 // Build the tree.
876 $comments->add_child($comment);
878 // Define sources.
879 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
881 // Define id annotations.
882 $comment->annotate_ids('user', 'userid');
884 // Return the root element (comments).
885 return $comments;
890 * structure step in charge of constructing the badges.xml file for all the badges found
891 * in a given context
893 class backup_badges_structure_step extends backup_structure_step {
895 protected function execute_condition() {
896 // Check that all activities have been included.
897 if ($this->task->is_excluding_activities()) {
898 return false;
900 return true;
903 protected function define_structure() {
904 global $CFG;
906 require_once($CFG->libdir . '/badgeslib.php');
907 // Define each element separated.
909 $badges = new backup_nested_element('badges');
910 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
911 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
912 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
913 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron',
914 'version', 'language', 'imageauthorname', 'imageauthoremail', 'imageauthorurl',
915 'imagecaption'));
917 $criteria = new backup_nested_element('criteria');
918 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
919 'criteriatype', 'method', 'description', 'descriptionformat'));
921 $endorsement = new backup_nested_element('endorsement', array('id'), array('badgeid',
922 'issuername', 'issuerurl', 'issueremail', 'claimid', 'claimcomment', 'dateissued'));
924 $alignments = new backup_nested_element('alignments');
925 $alignment = new backup_nested_element('alignment', array('id'), array('badgeid',
926 'targetname', 'targeturl', 'targetdescription', 'targetframework', 'targetcode'));
928 $relatedbadges = new backup_nested_element('relatedbadges');
929 $relatedbadge = new backup_nested_element('relatedbadge', array('id'), array('badgeid',
930 'relatedbadgeid'));
932 $parameters = new backup_nested_element('parameters');
933 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
934 'name', 'value', 'criteriatype'));
936 $manual_awards = new backup_nested_element('manual_awards');
937 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
938 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
940 // Build the tree.
942 $badges->add_child($badge);
943 $badge->add_child($criteria);
944 $criteria->add_child($criterion);
945 $criterion->add_child($parameters);
946 $parameters->add_child($parameter);
947 $badge->add_child($endorsement);
948 $badge->add_child($alignments);
949 $alignments->add_child($alignment);
950 $badge->add_child($relatedbadges);
951 $relatedbadges->add_child($relatedbadge);
952 $badge->add_child($manual_awards);
953 $manual_awards->add_child($manual_award);
955 // Define sources.
957 $parametersql = '
958 SELECT *
959 FROM {badge}
960 WHERE courseid = :courseid
961 AND status != ' . BADGE_STATUS_ARCHIVED;
962 $parameterparams = [
963 'courseid' => backup::VAR_COURSEID
965 $badge->set_source_sql($parametersql, $parameterparams);
966 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
967 $endorsement->set_source_table('badge_endorsement', array('badgeid' => backup::VAR_PARENTID));
969 $alignment->set_source_table('badge_alignment', array('badgeid' => backup::VAR_PARENTID));
970 $relatedbadge->set_source_table('badge_related', array('badgeid' => backup::VAR_PARENTID));
972 $parametersql = 'SELECT cp.*, c.criteriatype
973 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
974 ON cp.critid = c.id
975 WHERE critid = :critid';
976 $parameterparams = array('critid' => backup::VAR_PARENTID);
977 $parameter->set_source_sql($parametersql, $parameterparams);
979 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
981 // Define id annotations.
983 $badge->annotate_ids('user', 'usercreated');
984 $badge->annotate_ids('user', 'usermodified');
985 $criterion->annotate_ids('badge', 'badgeid');
986 $parameter->annotate_ids('criterion', 'critid');
987 $endorsement->annotate_ids('badge', 'badgeid');
988 $alignment->annotate_ids('badge', 'badgeid');
989 $relatedbadge->annotate_ids('badge', 'badgeid');
990 $relatedbadge->annotate_ids('badge', 'relatedbadgeid');
991 $badge->annotate_files('badges', 'badgeimage', 'id');
992 $manual_award->annotate_ids('badge', 'badgeid');
993 $manual_award->annotate_ids('user', 'recipientid');
994 $manual_award->annotate_ids('user', 'issuerid');
995 $manual_award->annotate_ids('role', 'issuerrole');
997 // Return the root element ($badges).
998 return $badges;
1003 * structure step in charge of constructing the calender.xml file for all the events found
1004 * in a given context
1006 class backup_calendarevents_structure_step extends backup_structure_step {
1008 protected function define_structure() {
1010 // Define each element separated
1012 $events = new backup_nested_element('events');
1014 $event = new backup_nested_element('event', array('id'), array(
1015 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
1016 'repeatid', 'modulename', 'instance', 'type', 'eventtype', 'timestart',
1017 'timeduration', 'timesort', 'visible', 'uuid', 'sequence', 'timemodified',
1018 'priority', 'location'));
1020 // Build the tree
1021 $events->add_child($event);
1023 // Define sources
1024 if ($this->name == 'course_calendar') {
1025 $calendar_items_sql ="SELECT * FROM {event}
1026 WHERE courseid = :courseid
1027 AND (eventtype = 'course' OR eventtype = 'group')";
1028 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
1029 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
1030 } else if ($this->name == 'activity_calendar') {
1031 // We don't backup action events.
1032 $params = array('instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME,
1033 'type' => array('sqlparam' => CALENDAR_EVENT_TYPE_ACTION));
1034 // If we don't want to include the userinfo in the backup then setting the courseid
1035 // will filter out all of the user override events (which have a course id of zero).
1036 $coursewhere = "";
1037 if (!$this->get_setting_value('userinfo')) {
1038 $params['courseid'] = backup::VAR_COURSEID;
1039 $coursewhere = " AND courseid = :courseid";
1041 $calendarsql = "SELECT * FROM {event}
1042 WHERE instance = :instance
1043 AND type <> :type
1044 AND modulename = :modulename";
1045 $calendarsql = $calendarsql . $coursewhere;
1046 $event->set_source_sql($calendarsql, $params);
1047 } else {
1048 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
1051 // Define id annotations
1053 $event->annotate_ids('user', 'userid');
1054 $event->annotate_ids('group', 'groupid');
1055 $event->annotate_files('calendar', 'event_description', 'id');
1057 // Return the root element (events)
1058 return $events;
1063 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
1064 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
1066 class backup_gradebook_structure_step extends backup_structure_step {
1069 * We need to decide conditionally, based on dynamic information
1070 * about the execution of this step. Only will be executed if all
1071 * the module gradeitems have been already included in backup
1073 protected function execute_condition() {
1074 $courseid = $this->get_courseid();
1075 if ($courseid == SITEID) {
1076 return false;
1079 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
1082 protected function define_structure() {
1083 global $CFG, $DB;
1085 // are we including user info?
1086 $userinfo = $this->get_setting_value('users');
1088 $gradebook = new backup_nested_element('gradebook');
1090 //grade_letters are done in backup_activity_grades_structure_step()
1092 //calculated grade items
1093 $grade_items = new backup_nested_element('grade_items');
1094 $grade_item = new backup_nested_element('grade_item', array('id'), array(
1095 'categoryid', 'itemname', 'itemtype', 'itemmodule',
1096 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
1097 'calculation', 'gradetype', 'grademax', 'grademin',
1098 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
1099 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
1100 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
1101 'needsupdate', 'timecreated', 'timemodified'));
1103 $this->add_plugin_structure('local', $grade_item, true);
1105 $grade_grades = new backup_nested_element('grade_grades');
1106 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
1107 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
1108 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
1109 'locked', 'locktime', 'exported', 'overridden',
1110 'excluded', 'feedback', 'feedbackformat', 'information',
1111 'informationformat', 'timecreated', 'timemodified',
1112 'aggregationstatus', 'aggregationweight'));
1114 //grade_categories
1115 $grade_categories = new backup_nested_element('grade_categories');
1116 $grade_category = new backup_nested_element('grade_category', array('id'), array(
1117 //'courseid',
1118 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
1119 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
1120 'timecreated', 'timemodified', 'hidden'));
1122 $letters = new backup_nested_element('grade_letters');
1123 $letter = new backup_nested_element('grade_letter', 'id', array(
1124 'lowerboundary', 'letter'));
1126 $grade_settings = new backup_nested_element('grade_settings');
1127 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
1128 'name', 'value'));
1130 $gradebook_attributes = new backup_nested_element('attributes', null, array('calculations_freeze'));
1132 // Build the tree
1133 $gradebook->add_child($gradebook_attributes);
1135 $gradebook->add_child($grade_categories);
1136 $grade_categories->add_child($grade_category);
1138 $gradebook->add_child($grade_items);
1139 $grade_items->add_child($grade_item);
1140 $grade_item->add_child($grade_grades);
1141 $grade_grades->add_child($grade_grade);
1143 $gradebook->add_child($letters);
1144 $letters->add_child($letter);
1146 $gradebook->add_child($grade_settings);
1147 $grade_settings->add_child($grade_setting);
1149 // Define sources
1151 // Add attribute with gradebook calculation freeze date if needed.
1152 $attributes = new stdClass();
1153 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
1154 if ($gradebookcalculationfreeze) {
1155 $attributes->calculations_freeze = $gradebookcalculationfreeze;
1157 $gradebook_attributes->set_source_array([$attributes]);
1159 //Include manual, category and the course grade item
1160 $grade_items_sql ="SELECT * FROM {grade_items}
1161 WHERE courseid = :courseid
1162 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1163 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
1164 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1166 if ($userinfo) {
1167 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1170 $grade_category_sql = "SELECT gc.*, gi.sortorder
1171 FROM {grade_categories} gc
1172 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1173 WHERE gc.courseid = :courseid
1174 AND (gi.itemtype='course' OR gi.itemtype='category')
1175 ORDER BY gc.parent ASC";//need parent categories before their children
1176 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1177 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1179 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1181 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1182 $settings = array();
1183 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1184 foreach ($rs as $record) {
1185 $settings[$record->name] = $record;
1187 $rs->close();
1188 if (!isset($settings['minmaxtouse'])) {
1189 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse);
1191 $grade_setting->set_source_array($settings);
1194 // Annotations (both as final as far as they are going to be exported in next steps)
1195 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1196 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1198 //just in case there are any users not already annotated by the activities
1199 $grade_grade->annotate_ids('userfinal', 'userid');
1201 // Return the root element
1202 return $gradebook;
1207 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1209 class backup_grade_history_structure_step extends backup_structure_step {
1212 * Limit the execution.
1214 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1215 * because we do not want to save the history of items which are not backed up. At least for now.
1217 protected function execute_condition() {
1218 $courseid = $this->get_courseid();
1219 if ($courseid == SITEID) {
1220 return false;
1223 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
1226 protected function define_structure() {
1228 // Settings to use.
1229 $userinfo = $this->get_setting_value('users');
1230 $history = $this->get_setting_value('grade_histories');
1232 // Create the nested elements.
1233 $bookhistory = new backup_nested_element('grade_history');
1234 $grades = new backup_nested_element('grade_grades');
1235 $grade = new backup_nested_element('grade_grade', array('id'), array(
1236 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1237 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1238 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1239 'excluded', 'feedback', 'feedbackformat', 'information',
1240 'informationformat', 'timemodified'));
1242 // Build the tree.
1243 $bookhistory->add_child($grades);
1244 $grades->add_child($grade);
1246 // This only happens if we are including user info and history.
1247 if ($userinfo && $history) {
1248 // Only keep the history of grades related to items which have been backed up, The query is
1249 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1250 $gradesql = "SELECT ggh.*
1251 FROM {grade_grades_history} ggh
1252 JOIN {grade_items} gi ON ggh.itemid = gi.id
1253 WHERE gi.courseid = :courseid
1254 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1255 $grade->set_source_sql($gradesql, array('courseid' => backup::VAR_COURSEID));
1258 // Annotations. (Final annotations as this step is part of the final task).
1259 $grade->annotate_ids('scalefinal', 'rawscaleid');
1260 $grade->annotate_ids('userfinal', 'loggeduser');
1261 $grade->annotate_ids('userfinal', 'userid');
1262 $grade->annotate_ids('userfinal', 'usermodified');
1264 // Return the root element.
1265 return $bookhistory;
1271 * structure step in charge if constructing the completion.xml file for all the users completion
1272 * information in a given activity
1274 class backup_userscompletion_structure_step extends backup_structure_step {
1277 * Skip completion on the front page.
1278 * @return bool
1280 protected function execute_condition() {
1281 return ($this->get_courseid() != SITEID);
1284 protected function define_structure() {
1286 // Define each element separated
1288 $completions = new backup_nested_element('completions');
1290 $completion = new backup_nested_element('completion', array('id'), array(
1291 'userid', 'completionstate', 'viewed', 'timemodified'));
1293 // Build the tree
1295 $completions->add_child($completion);
1297 // Define sources
1299 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1301 // Define id annotations
1303 $completion->annotate_ids('user', 'userid');
1305 // Return the root element (completions)
1306 return $completions;
1311 * structure step in charge of constructing the main groups.xml file for all the groups and
1312 * groupings information already annotated
1314 class backup_groups_structure_step extends backup_structure_step {
1316 protected function define_structure() {
1318 // To know if we are including users.
1319 $userinfo = $this->get_setting_value('users');
1320 // To know if we are including groups and groupings.
1321 $groupinfo = $this->get_setting_value('groups');
1323 // Define each element separated
1325 $groups = new backup_nested_element('groups');
1327 $group = new backup_nested_element('group', array('id'), array(
1328 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1329 'picture', 'timecreated', 'timemodified'));
1331 $members = new backup_nested_element('group_members');
1333 $member = new backup_nested_element('group_member', array('id'), array(
1334 'userid', 'timeadded', 'component', 'itemid'));
1336 $groupings = new backup_nested_element('groupings');
1338 $grouping = new backup_nested_element('grouping', 'id', array(
1339 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1340 'timecreated', 'timemodified'));
1342 $groupinggroups = new backup_nested_element('grouping_groups');
1344 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1345 'groupid', 'timeadded'));
1347 // Build the tree
1349 $groups->add_child($group);
1350 $groups->add_child($groupings);
1352 $group->add_child($members);
1353 $members->add_child($member);
1355 $groupings->add_child($grouping);
1356 $grouping->add_child($groupinggroups);
1357 $groupinggroups->add_child($groupinggroup);
1359 // Define sources
1361 // This only happens if we are including groups/groupings.
1362 if ($groupinfo) {
1363 $group->set_source_sql("
1364 SELECT g.*
1365 FROM {groups} g
1366 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1367 WHERE bi.backupid = ?
1368 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1370 $grouping->set_source_sql("
1371 SELECT g.*
1372 FROM {groupings} g
1373 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1374 WHERE bi.backupid = ?
1375 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1376 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1378 // This only happens if we are including users.
1379 if ($userinfo) {
1380 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1384 // Define id annotations (as final)
1386 $member->annotate_ids('userfinal', 'userid');
1388 // Define file annotations
1390 $group->annotate_files('group', 'description', 'id');
1391 $group->annotate_files('group', 'icon', 'id');
1392 $grouping->annotate_files('grouping', 'description', 'id');
1394 // Return the root element (groups)
1395 return $groups;
1400 * structure step in charge of constructing the main users.xml file for all the users already
1401 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1402 * overrides.
1404 class backup_users_structure_step extends backup_structure_step {
1406 protected function define_structure() {
1407 global $CFG;
1409 // To know if we are anonymizing users
1410 $anonymize = $this->get_setting_value('anonymize');
1411 // To know if we are including role assignments
1412 $roleassignments = $this->get_setting_value('role_assignments');
1414 // Define each element separate.
1416 $users = new backup_nested_element('users');
1418 // Create the array of user fields by hand, as far as we have various bits to control
1419 // anonymize option, password backup, mnethostid...
1421 // First, the fields not needing anonymization nor special handling
1422 $normalfields = array(
1423 'confirmed', 'policyagreed', 'deleted',
1424 'lang', 'theme', 'timezone', 'firstaccess',
1425 'lastaccess', 'lastlogin', 'currentlogin',
1426 'mailformat', 'maildigest', 'maildisplay',
1427 'autosubscribe', 'trackforums', 'timecreated',
1428 'timemodified', 'trustbitmask');
1430 // Then, the fields potentially needing anonymization
1431 $anonfields = array(
1432 'username', 'idnumber', 'email', 'phone1',
1433 'phone2', 'institution', 'department', 'address',
1434 'city', 'country', 'lastip', 'picture',
1435 'description', 'descriptionformat', 'imagealt', 'auth');
1436 $anonfields = array_merge($anonfields, \core_user\fields::get_name_fields());
1438 // Add anonymized fields to $userfields with custom final element
1439 foreach ($anonfields as $field) {
1440 if ($anonymize) {
1441 $userfields[] = new anonymizer_final_element($field);
1442 } else {
1443 $userfields[] = $field; // No anonymization, normally added
1447 // mnethosturl requires special handling (custom final element)
1448 $userfields[] = new mnethosturl_final_element('mnethosturl');
1450 // password added conditionally
1451 if (!empty($CFG->includeuserpasswordsinbackup)) {
1452 $userfields[] = 'password';
1455 // Merge all the fields
1456 $userfields = array_merge($userfields, $normalfields);
1458 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1460 $customfields = new backup_nested_element('custom_fields');
1462 $customfield = new backup_nested_element('custom_field', array('id'), array(
1463 'field_name', 'field_type', 'field_data'));
1465 $tags = new backup_nested_element('tags');
1467 $tag = new backup_nested_element('tag', array('id'), array(
1468 'name', 'rawname'));
1470 $preferences = new backup_nested_element('preferences');
1472 $preference = new backup_nested_element('preference', array('id'), array(
1473 'name', 'value'));
1475 $roles = new backup_nested_element('roles');
1477 $overrides = new backup_nested_element('role_overrides');
1479 $override = new backup_nested_element('override', array('id'), array(
1480 'roleid', 'capability', 'permission', 'timemodified',
1481 'modifierid'));
1483 $assignments = new backup_nested_element('role_assignments');
1485 $assignment = new backup_nested_element('assignment', array('id'), array(
1486 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1487 'sortorder'));
1489 // Build the tree
1491 $users->add_child($user);
1493 $user->add_child($customfields);
1494 $customfields->add_child($customfield);
1496 $user->add_child($tags);
1497 $tags->add_child($tag);
1499 $user->add_child($preferences);
1500 $preferences->add_child($preference);
1502 $user->add_child($roles);
1504 $roles->add_child($overrides);
1505 $roles->add_child($assignments);
1507 $overrides->add_child($override);
1508 $assignments->add_child($assignment);
1510 // Define sources
1512 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1513 FROM {user} u
1514 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1515 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1516 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1517 WHERE bi.backupid = ?
1518 AND bi.itemname = ?', array(
1519 backup_helper::is_sqlparam($this->get_backupid()),
1520 backup_helper::is_sqlparam('userfinal')));
1522 // All the rest on information is only added if we arent
1523 // in an anonymized backup
1524 if (!$anonymize) {
1525 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1526 FROM {user_info_field} f
1527 JOIN {user_info_data} d ON d.fieldid = f.id
1528 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1530 $customfield->set_source_alias('shortname', 'field_name');
1531 $customfield->set_source_alias('datatype', 'field_type');
1532 $customfield->set_source_alias('data', 'field_data');
1534 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1535 FROM {tag} t
1536 JOIN {tag_instance} ti ON ti.tagid = t.id
1537 WHERE ti.itemtype = ?
1538 AND ti.itemid = ?', array(
1539 backup_helper::is_sqlparam('user'),
1540 backup::VAR_PARENTID));
1542 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1544 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1546 // Assignments only added if specified
1547 if ($roleassignments) {
1548 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1551 // Define id annotations (as final)
1552 $override->annotate_ids('rolefinal', 'roleid');
1554 // Return root element (users)
1555 return $users;
1560 * structure step in charge of constructing the block.xml file for one
1561 * given block (instance and positions). If the block has custom DB structure
1562 * that will go to a separate file (different step defined in block class)
1564 class backup_block_instance_structure_step extends backup_structure_step {
1566 protected function define_structure() {
1567 global $DB;
1569 // Define each element separated
1571 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1572 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1573 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata',
1574 'timecreated', 'timemodified'));
1576 $positions = new backup_nested_element('block_positions');
1578 $position = new backup_nested_element('block_position', array('id'), array(
1579 'contextid', 'pagetype', 'subpage', 'visible',
1580 'region', 'weight'));
1582 // Build the tree
1584 $block->add_child($positions);
1585 $positions->add_child($position);
1587 // Transform configdata information if needed (process links and friends)
1588 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1589 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1590 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1591 foreach ($configdata as $attribute => $value) {
1592 if (in_array($attribute, $attrstotransform)) {
1593 $configdata[$attribute] = $this->contenttransformer->process($value);
1596 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1598 $blockrec->contextid = $this->task->get_contextid();
1599 // Get the version of the block
1600 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1602 // Define sources
1604 $block->set_source_array(array($blockrec));
1606 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1608 // File anotations (for fileareas specified on each block)
1609 foreach ($this->task->get_fileareas() as $filearea) {
1610 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1613 // Return the root element (block)
1614 return $block;
1619 * structure step in charge of constructing the logs.xml file for all the log records found
1620 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1621 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1622 * that just in case they become restored some day in the future
1624 class backup_course_logs_structure_step extends backup_structure_step {
1626 protected function define_structure() {
1628 // Define each element separated
1630 $logs = new backup_nested_element('logs');
1632 $log = new backup_nested_element('log', array('id'), array(
1633 'time', 'userid', 'ip', 'module',
1634 'action', 'url', 'info'));
1636 // Build the tree
1638 $logs->add_child($log);
1640 // Define sources (all the records belonging to the course, having cmid = 0)
1642 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1644 // Annotations
1645 // NOTE: We don't annotate users from logs as far as they MUST be
1646 // always annotated by the course (enrol, ras... whatever)
1648 // Return the root element (logs)
1650 return $logs;
1655 * structure step in charge of constructing the logs.xml file for all the log records found
1656 * in activity
1658 class backup_activity_logs_structure_step extends backup_structure_step {
1660 protected function define_structure() {
1662 // Define each element separated
1664 $logs = new backup_nested_element('logs');
1666 $log = new backup_nested_element('log', array('id'), array(
1667 'time', 'userid', 'ip', 'module',
1668 'action', 'url', 'info'));
1670 // Build the tree
1672 $logs->add_child($log);
1674 // Define sources
1676 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1678 // Annotations
1679 // NOTE: We don't annotate users from logs as far as they MUST be
1680 // always annotated by the activity (true participants).
1682 // Return the root element (logs)
1684 return $logs;
1689 * Structure step in charge of constructing the logstores.xml file for the course logs.
1691 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1692 * it, for logs belonging to the course level.
1694 class backup_course_logstores_structure_step extends backup_structure_step {
1696 protected function define_structure() {
1698 // Define the structure of logstores container.
1699 $logstores = new backup_nested_element('logstores');
1700 $logstore = new backup_nested_element('logstore');
1701 $logstores->add_child($logstore);
1703 // Add the tool_log logstore subplugins information to the logstore element.
1704 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1706 return $logstores;
1711 * Structure step in charge of constructing the loglastaccess.xml file for the course logs.
1713 * This backup step will backup the logs of the user_lastaccess table.
1715 class backup_course_loglastaccess_structure_step extends backup_structure_step {
1718 * This function creates the structures for the loglastaccess.xml file.
1719 * Expected structure would look like this.
1720 * <loglastaccesses>
1721 * <loglastaccess id=2>
1722 * <userid>5</userid>
1723 * <timeaccess>1616887341</timeaccess>
1724 * </loglastaccess>
1725 * </loglastaccesses>
1727 * @return backup_nested_element
1729 protected function define_structure() {
1731 // To know if we are including userinfo.
1732 $userinfo = $this->get_setting_value('users');
1734 // Define the structure of logstores container.
1735 $lastaccesses = new backup_nested_element('lastaccesses');
1736 $lastaccess = new backup_nested_element('lastaccess', array('id'), array('userid', 'timeaccess'));
1738 // Define build tree.
1739 $lastaccesses->add_child($lastaccess);
1741 // This element should only happen if we are including user info.
1742 if ($userinfo) {
1743 // Define sources.
1744 $lastaccess->set_source_sql('
1745 SELECT id, userid, timeaccess
1746 FROM {user_lastaccess}
1747 WHERE courseid = ?',
1748 array(backup::VAR_COURSEID));
1750 // Define userid annotation to user.
1751 $lastaccess->annotate_ids('user', 'userid');
1754 // Return the root element (lastaccessess).
1755 return $lastaccesses;
1760 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1762 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1764 class backup_activity_logstores_structure_step extends backup_course_logstores_structure_step {
1768 * Course competencies backup structure step.
1770 class backup_course_competencies_structure_step extends backup_structure_step {
1772 protected function define_structure() {
1773 $userinfo = $this->get_setting_value('users');
1775 $wrapper = new backup_nested_element('course_competencies');
1777 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1778 $wrapper->add_child($settings);
1780 $sql = 'SELECT s.pushratingstouserplans
1781 FROM {' . \core_competency\course_competency_settings::TABLE . '} s
1782 WHERE s.courseid = :courseid';
1783 $settings->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1785 $competencies = new backup_nested_element('competencies');
1786 $wrapper->add_child($competencies);
1788 $competency = new backup_nested_element('competency', null, array('id', 'idnumber', 'ruleoutcome',
1789 'sortorder', 'frameworkid', 'frameworkidnumber'));
1790 $competencies->add_child($competency);
1792 $sql = 'SELECT c.id, c.idnumber, cc.ruleoutcome, cc.sortorder, f.id AS frameworkid, f.idnumber AS frameworkidnumber
1793 FROM {' . \core_competency\course_competency::TABLE . '} cc
1794 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cc.competencyid
1795 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1796 WHERE cc.courseid = :courseid
1797 ORDER BY cc.sortorder';
1798 $competency->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1800 $usercomps = new backup_nested_element('user_competencies');
1801 $wrapper->add_child($usercomps);
1802 if ($userinfo) {
1803 $usercomp = new backup_nested_element('user_competency', null, array('userid', 'competencyid',
1804 'proficiency', 'grade'));
1805 $usercomps->add_child($usercomp);
1807 $sql = 'SELECT ucc.userid, ucc.competencyid, ucc.proficiency, ucc.grade
1808 FROM {' . \core_competency\user_competency_course::TABLE . '} ucc
1809 WHERE ucc.courseid = :courseid
1810 AND ucc.grade IS NOT NULL';
1811 $usercomp->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1812 $usercomp->annotate_ids('user', 'userid');
1815 return $wrapper;
1819 * Execute conditions.
1821 * @return bool
1823 protected function execute_condition() {
1825 // Do not execute if competencies are not included.
1826 if (!$this->get_setting_value('competencies')) {
1827 return false;
1830 return true;
1835 * Activity competencies backup structure step.
1837 class backup_activity_competencies_structure_step extends backup_structure_step {
1839 protected function define_structure() {
1840 $wrapper = new backup_nested_element('course_module_competencies');
1842 $competencies = new backup_nested_element('competencies');
1843 $wrapper->add_child($competencies);
1845 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1846 'sortorder', 'frameworkidnumber'));
1847 $competencies->add_child($competency);
1849 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.sortorder, f.idnumber AS frameworkidnumber
1850 FROM {' . \core_competency\course_module_competency::TABLE . '} cmc
1851 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cmc.competencyid
1852 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1853 WHERE cmc.cmid = :coursemoduleid
1854 ORDER BY cmc.sortorder';
1855 $competency->set_source_sql($sql, array('coursemoduleid' => backup::VAR_MODID));
1857 return $wrapper;
1861 * Execute conditions.
1863 * @return bool
1865 protected function execute_condition() {
1867 // Do not execute if competencies are not included.
1868 if (!$this->get_setting_value('competencies')) {
1869 return false;
1872 return true;
1877 * structure in charge of constructing the inforef.xml file for all the items we want
1878 * to have referenced there (users, roles, files...)
1880 class backup_inforef_structure_step extends backup_structure_step {
1882 protected function define_structure() {
1884 // Items we want to include in the inforef file.
1885 $items = backup_helper::get_inforef_itemnames();
1887 // Build the tree
1889 $inforef = new backup_nested_element('inforef');
1891 // For each item, conditionally, if there are already records, build element
1892 foreach ($items as $itemname) {
1893 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1894 $elementroot = new backup_nested_element($itemname . 'ref');
1895 $element = new backup_nested_element($itemname, array(), array('id'));
1896 $inforef->add_child($elementroot);
1897 $elementroot->add_child($element);
1898 $element->set_source_sql("
1899 SELECT itemid AS id
1900 FROM {backup_ids_temp}
1901 WHERE backupid = ?
1902 AND itemname = ?",
1903 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1907 // We don't annotate anything there, but rely in the next step
1908 // (move_inforef_annotations_to_final) that will change all the
1909 // already saved 'inforref' entries to their 'final' annotations.
1910 return $inforef;
1915 * This step will get all the annotations already processed to inforef.xml file and
1916 * transform them into 'final' annotations.
1918 class move_inforef_annotations_to_final extends backup_execution_step {
1920 protected function define_execution() {
1922 // Items we want to include in the inforef file
1923 $items = backup_helper::get_inforef_itemnames();
1924 $progress = $this->task->get_progress();
1925 $progress->start_progress($this->get_name(), count($items));
1926 $done = 1;
1927 foreach ($items as $itemname) {
1928 // Delegate to dbops
1929 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1930 $itemname, $progress);
1931 $progress->progress($done++);
1933 $progress->end_progress();
1938 * structure in charge of constructing the files.xml file with all the
1939 * annotated (final) files along the process. At, the same time, and
1940 * using one specialised nested_element, will copy them form moodle storage
1941 * to backup storage
1943 class backup_final_files_structure_step extends backup_structure_step {
1945 protected function define_structure() {
1947 // Define elements
1949 $files = new backup_nested_element('files');
1951 $file = new file_nested_element('file', array('id'), array(
1952 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1953 'filepath', 'filename', 'userid', 'filesize',
1954 'mimetype', 'status', 'timecreated', 'timemodified',
1955 'source', 'author', 'license', 'sortorder',
1956 'repositorytype', 'repositoryid', 'reference'));
1958 // Build the tree
1960 $files->add_child($file);
1962 // Define sources
1964 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1965 FROM {files} f
1966 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1967 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1968 LEFT JOIN {repository} r ON r.id = ri.typeid
1969 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1970 WHERE bi.backupid = ?
1971 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1973 return $files;
1978 * Structure step in charge of creating the main moodle_backup.xml file
1979 * where all the information related to the backup, settings, license and
1980 * other information needed on restore is added*/
1981 class backup_main_structure_step extends backup_structure_step {
1983 protected function define_structure() {
1985 global $CFG;
1987 $info = array();
1989 $info['name'] = $this->get_setting_value('filename');
1990 $info['moodle_version'] = $CFG->version;
1991 $info['moodle_release'] = $CFG->release;
1992 $info['backup_version'] = $CFG->backup_version;
1993 $info['backup_release'] = $CFG->backup_release;
1994 $info['backup_date'] = time();
1995 $info['backup_uniqueid']= $this->get_backupid();
1996 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1997 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1998 $info['include_file_references_to_external_content'] =
1999 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
2000 $info['original_wwwroot']=$CFG->wwwroot;
2001 $info['original_site_identifier_hash'] = md5(get_site_identifier());
2002 $info['original_course_id'] = $this->get_courseid();
2003 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
2004 $info['original_course_format'] = $originalcourseinfo->format;
2005 $info['original_course_fullname'] = $originalcourseinfo->fullname;
2006 $info['original_course_shortname'] = $originalcourseinfo->shortname;
2007 $info['original_course_startdate'] = $originalcourseinfo->startdate;
2008 $info['original_course_enddate'] = $originalcourseinfo->enddate;
2009 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
2010 $info['original_system_contextid'] = context_system::instance()->id;
2012 // Get more information from controller
2013 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
2014 $this->get_backupid(), $this->get_task()->get_progress());
2016 // Define elements
2018 $moodle_backup = new backup_nested_element('moodle_backup');
2020 $information = new backup_nested_element('information', null, array(
2021 'name', 'moodle_version', 'moodle_release', 'backup_version',
2022 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
2023 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
2024 'original_course_fullname', 'original_course_shortname', 'original_course_startdate', 'original_course_enddate',
2025 'original_course_contextid', 'original_system_contextid'));
2027 $details = new backup_nested_element('details');
2029 $detail = new backup_nested_element('detail', array('backup_id'), array(
2030 'type', 'format', 'interactive', 'mode',
2031 'execution', 'executiontime'));
2033 $contents = new backup_nested_element('contents');
2035 $activities = new backup_nested_element('activities');
2037 $activity = new backup_nested_element('activity', null, array(
2038 'moduleid', 'sectionid', 'modulename', 'title',
2039 'directory'));
2041 $sections = new backup_nested_element('sections');
2043 $section = new backup_nested_element('section', null, array(
2044 'sectionid', 'title', 'directory'));
2046 $course = new backup_nested_element('course', null, array(
2047 'courseid', 'title', 'directory'));
2049 $settings = new backup_nested_element('settings');
2051 $setting = new backup_nested_element('setting', null, array(
2052 'level', 'section', 'activity', 'name', 'value'));
2054 // Build the tree
2056 $moodle_backup->add_child($information);
2058 $information->add_child($details);
2059 $details->add_child($detail);
2061 $information->add_child($contents);
2062 if (!empty($cinfo['activities'])) {
2063 $contents->add_child($activities);
2064 $activities->add_child($activity);
2066 if (!empty($cinfo['sections'])) {
2067 $contents->add_child($sections);
2068 $sections->add_child($section);
2070 if (!empty($cinfo['course'])) {
2071 $contents->add_child($course);
2074 $information->add_child($settings);
2075 $settings->add_child($setting);
2078 // Set the sources
2080 $information->set_source_array(array((object)$info));
2082 $detail->set_source_array($dinfo);
2084 $activity->set_source_array($cinfo['activities']);
2086 $section->set_source_array($cinfo['sections']);
2088 $course->set_source_array($cinfo['course']);
2090 $setting->set_source_array($sinfo);
2092 // Prepare some information to be sent to main moodle_backup.xml file
2093 return $moodle_backup;
2099 * Execution step that will generate the final zip (.mbz) file with all the contents
2101 class backup_zip_contents extends backup_execution_step implements file_progress {
2103 * @var bool True if we have started tracking progress
2105 protected $startedprogress;
2107 protected function define_execution() {
2109 // Get basepath
2110 $basepath = $this->get_basepath();
2112 // Get the list of files in directory
2113 $filestemp = get_directory_list($basepath, '', false, true, true);
2114 $files = array();
2115 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
2116 $files[$file] = $basepath . '/' . $file;
2119 // Add the log file if exists
2120 $logfilepath = $basepath . '.log';
2121 if (file_exists($logfilepath)) {
2122 $files['moodle_backup.log'] = $logfilepath;
2125 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2126 $zipfile = $basepath . '/backup.mbz';
2128 // Get the zip packer
2129 $zippacker = get_file_packer('application/vnd.moodle.backup');
2131 // Track overall progress for the 2 long-running steps (archive to
2132 // pathname, get backup information).
2133 $reporter = $this->task->get_progress();
2134 $reporter->start_progress('backup_zip_contents', 2);
2136 // Zip files
2137 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
2139 // If any sub-progress happened, end it.
2140 if ($this->startedprogress) {
2141 $this->task->get_progress()->end_progress();
2142 $this->startedprogress = false;
2143 } else {
2144 // No progress was reported, manually move it on to the next overall task.
2145 $reporter->progress(1);
2148 // Something went wrong.
2149 if ($result === false) {
2150 @unlink($zipfile);
2151 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
2153 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
2154 try {
2155 backup_general_helper::get_backup_information_from_mbz($zipfile, $this);
2156 } catch (backup_helper_exception $e) {
2157 @unlink($zipfile);
2158 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
2161 // If any sub-progress happened, end it.
2162 if ($this->startedprogress) {
2163 $this->task->get_progress()->end_progress();
2164 $this->startedprogress = false;
2165 } else {
2166 $reporter->progress(2);
2168 $reporter->end_progress();
2172 * Implementation for file_progress interface to display unzip progress.
2174 * @param int $progress Current progress
2175 * @param int $max Max value
2177 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
2178 $reporter = $this->task->get_progress();
2180 // Start tracking progress if necessary.
2181 if (!$this->startedprogress) {
2182 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
2183 ? \core\progress\base::INDETERMINATE : $max);
2184 $this->startedprogress = true;
2187 // Pass progress through to whatever handles it.
2188 $reporter->progress(($progress == file_progress::INDETERMINATE)
2189 ? \core\progress\base::INDETERMINATE : $progress);
2194 * This step will send the generated backup file to its final destination
2196 class backup_store_backup_file extends backup_execution_step {
2198 protected function define_execution() {
2200 // Get basepath
2201 $basepath = $this->get_basepath();
2203 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2204 $zipfile = $basepath . '/backup.mbz';
2206 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
2207 // Perform storage and return it (TODO: shouldn't be array but proper result object)
2208 return array(
2209 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
2210 $this->task->get_progress()),
2211 'include_file_references_to_external_content' => $has_file_references
2218 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
2219 * and put them to the backup_ids tables, to be used later as base to backup them
2221 class backup_activity_grade_items_to_ids extends backup_execution_step {
2223 protected function define_execution() {
2225 // Fetch all activity grade items
2226 if ($items = grade_item::fetch_all(array(
2227 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
2228 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
2229 // Annotate them in backup_ids
2230 foreach ($items as $item) {
2231 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
2239 * This step allows enrol plugins to annotate custom fields.
2241 * @package core_backup
2242 * @copyright 2014 University of Wisconsin
2243 * @author Matt Petro
2244 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2246 class backup_enrolments_execution_step extends backup_execution_step {
2249 * Function that will contain all the code to be executed.
2251 protected function define_execution() {
2252 global $DB;
2254 $plugins = enrol_get_plugins(true);
2255 $enrols = $DB->get_records('enrol', array(
2256 'courseid' => $this->task->get_courseid()));
2258 // Allow each enrol plugin to add annotations.
2259 foreach ($enrols as $enrol) {
2260 if (isset($plugins[$enrol->enrol])) {
2261 $plugins[$enrol->enrol]->backup_annotate_custom_fields($this, $enrol);
2267 * Annotate a single name/id pair.
2268 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
2270 * @param string $itemname
2271 * @param int $itemid
2273 public function annotate_id($itemname, $itemid) {
2274 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2279 * This step will annotate all the groups and groupings belonging to the course
2281 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
2283 protected function define_execution() {
2284 global $DB;
2286 // Get all the course groups
2287 if ($groups = $DB->get_records('groups', array(
2288 'courseid' => $this->task->get_courseid()))) {
2289 foreach ($groups as $group) {
2290 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
2294 // Get all the course groupings
2295 if ($groupings = $DB->get_records('groupings', array(
2296 'courseid' => $this->task->get_courseid()))) {
2297 foreach ($groupings as $grouping) {
2298 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
2305 * This step will annotate all the groups belonging to already annotated groupings
2307 class backup_annotate_groups_from_groupings extends backup_execution_step {
2309 protected function define_execution() {
2310 global $DB;
2312 // Fetch all the annotated groupings
2313 if ($groupings = $DB->get_records('backup_ids_temp', array(
2314 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2315 foreach ($groupings as $grouping) {
2316 if ($groups = $DB->get_records('groupings_groups', array(
2317 'groupingid' => $grouping->itemid))) {
2318 foreach ($groups as $group) {
2319 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
2328 * This step will annotate all the scales belonging to already annotated outcomes
2330 class backup_annotate_scales_from_outcomes extends backup_execution_step {
2332 protected function define_execution() {
2333 global $DB;
2335 // Fetch all the annotated outcomes
2336 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2337 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2338 foreach ($outcomes as $outcome) {
2339 if ($scale = $DB->get_record('grade_outcomes', array(
2340 'id' => $outcome->itemid))) {
2341 // Annotate as scalefinal because it's > 0
2342 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
2350 * This step will generate all the file annotations for the already
2351 * annotated (final) question_categories. It calculates the different
2352 * contexts that are being backup and, annotates all the files
2353 * on every context belonging to the "question" component. As far as
2354 * we are always including *complete* question banks it is safe and
2355 * optimal to do that in this (one pass) way
2357 class backup_annotate_all_question_files extends backup_execution_step {
2359 protected function define_execution() {
2360 global $DB;
2362 // Get all the different contexts for the final question_categories
2363 // annotated along the whole backup
2364 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2365 FROM {question_categories} qc
2366 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2367 WHERE bi.backupid = ?
2368 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2369 // To know about qtype specific components/fileareas
2370 $components = backup_qtype_plugin::get_components_and_fileareas();
2371 // Let's loop
2372 foreach($rs as $record) {
2373 // Backup all the file areas the are managed by the core question component.
2374 // That is, by the question_type base class. In particular, we don't want
2375 // to include files belonging to responses here.
2376 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'questiontext', null);
2377 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'generalfeedback', null);
2378 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answer', null);
2379 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answerfeedback', null);
2380 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'hint', null);
2381 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'correctfeedback', null);
2382 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'partiallycorrectfeedback', null);
2383 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'incorrectfeedback', null);
2385 // For files belonging to question types, we make the leap of faith that
2386 // all the files belonging to the question type are part of the question definition,
2387 // so we can just backup all the files in bulk, without specifying each
2388 // file area name separately.
2389 foreach ($components as $component => $fileareas) {
2390 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
2393 $rs->close();
2398 * structure step in charge of constructing the questions.xml file for all the
2399 * question categories and questions required by the backup
2400 * and letters related to one activity.
2402 class backup_questions_structure_step extends backup_structure_step {
2404 protected function define_structure() {
2406 // Define each element separately.
2407 $qcategories = new backup_nested_element('question_categories');
2409 $qcategory = new backup_nested_element('question_category', ['id'],
2411 'name',
2412 'contextid',
2413 'contextlevel',
2414 'contextinstanceid',
2415 'info',
2416 'infoformat',
2417 'stamp',
2418 'parent',
2419 'sortorder',
2420 'idnumber',
2423 $questionbankentries = new backup_nested_element('question_bank_entries');
2425 $questionbankentry = new backup_nested_element('question_bank_entry', ['id'],
2427 'questioncategoryid',
2428 'idnumber',
2429 'ownerid',
2432 $questionversions = new backup_nested_element('question_version');
2434 $questionverion = new backup_nested_element('question_versions', ['id'], ['version', 'status']);
2436 $questions = new backup_nested_element('questions');
2438 $question = new backup_nested_element('question', ['id'],
2440 'parent',
2441 'name',
2442 'questiontext',
2443 'questiontextformat',
2444 'generalfeedback',
2445 'generalfeedbackformat',
2446 'defaultmark',
2447 'penalty',
2448 'qtype',
2449 'length',
2450 'stamp',
2451 'timecreated',
2452 'timemodified',
2453 'createdby',
2454 'modifiedby',
2457 // Attach qtype plugin structure to $question element, only one allowed.
2458 $this->add_plugin_structure('qtype', $question, false);
2460 // Attach qbank plugin stucture to $question element, multiple allowed.
2461 $this->add_plugin_structure('qbank', $question, true);
2463 // attach local plugin stucture to $question element, multiple allowed
2464 $this->add_plugin_structure('local', $question, true);
2466 $qhints = new backup_nested_element('question_hints');
2468 $qhint = new backup_nested_element('question_hint', ['id'],
2470 'hint',
2471 'hintformat',
2472 'shownumcorrect',
2473 'clearwrong',
2474 'options',
2477 $tags = new backup_nested_element('tags');
2479 $tag = new backup_nested_element('tag', ['id', 'contextid'], ['name', 'rawname']);
2481 // Build the initial tree.
2482 $qcategories->add_child($qcategory);
2483 $qcategory->add_child($questionbankentries);
2484 $questionbankentries->add_child($questionbankentry);
2485 $questionbankentry->add_child($questionversions);
2486 $questionversions->add_child($questionverion);
2487 $questionverion->add_child($questions);
2488 $questions->add_child($question);
2489 $question->add_child($qhints);
2490 $qhints->add_child($qhint);
2492 // Add question tags.
2493 $question->add_child($tags);
2494 $tags->add_child($tag);
2496 $qcategory->set_source_sql("
2497 SELECT gc.*,
2498 contextlevel,
2499 instanceid AS contextinstanceid
2500 FROM {question_categories} gc
2501 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2502 JOIN {context} co ON co.id = gc.contextid
2503 WHERE bi.backupid = ?
2504 AND bi.itemname = 'question_categoryfinal'", [backup::VAR_BACKUPID]);
2506 $questionbankentry->set_source_table('question_bank_entries', ['questioncategoryid' => backup::VAR_PARENTID]);
2508 $questionverion->set_source_table('question_versions', ['questionbankentryid' => backup::VAR_PARENTID]);
2510 $question->set_source_sql('
2511 SELECT q.*
2512 FROM {question} q
2513 JOIN {question_versions} qv ON qv.questionid = q.id
2514 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2515 WHERE qv.id = ?', [backup::VAR_PARENTID]);
2517 $qhint->set_source_sql('
2518 SELECT *
2519 FROM {question_hints}
2520 WHERE questionid = :questionid
2521 ORDER BY id', ['questionid' => backup::VAR_PARENTID]);
2523 $tag->set_source_sql("SELECT t.id, ti.contextid, t.name, t.rawname
2524 FROM {tag} t
2525 JOIN {tag_instance} ti ON ti.tagid = t.id
2526 WHERE ti.itemid = ?
2527 AND ti.itemtype = 'question'
2528 AND ti.component = 'core_question'", [backup::VAR_PARENTID]);
2530 // Don't need to annotate ids nor files.
2531 // ...(already done by {@see backup_annotate_all_question_files()}.
2533 return $qcategories;
2540 * This step will generate all the file annotations for the already
2541 * annotated (final) users. Need to do this here because each user
2542 * has its own context and structure tasks only are able to handle
2543 * one context. Also, this step will guarantee that every user has
2544 * its context created (req for other steps)
2546 class backup_annotate_all_user_files extends backup_execution_step {
2548 protected function define_execution() {
2549 global $DB;
2551 // List of fileareas we are going to annotate
2552 $fileareas = array('profile', 'icon');
2554 // Fetch all annotated (final) users
2555 $rs = $DB->get_recordset('backup_ids_temp', array(
2556 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2557 $progress = $this->task->get_progress();
2558 $progress->start_progress($this->get_name());
2559 foreach ($rs as $record) {
2560 $userid = $record->itemid;
2561 $userctx = context_user::instance($userid, IGNORE_MISSING);
2562 if (!$userctx) {
2563 continue; // User has not context, sure it's a deleted user, so cannot have files
2565 // Proceed with every user filearea
2566 foreach ($fileareas as $filearea) {
2567 // We don't need to specify itemid ($userid - 5th param) as far as by
2568 // context we can get all the associated files. See MDL-22092
2569 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2570 $progress->progress();
2573 $progress->end_progress();
2574 $rs->close();
2580 * Defines the backup step for advanced grading methods attached to the activity module
2582 class backup_activity_grading_structure_step extends backup_structure_step {
2585 * Include the grading.xml only if the module supports advanced grading
2587 protected function execute_condition() {
2589 // No grades on the front page.
2590 if ($this->get_courseid() == SITEID) {
2591 return false;
2594 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2598 * Declares the gradable areas structures and data sources
2600 protected function define_structure() {
2602 // To know if we are including userinfo
2603 $userinfo = $this->get_setting_value('userinfo');
2605 // Define the elements
2607 $areas = new backup_nested_element('areas');
2609 $area = new backup_nested_element('area', array('id'), array(
2610 'areaname', 'activemethod'));
2612 $definitions = new backup_nested_element('definitions');
2614 $definition = new backup_nested_element('definition', array('id'), array(
2615 'method', 'name', 'description', 'descriptionformat', 'status',
2616 'timecreated', 'timemodified', 'options'));
2618 $instances = new backup_nested_element('instances');
2620 $instance = new backup_nested_element('instance', array('id'), array(
2621 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2622 'feedbackformat', 'timemodified'));
2624 // Build the tree including the method specific structures
2625 // (beware - the order of how gradingform plugins structures are attached is important)
2626 $areas->add_child($area);
2627 // attach local plugin stucture to $area element, multiple allowed
2628 $this->add_plugin_structure('local', $area, true);
2629 $area->add_child($definitions);
2630 $definitions->add_child($definition);
2631 $this->add_plugin_structure('gradingform', $definition, true);
2632 // attach local plugin stucture to $definition element, multiple allowed
2633 $this->add_plugin_structure('local', $definition, true);
2634 $definition->add_child($instances);
2635 $instances->add_child($instance);
2636 $this->add_plugin_structure('gradingform', $instance, false);
2637 // attach local plugin stucture to $instance element, multiple allowed
2638 $this->add_plugin_structure('local', $instance, true);
2640 // Define data sources
2642 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2643 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2645 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2647 if ($userinfo) {
2648 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2651 // Annotate references
2652 $definition->annotate_files('grading', 'description', 'id');
2653 $instance->annotate_ids('user', 'raterid');
2655 // Return the root element
2656 return $areas;
2662 * structure step in charge of constructing the grades.xml file for all the grade items
2663 * and letters related to one activity
2665 class backup_activity_grades_structure_step extends backup_structure_step {
2668 * No grades on the front page.
2669 * @return bool
2671 protected function execute_condition() {
2672 return ($this->get_courseid() != SITEID);
2675 protected function define_structure() {
2676 global $CFG;
2678 require_once($CFG->libdir . '/grade/constants.php');
2680 // To know if we are including userinfo
2681 $userinfo = $this->get_setting_value('userinfo');
2683 // Define each element separated
2685 $book = new backup_nested_element('activity_gradebook');
2687 $items = new backup_nested_element('grade_items');
2689 $item = new backup_nested_element('grade_item', array('id'), array(
2690 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2691 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2692 'calculation', 'gradetype', 'grademax', 'grademin',
2693 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2694 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2695 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2696 'needsupdate', 'timecreated', 'timemodified'));
2698 $grades = new backup_nested_element('grade_grades');
2700 $grade = new backup_nested_element('grade_grade', array('id'), array(
2701 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2702 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2703 'locked', 'locktime', 'exported', 'overridden',
2704 'excluded', 'feedback', 'feedbackformat', 'information',
2705 'informationformat', 'timecreated', 'timemodified',
2706 'aggregationstatus', 'aggregationweight'));
2708 $letters = new backup_nested_element('grade_letters');
2710 $letter = new backup_nested_element('grade_letter', 'id', array(
2711 'lowerboundary', 'letter'));
2713 // Build the tree
2715 $book->add_child($items);
2716 $items->add_child($item);
2718 $item->add_child($grades);
2719 $grades->add_child($grade);
2721 $book->add_child($letters);
2722 $letters->add_child($letter);
2724 // Define sources
2726 $item->set_source_sql("SELECT gi.*
2727 FROM {grade_items} gi
2728 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2729 WHERE bi.backupid = ?
2730 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2732 // This only happens if we are including user info
2733 if ($userinfo) {
2734 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2735 $grade->annotate_files(GRADE_FILE_COMPONENT, GRADE_FEEDBACK_FILEAREA, 'id');
2738 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2740 // Annotations
2742 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2743 $item->annotate_ids('outcome', 'outcomeid');
2745 $grade->annotate_ids('user', 'userid');
2746 $grade->annotate_ids('user', 'usermodified');
2748 // Return the root element (book)
2750 return $book;
2755 * Structure step in charge of constructing the grade history of an activity.
2757 * This step is added to the task regardless of the setting 'grade_histories'.
2758 * The reason is to allow for a more flexible step in case the logic needs to be
2759 * split accross different settings to control the history of items and/or grades.
2761 class backup_activity_grade_history_structure_step extends backup_structure_step {
2764 * No grades on the front page.
2765 * @return bool
2767 protected function execute_condition() {
2768 return ($this->get_courseid() != SITEID);
2771 protected function define_structure() {
2772 global $CFG;
2774 require_once($CFG->libdir . '/grade/constants.php');
2776 // Settings to use.
2777 $userinfo = $this->get_setting_value('userinfo');
2778 $history = $this->get_setting_value('grade_histories');
2780 // Create the nested elements.
2781 $bookhistory = new backup_nested_element('grade_history');
2782 $grades = new backup_nested_element('grade_grades');
2783 $grade = new backup_nested_element('grade_grade', array('id'), array(
2784 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2785 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2786 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2787 'excluded', 'feedback', 'feedbackformat', 'information',
2788 'informationformat', 'timemodified'));
2790 // Build the tree.
2791 $bookhistory->add_child($grades);
2792 $grades->add_child($grade);
2794 // This only happens if we are including user info and history.
2795 if ($userinfo && $history) {
2796 // Define sources. Only select the history related to existing activity items.
2797 $grade->set_source_sql("SELECT ggh.*
2798 FROM {grade_grades_history} ggh
2799 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2800 WHERE bi.backupid = ?
2801 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2802 $grade->annotate_files(GRADE_FILE_COMPONENT, GRADE_HISTORY_FEEDBACK_FILEAREA, 'id');
2805 // Annotations.
2806 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2807 $grade->annotate_ids('user', 'loggeduser');
2808 $grade->annotate_ids('user', 'userid');
2809 $grade->annotate_ids('user', 'usermodified');
2811 // Return the root element.
2812 return $bookhistory;
2817 * Backups up the course completion information for the course.
2819 class backup_course_completion_structure_step extends backup_structure_step {
2821 protected function execute_condition() {
2823 // No completion on front page.
2824 if ($this->get_courseid() == SITEID) {
2825 return false;
2828 // Check that all activities have been included
2829 if ($this->task->is_excluding_activities()) {
2830 return false;
2832 return true;
2836 * The structure of the course completion backup
2838 * @return backup_nested_element
2840 protected function define_structure() {
2842 // To know if we are including user completion info
2843 $userinfo = $this->get_setting_value('userscompletion');
2845 $cc = new backup_nested_element('course_completion');
2847 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2848 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2849 'timeend', 'gradepass', 'role', 'roleshortname'
2852 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2854 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2855 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2858 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2859 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2862 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2863 'course','criteriatype','method','value'
2866 $cc->add_child($criteria);
2867 $criteria->add_child($criteriacompletions);
2868 $criteriacompletions->add_child($criteriacomplete);
2869 $cc->add_child($coursecompletions);
2870 $cc->add_child($aggregatemethod);
2872 // We need some extra data for the restore.
2873 // - courseinstances shortname rather than an ID.
2874 // - roleshortname in case restoring on a different site.
2875 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2876 FROM {course_completion_criteria} ccc
2877 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2878 LEFT JOIN {role} r ON r.id = ccc.role
2879 WHERE ccc.course = ?";
2880 $criteria->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2882 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2884 if ($userinfo) {
2885 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2886 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2889 $criteria->annotate_ids('role', 'role');
2890 $criteriacomplete->annotate_ids('user', 'userid');
2891 $coursecompletions->annotate_ids('user', 'userid');
2893 return $cc;
2899 * Backup completion defaults for each module type.
2901 * @package core_backup
2902 * @copyright 2017 Marina Glancy
2903 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2905 class backup_completion_defaults_structure_step extends backup_structure_step {
2908 * To conditionally decide if one step will be executed or no
2910 protected function execute_condition() {
2911 // No completion on front page.
2912 if ($this->get_courseid() == SITEID) {
2913 return false;
2915 return true;
2919 * The structure of the course completion backup
2921 * @return backup_nested_element
2923 protected function define_structure() {
2925 $cc = new backup_nested_element('course_completion_defaults');
2927 $defaults = new backup_nested_element('course_completion_default', array('id'), array(
2928 'modulename', 'completion', 'completionview', 'completionusegrade', 'completionpassgrade',
2929 'completionexpected', 'customrules'
2932 // Use module name instead of module id so we can insert into another site later.
2933 $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
2934 d.completionpassgrade, d.completionexpected, d.customrules
2935 FROM {course_completion_defaults} d join {modules} m on d.module = m.id
2936 WHERE d.course = ?";
2937 $defaults->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2939 $cc->add_child($defaults);
2940 return $cc;
2946 * Structure step in charge of constructing the contentbank.xml file for all the contents found in a given context
2948 class backup_contentbankcontent_structure_step extends backup_structure_step {
2951 * Define structure for content bank step
2953 protected function define_structure() {
2955 // Define each element separated.
2956 $contents = new backup_nested_element('contents');
2957 $content = new backup_nested_element('content', ['id'], [
2958 'name', 'contenttype', 'instanceid', 'configdata', 'usercreated', 'usermodified', 'timecreated', 'timemodified']);
2960 // Build the tree.
2961 $contents->add_child($content);
2963 // Define sources.
2964 $content->set_source_table('contentbank_content', ['contextid' => backup::VAR_CONTEXTID]);
2966 // Define annotations.
2967 $content->annotate_ids('user', 'usercreated');
2968 $content->annotate_ids('user', 'usermodified');
2969 $content->annotate_files('contentbank', 'public', 'id');
2971 // Return the root element (contents).
2972 return $contents;