3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Defines various backup steps that will be used by common tasks in backup
21 * @package core_backup
24 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
31 * Create the temp dir where backup/restore will happen and create temp ids table.
33 class create_and_clean_temp_stuff extends backup_execution_step {
35 protected function define_execution() {
36 $progress = $this->task->get_progress();
37 $progress->start_progress('Deleting backup directories');
38 backup_helper::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
39 backup_helper::clear_backup_dir($this->get_backupid(), $progress); // Empty temp dir, just in case
40 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
41 backup_controller_dbops::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
42 $progress->end_progress();
47 * Delete the temp dir used by backup/restore (conditionally),
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() {
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;
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() {
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);
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 {
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);
111 $activity->add_child($activitystructure);
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)
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 = '') {
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',
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'));
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);
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));
191 $qa->annotate_ids('question', 'questionid');
192 $step->annotate_ids('user', 'userid');
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);
238 $block->add_child($blockstructure);
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)
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() {
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',
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);
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
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)
317 * structure step that will generate the section.xml file for the section
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'));
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);
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
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));
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');
357 $section->annotate_files('course', 'section', 'id');
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() {
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',
379 'marker', 'maxbytes', 'legacyfiles', 'showreports',
380 'visible', 'groupmode', 'groupmodeforce',
381 'defaultgroupingid', 'lang', 'theme',
382 'timecreated', 'timemodified',
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(
394 // attach format plugin structure to $course element, only one allowed
395 $this->add_plugin_structure('format', $course, false);
397 // attach theme plugin structure to $course element; multiple themes can
398 // save course data (in case of user theme, legacy theme, etc)
399 $this->add_plugin_structure('theme', $course, true);
401 // attach general report plugin structure to $course element; multiple
402 // reports can save course data if required
403 $this->add_plugin_structure('report', $course, true);
405 // attach course report plugin structure to $course element; multiple
406 // course reports can save course data if required
407 $this->add_plugin_structure('coursereport', $course, true);
409 // attach plagiarism plugin structure to $course element, there can be potentially
410 // many plagiarism plugins storing information about this course
411 $this->add_plugin_structure('plagiarism', $course, true);
413 // attach local plugin structure to $course element; multiple local plugins
414 // can save course data if required
415 $this->add_plugin_structure('local', $course, true);
417 // Attach admin tools plugin structure to $course element; multiple plugins
418 // can save course data if required.
419 $this->add_plugin_structure('tool', $course, true);
423 $course->add_child($category);
425 $course->add_child($tags);
426 $tags->add_child($tag);
430 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
431 $courserec->contextid = $this->task->get_contextid();
433 $formatoptions = course_get_format($courserec)->get_format_options();
434 $course->add_final_elements(array_keys($formatoptions));
435 foreach ($formatoptions as $key => $value) {
436 $courserec->$key = $value;
439 $course->set_source_array(array($courserec));
441 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
443 $category->set_source_array(array($categoryrec));
445 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
447 JOIN {tag_instance} ti ON ti.tagid = t.id
448 WHERE ti.itemtype = ?
449 AND ti.itemid = ?', array(
450 backup_helper::is_sqlparam('course'),
451 backup::VAR_PARENTID));
455 $course->annotate_ids('grouping', 'defaultgroupingid');
457 $course->annotate_files('course', 'summary', null);
458 $course->annotate_files('course', 'overviewfiles', null);
459 $course->annotate_files('course', 'legacy', null);
461 // Return root element ($course)
468 * structure step that will generate the enrolments.xml file for the given course
470 class backup_enrolments_structure_step extends backup_structure_step {
473 * Skip enrolments on the front page.
476 protected function execute_condition() {
477 return ($this->get_courseid() != SITEID);
480 protected function define_structure() {
482 // To know if we are including users
483 $users = $this->get_setting_value('users');
485 // Define each element separated
487 $enrolments = new backup_nested_element('enrolments');
489 $enrols = new backup_nested_element('enrols');
491 $enrol = new backup_nested_element('enrol', array('id'), array(
492 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
493 'enrolenddate', 'expirynotify', 'expirythreshold', 'notifyall',
494 'password', 'cost', 'currency', 'roleid',
495 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
496 'customchar1', 'customchar2', 'customchar3',
497 'customdec1', 'customdec2',
498 'customtext1', 'customtext2', 'customtext3', 'customtext4',
499 'timecreated', 'timemodified'));
501 $userenrolments = new backup_nested_element('user_enrolments');
503 $enrolment = new backup_nested_element('enrolment', array('id'), array(
504 'status', 'userid', 'timestart', 'timeend', 'modifierid',
508 $enrolments->add_child($enrols);
509 $enrols->add_child($enrol);
510 $enrol->add_child($userenrolments);
511 $userenrolments->add_child($enrolment);
513 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
514 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
516 // User enrolments only added only if users included
518 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
519 $enrolment->annotate_ids('user', 'userid');
522 $enrol->annotate_ids('role', 'roleid');
524 // Add enrol plugin structure.
525 $this->add_plugin_structure('enrol', $enrol, false);
532 * structure step that will generate the roles.xml file for the given context, observing
533 * the role_assignments setting to know if that part needs to be included
535 class backup_roles_structure_step extends backup_structure_step {
537 protected function define_structure() {
539 // To know if we are including role assignments
540 $roleassignments = $this->get_setting_value('role_assignments');
542 // Define each element separated
544 $roles = new backup_nested_element('roles');
546 $overrides = new backup_nested_element('role_overrides');
548 $override = new backup_nested_element('override', array('id'), array(
549 'roleid', 'capability', 'permission', 'timemodified',
552 $assignments = new backup_nested_element('role_assignments');
554 $assignment = new backup_nested_element('assignment', array('id'), array(
555 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
559 $roles->add_child($overrides);
560 $roles->add_child($assignments);
562 $overrides->add_child($override);
563 $assignments->add_child($assignment);
567 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
569 // Assignments only added if specified
570 if ($roleassignments) {
571 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
574 // Define id annotations
575 $override->annotate_ids('role', 'roleid');
577 $assignment->annotate_ids('role', 'roleid');
579 $assignment->annotate_ids('user', 'userid');
581 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
588 * structure step that will generate the roles.xml containing the
589 * list of roles used along the whole backup process. Just raw
590 * list of used roles from role table
592 class backup_final_roles_structure_step extends backup_structure_step {
594 protected function define_structure() {
598 $rolesdef = new backup_nested_element('roles_definition');
600 $role = new backup_nested_element('role', array('id'), array(
601 'name', 'shortname', 'nameincourse', 'description',
602 'sortorder', 'archetype'));
606 $rolesdef->add_child($role);
610 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
612 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
613 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
614 WHERE bi.backupid = ?
615 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
617 // Return main element (rolesdef)
623 * structure step that will generate the scales.xml containing the
624 * list of scales used along the whole backup process.
626 class backup_final_scales_structure_step extends backup_structure_step {
628 protected function define_structure() {
632 $scalesdef = new backup_nested_element('scales_definition');
634 $scale = new backup_nested_element('scale', array('id'), array(
635 'courseid', 'userid', 'name', 'scale',
636 'description', 'descriptionformat', 'timemodified'));
640 $scalesdef->add_child($scale);
644 $scale->set_source_sql("SELECT s.*
646 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
647 WHERE bi.backupid = ?
648 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
650 // Annotate scale files (they store files in system context, so pass it instead of default one)
651 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
653 // Return main element (scalesdef)
659 * structure step that will generate the outcomes.xml containing the
660 * list of outcomes used along the whole backup process.
662 class backup_final_outcomes_structure_step extends backup_structure_step {
664 protected function define_structure() {
668 $outcomesdef = new backup_nested_element('outcomes_definition');
670 $outcome = new backup_nested_element('outcome', array('id'), array(
671 'courseid', 'userid', 'shortname', 'fullname',
672 'scaleid', 'description', 'descriptionformat', 'timecreated',
673 'timemodified','usermodified'));
677 $outcomesdef->add_child($outcome);
681 $outcome->set_source_sql("SELECT o.*
682 FROM {grade_outcomes} o
683 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
684 WHERE bi.backupid = ?
685 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
687 // Annotate outcome files (they store files in system context, so pass it instead of default one)
688 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
690 // Return main element (outcomesdef)
696 * structure step in charge of constructing the filters.xml file for all the filters found
699 class backup_filters_structure_step extends backup_structure_step {
701 protected function define_structure() {
703 // Define each element separated
705 $filters = new backup_nested_element('filters');
707 $actives = new backup_nested_element('filter_actives');
709 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
711 $configs = new backup_nested_element('filter_configs');
713 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
717 $filters->add_child($actives);
718 $filters->add_child($configs);
720 $actives->add_child($active);
721 $configs->add_child($config);
725 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
727 $active->set_source_array($activearr);
728 $config->set_source_array($configarr);
730 // Return the root element (filters)
736 * structure step in charge of constructing the comments.xml file for all the comments found
739 class backup_comments_structure_step extends backup_structure_step {
741 protected function define_structure() {
743 // Define each element separated
745 $comments = new backup_nested_element('comments');
747 $comment = new backup_nested_element('comment', array('id'), array(
748 'commentarea', 'itemid', 'content', 'format',
749 'userid', 'timecreated'));
753 $comments->add_child($comment);
757 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
759 // Define id annotations
761 $comment->annotate_ids('user', 'userid');
763 // Return the root element (comments)
769 * structure step in charge of constructing the badges.xml file for all the badges found
772 class backup_badges_structure_step extends backup_structure_step {
774 protected function execute_condition() {
775 // Check that all activities have been included.
776 if ($this->task->is_excluding_activities()) {
782 protected function define_structure() {
784 // Define each element separated.
786 $badges = new backup_nested_element('badges');
787 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
788 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
789 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
790 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron'));
792 $criteria = new backup_nested_element('criteria');
793 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
794 'criteriatype', 'method', 'description', 'descriptionformat'));
796 $parameters = new backup_nested_element('parameters');
797 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
798 'name', 'value', 'criteriatype'));
800 $manual_awards = new backup_nested_element('manual_awards');
801 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
802 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
806 $badges->add_child($badge);
807 $badge->add_child($criteria);
808 $criteria->add_child($criterion);
809 $criterion->add_child($parameters);
810 $parameters->add_child($parameter);
811 $badge->add_child($manual_awards);
812 $manual_awards->add_child($manual_award);
816 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
817 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
819 $parametersql = 'SELECT cp.*, c.criteriatype
820 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
822 WHERE critid = :critid';
823 $parameterparams = array('critid' => backup::VAR_PARENTID);
824 $parameter->set_source_sql($parametersql, $parameterparams);
826 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
828 // Define id annotations.
830 $badge->annotate_ids('user', 'usercreated');
831 $badge->annotate_ids('user', 'usermodified');
832 $criterion->annotate_ids('badge', 'badgeid');
833 $parameter->annotate_ids('criterion', 'critid');
834 $badge->annotate_files('badges', 'badgeimage', 'id');
835 $manual_award->annotate_ids('badge', 'badgeid');
836 $manual_award->annotate_ids('user', 'recipientid');
837 $manual_award->annotate_ids('user', 'issuerid');
838 $manual_award->annotate_ids('role', 'issuerrole');
840 // Return the root element ($badges).
846 * structure step in charge of constructing the calender.xml file for all the events found
849 class backup_calendarevents_structure_step extends backup_structure_step {
851 protected function define_structure() {
853 // Define each element separated
855 $events = new backup_nested_element('events');
857 $event = new backup_nested_element('event', array('id'), array(
858 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
859 'repeatid', 'modulename', 'instance', 'eventtype', 'timestart',
860 'timeduration', 'visible', 'uuid', 'sequence', 'timemodified'));
863 $events->add_child($event);
866 if ($this->name == 'course_calendar') {
867 $calendar_items_sql ="SELECT * FROM {event}
868 WHERE courseid = :courseid
869 AND (eventtype = 'course' OR eventtype = 'group')";
870 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
871 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
873 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
876 // Define id annotations
878 $event->annotate_ids('user', 'userid');
879 $event->annotate_ids('group', 'groupid');
880 $event->annotate_files('calendar', 'event_description', 'id');
882 // Return the root element (events)
888 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
889 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
891 class backup_gradebook_structure_step extends backup_structure_step {
894 * We need to decide conditionally, based on dynamic information
895 * about the execution of this step. Only will be executed if all
896 * the module gradeitems have been already included in backup
898 protected function execute_condition() {
899 $courseid = $this->get_courseid();
900 if ($courseid == SITEID) {
904 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
907 protected function define_structure() {
910 // are we including user info?
911 $userinfo = $this->get_setting_value('users');
913 $gradebook = new backup_nested_element('gradebook');
915 //grade_letters are done in backup_activity_grades_structure_step()
917 //calculated grade items
918 $grade_items = new backup_nested_element('grade_items');
919 $grade_item = new backup_nested_element('grade_item', array('id'), array(
920 'categoryid', 'itemname', 'itemtype', 'itemmodule',
921 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
922 'calculation', 'gradetype', 'grademax', 'grademin',
923 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
924 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
925 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
926 'needsupdate', 'timecreated', 'timemodified'));
928 $grade_grades = new backup_nested_element('grade_grades');
929 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
930 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
931 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
932 'locked', 'locktime', 'exported', 'overridden',
933 'excluded', 'feedback', 'feedbackformat', 'information',
934 'informationformat', 'timecreated', 'timemodified',
935 'aggregationstatus', 'aggregationweight'));
938 $grade_categories = new backup_nested_element('grade_categories');
939 $grade_category = new backup_nested_element('grade_category', array('id'), array(
941 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
942 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
943 'timecreated', 'timemodified', 'hidden'));
945 $letters = new backup_nested_element('grade_letters');
946 $letter = new backup_nested_element('grade_letter', 'id', array(
947 'lowerboundary', 'letter'));
949 $grade_settings = new backup_nested_element('grade_settings');
950 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
955 $gradebook->add_child($grade_categories);
956 $grade_categories->add_child($grade_category);
958 $gradebook->add_child($grade_items);
959 $grade_items->add_child($grade_item);
960 $grade_item->add_child($grade_grades);
961 $grade_grades->add_child($grade_grade);
963 $gradebook->add_child($letters);
964 $letters->add_child($letter);
966 $gradebook->add_child($grade_settings);
967 $grade_settings->add_child($grade_setting);
969 // Add attribute with gradebook calculation freeze date if needed.
970 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
971 if ($gradebookcalculationfreeze) {
972 $gradebook->add_attributes(array('calculations_freeze'));
973 $gradebook->get_attribute('calculations_freeze')->set_value($gradebookcalculationfreeze);
978 //Include manual, category and the course grade item
979 $grade_items_sql ="SELECT * FROM {grade_items}
980 WHERE courseid = :courseid
981 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
982 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
983 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
986 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
989 $grade_category_sql = "SELECT gc.*, gi.sortorder
990 FROM {grade_categories} gc
991 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
992 WHERE gc.courseid = :courseid
993 AND (gi.itemtype='course' OR gi.itemtype='category')
994 ORDER BY gc.parent ASC";//need parent categories before their children
995 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
996 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
998 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1000 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1001 $settings = array();
1002 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1003 foreach ($rs as $record) {
1004 $settings[$record->name] = $record;
1007 if (!isset($settings['minmaxtouse'])) {
1008 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse);
1010 $grade_setting->set_source_array($settings);
1013 // Annotations (both as final as far as they are going to be exported in next steps)
1014 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1015 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1017 //just in case there are any users not already annotated by the activities
1018 $grade_grade->annotate_ids('userfinal', 'userid');
1020 // Return the root element
1026 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1028 class backup_grade_history_structure_step extends backup_structure_step {
1031 * Limit the execution.
1033 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1034 * because we do not want to save the history of items which are not backed up. At least for now.
1036 protected function execute_condition() {
1037 $courseid = $this->get_courseid();
1038 if ($courseid == SITEID) {
1042 return backup_plan_dbops::require_gradebook_backup($courseid, $this->get_backupid());
1045 protected function define_structure() {
1048 $userinfo = $this->get_setting_value('users');
1049 $history = $this->get_setting_value('grade_histories');
1051 // Create the nested elements.
1052 $bookhistory = new backup_nested_element('grade_history');
1053 $grades = new backup_nested_element('grade_grades');
1054 $grade = new backup_nested_element('grade_grade', array('id'), array(
1055 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1056 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1057 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1058 'excluded', 'feedback', 'feedbackformat', 'information',
1059 'informationformat', 'timemodified'));
1062 $bookhistory->add_child($grades);
1063 $grades->add_child($grade);
1065 // This only happens if we are including user info and history.
1066 if ($userinfo && $history) {
1067 // Only keep the history of grades related to items which have been backed up, The query is
1068 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1069 $gradesql = "SELECT ggh.*
1070 FROM {grade_grades_history} ggh
1071 JOIN {grade_items} gi ON ggh.itemid = gi.id
1072 WHERE gi.courseid = :courseid
1073 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1074 $grade->set_source_sql($gradesql, array('courseid' => backup::VAR_COURSEID));
1077 // Annotations. (Final annotations as this step is part of the final task).
1078 $grade->annotate_ids('scalefinal', 'rawscaleid');
1079 $grade->annotate_ids('userfinal', 'loggeduser');
1080 $grade->annotate_ids('userfinal', 'userid');
1081 $grade->annotate_ids('userfinal', 'usermodified');
1083 // Return the root element.
1084 return $bookhistory;
1090 * structure step in charge if constructing the completion.xml file for all the users completion
1091 * information in a given activity
1093 class backup_userscompletion_structure_step extends backup_structure_step {
1096 * Skip completion on the front page.
1099 protected function execute_condition() {
1100 return ($this->get_courseid() != SITEID);
1103 protected function define_structure() {
1105 // Define each element separated
1107 $completions = new backup_nested_element('completions');
1109 $completion = new backup_nested_element('completion', array('id'), array(
1110 'userid', 'completionstate', 'viewed', 'timemodified'));
1114 $completions->add_child($completion);
1118 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1120 // Define id annotations
1122 $completion->annotate_ids('user', 'userid');
1124 // Return the root element (completions)
1125 return $completions;
1130 * structure step in charge of constructing the main groups.xml file for all the groups and
1131 * groupings information already annotated
1133 class backup_groups_structure_step extends backup_structure_step {
1135 protected function define_structure() {
1137 // To know if we are including users.
1138 $userinfo = $this->get_setting_value('users');
1139 // To know if we are including groups and groupings.
1140 $groupinfo = $this->get_setting_value('groups');
1142 // Define each element separated
1144 $groups = new backup_nested_element('groups');
1146 $group = new backup_nested_element('group', array('id'), array(
1147 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1148 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1150 $members = new backup_nested_element('group_members');
1152 $member = new backup_nested_element('group_member', array('id'), array(
1153 'userid', 'timeadded', 'component', 'itemid'));
1155 $groupings = new backup_nested_element('groupings');
1157 $grouping = new backup_nested_element('grouping', 'id', array(
1158 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1159 'timecreated', 'timemodified'));
1161 $groupinggroups = new backup_nested_element('grouping_groups');
1163 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1164 'groupid', 'timeadded'));
1168 $groups->add_child($group);
1169 $groups->add_child($groupings);
1171 $group->add_child($members);
1172 $members->add_child($member);
1174 $groupings->add_child($grouping);
1175 $grouping->add_child($groupinggroups);
1176 $groupinggroups->add_child($groupinggroup);
1180 // This only happens if we are including groups/groupings.
1182 $group->set_source_sql("
1185 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1186 WHERE bi.backupid = ?
1187 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1189 $grouping->set_source_sql("
1192 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1193 WHERE bi.backupid = ?
1194 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1195 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1197 // This only happens if we are including users.
1199 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1203 // Define id annotations (as final)
1205 $member->annotate_ids('userfinal', 'userid');
1207 // Define file annotations
1209 $group->annotate_files('group', 'description', 'id');
1210 $group->annotate_files('group', 'icon', 'id');
1211 $grouping->annotate_files('grouping', 'description', 'id');
1213 // Return the root element (groups)
1219 * structure step in charge of constructing the main users.xml file for all the users already
1220 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1223 class backup_users_structure_step extends backup_structure_step {
1225 protected function define_structure() {
1228 // To know if we are anonymizing users
1229 $anonymize = $this->get_setting_value('anonymize');
1230 // To know if we are including role assignments
1231 $roleassignments = $this->get_setting_value('role_assignments');
1233 // Define each element separate.
1235 $users = new backup_nested_element('users');
1237 // Create the array of user fields by hand, as far as we have various bits to control
1238 // anonymize option, password backup, mnethostid...
1240 // First, the fields not needing anonymization nor special handling
1241 $normalfields = array(
1242 'confirmed', 'policyagreed', 'deleted',
1243 'lang', 'theme', 'timezone', 'firstaccess',
1244 'lastaccess', 'lastlogin', 'currentlogin',
1245 'mailformat', 'maildigest', 'maildisplay',
1246 'autosubscribe', 'trackforums', 'timecreated',
1247 'timemodified', 'trustbitmask');
1249 // Then, the fields potentially needing anonymization
1250 $anonfields = array(
1251 'username', 'idnumber', 'email', 'icq', 'skype',
1252 'yahoo', 'aim', 'msn', 'phone1',
1253 'phone2', 'institution', 'department', 'address',
1254 'city', 'country', 'lastip', 'picture',
1255 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1256 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1258 // Add anonymized fields to $userfields with custom final element
1259 foreach ($anonfields as $field) {
1261 $userfields[] = new anonymizer_final_element($field);
1263 $userfields[] = $field; // No anonymization, normally added
1267 // mnethosturl requires special handling (custom final element)
1268 $userfields[] = new mnethosturl_final_element('mnethosturl');
1270 // password added conditionally
1271 if (!empty($CFG->includeuserpasswordsinbackup)) {
1272 $userfields[] = 'password';
1275 // Merge all the fields
1276 $userfields = array_merge($userfields, $normalfields);
1278 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1280 $customfields = new backup_nested_element('custom_fields');
1282 $customfield = new backup_nested_element('custom_field', array('id'), array(
1283 'field_name', 'field_type', 'field_data'));
1285 $tags = new backup_nested_element('tags');
1287 $tag = new backup_nested_element('tag', array('id'), array(
1288 'name', 'rawname'));
1290 $preferences = new backup_nested_element('preferences');
1292 $preference = new backup_nested_element('preference', array('id'), array(
1295 $roles = new backup_nested_element('roles');
1297 $overrides = new backup_nested_element('role_overrides');
1299 $override = new backup_nested_element('override', array('id'), array(
1300 'roleid', 'capability', 'permission', 'timemodified',
1303 $assignments = new backup_nested_element('role_assignments');
1305 $assignment = new backup_nested_element('assignment', array('id'), array(
1306 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1311 $users->add_child($user);
1313 $user->add_child($customfields);
1314 $customfields->add_child($customfield);
1316 $user->add_child($tags);
1317 $tags->add_child($tag);
1319 $user->add_child($preferences);
1320 $preferences->add_child($preference);
1322 $user->add_child($roles);
1324 $roles->add_child($overrides);
1325 $roles->add_child($assignments);
1327 $overrides->add_child($override);
1328 $assignments->add_child($assignment);
1332 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1334 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1335 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1336 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1337 WHERE bi.backupid = ?
1338 AND bi.itemname = ?', array(
1339 backup_helper::is_sqlparam($this->get_backupid()),
1340 backup_helper::is_sqlparam('userfinal')));
1342 // All the rest on information is only added if we arent
1343 // in an anonymized backup
1345 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1346 FROM {user_info_field} f
1347 JOIN {user_info_data} d ON d.fieldid = f.id
1348 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1350 $customfield->set_source_alias('shortname', 'field_name');
1351 $customfield->set_source_alias('datatype', 'field_type');
1352 $customfield->set_source_alias('data', 'field_data');
1354 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1356 JOIN {tag_instance} ti ON ti.tagid = t.id
1357 WHERE ti.itemtype = ?
1358 AND ti.itemid = ?', array(
1359 backup_helper::is_sqlparam('user'),
1360 backup::VAR_PARENTID));
1362 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1364 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1366 // Assignments only added if specified
1367 if ($roleassignments) {
1368 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1371 // Define id annotations (as final)
1372 $override->annotate_ids('rolefinal', 'roleid');
1375 // Return root element (users)
1381 * structure step in charge of constructing the block.xml file for one
1382 * given block (instance and positions). If the block has custom DB structure
1383 * that will go to a separate file (different step defined in block class)
1385 class backup_block_instance_structure_step extends backup_structure_step {
1387 protected function define_structure() {
1390 // Define each element separated
1392 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1393 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1394 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1396 $positions = new backup_nested_element('block_positions');
1398 $position = new backup_nested_element('block_position', array('id'), array(
1399 'contextid', 'pagetype', 'subpage', 'visible',
1400 'region', 'weight'));
1404 $block->add_child($positions);
1405 $positions->add_child($position);
1407 // Transform configdata information if needed (process links and friends)
1408 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1409 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1410 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1411 foreach ($configdata as $attribute => $value) {
1412 if (in_array($attribute, $attrstotransform)) {
1413 $configdata[$attribute] = $this->contenttransformer->process($value);
1416 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1418 $blockrec->contextid = $this->task->get_contextid();
1419 // Get the version of the block
1420 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1424 $block->set_source_array(array($blockrec));
1426 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1428 // File anotations (for fileareas specified on each block)
1429 foreach ($this->task->get_fileareas() as $filearea) {
1430 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1433 // Return the root element (block)
1439 * structure step in charge of constructing the logs.xml file for all the log records found
1440 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1441 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1442 * that just in case they become restored some day in the future
1444 class backup_course_logs_structure_step extends backup_structure_step {
1446 protected function define_structure() {
1448 // Define each element separated
1450 $logs = new backup_nested_element('logs');
1452 $log = new backup_nested_element('log', array('id'), array(
1453 'time', 'userid', 'ip', 'module',
1454 'action', 'url', 'info'));
1458 $logs->add_child($log);
1460 // Define sources (all the records belonging to the course, having cmid = 0)
1462 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1465 // NOTE: We don't annotate users from logs as far as they MUST be
1466 // always annotated by the course (enrol, ras... whatever)
1468 // Return the root element (logs)
1475 * structure step in charge of constructing the logs.xml file for all the log records found
1478 class backup_activity_logs_structure_step extends backup_structure_step {
1480 protected function define_structure() {
1482 // Define each element separated
1484 $logs = new backup_nested_element('logs');
1486 $log = new backup_nested_element('log', array('id'), array(
1487 'time', 'userid', 'ip', 'module',
1488 'action', 'url', 'info'));
1492 $logs->add_child($log);
1496 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1499 // NOTE: We don't annotate users from logs as far as they MUST be
1500 // always annotated by the activity (true participants).
1502 // Return the root element (logs)
1509 * Structure step in charge of constructing the logstores.xml file for the course logs.
1511 * This backup step will backup the logs for all the enabled logstore subplugins supporting
1512 * it, for logs belonging to the course level.
1514 class backup_course_logstores_structure_step extends backup_structure_step {
1516 protected function define_structure() {
1518 // Define the structure of logstores container.
1519 $logstores = new backup_nested_element('logstores');
1520 $logstore = new backup_nested_element('logstore');
1521 $logstores->add_child($logstore);
1523 // Add the tool_log logstore subplugins information to the logstore element.
1524 $this->add_subplugin_structure('logstore', $logstore, true, 'tool', 'log');
1531 * Structure step in charge of constructing the logstores.xml file for the activity logs.
1533 * Note: Activity structure is completely equivalent to the course one, so just extend it.
1535 class backup_activity_logstores_structure_step extends backup_course_logstores_structure_step {
1539 * Course competencies backup structure step.
1541 class backup_course_competencies_structure_step extends backup_structure_step {
1543 protected function define_structure() {
1544 $wrapper = new backup_nested_element('course_competencies');
1546 $settings = new backup_nested_element('settings', array('id'), array('pushratingstouserplans'));
1547 $wrapper->add_child($settings);
1549 $sql = 'SELECT s.pushratingstouserplans
1550 FROM {' . \core_competency\course_competency_settings::TABLE . '} s
1551 WHERE s.courseid = :courseid';
1552 $settings->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1554 $competencies = new backup_nested_element('competencies');
1555 $wrapper->add_child($competencies);
1557 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1558 'sortorder', 'frameworkidnumber'));
1559 $competencies->add_child($competency);
1561 $sql = 'SELECT c.idnumber, cc.ruleoutcome, cc.sortorder, f.idnumber AS frameworkidnumber
1562 FROM {' . \core_competency\course_competency::TABLE . '} cc
1563 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cc.competencyid
1564 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1565 WHERE cc.courseid = :courseid
1566 ORDER BY cc.sortorder';
1567 $competency->set_source_sql($sql, array('courseid' => backup::VAR_COURSEID));
1574 * Activity competencies backup structure step.
1576 class backup_activity_competencies_structure_step extends backup_structure_step {
1578 protected function define_structure() {
1579 $wrapper = new backup_nested_element('course_module_competencies');
1581 $competencies = new backup_nested_element('competencies');
1582 $wrapper->add_child($competencies);
1584 $competency = new backup_nested_element('competency', null, array('idnumber', 'ruleoutcome',
1585 'sortorder', 'frameworkidnumber'));
1586 $competencies->add_child($competency);
1588 $sql = 'SELECT c.idnumber, cmc.ruleoutcome, cmc.sortorder, f.idnumber AS frameworkidnumber
1589 FROM {' . \core_competency\course_module_competency::TABLE . '} cmc
1590 JOIN {' . \core_competency\competency::TABLE . '} c ON c.id = cmc.competencyid
1591 JOIN {' . \core_competency\competency_framework::TABLE . '} f ON f.id = c.competencyframeworkid
1592 WHERE cmc.cmid = :coursemoduleid
1593 ORDER BY cmc.sortorder';
1594 $competency->set_source_sql($sql, array('coursemoduleid' => backup::VAR_MODID));
1601 * structure in charge of constructing the inforef.xml file for all the items we want
1602 * to have referenced there (users, roles, files...)
1604 class backup_inforef_structure_step extends backup_structure_step {
1606 protected function define_structure() {
1608 // Items we want to include in the inforef file.
1609 $items = backup_helper::get_inforef_itemnames();
1613 $inforef = new backup_nested_element('inforef');
1615 // For each item, conditionally, if there are already records, build element
1616 foreach ($items as $itemname) {
1617 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1618 $elementroot = new backup_nested_element($itemname . 'ref');
1619 $element = new backup_nested_element($itemname, array(), array('id'));
1620 $inforef->add_child($elementroot);
1621 $elementroot->add_child($element);
1622 $element->set_source_sql("
1624 FROM {backup_ids_temp}
1627 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1631 // We don't annotate anything there, but rely in the next step
1632 // (move_inforef_annotations_to_final) that will change all the
1633 // already saved 'inforref' entries to their 'final' annotations.
1639 * This step will get all the annotations already processed to inforef.xml file and
1640 * transform them into 'final' annotations.
1642 class move_inforef_annotations_to_final extends backup_execution_step {
1644 protected function define_execution() {
1646 // Items we want to include in the inforef file
1647 $items = backup_helper::get_inforef_itemnames();
1648 $progress = $this->task->get_progress();
1649 $progress->start_progress($this->get_name(), count($items));
1651 foreach ($items as $itemname) {
1652 // Delegate to dbops
1653 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1654 $itemname, $progress);
1655 $progress->progress($done++);
1657 $progress->end_progress();
1662 * structure in charge of constructing the files.xml file with all the
1663 * annotated (final) files along the process. At, the same time, and
1664 * using one specialised nested_element, will copy them form moodle storage
1667 class backup_final_files_structure_step extends backup_structure_step {
1669 protected function define_structure() {
1673 $files = new backup_nested_element('files');
1675 $file = new file_nested_element('file', array('id'), array(
1676 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1677 'filepath', 'filename', 'userid', 'filesize',
1678 'mimetype', 'status', 'timecreated', 'timemodified',
1679 'source', 'author', 'license', 'sortorder',
1680 'repositorytype', 'repositoryid', 'reference'));
1684 $files->add_child($file);
1688 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1690 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1691 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1692 LEFT JOIN {repository} r ON r.id = ri.typeid
1693 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1694 WHERE bi.backupid = ?
1695 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1702 * Structure step in charge of creating the main moodle_backup.xml file
1703 * where all the information related to the backup, settings, license and
1704 * other information needed on restore is added*/
1705 class backup_main_structure_step extends backup_structure_step {
1707 protected function define_structure() {
1713 $info['name'] = $this->get_setting_value('filename');
1714 $info['moodle_version'] = $CFG->version;
1715 $info['moodle_release'] = $CFG->release;
1716 $info['backup_version'] = $CFG->backup_version;
1717 $info['backup_release'] = $CFG->backup_release;
1718 $info['backup_date'] = time();
1719 $info['backup_uniqueid']= $this->get_backupid();
1720 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1721 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1722 $info['include_file_references_to_external_content'] =
1723 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1724 $info['original_wwwroot']=$CFG->wwwroot;
1725 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1726 $info['original_course_id'] = $this->get_courseid();
1727 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1728 $info['original_course_format'] = $originalcourseinfo->format;
1729 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1730 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1731 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1732 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1733 $info['original_system_contextid'] = context_system::instance()->id;
1735 // Get more information from controller
1736 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
1737 $this->get_backupid(), $this->get_task()->get_progress());
1741 $moodle_backup = new backup_nested_element('moodle_backup');
1743 $information = new backup_nested_element('information', null, array(
1744 'name', 'moodle_version', 'moodle_release', 'backup_version',
1745 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1746 'original_site_identifier_hash', 'original_course_id', 'original_course_format',
1747 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1748 'original_course_contextid', 'original_system_contextid'));
1750 $details = new backup_nested_element('details');
1752 $detail = new backup_nested_element('detail', array('backup_id'), array(
1753 'type', 'format', 'interactive', 'mode',
1754 'execution', 'executiontime'));
1756 $contents = new backup_nested_element('contents');
1758 $activities = new backup_nested_element('activities');
1760 $activity = new backup_nested_element('activity', null, array(
1761 'moduleid', 'sectionid', 'modulename', 'title',
1764 $sections = new backup_nested_element('sections');
1766 $section = new backup_nested_element('section', null, array(
1767 'sectionid', 'title', 'directory'));
1769 $course = new backup_nested_element('course', null, array(
1770 'courseid', 'title', 'directory'));
1772 $settings = new backup_nested_element('settings');
1774 $setting = new backup_nested_element('setting', null, array(
1775 'level', 'section', 'activity', 'name', 'value'));
1779 $moodle_backup->add_child($information);
1781 $information->add_child($details);
1782 $details->add_child($detail);
1784 $information->add_child($contents);
1785 if (!empty($cinfo['activities'])) {
1786 $contents->add_child($activities);
1787 $activities->add_child($activity);
1789 if (!empty($cinfo['sections'])) {
1790 $contents->add_child($sections);
1791 $sections->add_child($section);
1793 if (!empty($cinfo['course'])) {
1794 $contents->add_child($course);
1797 $information->add_child($settings);
1798 $settings->add_child($setting);
1803 $information->set_source_array(array((object)$info));
1805 $detail->set_source_array($dinfo);
1807 $activity->set_source_array($cinfo['activities']);
1809 $section->set_source_array($cinfo['sections']);
1811 $course->set_source_array($cinfo['course']);
1813 $setting->set_source_array($sinfo);
1815 // Prepare some information to be sent to main moodle_backup.xml file
1816 return $moodle_backup;
1822 * Execution step that will generate the final zip (.mbz) file with all the contents
1824 class backup_zip_contents extends backup_execution_step implements file_progress {
1826 * @var bool True if we have started tracking progress
1828 protected $startedprogress;
1830 protected function define_execution() {
1833 $basepath = $this->get_basepath();
1835 // Get the list of files in directory
1836 $filestemp = get_directory_list($basepath, '', false, true, true);
1838 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1839 $files[$file] = $basepath . '/' . $file;
1842 // Add the log file if exists
1843 $logfilepath = $basepath . '.log';
1844 if (file_exists($logfilepath)) {
1845 $files['moodle_backup.log'] = $logfilepath;
1848 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1849 $zipfile = $basepath . '/backup.mbz';
1851 // Get the zip packer
1852 $zippacker = get_file_packer('application/vnd.moodle.backup');
1854 // Track overall progress for the 2 long-running steps (archive to
1855 // pathname, get backup information).
1856 $reporter = $this->task->get_progress();
1857 $reporter->start_progress('backup_zip_contents', 2);
1860 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1862 // If any sub-progress happened, end it.
1863 if ($this->startedprogress) {
1864 $this->task->get_progress()->end_progress();
1865 $this->startedprogress = false;
1867 // No progress was reported, manually move it on to the next overall task.
1868 $reporter->progress(1);
1871 // Something went wrong.
1872 if ($result === false) {
1874 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
1876 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
1878 backup_general_helper::get_backup_information_from_mbz($zipfile, $this);
1879 } catch (backup_helper_exception $e) {
1881 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
1884 // If any sub-progress happened, end it.
1885 if ($this->startedprogress) {
1886 $this->task->get_progress()->end_progress();
1887 $this->startedprogress = false;
1889 $reporter->progress(2);
1891 $reporter->end_progress();
1895 * Implementation for file_progress interface to display unzip progress.
1897 * @param int $progress Current progress
1898 * @param int $max Max value
1900 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
1901 $reporter = $this->task->get_progress();
1903 // Start tracking progress if necessary.
1904 if (!$this->startedprogress) {
1905 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
1906 ? \core\progress\base::INDETERMINATE : $max);
1907 $this->startedprogress = true;
1910 // Pass progress through to whatever handles it.
1911 $reporter->progress(($progress == file_progress::INDETERMINATE)
1912 ? \core\progress\base::INDETERMINATE : $progress);
1917 * This step will send the generated backup file to its final destination
1919 class backup_store_backup_file extends backup_execution_step {
1921 protected function define_execution() {
1924 $basepath = $this->get_basepath();
1926 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1927 $zipfile = $basepath . '/backup.mbz';
1929 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1930 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1932 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
1933 $this->task->get_progress()),
1934 'include_file_references_to_external_content' => $has_file_references
1941 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1942 * and put them to the backup_ids tables, to be used later as base to backup them
1944 class backup_activity_grade_items_to_ids extends backup_execution_step {
1946 protected function define_execution() {
1948 // Fetch all activity grade items
1949 if ($items = grade_item::fetch_all(array(
1950 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1951 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1952 // Annotate them in backup_ids
1953 foreach ($items as $item) {
1954 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1962 * This step allows enrol plugins to annotate custom fields.
1964 * @package core_backup
1965 * @copyright 2014 University of Wisconsin
1966 * @author Matt Petro
1967 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1969 class backup_enrolments_execution_step extends backup_execution_step {
1972 * Function that will contain all the code to be executed.
1974 protected function define_execution() {
1977 $plugins = enrol_get_plugins(true);
1978 $enrols = $DB->get_records('enrol', array(
1979 'courseid' => $this->task->get_courseid()));
1981 // Allow each enrol plugin to add annotations.
1982 foreach ($enrols as $enrol) {
1983 if (isset($plugins[$enrol->enrol])) {
1984 $plugins[$enrol->enrol]->backup_annotate_custom_fields($this, $enrol);
1990 * Annotate a single name/id pair.
1991 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
1993 * @param string $itemname
1994 * @param int $itemid
1996 public function annotate_id($itemname, $itemid) {
1997 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
2002 * This step will annotate all the groups and groupings belonging to the course
2004 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
2006 protected function define_execution() {
2009 // Get all the course groups
2010 if ($groups = $DB->get_records('groups', array(
2011 'courseid' => $this->task->get_courseid()))) {
2012 foreach ($groups as $group) {
2013 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
2017 // Get all the course groupings
2018 if ($groupings = $DB->get_records('groupings', array(
2019 'courseid' => $this->task->get_courseid()))) {
2020 foreach ($groupings as $grouping) {
2021 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
2028 * This step will annotate all the groups belonging to already annotated groupings
2030 class backup_annotate_groups_from_groupings extends backup_execution_step {
2032 protected function define_execution() {
2035 // Fetch all the annotated groupings
2036 if ($groupings = $DB->get_records('backup_ids_temp', array(
2037 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
2038 foreach ($groupings as $grouping) {
2039 if ($groups = $DB->get_records('groupings_groups', array(
2040 'groupingid' => $grouping->itemid))) {
2041 foreach ($groups as $group) {
2042 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
2051 * This step will annotate all the scales belonging to already annotated outcomes
2053 class backup_annotate_scales_from_outcomes extends backup_execution_step {
2055 protected function define_execution() {
2058 // Fetch all the annotated outcomes
2059 if ($outcomes = $DB->get_records('backup_ids_temp', array(
2060 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
2061 foreach ($outcomes as $outcome) {
2062 if ($scale = $DB->get_record('grade_outcomes', array(
2063 'id' => $outcome->itemid))) {
2064 // Annotate as scalefinal because it's > 0
2065 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
2073 * This step will generate all the file annotations for the already
2074 * annotated (final) question_categories. It calculates the different
2075 * contexts that are being backup and, annotates all the files
2076 * on every context belonging to the "question" component. As far as
2077 * we are always including *complete* question banks it is safe and
2078 * optimal to do that in this (one pass) way
2080 class backup_annotate_all_question_files extends backup_execution_step {
2082 protected function define_execution() {
2085 // Get all the different contexts for the final question_categories
2086 // annotated along the whole backup
2087 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
2088 FROM {question_categories} qc
2089 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2090 WHERE bi.backupid = ?
2091 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2092 // To know about qtype specific components/fileareas
2093 $components = backup_qtype_plugin::get_components_and_fileareas();
2095 foreach($rs as $record) {
2096 // Backup all the file areas the are managed by the core question component.
2097 // That is, by the question_type base class. In particular, we don't want
2098 // to include files belonging to responses here.
2099 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'questiontext', null);
2100 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'generalfeedback', null);
2101 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answer', null);
2102 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answerfeedback', null);
2103 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'hint', null);
2104 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'correctfeedback', null);
2105 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'partiallycorrectfeedback', null);
2106 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'incorrectfeedback', null);
2108 // For files belonging to question types, we make the leap of faith that
2109 // all the files belonging to the question type are part of the question definition,
2110 // so we can just backup all the files in bulk, without specifying each
2111 // file area name separately.
2112 foreach ($components as $component => $fileareas) {
2113 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
2121 * structure step in charge of constructing the questions.xml file for all the
2122 * question categories and questions required by the backup
2123 * and letters related to one activity
2125 class backup_questions_structure_step extends backup_structure_step {
2127 protected function define_structure() {
2129 // Define each element separated
2131 $qcategories = new backup_nested_element('question_categories');
2133 $qcategory = new backup_nested_element('question_category', array('id'), array(
2134 'name', 'contextid', 'contextlevel', 'contextinstanceid',
2135 'info', 'infoformat', 'stamp', 'parent',
2138 $questions = new backup_nested_element('questions');
2140 $question = new backup_nested_element('question', array('id'), array(
2141 'parent', 'name', 'questiontext', 'questiontextformat',
2142 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
2143 'qtype', 'length', 'stamp', 'version',
2144 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
2146 // attach qtype plugin structure to $question element, only one allowed
2147 $this->add_plugin_structure('qtype', $question, false);
2149 // attach local plugin stucture to $question element, multiple allowed
2150 $this->add_plugin_structure('local', $question, true);
2152 $qhints = new backup_nested_element('question_hints');
2154 $qhint = new backup_nested_element('question_hint', array('id'), array(
2155 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
2157 $tags = new backup_nested_element('tags');
2159 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
2163 $qcategories->add_child($qcategory);
2164 $qcategory->add_child($questions);
2165 $questions->add_child($question);
2166 $question->add_child($qhints);
2167 $qhints->add_child($qhint);
2169 $question->add_child($tags);
2170 $tags->add_child($tag);
2172 // Define the sources
2174 $qcategory->set_source_sql("
2175 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
2176 FROM {question_categories} gc
2177 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2178 JOIN {context} co ON co.id = gc.contextid
2179 WHERE bi.backupid = ?
2180 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
2182 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
2184 $qhint->set_source_sql('
2186 FROM {question_hints}
2187 WHERE questionid = :questionid
2189 array('questionid' => backup::VAR_PARENTID));
2191 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
2193 JOIN {tag_instance} ti ON ti.tagid = t.id
2195 AND ti.itemtype = 'question'", array(backup::VAR_PARENTID));
2197 // don't need to annotate ids nor files
2198 // (already done by {@link backup_annotate_all_question_files}
2200 return $qcategories;
2207 * This step will generate all the file annotations for the already
2208 * annotated (final) users. Need to do this here because each user
2209 * has its own context and structure tasks only are able to handle
2210 * one context. Also, this step will guarantee that every user has
2211 * its context created (req for other steps)
2213 class backup_annotate_all_user_files extends backup_execution_step {
2215 protected function define_execution() {
2218 // List of fileareas we are going to annotate
2219 $fileareas = array('profile', 'icon');
2221 // Fetch all annotated (final) users
2222 $rs = $DB->get_recordset('backup_ids_temp', array(
2223 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2224 $progress = $this->task->get_progress();
2225 $progress->start_progress($this->get_name());
2226 foreach ($rs as $record) {
2227 $userid = $record->itemid;
2228 $userctx = context_user::instance($userid, IGNORE_MISSING);
2230 continue; // User has not context, sure it's a deleted user, so cannot have files
2232 // Proceed with every user filearea
2233 foreach ($fileareas as $filearea) {
2234 // We don't need to specify itemid ($userid - 5th param) as far as by
2235 // context we can get all the associated files. See MDL-22092
2236 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2237 $progress->progress();
2240 $progress->end_progress();
2247 * Defines the backup step for advanced grading methods attached to the activity module
2249 class backup_activity_grading_structure_step extends backup_structure_step {
2252 * Include the grading.xml only if the module supports advanced grading
2254 protected function execute_condition() {
2256 // No grades on the front page.
2257 if ($this->get_courseid() == SITEID) {
2261 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2265 * Declares the gradable areas structures and data sources
2267 protected function define_structure() {
2269 // To know if we are including userinfo
2270 $userinfo = $this->get_setting_value('userinfo');
2272 // Define the elements
2274 $areas = new backup_nested_element('areas');
2276 $area = new backup_nested_element('area', array('id'), array(
2277 'areaname', 'activemethod'));
2279 $definitions = new backup_nested_element('definitions');
2281 $definition = new backup_nested_element('definition', array('id'), array(
2282 'method', 'name', 'description', 'descriptionformat', 'status',
2283 'timecreated', 'timemodified', 'options'));
2285 $instances = new backup_nested_element('instances');
2287 $instance = new backup_nested_element('instance', array('id'), array(
2288 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2289 'feedbackformat', 'timemodified'));
2291 // Build the tree including the method specific structures
2292 // (beware - the order of how gradingform plugins structures are attached is important)
2293 $areas->add_child($area);
2294 // attach local plugin stucture to $area element, multiple allowed
2295 $this->add_plugin_structure('local', $area, true);
2296 $area->add_child($definitions);
2297 $definitions->add_child($definition);
2298 $this->add_plugin_structure('gradingform', $definition, true);
2299 // attach local plugin stucture to $definition element, multiple allowed
2300 $this->add_plugin_structure('local', $definition, true);
2301 $definition->add_child($instances);
2302 $instances->add_child($instance);
2303 $this->add_plugin_structure('gradingform', $instance, false);
2304 // attach local plugin stucture to $instance element, multiple allowed
2305 $this->add_plugin_structure('local', $instance, true);
2307 // Define data sources
2309 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2310 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2312 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2315 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2318 // Annotate references
2319 $definition->annotate_files('grading', 'description', 'id');
2320 $instance->annotate_ids('user', 'raterid');
2322 // Return the root element
2329 * structure step in charge of constructing the grades.xml file for all the grade items
2330 * and letters related to one activity
2332 class backup_activity_grades_structure_step extends backup_structure_step {
2335 * No grades on the front page.
2338 protected function execute_condition() {
2339 return ($this->get_courseid() != SITEID);
2342 protected function define_structure() {
2344 // To know if we are including userinfo
2345 $userinfo = $this->get_setting_value('userinfo');
2347 // Define each element separated
2349 $book = new backup_nested_element('activity_gradebook');
2351 $items = new backup_nested_element('grade_items');
2353 $item = new backup_nested_element('grade_item', array('id'), array(
2354 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2355 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2356 'calculation', 'gradetype', 'grademax', 'grademin',
2357 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2358 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2359 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2360 'needsupdate', 'timecreated', 'timemodified'));
2362 $grades = new backup_nested_element('grade_grades');
2364 $grade = new backup_nested_element('grade_grade', array('id'), array(
2365 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2366 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2367 'locked', 'locktime', 'exported', 'overridden',
2368 'excluded', 'feedback', 'feedbackformat', 'information',
2369 'informationformat', 'timecreated', 'timemodified',
2370 'aggregationstatus', 'aggregationweight'));
2372 $letters = new backup_nested_element('grade_letters');
2374 $letter = new backup_nested_element('grade_letter', 'id', array(
2375 'lowerboundary', 'letter'));
2379 $book->add_child($items);
2380 $items->add_child($item);
2382 $item->add_child($grades);
2383 $grades->add_child($grade);
2385 $book->add_child($letters);
2386 $letters->add_child($letter);
2390 $item->set_source_sql("SELECT gi.*
2391 FROM {grade_items} gi
2392 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2393 WHERE bi.backupid = ?
2394 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2396 // This only happens if we are including user info
2398 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2401 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2405 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2406 $item->annotate_ids('outcome', 'outcomeid');
2408 $grade->annotate_ids('user', 'userid');
2409 $grade->annotate_ids('user', 'usermodified');
2411 // Return the root element (book)
2418 * Structure step in charge of constructing the grade history of an activity.
2420 * This step is added to the task regardless of the setting 'grade_histories'.
2421 * The reason is to allow for a more flexible step in case the logic needs to be
2422 * split accross different settings to control the history of items and/or grades.
2424 class backup_activity_grade_history_structure_step extends backup_structure_step {
2427 * No grades on the front page.
2430 protected function execute_condition() {
2431 return ($this->get_courseid() != SITEID);
2434 protected function define_structure() {
2437 $userinfo = $this->get_setting_value('userinfo');
2438 $history = $this->get_setting_value('grade_histories');
2440 // Create the nested elements.
2441 $bookhistory = new backup_nested_element('grade_history');
2442 $grades = new backup_nested_element('grade_grades');
2443 $grade = new backup_nested_element('grade_grade', array('id'), array(
2444 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2445 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2446 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2447 'excluded', 'feedback', 'feedbackformat', 'information',
2448 'informationformat', 'timemodified'));
2451 $bookhistory->add_child($grades);
2452 $grades->add_child($grade);
2454 // This only happens if we are including user info and history.
2455 if ($userinfo && $history) {
2456 // Define sources. Only select the history related to existing activity items.
2457 $grade->set_source_sql("SELECT ggh.*
2458 FROM {grade_grades_history} ggh
2459 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2460 WHERE bi.backupid = ?
2461 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2465 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2466 $grade->annotate_ids('user', 'loggeduser');
2467 $grade->annotate_ids('user', 'userid');
2468 $grade->annotate_ids('user', 'usermodified');
2470 // Return the root element.
2471 return $bookhistory;
2476 * Backups up the course completion information for the course.
2478 class backup_course_completion_structure_step extends backup_structure_step {
2480 protected function execute_condition() {
2482 // No completion on front page.
2483 if ($this->get_courseid() == SITEID) {
2487 // Check that all activities have been included
2488 if ($this->task->is_excluding_activities()) {
2495 * The structure of the course completion backup
2497 * @return backup_nested_element
2499 protected function define_structure() {
2501 // To know if we are including user completion info
2502 $userinfo = $this->get_setting_value('userscompletion');
2504 $cc = new backup_nested_element('course_completion');
2506 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2507 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2508 'timeend', 'gradepass', 'role', 'roleshortname'
2511 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2513 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2514 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2517 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2518 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2521 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2522 'course','criteriatype','method','value'
2525 $cc->add_child($criteria);
2526 $criteria->add_child($criteriacompletions);
2527 $criteriacompletions->add_child($criteriacomplete);
2528 $cc->add_child($coursecompletions);
2529 $cc->add_child($aggregatemethod);
2531 // We need some extra data for the restore.
2532 // - courseinstances shortname rather than an ID.
2533 // - roleshortname in case restoring on a different site.
2534 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2535 FROM {course_completion_criteria} ccc
2536 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2537 LEFT JOIN {role} r ON r.id = ccc.role
2538 WHERE ccc.course = ?";
2539 $criteria->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2541 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2544 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2545 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2548 $criteria->annotate_ids('role', 'role');
2549 $criteriacomplete->annotate_ids('user', 'userid');
2550 $coursecompletions->annotate_ids('user', 'userid');