MDL-58439 admin: Ignore guest logins for all admin pages
[moodle.git] / backup / moodle2 / backup_stepslib.php
blob11dd4ce9c7827df196372dfb580b7f23ce229e58
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),
48 * delete old directories and drop temp ids table. Note we delete
49 * the directory but not the corresponding log file that will be
50 * there for, at least, 1 week - only delete_old_backup_dirs() or cron
51 * deletes log files (for easier access to them).
53 class drop_and_clean_temp_stuff extends backup_execution_step {
55 protected $skipcleaningtempdir = false;
57 protected function define_execution() {
58 global $CFG;
60 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
61 backup_helper::delete_old_backup_dirs(strtotime('-1 week')); // Delete > 1 week old temp dirs.
62 // Delete temp dir conditionally:
63 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
64 // 2) If backup temp dir deletion has been marked to be avoided
65 if (empty($CFG->keeptempdirectoriesonbackup) && !$this->skipcleaningtempdir) {
66 $progress = $this->task->get_progress();
67 $progress->start_progress('Deleting backup dir');
68 backup_helper::delete_backup_dir($this->get_backupid(), $progress); // Empty backup dir
69 $progress->end_progress();
73 public function skip_cleaning_temp_dir($skip) {
74 $this->skipcleaningtempdir = $skip;
78 /**
79 * Create the directory where all the task (activity/block...) information will be stored
81 class create_taskbasepath_directory extends backup_execution_step {
83 protected function define_execution() {
84 global $CFG;
85 $basepath = $this->task->get_taskbasepath();
86 if (!check_dir_exists($basepath, true, true)) {
87 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
92 /**
93 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
94 * activity structure definition within the main <activity ...> tag.
96 abstract class backup_activity_structure_step extends backup_structure_step {
98 /**
99 * Wraps any activity backup structure within the common 'activity' element
100 * that will include common to all activities information like id, context...
102 * @param backup_nested_element $activitystructure the element to wrap
103 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
105 protected function prepare_activity_structure($activitystructure) {
107 // Create the wrap element
108 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
110 // Build the tree
111 $activity->add_child($activitystructure);
113 // Set the source
114 $activityarr = array((object)array(
115 'id' => $this->task->get_activityid(),
116 'moduleid' => $this->task->get_moduleid(),
117 'modulename' => $this->task->get_modulename(),
118 'contextid' => $this->task->get_contextid()));
120 $activity->set_source_array($activityarr);
122 // Return the root element (activity)
123 return $activity;
128 * Abstract structure step, to be used by all the activities using core questions stuff
129 * (namely quiz module), supporting question plugins, states and sessions
131 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
134 * Attach to $element (usually attempts) the needed backup structures
135 * for question_usages and all the associated data.
137 * @param backup_nested_element $element the element that will contain all the question_usages data.
138 * @param string $usageidname the name of the element that holds the usageid.
139 * This must be child of $element, and must be a final element.
140 * @param string $nameprefix this prefix is added to all the element names we create.
141 * Element names in the XML must be unique, so if you are using usages in
142 * two different ways, you must give a prefix to at least one of them. If
143 * you only use one sort of usage, then you can just use the default empty prefix.
144 * This should include a trailing underscore. For example "myprefix_"
146 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
147 global $CFG;
148 require_once($CFG->dirroot . '/question/engine/lib.php');
150 // Check $element is one nested_backup_element
151 if (! $element instanceof backup_nested_element) {
152 throw new backup_step_exception('question_states_bad_parent_element', $element);
154 if (! $element->get_final_element($usageidname)) {
155 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
158 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
159 array('component', 'preferredbehaviour'));
161 $qas = new backup_nested_element($nameprefix . 'question_attempts');
162 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
163 'slot', 'behaviour', 'questionid', 'variant', 'maxmark', 'minfraction', 'maxfraction',
164 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
165 'timemodified'));
167 $steps = new backup_nested_element($nameprefix . 'steps');
168 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
169 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
171 $response = new backup_nested_element($nameprefix . 'response');
172 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
174 // Build the tree
175 $element->add_child($quba);
176 $quba->add_child($qas);
177 $qas->add_child($qa);
178 $qa->add_child($steps);
179 $steps->add_child($step);
180 $step->add_child($response);
181 $response->add_child($variable);
183 // Set the sources
184 $quba->set_source_table('question_usages',
185 array('id' => '../' . $usageidname));
186 $qa->set_source_table('question_attempts', array('questionusageid' => backup::VAR_PARENTID), 'slot ASC');
187 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup::VAR_PARENTID), 'sequencenumber ASC');
188 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup::VAR_PARENTID));
190 // Annotate ids
191 $qa->annotate_ids('question', 'questionid');
192 $step->annotate_ids('user', 'userid');
194 // Annotate files
195 $fileareas = question_engine::get_all_response_file_areas();
196 foreach ($fileareas as $filearea) {
197 $step->annotate_files('question', $filearea, 'id');
204 * backup structure step in charge of calculating the categories to be
205 * included in backup, based in the context being backuped (module/course)
206 * and the already annotated questions present in backup_ids_temp
208 class backup_calculate_question_categories extends backup_execution_step {
210 protected function define_execution() {
211 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
216 * backup structure step in charge of deleting all the questions annotated
217 * in the backup_ids_temp table
219 class backup_delete_temp_questions extends backup_execution_step {
221 protected function define_execution() {
222 backup_question_dbops::delete_temp_questions($this->get_backupid());
227 * Abstract structure step, parent of all the block structure steps. Used to wrap the
228 * block structure definition within the main <block ...> tag
230 abstract class backup_block_structure_step extends backup_structure_step {
232 protected function prepare_block_structure($blockstructure) {
234 // Create the wrap element
235 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
237 // Build the tree
238 $block->add_child($blockstructure);
240 // Set the source
241 $blockarr = array((object)array(
242 'id' => $this->task->get_blockid(),
243 'blockname' => $this->task->get_blockname(),
244 'contextid' => $this->task->get_contextid()));
246 $block->set_source_array($blockarr);
248 // Return the root element (block)
249 return $block;
254 * structure step that will generate the module.xml file for the activity,
255 * accumulating various information about the activity, annotating groupings
256 * and completion/avail conf
258 class backup_module_structure_step extends backup_structure_step {
260 protected function define_structure() {
261 global $DB;
263 // Define each element separated
265 $module = new backup_nested_element('module', array('id', 'version'), array(
266 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
267 'added', 'score', 'indent', 'visible', 'visibleoncoursepage',
268 'visibleold', 'groupmode', 'groupingid',
269 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
270 'availability', 'showdescription'));
272 $tags = new backup_nested_element('tags');
273 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
275 // attach format plugin structure to $module element, only one allowed
276 $this->add_plugin_structure('format', $module, false);
278 // attach plagiarism plugin structure to $module element, there can be potentially
279 // many plagiarism plugins storing information about this course
280 $this->add_plugin_structure('plagiarism', $module, true);
282 // attach local plugin structure to $module, multiple allowed
283 $this->add_plugin_structure('local', $module, true);
285 // Attach admin tools plugin structure to $module.
286 $this->add_plugin_structure('tool', $module, true);
288 $module->add_child($tags);
289 $tags->add_child($tag);
291 // Set the sources
292 $concat = $DB->sql_concat("'mod_'", 'm.name');
293 $module->set_source_sql("
294 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
295 FROM {course_modules} cm
296 JOIN {modules} m ON m.id = cm.module
297 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
298 JOIN {course_sections} s ON s.id = cm.section
299 WHERE cm.id = ?", array(backup::VAR_MODID));
301 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
302 FROM {tag} t
303 JOIN {tag_instance} ti ON ti.tagid = t.id
304 WHERE ti.itemtype = 'course_modules'
305 AND ti.component = 'core'
306 AND ti.itemid = ?", array(backup::VAR_MODID));
308 // Define annotations
309 $module->annotate_ids('grouping', 'groupingid');
311 // Return the root element ($module)
312 return $module;
317 * structure step that will generate the section.xml file for the section
318 * annotating files
320 class backup_section_structure_step extends backup_structure_step {
322 protected function define_structure() {
324 // Define each element separated
326 $section = new backup_nested_element('section', array('id'), array(
327 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
328 'availabilityjson', 'timemodified'));
330 // attach format plugin structure to $section element, only one allowed
331 $this->add_plugin_structure('format', $section, false);
333 // attach local plugin structure to $section element, multiple allowed
334 $this->add_plugin_structure('local', $section, true);
336 // Add nested elements for course_format_options table
337 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
338 'format', 'name', 'value'));
339 $section->add_child($formatoptions);
341 // Define sources.
342 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
343 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
344 FROM {course} c
345 JOIN {course_format_options} cfo
346 ON cfo.courseid = c.id AND cfo.format = c.format
347 WHERE c.id = ? AND cfo.sectionid = ?',
348 array(backup::VAR_COURSEID, backup::VAR_SECTIONID));
350 // Aliases
351 $section->set_source_alias('section', 'number');
352 // The 'availability' field needs to be renamed because it clashes with
353 // the old nested element structure for availability data.
354 $section->set_source_alias('availability', 'availabilityjson');
356 // Set annotations
357 $section->annotate_files('course', 'section', 'id');
359 return $section;
364 * structure step that will generate the course.xml file for the course, including
365 * course category reference, tags, modules restriction information
366 * and some annotations (files & groupings)
368 class backup_course_structure_step extends backup_structure_step {
370 protected function define_structure() {
371 global $DB;
373 // Define each element separated
375 $course = new backup_nested_element('course', array('id', 'contextid'), array(
376 'shortname', 'fullname', 'idnumber',
377 'summary', 'summaryformat', 'format', 'showgrades',
378 'newsitems', 'startdate', 'enddate',
379 'marker', 'maxbytes', 'legacyfiles', 'showreports',
380 'visible', 'groupmode', 'groupmodeforce',
381 'defaultgroupingid', 'lang', 'theme',
382 'timecreated', 'timemodified',
383 'requested',
384 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
386 $category = new backup_nested_element('category', array('id'), array(
387 'name', 'description'));
389 $tags = new backup_nested_element('tags');
391 $tag = new backup_nested_element('tag', array('id'), array(
392 'name', 'rawname'));
394 $customfields = new backup_nested_element('customfields');
395 $customfield = new backup_nested_element('customfield', array('id'), array(
396 'shortname', 'type', 'value', 'valueformat'
399 // attach format plugin structure to $course element, only one allowed
400 $this->add_plugin_structure('format', $course, false);
402 // attach theme plugin structure to $course element; multiple themes can
403 // save course data (in case of user theme, legacy theme, etc)
404 $this->add_plugin_structure('theme', $course, true);
406 // attach general report plugin structure to $course element; multiple
407 // reports can save course data if required
408 $this->add_plugin_structure('report', $course, true);
410 // attach course report plugin structure to $course element; multiple
411 // course reports can save course data if required
412 $this->add_plugin_structure('coursereport', $course, true);
414 // attach plagiarism plugin structure to $course element, there can be potentially
415 // many plagiarism plugins storing information about this course
416 $this->add_plugin_structure('plagiarism', $course, true);
418 // attach local plugin structure to $course element; multiple local plugins
419 // can save course data if required
420 $this->add_plugin_structure('local', $course, true);
422 // Attach admin tools plugin structure to $course element; multiple plugins
423 // can save course data if required.
424 $this->add_plugin_structure('tool', $course, true);
426 // Build the tree
428 $course->add_child($category);
430 $course->add_child($tags);
431 $tags->add_child($tag);
433 $course->add_child($customfields);
434 $customfields->add_child($customfield);
436 // Set the sources
438 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
439 $courserec->contextid = $this->task->get_contextid();
441 $formatoptions = course_get_format($courserec)->get_format_options();
442 $course->add_final_elements(array_keys($formatoptions));
443 foreach ($formatoptions as $key => $value) {
444 $courserec->$key = $value;
447 // Add 'numsections' in order to be able to restore in previous versions of Moodle.
448 // Even though Moodle does not officially support restore into older verions of Moodle from the
449 // version where backup was made, without 'numsections' restoring will go very wrong.
450 if (!property_exists($courserec, 'numsections') && course_get_format($courserec)->uses_sections()) {
451 $courserec->numsections = course_get_format($courserec)->get_last_section_number();
454 $course->set_source_array(array($courserec));
456 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
458 $category->set_source_array(array($categoryrec));
460 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
461 FROM {tag} t
462 JOIN {tag_instance} ti ON ti.tagid = t.id
463 WHERE ti.itemtype = ?
464 AND ti.itemid = ?', array(
465 backup_helper::is_sqlparam('course'),
466 backup::VAR_PARENTID));
468 $handler = core_course\customfield\course_handler::create();
469 $fieldsforbackup = $handler->get_instance_data_for_backup($this->task->get_courseid());
470 $customfield->set_source_array($fieldsforbackup);
472 // Some annotations
474 $course->annotate_ids('grouping', 'defaultgroupingid');
476 $course->annotate_files('course', 'summary', null);
477 $course->annotate_files('course', 'overviewfiles', null);
478 $course->annotate_files('course', 'legacy', null);
480 // Return root element ($course)
482 return $course;
487 * structure step that will generate the enrolments.xml file for the given course
489 class backup_enrolments_structure_step extends backup_structure_step {
492 * Skip enrolments on the front page.
493 * @return bool
495 protected function execute_condition() {
496 return ($this->get_courseid() != SITEID);
499 protected function define_structure() {
501 // To know if we are including users
502 $users = $this->get_setting_value('users');
504 // Define each element separated
506 $enrolments = new backup_nested_element('enrolments');
508 $enrols = new backup_nested_element('enrols');
510 $enrol = new backup_nested_element('enrol', array('id'), array(
511 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
512 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
513 'password', 'cost', 'currency', 'roleid',
514 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
515 'customchar1', 'customchar2', 'customchar3',
516 'customdec1', 'customdec2',
517 'customtext1', 'customtext2', 'customtext3', 'customtext4',
518 'timecreated', 'timemodified'));
520 $userenrolments = new backup_nested_element('user_enrolments');
522 $enrolment = new backup_nested_element('enrolment', array('id'), array(
523 'status', 'userid', 'timestart', 'timeend', 'modifierid',
524 'timemodified'));
526 // Build the tree
527 $enrolments->add_child($enrols);
528 $enrols->add_child($enrol);
529 $enrol->add_child($userenrolments);
530 $userenrolments->add_child($enrolment);
532 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
533 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
535 // User enrolments only added only if users included
536 if ($users) {
537 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
538 $enrolment->annotate_ids('user', 'userid');
541 $enrol->annotate_ids('role', 'roleid');
543 // Add enrol plugin structure.
544 $this->add_plugin_structure('enrol', $enrol, true);
546 return $enrolments;
551 * structure step that will generate the roles.xml file for the given context, observing
552 * the role_assignments setting to know if that part needs to be included
554 class backup_roles_structure_step extends backup_structure_step {
556 protected function define_structure() {
558 // To know if we are including role assignments
559 $roleassignments = $this->get_setting_value('role_assignments');
561 // Define each element separated
563 $roles = new backup_nested_element('roles');
565 $overrides = new backup_nested_element('role_overrides');
567 $override = new backup_nested_element('override', array('id'), array(
568 'roleid', 'capability', 'permission', 'timemodified',
569 'modifierid'));
571 $assignments = new backup_nested_element('role_assignments');
573 $assignment = new backup_nested_element('assignment', array('id'), array(
574 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
575 'sortorder'));
577 // Build the tree
578 $roles->add_child($overrides);
579 $roles->add_child($assignments);
581 $overrides->add_child($override);
582 $assignments->add_child($assignment);
584 // Define sources
586 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
588 // Assignments only added if specified
589 if ($roleassignments) {
590 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
593 // Define id annotations
594 $override->annotate_ids('role', 'roleid');
596 $assignment->annotate_ids('role', 'roleid');
598 $assignment->annotate_ids('user', 'userid');
600 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
602 return $roles;
607 * structure step that will generate the roles.xml containing the
608 * list of roles used along the whole backup process. Just raw
609 * list of used roles from role table
611 class backup_final_roles_structure_step extends backup_structure_step {
613 protected function define_structure() {
615 // Define elements
617 $rolesdef = new backup_nested_element('roles_definition');
619 $role = new backup_nested_element('role', array('id'), array(
620 'name', 'shortname', 'nameincourse', 'description',
621 'sortorder', 'archetype'));
623 // Build the tree
625 $rolesdef->add_child($role);
627 // Define sources
629 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
630 FROM {role} r
631 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
632 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
633 WHERE bi.backupid = ?
634 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
636 // Return main element (rolesdef)
637 return $rolesdef;
642 * structure step that will generate the scales.xml containing the
643 * list of scales used along the whole backup process.
645 class backup_final_scales_structure_step extends backup_structure_step {
647 protected function define_structure() {
649 // Define elements
651 $scalesdef = new backup_nested_element('scales_definition');
653 $scale = new backup_nested_element('scale', array('id'), array(
654 'courseid', 'userid', 'name', 'scale',
655 'description', 'descriptionformat', 'timemodified'));
657 // Build the tree
659 $scalesdef->add_child($scale);
661 // Define sources
663 $scale->set_source_sql("SELECT s.*
664 FROM {scale} s
665 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
666 WHERE bi.backupid = ?
667 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
669 // Annotate scale files (they store files in system context, so pass it instead of default one)
670 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
672 // Return main element (scalesdef)
673 return $scalesdef;
678 * structure step that will generate the outcomes.xml containing the
679 * list of outcomes used along the whole backup process.
681 class backup_final_outcomes_structure_step extends backup_structure_step {
683 protected function define_structure() {
685 // Define elements
687 $outcomesdef = new backup_nested_element('outcomes_definition');
689 $outcome = new backup_nested_element('outcome', array('id'), array(
690 'courseid', 'userid', 'shortname', 'fullname',
691 'scaleid', 'description', 'descriptionformat', 'timecreated',
692 'timemodified','usermodified'));
694 // Build the tree
696 $outcomesdef->add_child($outcome);
698 // Define sources
700 $outcome->set_source_sql("SELECT o.*
701 FROM {grade_outcomes} o
702 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
703 WHERE bi.backupid = ?
704 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
706 // Annotate outcome files (they store files in system context, so pass it instead of default one)
707 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
709 // Return main element (outcomesdef)
710 return $outcomesdef;
715 * structure step in charge of constructing the filters.xml file for all the filters found
716 * in activity
718 class backup_filters_structure_step extends backup_structure_step {
720 protected function define_structure() {
722 // Define each element separated
724 $filters = new backup_nested_element('filters');
726 $actives = new backup_nested_element('filter_actives');
728 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
730 $configs = new backup_nested_element('filter_configs');
732 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
734 // Build the tree
736 $filters->add_child($actives);
737 $filters->add_child($configs);
739 $actives->add_child($active);
740 $configs->add_child($config);
742 // Define sources
744 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
746 $active->set_source_array($activearr);
747 $config->set_source_array($configarr);
749 // Return the root element (filters)
750 return $filters;
755 * structure step in charge of constructing the comments.xml file for all the comments found
756 * in a given context
758 class backup_comments_structure_step extends backup_structure_step {
760 protected function define_structure() {
762 // Define each element separated
764 $comments = new backup_nested_element('comments');
766 $comment = new backup_nested_element('comment', array('id'), array(
767 'commentarea', 'itemid', 'content', 'format',
768 'userid', 'timecreated'));
770 // Build the tree
772 $comments->add_child($comment);
774 // Define sources
776 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
778 // Define id annotations
780 $comment->annotate_ids('user', 'userid');
782 // Return the root element (comments)
783 return $comments;
788 * structure step in charge of constructing the badges.xml file for all the badges found
789 * in a given context
791 class backup_badges_structure_step extends backup_structure_step {
793 protected function execute_condition() {
794 // Check that all activities have been included.
795 if ($this->task->is_excluding_activities()) {
796 return false;
798 return true;
801 protected function define_structure() {
803 // Define each element separated.
805 $badges = new backup_nested_element('badges');
806 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
807 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
808 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
809 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron',
810 'version', 'language', 'imageauthorname', 'imageauthoremail', 'imageauthorurl',
811 'imagecaption'));
813 $criteria = new backup_nested_element('criteria');
814 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
815 'criteriatype', 'method', 'description', 'descriptionformat'));
817 $endorsement = new backup_nested_element('endorsement', array('id'), array('badgeid',
818 'issuername', 'issuerurl', 'issueremail', 'claimid', 'claimcomment', 'dateissued'));
820 $alignments = new backup_nested_element('alignments');
821 $alignment = new backup_nested_element('alignment', array('id'), array('badgeid',
822 'targetname', 'targeturl', 'targetdescription', 'targetframework', 'targetcode'));
824 $relatedbadges = new backup_nested_element('relatedbadges');
825 $relatedbadge = new backup_nested_element('relatedbadge', array('id'), array('badgeid',
826 'relatedbadgeid'));
828 $parameters = new backup_nested_element('parameters');
829 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
830 'name', 'value', 'criteriatype'));
832 $manual_awards = new backup_nested_element('manual_awards');
833 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
834 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
836 // Build the tree.
838 $badges->add_child($badge);
839 $badge->add_child($criteria);
840 $criteria->add_child($criterion);
841 $criterion->add_child($parameters);
842 $parameters->add_child($parameter);
843 $badge->add_child($endorsement);
844 $badge->add_child($alignments);
845 $alignments->add_child($alignment);
846 $badge->add_child($relatedbadges);
847 $relatedbadges->add_child($relatedbadge);
848 $badge->add_child($manual_awards);
849 $manual_awards->add_child($manual_award);
851 // Define sources.
853 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
854 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
855 $endorsement->set_source_table('badge_endorsement', array('badgeid' => backup::VAR_PARENTID));
857 $alignment->set_source_table('badge_alignment', array('badgeid' => backup::VAR_PARENTID));
858 $relatedbadge->set_source_table('badge_related', array('badgeid' => backup::VAR_PARENTID));
860 $parametersql = 'SELECT cp.*, c.criteriatype
861 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
862 ON cp.critid = c.id
863 WHERE critid = :critid';
864 $parameterparams = array('critid' => backup::VAR_PARENTID);
865 $parameter->set_source_sql($parametersql, $parameterparams);
867 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
869 // Define id annotations.
871 $badge->annotate_ids('user', 'usercreated');
872 $badge->annotate_ids('user', 'usermodified');
873 $criterion->annotate_ids('badge', 'badgeid');
874 $parameter->annotate_ids('criterion', 'critid');
875 $endorsement->annotate_ids('badge', 'badgeid');
876 $alignment->annotate_ids('badge', 'badgeid');
877 $relatedbadge->annotate_ids('badge', 'badgeid');
878 $relatedbadge->annotate_ids('badge', 'relatedbadgeid');
879 $badge->annotate_files('badges', 'badgeimage', 'id');
880 $manual_award->annotate_ids('badge', 'badgeid');
881 $manual_award->annotate_ids('user', 'recipientid');
882 $manual_award->annotate_ids('user', 'issuerid');
883 $manual_award->annotate_ids('role', 'issuerrole');
885 // Return the root element ($badges).
886 return $badges;
891 * structure step in charge of constructing the calender.xml file for all the events found
892 * in a given context
894 class backup_calendarevents_structure_step extends backup_structure_step {
896 protected function define_structure() {
898 // Define each element separated
900 $events = new backup_nested_element('events');
902 $event = new backup_nested_element('event', array('id'), array(
903 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
904 'repeatid', 'modulename', 'instance', 'type', 'eventtype', 'timestart',
905 'timeduration', 'timesort', 'visible', 'uuid', 'sequence', 'timemodified',
906 'priority', 'location'));
908 // Build the tree
909 $events->add_child($event);
911 // Define sources
912 if ($this->name == 'course_calendar') {
913 $calendar_items_sql ="SELECT * FROM {event}
914 WHERE courseid = :courseid
915 AND (eventtype = 'course' OR eventtype = 'group')";
916 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
917 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
918 } else if ($this->name == 'activity_calendar') {
919 // We don't backup action events.
920 $params = array('instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME,
921 'type' => array('sqlparam' => CALENDAR_EVENT_TYPE_ACTION));
922 // If we don't want to include the userinfo in the backup then setting the courseid
923 // will filter out all of the user override events (which have a course id of zero).
924 $coursewhere = "";
925 if (!$this->get_setting_value('userinfo')) {
926 $params['courseid'] = backup::VAR_COURSEID;
927 $coursewhere = " AND courseid = :courseid";
929 $calendarsql = "SELECT * FROM {event}
930 WHERE instance = :instance
931 AND type <> :type
932 AND modulename = :modulename";
933 $calendarsql = $calendarsql . $coursewhere;
934 $event->set_source_sql($calendarsql, $params);
935 } else {
936 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
939 // Define id annotations
941 $event->annotate_ids('user', 'userid');
942 $event->annotate_ids('group', 'groupid');
943 $event->annotate_files('calendar', 'event_description', 'id');
945 // Return the root element (events)
946 return $events;
951 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
952 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
954 class backup_gradebook_structure_step extends backup_structure_step {
957 * We need to decide conditionally, based on dynamic information
958 * about the execution of this step. Only will be executed if all
959 * the module gradeitems have been already included in backup
961 protected function execute_condition() {
962 $courseid = $this->get_courseid();
963 if ($courseid == SITEID) {
964 return false;
967 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
970 protected function define_structure() {
971 global $CFG, $DB;
973 // are we including user info?
974 $userinfo = $this->get_setting_value('users');
976 $gradebook = new backup_nested_element('gradebook');
978 //grade_letters are done in backup_activity_grades_structure_step()
980 //calculated grade items
981 $grade_items = new backup_nested_element('grade_items');
982 $grade_item = new backup_nested_element('grade_item', array('id'), array(
983 'categoryid', 'itemname', 'itemtype', 'itemmodule',
984 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
985 'calculation', 'gradetype', 'grademax', 'grademin',
986 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
987 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
988 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
989 'needsupdate', 'timecreated', 'timemodified'));
991 $grade_grades = new backup_nested_element('grade_grades');
992 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
993 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
994 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
995 'locked', 'locktime', 'exported', 'overridden',
996 'excluded', 'feedback', 'feedbackformat', 'information',
997 'informationformat', 'timecreated', 'timemodified',
998 'aggregationstatus', 'aggregationweight'));
1000 //grade_categories
1001 $grade_categories = new backup_nested_element('grade_categories');
1002 $grade_category = new backup_nested_element('grade_category', array('id'), array(
1003 //'courseid',
1004 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
1005 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
1006 'timecreated', 'timemodified', 'hidden'));
1008 $letters = new backup_nested_element('grade_letters');
1009 $letter = new backup_nested_element('grade_letter', 'id', array(
1010 'lowerboundary', 'letter'));
1012 $grade_settings = new backup_nested_element('grade_settings');
1013 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
1014 'name', 'value'));
1016 $gradebook_attributes = new backup_nested_element('attributes', null, array('calculations_freeze'));
1018 // Build the tree
1019 $gradebook->add_child($gradebook_attributes);
1021 $gradebook->add_child($grade_categories);
1022 $grade_categories->add_child($grade_category);
1024 $gradebook->add_child($grade_items);
1025 $grade_items->add_child($grade_item);
1026 $grade_item->add_child($grade_grades);
1027 $grade_grades->add_child($grade_grade);
1029 $gradebook->add_child($letters);
1030 $letters->add_child($letter);
1032 $gradebook->add_child($grade_settings);
1033 $grade_settings->add_child($grade_setting);
1035 // Define sources
1037 // Add attribute with gradebook calculation freeze date if needed.
1038 $attributes = new stdClass();
1039 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
1040 if ($gradebookcalculationfreeze) {
1041 $attributes->calculations_freeze = $gradebookcalculationfreeze;
1043 $gradebook_attributes->set_source_array([$attributes]);
1045 //Include manual, category and the course grade item
1046 $grade_items_sql ="SELECT * FROM {grade_items}
1047 WHERE courseid = :courseid
1048 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1049 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
1050 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1052 if ($userinfo) {
1053 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1056 $grade_category_sql = "SELECT gc.*, gi.sortorder
1057 FROM {grade_categories} gc
1058 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1059 WHERE gc.courseid = :courseid
1060 AND (gi.itemtype='course' OR gi.itemtype='category')
1061 ORDER BY gc.parent ASC";//need parent categories before their children
1062 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1063 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1065 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1067 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1068 $settings = array();
1069 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1070 foreach ($rs as $record) {
1071 $settings[$record->name] = $record;
1073 $rs->close();
1074 if (!isset($settings['minmaxtouse'])) {
1075 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse);
1077 $grade_setting->set_source_array($settings);
1080 // Annotations (both as final as far as they are going to be exported in next steps)
1081 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1082 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1084 //just in case there are any users not already annotated by the activities
1085 $grade_grade->annotate_ids('userfinal', 'userid');
1087 // Return the root element
1088 return $gradebook;
1093 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1095 class backup_grade_history_structure_step extends backup_structure_step {
1098 * Limit the execution.
1100 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1101 * because we do not want to save the history of items which are not backed up. At least for now.
1103 protected function execute_condition() {
1104 $courseid = $this->get_courseid();
1105 if ($courseid == SITEID) {
1106 return false;
1109 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
1112 protected function define_structure() {
1114 // Settings to use.
1115 $userinfo = $this->get_setting_value('users');
1116 $history = $this->get_setting_value('grade_histories');
1118 // Create the nested elements.
1119 $bookhistory = new backup_nested_element('grade_history');
1120 $grades = new backup_nested_element('grade_grades');
1121 $grade = new backup_nested_element('grade_grade', array('id'), array(
1122 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1123 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1124 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1125 'excluded', 'feedback', 'feedbackformat', 'information',
1126 'informationformat', 'timemodified'));
1128 // Build the tree.
1129 $bookhistory->add_child($grades);
1130 $grades->add_child($grade);
1132 // This only happens if we are including user info and history.
1133 if ($userinfo && $history) {
1134 // Only keep the history of grades related to items which have been backed up, The query is
1135 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1136 $gradesql = "SELECT ggh.*
1137 FROM {grade_grades_history} ggh
1138 JOIN {grade_items} gi ON ggh.itemid = gi.id
1139 WHERE gi.courseid = :courseid
1140 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1141 $grade->set_source_sql($gradesql, array('courseid' => backup::VAR_COURSEID));
1144 // Annotations. (Final annotations as this step is part of the final task).
1145 $grade->annotate_ids('scalefinal', 'rawscaleid');
1146 $grade->annotate_ids('userfinal', 'loggeduser');
1147 $grade->annotate_ids('userfinal', 'userid');
1148 $grade->annotate_ids('userfinal', 'usermodified');
1150 // Return the root element.
1151 return $bookhistory;
1157 * structure step in charge if constructing the completion.xml file for all the users completion
1158 * information in a given activity
1160 class backup_userscompletion_structure_step extends backup_structure_step {
1163 * Skip completion on the front page.
1164 * @return bool
1166 protected function execute_condition() {
1167 return ($this->get_courseid() != SITEID);
1170 protected function define_structure() {
1172 // Define each element separated
1174 $completions = new backup_nested_element('completions');
1176 $completion = new backup_nested_element('completion', array('id'), array(
1177 'userid', 'completionstate', 'viewed', 'timemodified'));
1179 // Build the tree
1181 $completions->add_child($completion);
1183 // Define sources
1185 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1187 // Define id annotations
1189 $completion->annotate_ids('user', 'userid');
1191 // Return the root element (completions)
1192 return $completions;
1197 * structure step in charge of constructing the main groups.xml file for all the groups and
1198 * groupings information already annotated
1200 class backup_groups_structure_step extends backup_structure_step {
1202 protected function define_structure() {
1204 // To know if we are including users.
1205 $userinfo = $this->get_setting_value('users');
1206 // To know if we are including groups and groupings.
1207 $groupinfo = $this->get_setting_value('groups');
1209 // Define each element separated
1211 $groups = new backup_nested_element('groups');
1213 $group = new backup_nested_element('group', array('id'), array(
1214 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1215 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1217 $members = new backup_nested_element('group_members');
1219 $member = new backup_nested_element('group_member', array('id'), array(
1220 'userid', 'timeadded', 'component', 'itemid'));
1222 $groupings = new backup_nested_element('groupings');
1224 $grouping = new backup_nested_element('grouping', 'id', array(
1225 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1226 'timecreated', 'timemodified'));
1228 $groupinggroups = new backup_nested_element('grouping_groups');
1230 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1231 'groupid', 'timeadded'));
1233 // Build the tree
1235 $groups->add_child($group);
1236 $groups->add_child($groupings);
1238 $group->add_child($members);
1239 $members->add_child($member);
1241 $groupings->add_child($grouping);
1242 $grouping->add_child($groupinggroups);
1243 $groupinggroups->add_child($groupinggroup);
1245 // Define sources
1247 // This only happens if we are including groups/groupings.
1248 if ($groupinfo) {
1249 $group->set_source_sql("
1250 SELECT g.*
1251 FROM {groups} g
1252 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1253 WHERE bi.backupid = ?
1254 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1256 $grouping->set_source_sql("
1257 SELECT g.*
1258 FROM {groupings} g
1259 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1260 WHERE bi.backupid = ?
1261 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1262 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1264 // This only happens if we are including users.
1265 if ($userinfo) {
1266 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1270 // Define id annotations (as final)
1272 $member->annotate_ids('userfinal', 'userid');
1274 // Define file annotations
1276 $group->annotate_files('group', 'description', 'id');
1277 $group->annotate_files('group', 'icon', 'id');
1278 $grouping->annotate_files('grouping', 'description', 'id');
1280 // Return the root element (groups)
1281 return $groups;
1286 * structure step in charge of constructing the main users.xml file for all the users already
1287 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1288 * overrides.
1290 class backup_users_structure_step extends backup_structure_step {
1292 protected function define_structure() {
1293 global $CFG;
1295 // To know if we are anonymizing users
1296 $anonymize = $this->get_setting_value('anonymize');
1297 // To know if we are including role assignments
1298 $roleassignments = $this->get_setting_value('role_assignments');
1300 // Define each element separate.
1302 $users = new backup_nested_element('users');
1304 // Create the array of user fields by hand, as far as we have various bits to control
1305 // anonymize option, password backup, mnethostid...
1307 // First, the fields not needing anonymization nor special handling
1308 $normalfields = array(
1309 'confirmed', 'policyagreed', 'deleted',
1310 'lang', 'theme', 'timezone', 'firstaccess',
1311 'lastaccess', 'lastlogin', 'currentlogin',
1312 'mailformat', 'maildigest', 'maildisplay',
1313 'autosubscribe', 'trackforums', 'timecreated',
1314 'timemodified', 'trustbitmask');
1316 // Then, the fields potentially needing anonymization
1317 $anonfields = array(
1318 'username', 'idnumber', 'email', 'icq', 'skype',
1319 'yahoo', 'aim', 'msn', 'phone1',
1320 'phone2', 'institution', 'department', 'address',
1321 'city', 'country', 'lastip', 'picture',
1322 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1323 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1325 // Add anonymized fields to $userfields with custom final element
1326 foreach ($anonfields as $field) {
1327 if ($anonymize) {
1328 $userfields[] = new anonymizer_final_element($field);
1329 } else {
1330 $userfields[] = $field; // No anonymization, normally added
1334 // mnethosturl requires special handling (custom final element)
1335 $userfields[] = new mnethosturl_final_element('mnethosturl');
1337 // password added conditionally
1338 if (!empty($CFG->includeuserpasswordsinbackup)) {
1339 $userfields[] = 'password';
1342 // Merge all the fields
1343 $userfields = array_merge($userfields, $normalfields);
1345 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1347 $customfields = new backup_nested_element('custom_fields');
1349 $customfield = new backup_nested_element('custom_field', array('id'), array(
1350 'field_name', 'field_type', 'field_data'));
1352 $tags = new backup_nested_element('tags');
1354 $tag = new backup_nested_element('tag', array('id'), array(
1355 'name', 'rawname'));
1357 $preferences = new backup_nested_element('preferences');
1359 $preference = new backup_nested_element('preference', array('id'), array(
1360 'name', 'value'));
1362 $roles = new backup_nested_element('roles');
1364 $overrides = new backup_nested_element('role_overrides');
1366 $override = new backup_nested_element('override', array('id'), array(
1367 'roleid', 'capability', 'permission', 'timemodified',
1368 'modifierid'));
1370 $assignments = new backup_nested_element('role_assignments');
1372 $assignment = new backup_nested_element('assignment', array('id'), array(
1373 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1374 'sortorder'));
1376 // Build the tree
1378 $users->add_child($user);
1380 $user->add_child($customfields);
1381 $customfields->add_child($customfield);
1383 $user->add_child($tags);
1384 $tags->add_child($tag);
1386 $user->add_child($preferences);
1387 $preferences->add_child($preference);
1389 $user->add_child($roles);
1391 $roles->add_child($overrides);
1392 $roles->add_child($assignments);
1394 $overrides->add_child($override);
1395 $assignments->add_child($assignment);
1397 // Define sources
1399 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1400 FROM {user} u
1401 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1402 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1403 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1404 WHERE bi.backupid = ?
1405 AND bi.itemname = ?', array(
1406 backup_helper::is_sqlparam($this->get_backupid()),
1407 backup_helper::is_sqlparam('userfinal')));
1409 // All the rest on information is only added if we arent
1410 // in an anonymized backup
1411 if (!$anonymize) {
1412 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1413 FROM {user_info_field} f
1414 JOIN {user_info_data} d ON d.fieldid = f.id
1415 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1417 $customfield->set_source_alias('shortname', 'field_name');
1418 $customfield->set_source_alias('datatype', 'field_type');
1419 $customfield->set_source_alias('data', 'field_data');
1421 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1422 FROM {tag} t
1423 JOIN {tag_instance} ti ON ti.tagid = t.id
1424 WHERE ti.itemtype = ?
1425 AND ti.itemid = ?', array(
1426 backup_helper::is_sqlparam('user'),
1427 backup::VAR_PARENTID));
1429 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1431 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1433 // Assignments only added if specified
1434 if ($roleassignments) {
1435 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1438 // Define id annotations (as final)
1439 $override->annotate_ids('rolefinal', 'roleid');
1442 // Return root element (users)
1443 return $users;
1448 * structure step in charge of constructing the block.xml file for one
1449 * given block (instance and positions). If the block has custom DB structure
1450 * that will go to a separate file (different step defined in block class)
1452 class backup_block_instance_structure_step extends backup_structure_step {
1454 protected function define_structure() {
1455 global $DB;
1457 // Define each element separated
1459 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1460 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1461 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata',
1462 'timecreated', 'timemodified'));
1464 $positions = new backup_nested_element('block_positions');
1466 $position = new backup_nested_element('block_position', array('id'), array(
1467 'contextid', 'pagetype', 'subpage', 'visible',
1468 'region', 'weight'));
1470 // Build the tree
1472 $block->add_child($positions);
1473 $positions->add_child($position);
1475 // Transform configdata information if needed (process links and friends)
1476 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1477 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1478 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1479 foreach ($configdata as $attribute => $value) {
1480 if (in_array($attribute, $attrstotransform)) {
1481 $configdata[$attribute] = $this->contenttransformer->process($value);
1484 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1486 $blockrec->contextid = $this->task->get_contextid();
1487 // Get the version of the block
1488 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1490 // Define sources
1492 $block->set_source_array(array($blockrec));
1494 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1496 // File anotations (for fileareas specified on each block)
1497 foreach ($this->task->get_fileareas() as $filearea) {
1498 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1501 // Return the root element (block)
1502 return $block;
1507 * structure step in charge of constructing the logs.xml file for all the log records found
1508 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1509 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1510 * that just in case they become restored some day in the future
1512 class backup_course_logs_structure_step extends backup_structure_step {
1514 protected function define_structure() {
1516 // Define each element separated
1518 $logs = new backup_nested_element('logs');
1520 $log = new backup_nested_element('log', array('id'), array(
1521 'time', 'userid', 'ip', 'module',
1522 'action', 'url', 'info'));
1524 // Build the tree
1526 $logs->add_child($log);
1528 // Define sources (all the records belonging to the course, having cmid = 0)
1530 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1532 // Annotations
1533 // NOTE: We don't annotate users from logs as far as they MUST be
1534 // always annotated by the course (enrol, ras... whatever)
1536 // Return the root element (logs)
1538 return $logs;
1543 * structure step in charge of constructing the logs.xml file for all the log records found
1544 * in activity
1546 class backup_activity_logs_structure_step extends backup_structure_step {
1548 protected function define_structure() {
1550 // Define each element separated
1552 $logs = new backup_nested_element('logs');
1554 $log = new backup_nested_element('log', array('id'), array(
1555 'time', 'userid', 'ip', 'module',
1556 'action', 'url', 'info'));
1558 // Build the tree
1560 $logs->add_child($log);
1562 // Define sources
1564 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1566 // Annotations
1567 // NOTE: We don't annotate users from logs as far as they MUST be
1568 // always annotated by the activity (true participants).
1570 // Return the root element (logs)
1572 return $logs;
1577 * Structure step in charge of constructing the logstores.xml file for the course logs.
1579 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1580 * it, for logs belonging to the course level.
1582 class backup_course_logstores_structure_step extends backup_structure_step {
1584 protected function define_structure() {
1586 // Define the structure of logstores container.
1587 $logstores = new backup_nested_element('logstores');
1588 $logstore = new backup_nested_element('logstore');
1589 $logstores->add_child($logstore);
1591 // Add the tool_log logstore subplugins information to the logstore element.
1592 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1594 return $logstores;
1599 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1601 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1603 class backup_activity_logstores_structure_step extends backup_course_logstores_structure_step {
1607 * Course competencies backup structure step.
1609 class backup_course_competencies_structure_step extends backup_structure_step {
1611 protected function define_structure() {
1612 $userinfo = $this->get_setting_value('users');
1614 $wrapper = new backup_nested_element('course_competencies');
1616 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1617 $wrapper->add_child($settings);
1619 $sql = 'SELECT s.pushratingstouserplans
1620 FROM {' . \core_competency\course_competency_settings::TABLE . '} s
1621 WHERE s.courseid = :courseid';
1622 $settings->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1624 $competencies = new backup_nested_element('competencies');
1625 $wrapper->add_child($competencies);
1627 $competency = new backup_nested_element('competency', null, array('id', 'idnumber', 'ruleoutcome',
1628 'sortorder', 'frameworkid', 'frameworkidnumber'));
1629 $competencies->add_child($competency);
1631 $sql = 'SELECT c.id, c.idnumber, cc.ruleoutcome, cc.sortorder, f.id AS frameworkid, f.idnumber AS frameworkidnumber
1632 FROM {' . \core_competency\course_competency::TABLE . '} cc
1633 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cc.competencyid
1634 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1635 WHERE cc.courseid = :courseid
1636 ORDER BY cc.sortorder';
1637 $competency->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1639 $usercomps = new backup_nested_element('user_competencies');
1640 $wrapper->add_child($usercomps);
1641 if ($userinfo) {
1642 $usercomp = new backup_nested_element('user_competency', null, array('userid', 'competencyid',
1643 'proficiency', 'grade'));
1644 $usercomps->add_child($usercomp);
1646 $sql = 'SELECT ucc.userid, ucc.competencyid, ucc.proficiency, ucc.grade
1647 FROM {' . \core_competency\user_competency_course::TABLE . '} ucc
1648 WHERE ucc.courseid = :courseid
1649 AND ucc.grade IS NOT NULL';
1650 $usercomp->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1651 $usercomp->annotate_ids('user', 'userid');
1654 return $wrapper;
1658 * Execute conditions.
1660 * @return bool
1662 protected function execute_condition() {
1664 // Do not execute if competencies are not included.
1665 if (!$this->get_setting_value('competencies')) {
1666 return false;
1669 return true;
1674 * Activity competencies backup structure step.
1676 class backup_activity_competencies_structure_step extends backup_structure_step {
1678 protected function define_structure() {
1679 $wrapper = new backup_nested_element('course_module_competencies');
1681 $competencies = new backup_nested_element('competencies');
1682 $wrapper->add_child($competencies);
1684 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1685 'sortorder', 'frameworkidnumber'));
1686 $competencies->add_child($competency);
1688 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.sortorder, f.idnumber AS frameworkidnumber
1689 FROM {' . \core_competency\course_module_competency::TABLE . '} cmc
1690 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cmc.competencyid
1691 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1692 WHERE cmc.cmid = :coursemoduleid
1693 ORDER BY cmc.sortorder';
1694 $competency->set_source_sql($sql, array('coursemoduleid' => backup::VAR_MODID));
1696 return $wrapper;
1700 * Execute conditions.
1702 * @return bool
1704 protected function execute_condition() {
1706 // Do not execute if competencies are not included.
1707 if (!$this->get_setting_value('competencies')) {
1708 return false;
1711 return true;
1716 * structure in charge of constructing the inforef.xml file for all the items we want
1717 * to have referenced there (users, roles, files...)
1719 class backup_inforef_structure_step extends backup_structure_step {
1721 protected function define_structure() {
1723 // Items we want to include in the inforef file.
1724 $items = backup_helper::get_inforef_itemnames();
1726 // Build the tree
1728 $inforef = new backup_nested_element('inforef');
1730 // For each item, conditionally, if there are already records, build element
1731 foreach ($items as $itemname) {
1732 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1733 $elementroot = new backup_nested_element($itemname . 'ref');
1734 $element = new backup_nested_element($itemname, array(), array('id'));
1735 $inforef->add_child($elementroot);
1736 $elementroot->add_child($element);
1737 $element->set_source_sql("
1738 SELECT itemid AS id
1739 FROM {backup_ids_temp}
1740 WHERE backupid = ?
1741 AND itemname = ?",
1742 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1746 // We don't annotate anything there, but rely in the next step
1747 // (move_inforef_annotations_to_final) that will change all the
1748 // already saved 'inforref' entries to their 'final' annotations.
1749 return $inforef;
1754 * This step will get all the annotations already processed to inforef.xml file and
1755 * transform them into 'final' annotations.
1757 class move_inforef_annotations_to_final extends backup_execution_step {
1759 protected function define_execution() {
1761 // Items we want to include in the inforef file
1762 $items = backup_helper::get_inforef_itemnames();
1763 $progress = $this->task->get_progress();
1764 $progress->start_progress($this->get_name(), count($items));
1765 $done = 1;
1766 foreach ($items as $itemname) {
1767 // Delegate to dbops
1768 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1769 $itemname, $progress);
1770 $progress->progress($done++);
1772 $progress->end_progress();
1777 * structure in charge of constructing the files.xml file with all the
1778 * annotated (final) files along the process. At, the same time, and
1779 * using one specialised nested_element, will copy them form moodle storage
1780 * to backup storage
1782 class backup_final_files_structure_step extends backup_structure_step {
1784 protected function define_structure() {
1786 // Define elements
1788 $files = new backup_nested_element('files');
1790 $file = new file_nested_element('file', array('id'), array(
1791 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1792 'filepath', 'filename', 'userid', 'filesize',
1793 'mimetype', 'status', 'timecreated', 'timemodified',
1794 'source', 'author', 'license', 'sortorder',
1795 'repositorytype', 'repositoryid', 'reference'));
1797 // Build the tree
1799 $files->add_child($file);
1801 // Define sources
1803 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1804 FROM {files} f
1805 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1806 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1807 LEFT JOIN {repository} r ON r.id = ri.typeid
1808 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1809 WHERE bi.backupid = ?
1810 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1812 return $files;
1817 * Structure step in charge of creating the main moodle_backup.xml file
1818 * where all the information related to the backup, settings, license and
1819 * other information needed on restore is added*/
1820 class backup_main_structure_step extends backup_structure_step {
1822 protected function define_structure() {
1824 global $CFG;
1826 $info = array();
1828 $info['name'] = $this->get_setting_value('filename');
1829 $info['moodle_version'] = $CFG->version;
1830 $info['moodle_release'] = $CFG->release;
1831 $info['backup_version'] = $CFG->backup_version;
1832 $info['backup_release'] = $CFG->backup_release;
1833 $info['backup_date'] = time();
1834 $info['backup_uniqueid']= $this->get_backupid();
1835 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1836 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1837 $info['include_file_references_to_external_content'] =
1838 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1839 $info['original_wwwroot']=$CFG->wwwroot;
1840 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1841 $info['original_course_id'] = $this->get_courseid();
1842 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1843 $info['original_course_format'] = $originalcourseinfo->format;
1844 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1845 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1846 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1847 $info['original_course_enddate'] = $originalcourseinfo->enddate;
1848 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1849 $info['original_system_contextid'] = context_system::instance()->id;
1851 // Get more information from controller
1852 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
1853 $this->get_backupid(), $this->get_task()->get_progress());
1855 // Define elements
1857 $moodle_backup = new backup_nested_element('moodle_backup');
1859 $information = new backup_nested_element('information', null, array(
1860 'name', 'moodle_version', 'moodle_release', 'backup_version',
1861 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1862 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
1863 'original_course_fullname', 'original_course_shortname', 'original_course_startdate', 'original_course_enddate',
1864 'original_course_contextid', 'original_system_contextid'));
1866 $details = new backup_nested_element('details');
1868 $detail = new backup_nested_element('detail', array('backup_id'), array(
1869 'type', 'format', 'interactive', 'mode',
1870 'execution', 'executiontime'));
1872 $contents = new backup_nested_element('contents');
1874 $activities = new backup_nested_element('activities');
1876 $activity = new backup_nested_element('activity', null, array(
1877 'moduleid', 'sectionid', 'modulename', 'title',
1878 'directory'));
1880 $sections = new backup_nested_element('sections');
1882 $section = new backup_nested_element('section', null, array(
1883 'sectionid', 'title', 'directory'));
1885 $course = new backup_nested_element('course', null, array(
1886 'courseid', 'title', 'directory'));
1888 $settings = new backup_nested_element('settings');
1890 $setting = new backup_nested_element('setting', null, array(
1891 'level', 'section', 'activity', 'name', 'value'));
1893 // Build the tree
1895 $moodle_backup->add_child($information);
1897 $information->add_child($details);
1898 $details->add_child($detail);
1900 $information->add_child($contents);
1901 if (!empty($cinfo['activities'])) {
1902 $contents->add_child($activities);
1903 $activities->add_child($activity);
1905 if (!empty($cinfo['sections'])) {
1906 $contents->add_child($sections);
1907 $sections->add_child($section);
1909 if (!empty($cinfo['course'])) {
1910 $contents->add_child($course);
1913 $information->add_child($settings);
1914 $settings->add_child($setting);
1917 // Set the sources
1919 $information->set_source_array(array((object)$info));
1921 $detail->set_source_array($dinfo);
1923 $activity->set_source_array($cinfo['activities']);
1925 $section->set_source_array($cinfo['sections']);
1927 $course->set_source_array($cinfo['course']);
1929 $setting->set_source_array($sinfo);
1931 // Prepare some information to be sent to main moodle_backup.xml file
1932 return $moodle_backup;
1938 * Execution step that will generate the final zip (.mbz) file with all the contents
1940 class backup_zip_contents extends backup_execution_step implements file_progress {
1942 * @var bool True if we have started tracking progress
1944 protected $startedprogress;
1946 protected function define_execution() {
1948 // Get basepath
1949 $basepath = $this->get_basepath();
1951 // Get the list of files in directory
1952 $filestemp = get_directory_list($basepath, '', false, true, true);
1953 $files = array();
1954 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1955 $files[$file] = $basepath . '/' . $file;
1958 // Add the log file if exists
1959 $logfilepath = $basepath . '.log';
1960 if (file_exists($logfilepath)) {
1961 $files['moodle_backup.log'] = $logfilepath;
1964 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1965 $zipfile = $basepath . '/backup.mbz';
1967 // Get the zip packer
1968 $zippacker = get_file_packer('application/vnd.moodle.backup');
1970 // Track overall progress for the 2 long-running steps (archive to
1971 // pathname, get backup information).
1972 $reporter = $this->task->get_progress();
1973 $reporter->start_progress('backup_zip_contents', 2);
1975 // Zip files
1976 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1978 // If any sub-progress happened, end it.
1979 if ($this->startedprogress) {
1980 $this->task->get_progress()->end_progress();
1981 $this->startedprogress = false;
1982 } else {
1983 // No progress was reported, manually move it on to the next overall task.
1984 $reporter->progress(1);
1987 // Something went wrong.
1988 if ($result === false) {
1989 @unlink($zipfile);
1990 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
1992 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
1993 try {
1994 backup_general_helper::get_backup_information_from_mbz($zipfile, $this);
1995 } catch (backup_helper_exception $e) {
1996 @unlink($zipfile);
1997 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
2000 // If any sub-progress happened, end it.
2001 if ($this->startedprogress) {
2002 $this->task->get_progress()->end_progress();
2003 $this->startedprogress = false;
2004 } else {
2005 $reporter->progress(2);
2007 $reporter->end_progress();
2011 * Implementation for file_progress interface to display unzip progress.
2013 * @param int $progress Current progress
2014 * @param int $max Max value
2016 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
2017 $reporter = $this->task->get_progress();
2019 // Start tracking progress if necessary.
2020 if (!$this->startedprogress) {
2021 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
2022 ? \core\progress\base::INDETERMINATE : $max);
2023 $this->startedprogress = true;
2026 // Pass progress through to whatever handles it.
2027 $reporter->progress(($progress == file_progress::INDETERMINATE)
2028 ? \core\progress\base::INDETERMINATE : $progress);
2033 * This step will send the generated backup file to its final destination
2035 class backup_store_backup_file extends backup_execution_step {
2037 protected function define_execution() {
2039 // Get basepath
2040 $basepath = $this->get_basepath();
2042 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
2043 $zipfile = $basepath . '/backup.mbz';
2045 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
2046 // Perform storage and return it (TODO: shouldn't be array but proper result object)
2047 return array(
2048 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
2049 $this->task->get_progress()),
2050 'include_file_references_to_external_content' => $has_file_references
2057 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
2058 * and put them to the backup_ids tables, to be used later as base to backup them
2060 class backup_activity_grade_items_to_ids extends backup_execution_step {
2062 protected function define_execution() {
2064 // Fetch all activity grade items
2065 if ($items = grade_item::fetch_all(array(
2066 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
2067 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
2068 // Annotate them in backup_ids
2069 foreach ($items as $item) {
2070 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
2078 * This step allows enrol plugins to annotate custom fields.
2080 * @package core_backup
2081 * @copyright 2014 University of Wisconsin
2082 * @author Matt Petro
2083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2085 class backup_enrolments_execution_step extends backup_execution_step {
2088 * Function that will contain all the code to be executed.
2090 protected function define_execution() {
2091 global $DB;
2093 $plugins = enrol_get_plugins(true);
2094 $enrols = $DB->get_records('enrol', array(
2095 'courseid' => $this->task->get_courseid()));
2097 // Allow each enrol plugin to add annotations.
2098 foreach ($enrols as $enrol) {
2099 if (isset($plugins[$enrol->enrol])) {
2100 $plugins[$enrol->enrol]->backup_annotate_custom_fields($this, $enrol);
2106 * Annotate a single name/id pair.
2107 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
2109 * @param string $itemname
2110 * @param int $itemid
2112 public function annotate_id($itemname, $itemid) {
2113 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2118 * This step will annotate all the groups and groupings belonging to the course
2120 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
2122 protected function define_execution() {
2123 global $DB;
2125 // Get all the course groups
2126 if ($groups = $DB->get_records('groups', array(
2127 'courseid' => $this->task->get_courseid()))) {
2128 foreach ($groups as $group) {
2129 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
2133 // Get all the course groupings
2134 if ($groupings = $DB->get_records('groupings', array(
2135 'courseid' => $this->task->get_courseid()))) {
2136 foreach ($groupings as $grouping) {
2137 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
2144 * This step will annotate all the groups belonging to already annotated groupings
2146 class backup_annotate_groups_from_groupings extends backup_execution_step {
2148 protected function define_execution() {
2149 global $DB;
2151 // Fetch all the annotated groupings
2152 if ($groupings = $DB->get_records('backup_ids_temp', array(
2153 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2154 foreach ($groupings as $grouping) {
2155 if ($groups = $DB->get_records('groupings_groups', array(
2156 'groupingid' => $grouping->itemid))) {
2157 foreach ($groups as $group) {
2158 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
2167 * This step will annotate all the scales belonging to already annotated outcomes
2169 class backup_annotate_scales_from_outcomes extends backup_execution_step {
2171 protected function define_execution() {
2172 global $DB;
2174 // Fetch all the annotated outcomes
2175 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2176 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2177 foreach ($outcomes as $outcome) {
2178 if ($scale = $DB->get_record('grade_outcomes', array(
2179 'id' => $outcome->itemid))) {
2180 // Annotate as scalefinal because it's > 0
2181 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
2189 * This step will generate all the file annotations for the already
2190 * annotated (final) question_categories. It calculates the different
2191 * contexts that are being backup and, annotates all the files
2192 * on every context belonging to the "question" component. As far as
2193 * we are always including *complete* question banks it is safe and
2194 * optimal to do that in this (one pass) way
2196 class backup_annotate_all_question_files extends backup_execution_step {
2198 protected function define_execution() {
2199 global $DB;
2201 // Get all the different contexts for the final question_categories
2202 // annotated along the whole backup
2203 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2204 FROM {question_categories} qc
2205 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2206 WHERE bi.backupid = ?
2207 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2208 // To know about qtype specific components/fileareas
2209 $components = backup_qtype_plugin::get_components_and_fileareas();
2210 // Let's loop
2211 foreach($rs as $record) {
2212 // Backup all the file areas the are managed by the core question component.
2213 // That is, by the question_type base class. In particular, we don't want
2214 // to include files belonging to responses here.
2215 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'questiontext', null);
2216 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'generalfeedback', null);
2217 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answer', null);
2218 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answerfeedback', null);
2219 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'hint', null);
2220 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'correctfeedback', null);
2221 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'partiallycorrectfeedback', null);
2222 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'incorrectfeedback', null);
2224 // For files belonging to question types, we make the leap of faith that
2225 // all the files belonging to the question type are part of the question definition,
2226 // so we can just backup all the files in bulk, without specifying each
2227 // file area name separately.
2228 foreach ($components as $component => $fileareas) {
2229 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
2232 $rs->close();
2237 * structure step in charge of constructing the questions.xml file for all the
2238 * question categories and questions required by the backup
2239 * and letters related to one activity
2241 class backup_questions_structure_step extends backup_structure_step {
2243 protected function define_structure() {
2245 // Define each element separated
2247 $qcategories = new backup_nested_element('question_categories');
2249 $qcategory = new backup_nested_element('question_category', array('id'), array(
2250 'name', 'contextid', 'contextlevel', 'contextinstanceid',
2251 'info', 'infoformat', 'stamp', 'parent',
2252 'sortorder', 'idnumber'));
2254 $questions = new backup_nested_element('questions');
2256 $question = new backup_nested_element('question', array('id'), array(
2257 'parent', 'name', 'questiontext', 'questiontextformat',
2258 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
2259 'qtype', 'length', 'stamp', 'version',
2260 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby', 'idnumber'));
2262 // attach qtype plugin structure to $question element, only one allowed
2263 $this->add_plugin_structure('qtype', $question, false);
2265 // attach local plugin stucture to $question element, multiple allowed
2266 $this->add_plugin_structure('local', $question, true);
2268 $qhints = new backup_nested_element('question_hints');
2270 $qhint = new backup_nested_element('question_hint', array('id'), array(
2271 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
2273 $tags = new backup_nested_element('tags');
2275 $tag = new backup_nested_element('tag', array('id', 'contextid'), array('name', 'rawname'));
2277 // Build the tree
2279 $qcategories->add_child($qcategory);
2280 $qcategory->add_child($questions);
2281 $questions->add_child($question);
2282 $question->add_child($qhints);
2283 $qhints->add_child($qhint);
2285 $question->add_child($tags);
2286 $tags->add_child($tag);
2288 // Define the sources
2290 $qcategory->set_source_sql("
2291 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
2292 FROM {question_categories} gc
2293 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2294 JOIN {context} co ON co.id = gc.contextid
2295 WHERE bi.backupid = ?
2296 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
2298 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
2300 $qhint->set_source_sql('
2301 SELECT *
2302 FROM {question_hints}
2303 WHERE questionid = :questionid
2304 ORDER BY id',
2305 array('questionid' => backup::VAR_PARENTID));
2307 $tag->set_source_sql("SELECT t.id, ti.contextid, t.name, t.rawname
2308 FROM {tag} t
2309 JOIN {tag_instance} ti ON ti.tagid = t.id
2310 WHERE ti.itemid = ?
2311 AND ti.itemtype = 'question'
2312 AND ti.component = 'core_question'",
2314 backup::VAR_PARENTID
2317 // don't need to annotate ids nor files
2318 // (already done by {@link backup_annotate_all_question_files}
2320 return $qcategories;
2327 * This step will generate all the file annotations for the already
2328 * annotated (final) users. Need to do this here because each user
2329 * has its own context and structure tasks only are able to handle
2330 * one context. Also, this step will guarantee that every user has
2331 * its context created (req for other steps)
2333 class backup_annotate_all_user_files extends backup_execution_step {
2335 protected function define_execution() {
2336 global $DB;
2338 // List of fileareas we are going to annotate
2339 $fileareas = array('profile', 'icon');
2341 // Fetch all annotated (final) users
2342 $rs = $DB->get_recordset('backup_ids_temp', array(
2343 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2344 $progress = $this->task->get_progress();
2345 $progress->start_progress($this->get_name());
2346 foreach ($rs as $record) {
2347 $userid = $record->itemid;
2348 $userctx = context_user::instance($userid, IGNORE_MISSING);
2349 if (!$userctx) {
2350 continue; // User has not context, sure it's a deleted user, so cannot have files
2352 // Proceed with every user filearea
2353 foreach ($fileareas as $filearea) {
2354 // We don't need to specify itemid ($userid - 5th param) as far as by
2355 // context we can get all the associated files. See MDL-22092
2356 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2357 $progress->progress();
2360 $progress->end_progress();
2361 $rs->close();
2367 * Defines the backup step for advanced grading methods attached to the activity module
2369 class backup_activity_grading_structure_step extends backup_structure_step {
2372 * Include the grading.xml only if the module supports advanced grading
2374 protected function execute_condition() {
2376 // No grades on the front page.
2377 if ($this->get_courseid() == SITEID) {
2378 return false;
2381 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2385 * Declares the gradable areas structures and data sources
2387 protected function define_structure() {
2389 // To know if we are including userinfo
2390 $userinfo = $this->get_setting_value('userinfo');
2392 // Define the elements
2394 $areas = new backup_nested_element('areas');
2396 $area = new backup_nested_element('area', array('id'), array(
2397 'areaname', 'activemethod'));
2399 $definitions = new backup_nested_element('definitions');
2401 $definition = new backup_nested_element('definition', array('id'), array(
2402 'method', 'name', 'description', 'descriptionformat', 'status',
2403 'timecreated', 'timemodified', 'options'));
2405 $instances = new backup_nested_element('instances');
2407 $instance = new backup_nested_element('instance', array('id'), array(
2408 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2409 'feedbackformat', 'timemodified'));
2411 // Build the tree including the method specific structures
2412 // (beware - the order of how gradingform plugins structures are attached is important)
2413 $areas->add_child($area);
2414 // attach local plugin stucture to $area element, multiple allowed
2415 $this->add_plugin_structure('local', $area, true);
2416 $area->add_child($definitions);
2417 $definitions->add_child($definition);
2418 $this->add_plugin_structure('gradingform', $definition, true);
2419 // attach local plugin stucture to $definition element, multiple allowed
2420 $this->add_plugin_structure('local', $definition, true);
2421 $definition->add_child($instances);
2422 $instances->add_child($instance);
2423 $this->add_plugin_structure('gradingform', $instance, false);
2424 // attach local plugin stucture to $instance element, multiple allowed
2425 $this->add_plugin_structure('local', $instance, true);
2427 // Define data sources
2429 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2430 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2432 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2434 if ($userinfo) {
2435 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2438 // Annotate references
2439 $definition->annotate_files('grading', 'description', 'id');
2440 $instance->annotate_ids('user', 'raterid');
2442 // Return the root element
2443 return $areas;
2449 * structure step in charge of constructing the grades.xml file for all the grade items
2450 * and letters related to one activity
2452 class backup_activity_grades_structure_step extends backup_structure_step {
2455 * No grades on the front page.
2456 * @return bool
2458 protected function execute_condition() {
2459 return ($this->get_courseid() != SITEID);
2462 protected function define_structure() {
2463 global $CFG;
2465 require_once($CFG->libdir . '/grade/constants.php');
2467 // To know if we are including userinfo
2468 $userinfo = $this->get_setting_value('userinfo');
2470 // Define each element separated
2472 $book = new backup_nested_element('activity_gradebook');
2474 $items = new backup_nested_element('grade_items');
2476 $item = new backup_nested_element('grade_item', array('id'), array(
2477 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2478 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2479 'calculation', 'gradetype', 'grademax', 'grademin',
2480 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2481 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2482 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2483 'needsupdate', 'timecreated', 'timemodified'));
2485 $grades = new backup_nested_element('grade_grades');
2487 $grade = new backup_nested_element('grade_grade', array('id'), array(
2488 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2489 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2490 'locked', 'locktime', 'exported', 'overridden',
2491 'excluded', 'feedback', 'feedbackformat', 'information',
2492 'informationformat', 'timecreated', 'timemodified',
2493 'aggregationstatus', 'aggregationweight'));
2495 $letters = new backup_nested_element('grade_letters');
2497 $letter = new backup_nested_element('grade_letter', 'id', array(
2498 'lowerboundary', 'letter'));
2500 // Build the tree
2502 $book->add_child($items);
2503 $items->add_child($item);
2505 $item->add_child($grades);
2506 $grades->add_child($grade);
2508 $book->add_child($letters);
2509 $letters->add_child($letter);
2511 // Define sources
2513 $item->set_source_sql("SELECT gi.*
2514 FROM {grade_items} gi
2515 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2516 WHERE bi.backupid = ?
2517 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2519 // This only happens if we are including user info
2520 if ($userinfo) {
2521 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2522 $grade->annotate_files(GRADE_FILE_COMPONENT, GRADE_FEEDBACK_FILEAREA, 'id');
2525 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2527 // Annotations
2529 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2530 $item->annotate_ids('outcome', 'outcomeid');
2532 $grade->annotate_ids('user', 'userid');
2533 $grade->annotate_ids('user', 'usermodified');
2535 // Return the root element (book)
2537 return $book;
2542 * Structure step in charge of constructing the grade history of an activity.
2544 * This step is added to the task regardless of the setting 'grade_histories'.
2545 * The reason is to allow for a more flexible step in case the logic needs to be
2546 * split accross different settings to control the history of items and/or grades.
2548 class backup_activity_grade_history_structure_step extends backup_structure_step {
2551 * No grades on the front page.
2552 * @return bool
2554 protected function execute_condition() {
2555 return ($this->get_courseid() != SITEID);
2558 protected function define_structure() {
2559 global $CFG;
2561 require_once($CFG->libdir . '/grade/constants.php');
2563 // Settings to use.
2564 $userinfo = $this->get_setting_value('userinfo');
2565 $history = $this->get_setting_value('grade_histories');
2567 // Create the nested elements.
2568 $bookhistory = new backup_nested_element('grade_history');
2569 $grades = new backup_nested_element('grade_grades');
2570 $grade = new backup_nested_element('grade_grade', array('id'), array(
2571 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2572 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2573 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2574 'excluded', 'feedback', 'feedbackformat', 'information',
2575 'informationformat', 'timemodified'));
2577 // Build the tree.
2578 $bookhistory->add_child($grades);
2579 $grades->add_child($grade);
2581 // This only happens if we are including user info and history.
2582 if ($userinfo && $history) {
2583 // Define sources. Only select the history related to existing activity items.
2584 $grade->set_source_sql("SELECT ggh.*
2585 FROM {grade_grades_history} ggh
2586 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2587 WHERE bi.backupid = ?
2588 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2589 $grade->annotate_files(GRADE_FILE_COMPONENT, GRADE_HISTORY_FEEDBACK_FILEAREA, 'id');
2592 // Annotations.
2593 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2594 $grade->annotate_ids('user', 'loggeduser');
2595 $grade->annotate_ids('user', 'userid');
2596 $grade->annotate_ids('user', 'usermodified');
2598 // Return the root element.
2599 return $bookhistory;
2604 * Backups up the course completion information for the course.
2606 class backup_course_completion_structure_step extends backup_structure_step {
2608 protected function execute_condition() {
2610 // No completion on front page.
2611 if ($this->get_courseid() == SITEID) {
2612 return false;
2615 // Check that all activities have been included
2616 if ($this->task->is_excluding_activities()) {
2617 return false;
2619 return true;
2623 * The structure of the course completion backup
2625 * @return backup_nested_element
2627 protected function define_structure() {
2629 // To know if we are including user completion info
2630 $userinfo = $this->get_setting_value('userscompletion');
2632 $cc = new backup_nested_element('course_completion');
2634 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2635 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2636 'timeend', 'gradepass', 'role', 'roleshortname'
2639 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2641 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2642 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2645 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2646 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2649 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2650 'course','criteriatype','method','value'
2653 $cc->add_child($criteria);
2654 $criteria->add_child($criteriacompletions);
2655 $criteriacompletions->add_child($criteriacomplete);
2656 $cc->add_child($coursecompletions);
2657 $cc->add_child($aggregatemethod);
2659 // We need some extra data for the restore.
2660 // - courseinstances shortname rather than an ID.
2661 // - roleshortname in case restoring on a different site.
2662 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2663 FROM {course_completion_criteria} ccc
2664 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2665 LEFT JOIN {role} r ON r.id = ccc.role
2666 WHERE ccc.course = ?";
2667 $criteria->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2669 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2671 if ($userinfo) {
2672 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2673 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2676 $criteria->annotate_ids('role', 'role');
2677 $criteriacomplete->annotate_ids('user', 'userid');
2678 $coursecompletions->annotate_ids('user', 'userid');
2680 return $cc;
2686 * Backup completion defaults for each module type.
2688 * @package core_backup
2689 * @copyright 2017 Marina Glancy
2690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2692 class backup_completion_defaults_structure_step extends backup_structure_step {
2695 * To conditionally decide if one step will be executed or no
2697 protected function execute_condition() {
2698 // No completion on front page.
2699 if ($this->get_courseid() == SITEID) {
2700 return false;
2702 return true;
2706 * The structure of the course completion backup
2708 * @return backup_nested_element
2710 protected function define_structure() {
2712 $cc = new backup_nested_element('course_completion_defaults');
2714 $defaults = new backup_nested_element('course_completion_default', array('id'), array(
2715 'modulename', 'completion', 'completionview', 'completionusegrade', 'completionexpected', 'customrules'
2718 // Use module name instead of module id so we can insert into another site later.
2719 $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
2720 d.completionexpected, d.customrules
2721 FROM {course_completion_defaults} d join {modules} m on d.module = m.id
2722 WHERE d.course = ?";
2723 $defaults->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2725 $cc->add_child($defaults);
2726 return $cc;