Revert "Merge branch 'MDL-43127-27' of git://github.com/FMCorz/moodle into MOODLE_27_...
[moodle.git] / backup / moodle2 / backup_stepslib.php
blob8961e23f8c86c2627a28e3f722cf95961b5e4be7
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. Also provides
95 * subplugin support for activities (that must be properly declared)
97 abstract class backup_activity_structure_step extends backup_structure_step {
99 /**
100 * Add subplugin structure to any element in the activity backup tree
102 * @param string $subplugintype type of subplugin as defined in activity db/subplugins.php
103 * @param backup_nested_element $element element in the activity backup tree that
104 * we are going to add subplugin information to
105 * @param bool $multiple to define if multiple subplugins can produce information
106 * for each instance of $element (true) or no (false)
107 * @return void
109 protected function add_subplugin_structure($subplugintype, $element, $multiple) {
111 global $CFG;
113 // Check the requested subplugintype is a valid one
114 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
115 if (!file_exists($subpluginsfile)) {
116 throw new backup_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
118 include($subpluginsfile);
119 if (!array_key_exists($subplugintype, $subplugins)) {
120 throw new backup_step_exception('incorrect_subplugin_type', $subplugintype);
123 // Arrived here, subplugin is correct, let's create the optigroup
124 $optigroupname = $subplugintype . '_' . $element->get_name() . '_subplugin';
125 $optigroup = new backup_optigroup($optigroupname, null, $multiple);
126 $element->add_child($optigroup); // Add optigroup to stay connected since beginning
128 // Get all the optigroup_elements, looking across all the subplugin dirs
129 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
130 foreach ($subpluginsdirs as $name => $subpluginsdir) {
131 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
132 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
133 if (file_exists($backupfile)) {
134 require_once($backupfile);
135 $backupsubplugin = new $classname($subplugintype, $name, $optigroup, $this);
136 // Add subplugin returned structure to optigroup
137 $backupsubplugin->define_subplugin_structure($element->get_name());
143 * As far as activity backup steps are implementing backup_subplugin stuff, they need to
144 * have the parent task available for wrapping purposes (get course/context....)
146 * @return backup_activity_task
148 public function get_task() {
149 return $this->task;
153 * Wraps any activity backup structure within the common 'activity' element
154 * that will include common to all activities information like id, context...
156 * @param backup_nested_element $activitystructure the element to wrap
157 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
159 protected function prepare_activity_structure($activitystructure) {
161 // Create the wrap element
162 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
164 // Build the tree
165 $activity->add_child($activitystructure);
167 // Set the source
168 $activityarr = array((object)array(
169 'id' => $this->task->get_activityid(),
170 'moduleid' => $this->task->get_moduleid(),
171 'modulename' => $this->task->get_modulename(),
172 'contextid' => $this->task->get_contextid()));
174 $activity->set_source_array($activityarr);
176 // Return the root element (activity)
177 return $activity;
182 * Abstract structure step, to be used by all the activities using core questions stuff
183 * (namely quiz module), supporting question plugins, states and sessions
185 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
188 * Attach to $element (usually attempts) the needed backup structures
189 * for question_usages and all the associated data.
191 * @param backup_nested_element $element the element that will contain all the question_usages data.
192 * @param string $usageidname the name of the element that holds the usageid.
193 * This must be child of $element, and must be a final element.
194 * @param string $nameprefix this prefix is added to all the element names we create.
195 * Element names in the XML must be unique, so if you are using usages in
196 * two different ways, you must give a prefix to at least one of them. If
197 * you only use one sort of usage, then you can just use the default empty prefix.
198 * This should include a trailing underscore. For example "myprefix_"
200 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
201 global $CFG;
202 require_once($CFG->dirroot . '/question/engine/lib.php');
204 // Check $element is one nested_backup_element
205 if (! $element instanceof backup_nested_element) {
206 throw new backup_step_exception('question_states_bad_parent_element', $element);
208 if (! $element->get_final_element($usageidname)) {
209 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
212 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
213 array('component', 'preferredbehaviour'));
215 $qas = new backup_nested_element($nameprefix . 'question_attempts');
216 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
217 'slot', 'behaviour', 'questionid', 'variant', 'maxmark', 'minfraction', 'maxfraction',
218 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
219 'timemodified'));
221 $steps = new backup_nested_element($nameprefix . 'steps');
222 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
223 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
225 $response = new backup_nested_element($nameprefix . 'response');
226 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
228 // Build the tree
229 $element->add_child($quba);
230 $quba->add_child($qas);
231 $qas->add_child($qa);
232 $qa->add_child($steps);
233 $steps->add_child($step);
234 $step->add_child($response);
235 $response->add_child($variable);
237 // Set the sources
238 $quba->set_source_table('question_usages',
239 array('id' => '../' . $usageidname));
240 $qa->set_source_table('question_attempts', array('questionusageid' => backup::VAR_PARENTID), 'slot ASC');
241 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup::VAR_PARENTID), 'sequencenumber ASC');
242 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup::VAR_PARENTID));
244 // Annotate ids
245 $qa->annotate_ids('question', 'questionid');
246 $step->annotate_ids('user', 'userid');
248 // Annotate files
249 $fileareas = question_engine::get_all_response_file_areas();
250 foreach ($fileareas as $filearea) {
251 $step->annotate_files('question', $filearea, 'id');
258 * backup structure step in charge of calculating the categories to be
259 * included in backup, based in the context being backuped (module/course)
260 * and the already annotated questions present in backup_ids_temp
262 class backup_calculate_question_categories extends backup_execution_step {
264 protected function define_execution() {
265 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
270 * backup structure step in charge of deleting all the questions annotated
271 * in the backup_ids_temp table
273 class backup_delete_temp_questions extends backup_execution_step {
275 protected function define_execution() {
276 backup_question_dbops::delete_temp_questions($this->get_backupid());
281 * Abstract structure step, parent of all the block structure steps. Used to wrap the
282 * block structure definition within the main <block ...> tag
284 abstract class backup_block_structure_step extends backup_structure_step {
286 protected function prepare_block_structure($blockstructure) {
288 // Create the wrap element
289 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
291 // Build the tree
292 $block->add_child($blockstructure);
294 // Set the source
295 $blockarr = array((object)array(
296 'id' => $this->task->get_blockid(),
297 'blockname' => $this->task->get_blockname(),
298 'contextid' => $this->task->get_contextid()));
300 $block->set_source_array($blockarr);
302 // Return the root element (block)
303 return $block;
308 * structure step that will generate the module.xml file for the activity,
309 * accumulating various information about the activity, annotating groupings
310 * and completion/avail conf
312 class backup_module_structure_step extends backup_structure_step {
314 protected function define_structure() {
315 global $DB;
317 // Define each element separated
319 $module = new backup_nested_element('module', array('id', 'version'), array(
320 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
321 'added', 'score', 'indent', 'visible',
322 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
323 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
324 'availability', 'showdescription'));
326 // attach format plugin structure to $module element, only one allowed
327 $this->add_plugin_structure('format', $module, false);
329 // attach plagiarism plugin structure to $module element, there can be potentially
330 // many plagiarism plugins storing information about this course
331 $this->add_plugin_structure('plagiarism', $module, true);
333 // attach local plugin structure to $module, multiple allowed
334 $this->add_plugin_structure('local', $module, true);
336 // Set the sources
337 $concat = $DB->sql_concat("'mod_'", 'm.name');
338 $module->set_source_sql("
339 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
340 FROM {course_modules} cm
341 JOIN {modules} m ON m.id = cm.module
342 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
343 JOIN {course_sections} s ON s.id = cm.section
344 WHERE cm.id = ?", array(backup::VAR_MODID));
346 // Define annotations
347 $module->annotate_ids('grouping', 'groupingid');
349 // Return the root element ($module)
350 return $module;
355 * structure step that will generate the section.xml file for the section
356 * annotating files
358 class backup_section_structure_step extends backup_structure_step {
360 protected function define_structure() {
362 // Define each element separated
364 $section = new backup_nested_element('section', array('id'), array(
365 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
366 'availabilityjson'));
368 // attach format plugin structure to $section element, only one allowed
369 $this->add_plugin_structure('format', $section, false);
371 // attach local plugin structure to $section element, multiple allowed
372 $this->add_plugin_structure('local', $section, true);
374 // Add nested elements for course_format_options table
375 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
376 'format', 'name', 'value'));
377 $section->add_child($formatoptions);
379 // Define sources.
380 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
381 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
382 FROM {course} c
383 JOIN {course_format_options} cfo
384 ON cfo.courseid = c.id AND cfo.format = c.format
385 WHERE c.id = ? AND cfo.sectionid = ?',
386 array(backup::VAR_COURSEID, backup::VAR_SECTIONID));
388 // Aliases
389 $section->set_source_alias('section', 'number');
390 // The 'availability' field needs to be renamed because it clashes with
391 // the old nested element structure for availability data.
392 $section->set_source_alias('availability', 'availabilityjson');
394 // Set annotations
395 $section->annotate_files('course', 'section', 'id');
397 return $section;
402 * structure step that will generate the course.xml file for the course, including
403 * course category reference, tags, modules restriction information
404 * and some annotations (files & groupings)
406 class backup_course_structure_step extends backup_structure_step {
408 protected function define_structure() {
409 global $DB;
411 // Define each element separated
413 $course = new backup_nested_element('course', array('id', 'contextid'), array(
414 'shortname', 'fullname', 'idnumber',
415 'summary', 'summaryformat', 'format', 'showgrades',
416 'newsitems', 'startdate',
417 'marker', 'maxbytes', 'legacyfiles', 'showreports',
418 'visible', 'groupmode', 'groupmodeforce',
419 'defaultgroupingid', 'lang', 'theme',
420 'timecreated', 'timemodified',
421 'requested',
422 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
424 $category = new backup_nested_element('category', array('id'), array(
425 'name', 'description'));
427 $tags = new backup_nested_element('tags');
429 $tag = new backup_nested_element('tag', array('id'), array(
430 'name', 'rawname'));
432 // attach format plugin structure to $course element, only one allowed
433 $this->add_plugin_structure('format', $course, false);
435 // attach theme plugin structure to $course element; multiple themes can
436 // save course data (in case of user theme, legacy theme, etc)
437 $this->add_plugin_structure('theme', $course, true);
439 // attach general report plugin structure to $course element; multiple
440 // reports can save course data if required
441 $this->add_plugin_structure('report', $course, true);
443 // attach course report plugin structure to $course element; multiple
444 // course reports can save course data if required
445 $this->add_plugin_structure('coursereport', $course, true);
447 // attach plagiarism plugin structure to $course element, there can be potentially
448 // many plagiarism plugins storing information about this course
449 $this->add_plugin_structure('plagiarism', $course, true);
451 // attach local plugin structure to $course element; multiple local plugins
452 // can save course data if required
453 $this->add_plugin_structure('local', $course, true);
455 // Build the tree
457 $course->add_child($category);
459 $course->add_child($tags);
460 $tags->add_child($tag);
462 // Set the sources
464 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
465 $courserec->contextid = $this->task->get_contextid();
467 $formatoptions = course_get_format($courserec)->get_format_options();
468 $course->add_final_elements(array_keys($formatoptions));
469 foreach ($formatoptions as $key => $value) {
470 $courserec->$key = $value;
473 $course->set_source_array(array($courserec));
475 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
477 $category->set_source_array(array($categoryrec));
479 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
480 FROM {tag} t
481 JOIN {tag_instance} ti ON ti.tagid = t.id
482 WHERE ti.itemtype = ?
483 AND ti.itemid = ?', array(
484 backup_helper::is_sqlparam('course'),
485 backup::VAR_PARENTID));
487 // Some annotations
489 $course->annotate_ids('grouping', 'defaultgroupingid');
491 $course->annotate_files('course', 'summary', null);
492 $course->annotate_files('course', 'overviewfiles', null);
493 $course->annotate_files('course', 'legacy', null);
495 // Return root element ($course)
497 return $course;
502 * structure step that will generate the enrolments.xml file for the given course
504 class backup_enrolments_structure_step extends backup_structure_step {
506 protected function define_structure() {
508 // To know if we are including users
509 $users = $this->get_setting_value('users');
511 // Define each element separated
513 $enrolments = new backup_nested_element('enrolments');
515 $enrols = new backup_nested_element('enrols');
517 $enrol = new backup_nested_element('enrol', array('id'), array(
518 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
519 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
520 'password', 'cost', 'currency', 'roleid',
521 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
522 'customchar1', 'customchar2', 'customchar3',
523 'customdec1', 'customdec2',
524 'customtext1', 'customtext2', 'customtext3', 'customtext4',
525 'timecreated', 'timemodified'));
527 $userenrolments = new backup_nested_element('user_enrolments');
529 $enrolment = new backup_nested_element('enrolment', array('id'), array(
530 'status', 'userid', 'timestart', 'timeend', 'modifierid',
531 'timemodified'));
533 // Build the tree
534 $enrolments->add_child($enrols);
535 $enrols->add_child($enrol);
536 $enrol->add_child($userenrolments);
537 $userenrolments->add_child($enrolment);
539 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
540 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
542 // User enrolments only added only if users included
543 if ($users) {
544 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
545 $enrolment->annotate_ids('user', 'userid');
548 $enrol->annotate_ids('role', 'roleid');
550 //TODO: let plugins annotate custom fields too and add more children
552 return $enrolments;
557 * structure step that will generate the roles.xml file for the given context, observing
558 * the role_assignments setting to know if that part needs to be included
560 class backup_roles_structure_step extends backup_structure_step {
562 protected function define_structure() {
564 // To know if we are including role assignments
565 $roleassignments = $this->get_setting_value('role_assignments');
567 // Define each element separated
569 $roles = new backup_nested_element('roles');
571 $overrides = new backup_nested_element('role_overrides');
573 $override = new backup_nested_element('override', array('id'), array(
574 'roleid', 'capability', 'permission', 'timemodified',
575 'modifierid'));
577 $assignments = new backup_nested_element('role_assignments');
579 $assignment = new backup_nested_element('assignment', array('id'), array(
580 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
581 'sortorder'));
583 // Build the tree
584 $roles->add_child($overrides);
585 $roles->add_child($assignments);
587 $overrides->add_child($override);
588 $assignments->add_child($assignment);
590 // Define sources
592 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
594 // Assignments only added if specified
595 if ($roleassignments) {
596 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
599 // Define id annotations
600 $override->annotate_ids('role', 'roleid');
602 $assignment->annotate_ids('role', 'roleid');
604 $assignment->annotate_ids('user', 'userid');
606 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
608 return $roles;
613 * structure step that will generate the roles.xml containing the
614 * list of roles used along the whole backup process. Just raw
615 * list of used roles from role table
617 class backup_final_roles_structure_step extends backup_structure_step {
619 protected function define_structure() {
621 // Define elements
623 $rolesdef = new backup_nested_element('roles_definition');
625 $role = new backup_nested_element('role', array('id'), array(
626 'name', 'shortname', 'nameincourse', 'description',
627 'sortorder', 'archetype'));
629 // Build the tree
631 $rolesdef->add_child($role);
633 // Define sources
635 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
636 FROM {role} r
637 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
638 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
639 WHERE bi.backupid = ?
640 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
642 // Return main element (rolesdef)
643 return $rolesdef;
648 * structure step that will generate the scales.xml containing the
649 * list of scales used along the whole backup process.
651 class backup_final_scales_structure_step extends backup_structure_step {
653 protected function define_structure() {
655 // Define elements
657 $scalesdef = new backup_nested_element('scales_definition');
659 $scale = new backup_nested_element('scale', array('id'), array(
660 'courseid', 'userid', 'name', 'scale',
661 'description', 'descriptionformat', 'timemodified'));
663 // Build the tree
665 $scalesdef->add_child($scale);
667 // Define sources
669 $scale->set_source_sql("SELECT s.*
670 FROM {scale} s
671 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
672 WHERE bi.backupid = ?
673 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
675 // Annotate scale files (they store files in system context, so pass it instead of default one)
676 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
678 // Return main element (scalesdef)
679 return $scalesdef;
684 * structure step that will generate the outcomes.xml containing the
685 * list of outcomes used along the whole backup process.
687 class backup_final_outcomes_structure_step extends backup_structure_step {
689 protected function define_structure() {
691 // Define elements
693 $outcomesdef = new backup_nested_element('outcomes_definition');
695 $outcome = new backup_nested_element('outcome', array('id'), array(
696 'courseid', 'userid', 'shortname', 'fullname',
697 'scaleid', 'description', 'descriptionformat', 'timecreated',
698 'timemodified','usermodified'));
700 // Build the tree
702 $outcomesdef->add_child($outcome);
704 // Define sources
706 $outcome->set_source_sql("SELECT o.*
707 FROM {grade_outcomes} o
708 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
709 WHERE bi.backupid = ?
710 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
712 // Annotate outcome files (they store files in system context, so pass it instead of default one)
713 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
715 // Return main element (outcomesdef)
716 return $outcomesdef;
721 * structure step in charge of constructing the filters.xml file for all the filters found
722 * in activity
724 class backup_filters_structure_step extends backup_structure_step {
726 protected function define_structure() {
728 // Define each element separated
730 $filters = new backup_nested_element('filters');
732 $actives = new backup_nested_element('filter_actives');
734 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
736 $configs = new backup_nested_element('filter_configs');
738 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
740 // Build the tree
742 $filters->add_child($actives);
743 $filters->add_child($configs);
745 $actives->add_child($active);
746 $configs->add_child($config);
748 // Define sources
750 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
752 $active->set_source_array($activearr);
753 $config->set_source_array($configarr);
755 // Return the root element (filters)
756 return $filters;
761 * structure step in charge of constructing the comments.xml file for all the comments found
762 * in a given context
764 class backup_comments_structure_step extends backup_structure_step {
766 protected function define_structure() {
768 // Define each element separated
770 $comments = new backup_nested_element('comments');
772 $comment = new backup_nested_element('comment', array('id'), array(
773 'commentarea', 'itemid', 'content', 'format',
774 'userid', 'timecreated'));
776 // Build the tree
778 $comments->add_child($comment);
780 // Define sources
782 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
784 // Define id annotations
786 $comment->annotate_ids('user', 'userid');
788 // Return the root element (comments)
789 return $comments;
794 * structure step in charge of constructing the badges.xml file for all the badges found
795 * in a given context
797 class backup_badges_structure_step extends backup_structure_step {
799 protected function execute_condition() {
800 // Check that all activities have been included.
801 if ($this->task->is_excluding_activities()) {
802 return false;
804 return true;
807 protected function define_structure() {
809 // Define each element separated.
811 $badges = new backup_nested_element('badges');
812 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
813 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
814 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
815 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron'));
817 $criteria = new backup_nested_element('criteria');
818 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
819 'criteriatype', 'method'));
821 $parameters = new backup_nested_element('parameters');
822 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
823 'name', 'value', 'criteriatype'));
825 $manual_awards = new backup_nested_element('manual_awards');
826 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
827 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
829 // Build the tree.
831 $badges->add_child($badge);
832 $badge->add_child($criteria);
833 $criteria->add_child($criterion);
834 $criterion->add_child($parameters);
835 $parameters->add_child($parameter);
836 $badge->add_child($manual_awards);
837 $manual_awards->add_child($manual_award);
839 // Define sources.
841 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
842 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
844 $parametersql = 'SELECT cp.*, c.criteriatype
845 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
846 ON cp.critid = c.id
847 WHERE critid = :critid';
848 $parameterparams = array('critid' => backup::VAR_PARENTID);
849 $parameter->set_source_sql($parametersql, $parameterparams);
851 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
853 // Define id annotations.
855 $badge->annotate_ids('user', 'usercreated');
856 $badge->annotate_ids('user', 'usermodified');
857 $criterion->annotate_ids('badge', 'badgeid');
858 $parameter->annotate_ids('criterion', 'critid');
859 $badge->annotate_files('badges', 'badgeimage', 'id');
860 $manual_award->annotate_ids('badge', 'badgeid');
861 $manual_award->annotate_ids('user', 'recipientid');
862 $manual_award->annotate_ids('user', 'issuerid');
863 $manual_award->annotate_ids('role', 'issuerrole');
865 // Return the root element ($badges).
866 return $badges;
871 * structure step in charge of constructing the calender.xml file for all the events found
872 * in a given context
874 class backup_calendarevents_structure_step extends backup_structure_step {
876 protected function define_structure() {
878 // Define each element separated
880 $events = new backup_nested_element('events');
882 $event = new backup_nested_element('event', array('id'), array(
883 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
884 'repeatid', 'modulename', 'instance', 'eventtype', 'timestart',
885 'timeduration', 'visible', 'uuid', 'sequence', 'timemodified'));
887 // Build the tree
888 $events->add_child($event);
890 // Define sources
891 if ($this->name == 'course_calendar') {
892 $calendar_items_sql ="SELECT * FROM {event}
893 WHERE courseid = :courseid
894 AND (eventtype = 'course' OR eventtype = 'group')";
895 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
896 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
897 } else {
898 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
901 // Define id annotations
903 $event->annotate_ids('user', 'userid');
904 $event->annotate_ids('group', 'groupid');
905 $event->annotate_files('calendar', 'event_description', 'id');
907 // Return the root element (events)
908 return $events;
913 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
914 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
916 class backup_gradebook_structure_step extends backup_structure_step {
919 * We need to decide conditionally, based on dynamic information
920 * about the execution of this step. Only will be executed if all
921 * the module gradeitems have been already included in backup
923 protected function execute_condition() {
924 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
927 protected function define_structure() {
929 // are we including user info?
930 $userinfo = $this->get_setting_value('users');
932 $gradebook = new backup_nested_element('gradebook');
934 //grade_letters are done in backup_activity_grades_structure_step()
936 //calculated grade items
937 $grade_items = new backup_nested_element('grade_items');
938 $grade_item = new backup_nested_element('grade_item', array('id'), array(
939 'categoryid', 'itemname', 'itemtype', 'itemmodule',
940 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
941 'calculation', 'gradetype', 'grademax', 'grademin',
942 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
943 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
944 'decimals', 'hidden', 'locked', 'locktime',
945 'needsupdate', 'timecreated', 'timemodified'));
947 $grade_grades = new backup_nested_element('grade_grades');
948 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
949 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
950 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
951 'locked', 'locktime', 'exported', 'overridden',
952 'excluded', 'feedback', 'feedbackformat', 'information',
953 'informationformat', 'timecreated', 'timemodified'));
955 //grade_categories
956 $grade_categories = new backup_nested_element('grade_categories');
957 $grade_category = new backup_nested_element('grade_category', array('id'), array(
958 //'courseid',
959 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
960 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
961 'timecreated', 'timemodified', 'hidden'));
963 $letters = new backup_nested_element('grade_letters');
964 $letter = new backup_nested_element('grade_letter', 'id', array(
965 'lowerboundary', 'letter'));
967 $grade_settings = new backup_nested_element('grade_settings');
968 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
969 'name', 'value'));
972 // Build the tree
973 $gradebook->add_child($grade_categories);
974 $grade_categories->add_child($grade_category);
976 $gradebook->add_child($grade_items);
977 $grade_items->add_child($grade_item);
978 $grade_item->add_child($grade_grades);
979 $grade_grades->add_child($grade_grade);
981 $gradebook->add_child($letters);
982 $letters->add_child($letter);
984 $gradebook->add_child($grade_settings);
985 $grade_settings->add_child($grade_setting);
987 // Define sources
989 //Include manual, category and the course grade item
990 $grade_items_sql ="SELECT * FROM {grade_items}
991 WHERE courseid = :courseid
992 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
993 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
994 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
996 if ($userinfo) {
997 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1000 $grade_category_sql = "SELECT gc.*, gi.sortorder
1001 FROM {grade_categories} gc
1002 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1003 WHERE gc.courseid = :courseid
1004 AND (gi.itemtype='course' OR gi.itemtype='category')
1005 ORDER BY gc.parent ASC";//need parent categories before their children
1006 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1007 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1009 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1011 $grade_setting->set_source_table('grade_settings', array('courseid' => backup::VAR_COURSEID));
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
1021 return $gradebook;
1026 * structure step in charge if constructing the completion.xml file for all the users completion
1027 * information in a given activity
1029 class backup_userscompletion_structure_step extends backup_structure_step {
1031 protected function define_structure() {
1033 // Define each element separated
1035 $completions = new backup_nested_element('completions');
1037 $completion = new backup_nested_element('completion', array('id'), array(
1038 'userid', 'completionstate', 'viewed', 'timemodified'));
1040 // Build the tree
1042 $completions->add_child($completion);
1044 // Define sources
1046 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1048 // Define id annotations
1050 $completion->annotate_ids('user', 'userid');
1052 // Return the root element (completions)
1053 return $completions;
1058 * structure step in charge of constructing the main groups.xml file for all the groups and
1059 * groupings information already annotated
1061 class backup_groups_structure_step extends backup_structure_step {
1063 protected function define_structure() {
1065 // To know if we are including users
1066 $users = $this->get_setting_value('users');
1068 // Define each element separated
1070 $groups = new backup_nested_element('groups');
1072 $group = new backup_nested_element('group', array('id'), array(
1073 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1074 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1076 $members = new backup_nested_element('group_members');
1078 $member = new backup_nested_element('group_member', array('id'), array(
1079 'userid', 'timeadded', 'component', 'itemid'));
1081 $groupings = new backup_nested_element('groupings');
1083 $grouping = new backup_nested_element('grouping', 'id', array(
1084 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1085 'timecreated', 'timemodified'));
1087 $groupinggroups = new backup_nested_element('grouping_groups');
1089 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1090 'groupid', 'timeadded'));
1092 // Build the tree
1094 $groups->add_child($group);
1095 $groups->add_child($groupings);
1097 $group->add_child($members);
1098 $members->add_child($member);
1100 $groupings->add_child($grouping);
1101 $grouping->add_child($groupinggroups);
1102 $groupinggroups->add_child($groupinggroup);
1104 // Define sources
1106 $group->set_source_sql("
1107 SELECT g.*
1108 FROM {groups} g
1109 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1110 WHERE bi.backupid = ?
1111 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1113 // This only happens if we are including users
1114 if ($users) {
1115 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1118 $grouping->set_source_sql("
1119 SELECT g.*
1120 FROM {groupings} g
1121 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1122 WHERE bi.backupid = ?
1123 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1125 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1127 // Define id annotations (as final)
1129 $member->annotate_ids('userfinal', 'userid');
1131 // Define file annotations
1133 $group->annotate_files('group', 'description', 'id');
1134 $group->annotate_files('group', 'icon', 'id');
1135 $grouping->annotate_files('grouping', 'description', 'id');
1137 // Return the root element (groups)
1138 return $groups;
1143 * structure step in charge of constructing the main users.xml file for all the users already
1144 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1145 * overrides.
1147 class backup_users_structure_step extends backup_structure_step {
1149 protected function define_structure() {
1150 global $CFG;
1152 // To know if we are anonymizing users
1153 $anonymize = $this->get_setting_value('anonymize');
1154 // To know if we are including role assignments
1155 $roleassignments = $this->get_setting_value('role_assignments');
1157 // Define each element separated
1159 $users = new backup_nested_element('users');
1161 // Create the array of user fields by hand, as far as we have various bits to control
1162 // anonymize option, password backup, mnethostid...
1164 // First, the fields not needing anonymization nor special handling
1165 $normalfields = array(
1166 'confirmed', 'policyagreed', 'deleted',
1167 'lang', 'theme', 'timezone', 'firstaccess',
1168 'lastaccess', 'lastlogin', 'currentlogin',
1169 'mailformat', 'maildigest', 'maildisplay',
1170 'autosubscribe', 'trackforums', 'timecreated',
1171 'timemodified', 'trustbitmask');
1173 // Then, the fields potentially needing anonymization
1174 $anonfields = array(
1175 'username', 'idnumber', 'email', 'icq', 'skype',
1176 'yahoo', 'aim', 'msn', 'phone1',
1177 'phone2', 'institution', 'department', 'address',
1178 'city', 'country', 'lastip', 'picture',
1179 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1180 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1182 // Add anonymized fields to $userfields with custom final element
1183 foreach ($anonfields as $field) {
1184 if ($anonymize) {
1185 $userfields[] = new anonymizer_final_element($field);
1186 } else {
1187 $userfields[] = $field; // No anonymization, normally added
1191 // mnethosturl requires special handling (custom final element)
1192 $userfields[] = new mnethosturl_final_element('mnethosturl');
1194 // password added conditionally
1195 if (!empty($CFG->includeuserpasswordsinbackup)) {
1196 $userfields[] = 'password';
1199 // Merge all the fields
1200 $userfields = array_merge($userfields, $normalfields);
1202 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1204 $customfields = new backup_nested_element('custom_fields');
1206 $customfield = new backup_nested_element('custom_field', array('id'), array(
1207 'field_name', 'field_type', 'field_data'));
1209 $tags = new backup_nested_element('tags');
1211 $tag = new backup_nested_element('tag', array('id'), array(
1212 'name', 'rawname'));
1214 $preferences = new backup_nested_element('preferences');
1216 $preference = new backup_nested_element('preference', array('id'), array(
1217 'name', 'value'));
1219 $roles = new backup_nested_element('roles');
1221 $overrides = new backup_nested_element('role_overrides');
1223 $override = new backup_nested_element('override', array('id'), array(
1224 'roleid', 'capability', 'permission', 'timemodified',
1225 'modifierid'));
1227 $assignments = new backup_nested_element('role_assignments');
1229 $assignment = new backup_nested_element('assignment', array('id'), array(
1230 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1231 'sortorder'));
1233 // Build the tree
1235 $users->add_child($user);
1237 $user->add_child($customfields);
1238 $customfields->add_child($customfield);
1240 $user->add_child($tags);
1241 $tags->add_child($tag);
1243 $user->add_child($preferences);
1244 $preferences->add_child($preference);
1246 $user->add_child($roles);
1248 $roles->add_child($overrides);
1249 $roles->add_child($assignments);
1251 $overrides->add_child($override);
1252 $assignments->add_child($assignment);
1254 // Define sources
1256 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1257 FROM {user} u
1258 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1259 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1260 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1261 WHERE bi.backupid = ?
1262 AND bi.itemname = ?', array(
1263 backup_helper::is_sqlparam($this->get_backupid()),
1264 backup_helper::is_sqlparam('userfinal')));
1266 // All the rest on information is only added if we arent
1267 // in an anonymized backup
1268 if (!$anonymize) {
1269 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1270 FROM {user_info_field} f
1271 JOIN {user_info_data} d ON d.fieldid = f.id
1272 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1274 $customfield->set_source_alias('shortname', 'field_name');
1275 $customfield->set_source_alias('datatype', 'field_type');
1276 $customfield->set_source_alias('data', 'field_data');
1278 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1279 FROM {tag} t
1280 JOIN {tag_instance} ti ON ti.tagid = t.id
1281 WHERE ti.itemtype = ?
1282 AND ti.itemid = ?', array(
1283 backup_helper::is_sqlparam('user'),
1284 backup::VAR_PARENTID));
1286 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1288 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1290 // Assignments only added if specified
1291 if ($roleassignments) {
1292 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1295 // Define id annotations (as final)
1296 $override->annotate_ids('rolefinal', 'roleid');
1299 // Return root element (users)
1300 return $users;
1305 * structure step in charge of constructing the block.xml file for one
1306 * given block (instance and positions). If the block has custom DB structure
1307 * that will go to a separate file (different step defined in block class)
1309 class backup_block_instance_structure_step extends backup_structure_step {
1311 protected function define_structure() {
1312 global $DB;
1314 // Define each element separated
1316 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1317 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1318 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1320 $positions = new backup_nested_element('block_positions');
1322 $position = new backup_nested_element('block_position', array('id'), array(
1323 'contextid', 'pagetype', 'subpage', 'visible',
1324 'region', 'weight'));
1326 // Build the tree
1328 $block->add_child($positions);
1329 $positions->add_child($position);
1331 // Transform configdata information if needed (process links and friends)
1332 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1333 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1334 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1335 foreach ($configdata as $attribute => $value) {
1336 if (in_array($attribute, $attrstotransform)) {
1337 $configdata[$attribute] = $this->contenttransformer->process($value);
1340 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1342 $blockrec->contextid = $this->task->get_contextid();
1343 // Get the version of the block
1344 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1346 // Define sources
1348 $block->set_source_array(array($blockrec));
1350 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1352 // File anotations (for fileareas specified on each block)
1353 foreach ($this->task->get_fileareas() as $filearea) {
1354 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1357 // Return the root element (block)
1358 return $block;
1363 * structure step in charge of constructing the logs.xml file for all the log records found
1364 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1365 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1366 * that just in case they become restored some day in the future
1368 class backup_course_logs_structure_step extends backup_structure_step {
1370 protected function define_structure() {
1372 // Define each element separated
1374 $logs = new backup_nested_element('logs');
1376 $log = new backup_nested_element('log', array('id'), array(
1377 'time', 'userid', 'ip', 'module',
1378 'action', 'url', 'info'));
1380 // Build the tree
1382 $logs->add_child($log);
1384 // Define sources (all the records belonging to the course, having cmid = 0)
1386 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1388 // Annotations
1389 // NOTE: We don't annotate users from logs as far as they MUST be
1390 // always annotated by the course (enrol, ras... whatever)
1392 // Return the root element (logs)
1394 return $logs;
1399 * structure step in charge of constructing the logs.xml file for all the log records found
1400 * in activity
1402 class backup_activity_logs_structure_step extends backup_structure_step {
1404 protected function define_structure() {
1406 // Define each element separated
1408 $logs = new backup_nested_element('logs');
1410 $log = new backup_nested_element('log', array('id'), array(
1411 'time', 'userid', 'ip', 'module',
1412 'action', 'url', 'info'));
1414 // Build the tree
1416 $logs->add_child($log);
1418 // Define sources
1420 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1422 // Annotations
1423 // NOTE: We don't annotate users from logs as far as they MUST be
1424 // always annotated by the activity (true participants).
1426 // Return the root element (logs)
1428 return $logs;
1433 * structure in charge of constructing the inforef.xml file for all the items we want
1434 * to have referenced there (users, roles, files...)
1436 class backup_inforef_structure_step extends backup_structure_step {
1438 protected function define_structure() {
1440 // Items we want to include in the inforef file.
1441 $items = backup_helper::get_inforef_itemnames();
1443 // Build the tree
1445 $inforef = new backup_nested_element('inforef');
1447 // For each item, conditionally, if there are already records, build element
1448 foreach ($items as $itemname) {
1449 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1450 $elementroot = new backup_nested_element($itemname . 'ref');
1451 $element = new backup_nested_element($itemname, array(), array('id'));
1452 $inforef->add_child($elementroot);
1453 $elementroot->add_child($element);
1454 $element->set_source_sql("
1455 SELECT itemid AS id
1456 FROM {backup_ids_temp}
1457 WHERE backupid = ?
1458 AND itemname = ?",
1459 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1463 // We don't annotate anything there, but rely in the next step
1464 // (move_inforef_annotations_to_final) that will change all the
1465 // already saved 'inforref' entries to their 'final' annotations.
1466 return $inforef;
1471 * This step will get all the annotations already processed to inforef.xml file and
1472 * transform them into 'final' annotations.
1474 class move_inforef_annotations_to_final extends backup_execution_step {
1476 protected function define_execution() {
1478 // Items we want to include in the inforef file
1479 $items = backup_helper::get_inforef_itemnames();
1480 $progress = $this->task->get_progress();
1481 $progress->start_progress($this->get_name(), count($items));
1482 $done = 1;
1483 foreach ($items as $itemname) {
1484 // Delegate to dbops
1485 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1486 $itemname, $progress);
1487 $progress->progress($done++);
1489 $progress->end_progress();
1494 * structure in charge of constructing the files.xml file with all the
1495 * annotated (final) files along the process. At, the same time, and
1496 * using one specialised nested_element, will copy them form moodle storage
1497 * to backup storage
1499 class backup_final_files_structure_step extends backup_structure_step {
1501 protected function define_structure() {
1503 // Define elements
1505 $files = new backup_nested_element('files');
1507 $file = new file_nested_element('file', array('id'), array(
1508 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1509 'filepath', 'filename', 'userid', 'filesize',
1510 'mimetype', 'status', 'timecreated', 'timemodified',
1511 'source', 'author', 'license', 'sortorder',
1512 'repositorytype', 'repositoryid', 'reference'));
1514 // Build the tree
1516 $files->add_child($file);
1518 // Define sources
1520 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1521 FROM {files} f
1522 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1523 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1524 LEFT JOIN {repository} r ON r.id = ri.typeid
1525 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1526 WHERE bi.backupid = ?
1527 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1529 return $files;
1534 * Structure step in charge of creating the main moodle_backup.xml file
1535 * where all the information related to the backup, settings, license and
1536 * other information needed on restore is added*/
1537 class backup_main_structure_step extends backup_structure_step {
1539 protected function define_structure() {
1541 global $CFG;
1543 $info = array();
1545 $info['name'] = $this->get_setting_value('filename');
1546 $info['moodle_version'] = $CFG->version;
1547 $info['moodle_release'] = $CFG->release;
1548 $info['backup_version'] = $CFG->backup_version;
1549 $info['backup_release'] = $CFG->backup_release;
1550 $info['backup_date'] = time();
1551 $info['backup_uniqueid']= $this->get_backupid();
1552 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1553 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1554 $info['include_file_references_to_external_content'] =
1555 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1556 $info['original_wwwroot']=$CFG->wwwroot;
1557 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1558 $info['original_course_id'] = $this->get_courseid();
1559 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1560 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1561 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1562 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1563 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1564 $info['original_system_contextid'] = context_system::instance()->id;
1566 // Get more information from controller
1567 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
1568 $this->get_backupid(), $this->get_task()->get_progress());
1570 // Define elements
1572 $moodle_backup = new backup_nested_element('moodle_backup');
1574 $information = new backup_nested_element('information', null, array(
1575 'name', 'moodle_version', 'moodle_release', 'backup_version',
1576 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1577 'original_site_identifier_hash', 'original_course_id',
1578 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1579 'original_course_contextid', 'original_system_contextid'));
1581 $details = new backup_nested_element('details');
1583 $detail = new backup_nested_element('detail', array('backup_id'), array(
1584 'type', 'format', 'interactive', 'mode',
1585 'execution', 'executiontime'));
1587 $contents = new backup_nested_element('contents');
1589 $activities = new backup_nested_element('activities');
1591 $activity = new backup_nested_element('activity', null, array(
1592 'moduleid', 'sectionid', 'modulename', 'title',
1593 'directory'));
1595 $sections = new backup_nested_element('sections');
1597 $section = new backup_nested_element('section', null, array(
1598 'sectionid', 'title', 'directory'));
1600 $course = new backup_nested_element('course', null, array(
1601 'courseid', 'title', 'directory'));
1603 $settings = new backup_nested_element('settings');
1605 $setting = new backup_nested_element('setting', null, array(
1606 'level', 'section', 'activity', 'name', 'value'));
1608 // Build the tree
1610 $moodle_backup->add_child($information);
1612 $information->add_child($details);
1613 $details->add_child($detail);
1615 $information->add_child($contents);
1616 if (!empty($cinfo['activities'])) {
1617 $contents->add_child($activities);
1618 $activities->add_child($activity);
1620 if (!empty($cinfo['sections'])) {
1621 $contents->add_child($sections);
1622 $sections->add_child($section);
1624 if (!empty($cinfo['course'])) {
1625 $contents->add_child($course);
1628 $information->add_child($settings);
1629 $settings->add_child($setting);
1632 // Set the sources
1634 $information->set_source_array(array((object)$info));
1636 $detail->set_source_array($dinfo);
1638 $activity->set_source_array($cinfo['activities']);
1640 $section->set_source_array($cinfo['sections']);
1642 $course->set_source_array($cinfo['course']);
1644 $setting->set_source_array($sinfo);
1646 // Prepare some information to be sent to main moodle_backup.xml file
1647 return $moodle_backup;
1653 * Execution step that will generate the final zip (.mbz) file with all the contents
1655 class backup_zip_contents extends backup_execution_step implements file_progress {
1657 * @var bool True if we have started tracking progress
1659 protected $startedprogress;
1661 protected function define_execution() {
1663 // Get basepath
1664 $basepath = $this->get_basepath();
1666 // Get the list of files in directory
1667 $filestemp = get_directory_list($basepath, '', false, true, true);
1668 $files = array();
1669 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1670 $files[$file] = $basepath . '/' . $file;
1673 // Add the log file if exists
1674 $logfilepath = $basepath . '.log';
1675 if (file_exists($logfilepath)) {
1676 $files['moodle_backup.log'] = $logfilepath;
1679 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1680 $zipfile = $basepath . '/backup.mbz';
1682 // Get the zip packer
1683 $zippacker = get_file_packer('application/vnd.moodle.backup');
1685 // Track overall progress for the 2 long-running steps (archive to
1686 // pathname, get backup information).
1687 $reporter = $this->task->get_progress();
1688 $reporter->start_progress('backup_zip_contents', 2);
1690 // Zip files
1691 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1693 // If any sub-progress happened, end it.
1694 if ($this->startedprogress) {
1695 $this->task->get_progress()->end_progress();
1696 $this->startedprogress = false;
1697 } else {
1698 // No progress was reported, manually move it on to the next overall task.
1699 $reporter->progress(1);
1702 // Something went wrong.
1703 if ($result === false) {
1704 @unlink($zipfile);
1705 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
1707 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
1708 try {
1709 backup_general_helper::get_backup_information_from_mbz($zipfile, $this);
1710 } catch (backup_helper_exception $e) {
1711 @unlink($zipfile);
1712 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
1715 // If any sub-progress happened, end it.
1716 if ($this->startedprogress) {
1717 $this->task->get_progress()->end_progress();
1718 $this->startedprogress = false;
1719 } else {
1720 $reporter->progress(2);
1722 $reporter->end_progress();
1726 * Implementation for file_progress interface to display unzip progress.
1728 * @param int $progress Current progress
1729 * @param int $max Max value
1731 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
1732 $reporter = $this->task->get_progress();
1734 // Start tracking progress if necessary.
1735 if (!$this->startedprogress) {
1736 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
1737 ? \core\progress\base::INDETERMINATE : $max);
1738 $this->startedprogress = true;
1741 // Pass progress through to whatever handles it.
1742 $reporter->progress(($progress == file_progress::INDETERMINATE)
1743 ? \core\progress\base::INDETERMINATE : $progress);
1748 * This step will send the generated backup file to its final destination
1750 class backup_store_backup_file extends backup_execution_step {
1752 protected function define_execution() {
1754 // Get basepath
1755 $basepath = $this->get_basepath();
1757 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1758 $zipfile = $basepath . '/backup.mbz';
1760 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1761 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1762 return array(
1763 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
1764 $this->task->get_progress()),
1765 'include_file_references_to_external_content' => $has_file_references
1772 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1773 * and put them to the backup_ids tables, to be used later as base to backup them
1775 class backup_activity_grade_items_to_ids extends backup_execution_step {
1777 protected function define_execution() {
1779 // Fetch all activity grade items
1780 if ($items = grade_item::fetch_all(array(
1781 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1782 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1783 // Annotate them in backup_ids
1784 foreach ($items as $item) {
1785 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1792 * This step will annotate all the groups and groupings belonging to the course
1794 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1796 protected function define_execution() {
1797 global $DB;
1799 // Get all the course groups
1800 if ($groups = $DB->get_records('groups', array(
1801 'courseid' => $this->task->get_courseid()))) {
1802 foreach ($groups as $group) {
1803 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1807 // Get all the course groupings
1808 if ($groupings = $DB->get_records('groupings', array(
1809 'courseid' => $this->task->get_courseid()))) {
1810 foreach ($groupings as $grouping) {
1811 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1818 * This step will annotate all the groups belonging to already annotated groupings
1820 class backup_annotate_groups_from_groupings extends backup_execution_step {
1822 protected function define_execution() {
1823 global $DB;
1825 // Fetch all the annotated groupings
1826 if ($groupings = $DB->get_records('backup_ids_temp', array(
1827 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1828 foreach ($groupings as $grouping) {
1829 if ($groups = $DB->get_records('groupings_groups', array(
1830 'groupingid' => $grouping->itemid))) {
1831 foreach ($groups as $group) {
1832 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1841 * This step will annotate all the scales belonging to already annotated outcomes
1843 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1845 protected function define_execution() {
1846 global $DB;
1848 // Fetch all the annotated outcomes
1849 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1850 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1851 foreach ($outcomes as $outcome) {
1852 if ($scale = $DB->get_record('grade_outcomes', array(
1853 'id' => $outcome->itemid))) {
1854 // Annotate as scalefinal because it's > 0
1855 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1863 * This step will generate all the file annotations for the already
1864 * annotated (final) question_categories. It calculates the different
1865 * contexts that are being backup and, annotates all the files
1866 * on every context belonging to the "question" component. As far as
1867 * we are always including *complete* question banks it is safe and
1868 * optimal to do that in this (one pass) way
1870 class backup_annotate_all_question_files extends backup_execution_step {
1872 protected function define_execution() {
1873 global $DB;
1875 // Get all the different contexts for the final question_categories
1876 // annotated along the whole backup
1877 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1878 FROM {question_categories} qc
1879 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
1880 WHERE bi.backupid = ?
1881 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
1882 // To know about qtype specific components/fileareas
1883 $components = backup_qtype_plugin::get_components_and_fileareas();
1884 // Let's loop
1885 foreach($rs as $record) {
1886 // Backup all the file areas the are managed by the core question component.
1887 // That is, by the question_type base class. In particular, we don't want
1888 // to include files belonging to responses here.
1889 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'questiontext', null);
1890 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'generalfeedback', null);
1891 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answer', null);
1892 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answerfeedback', null);
1893 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'hint', null);
1894 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'correctfeedback', null);
1895 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'partiallycorrectfeedback', null);
1896 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'incorrectfeedback', null);
1898 // For files belonging to question types, we make the leap of faith that
1899 // all the files belonging to the question type are part of the question definition,
1900 // so we can just backup all the files in bulk, without specifying each
1901 // file area name separately.
1902 foreach ($components as $component => $fileareas) {
1903 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
1906 $rs->close();
1911 * structure step in charge of constructing the questions.xml file for all the
1912 * question categories and questions required by the backup
1913 * and letters related to one activity
1915 class backup_questions_structure_step extends backup_structure_step {
1917 protected function define_structure() {
1919 // Define each element separated
1921 $qcategories = new backup_nested_element('question_categories');
1923 $qcategory = new backup_nested_element('question_category', array('id'), array(
1924 'name', 'contextid', 'contextlevel', 'contextinstanceid',
1925 'info', 'infoformat', 'stamp', 'parent',
1926 'sortorder'));
1928 $questions = new backup_nested_element('questions');
1930 $question = new backup_nested_element('question', array('id'), array(
1931 'parent', 'name', 'questiontext', 'questiontextformat',
1932 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
1933 'qtype', 'length', 'stamp', 'version',
1934 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
1936 // attach qtype plugin structure to $question element, only one allowed
1937 $this->add_plugin_structure('qtype', $question, false);
1939 // attach local plugin stucture to $question element, multiple allowed
1940 $this->add_plugin_structure('local', $question, true);
1942 $qhints = new backup_nested_element('question_hints');
1944 $qhint = new backup_nested_element('question_hint', array('id'), array(
1945 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
1947 $tags = new backup_nested_element('tags');
1949 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
1951 // Build the tree
1953 $qcategories->add_child($qcategory);
1954 $qcategory->add_child($questions);
1955 $questions->add_child($question);
1956 $question->add_child($qhints);
1957 $qhints->add_child($qhint);
1959 $question->add_child($tags);
1960 $tags->add_child($tag);
1962 // Define the sources
1964 $qcategory->set_source_sql("
1965 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
1966 FROM {question_categories} gc
1967 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
1968 JOIN {context} co ON co.id = gc.contextid
1969 WHERE bi.backupid = ?
1970 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
1972 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
1974 $qhint->set_source_sql('
1975 SELECT *
1976 FROM {question_hints}
1977 WHERE questionid = :questionid
1978 ORDER BY id',
1979 array('questionid' => backup::VAR_PARENTID));
1981 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
1982 FROM {tag} t
1983 JOIN {tag_instance} ti ON ti.tagid = t.id
1984 WHERE ti.itemid = ?
1985 AND ti.itemtype = 'question'", array(backup::VAR_PARENTID));
1987 // don't need to annotate ids nor files
1988 // (already done by {@link backup_annotate_all_question_files}
1990 return $qcategories;
1997 * This step will generate all the file annotations for the already
1998 * annotated (final) users. Need to do this here because each user
1999 * has its own context and structure tasks only are able to handle
2000 * one context. Also, this step will guarantee that every user has
2001 * its context created (req for other steps)
2003 class backup_annotate_all_user_files extends backup_execution_step {
2005 protected function define_execution() {
2006 global $DB;
2008 // List of fileareas we are going to annotate
2009 $fileareas = array('profile', 'icon');
2011 // Fetch all annotated (final) users
2012 $rs = $DB->get_recordset('backup_ids_temp', array(
2013 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2014 $progress = $this->task->get_progress();
2015 $progress->start_progress($this->get_name());
2016 foreach ($rs as $record) {
2017 $userid = $record->itemid;
2018 $userctx = context_user::instance($userid, IGNORE_MISSING);
2019 if (!$userctx) {
2020 continue; // User has not context, sure it's a deleted user, so cannot have files
2022 // Proceed with every user filearea
2023 foreach ($fileareas as $filearea) {
2024 // We don't need to specify itemid ($userid - 5th param) as far as by
2025 // context we can get all the associated files. See MDL-22092
2026 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2027 $progress->progress();
2030 $progress->end_progress();
2031 $rs->close();
2037 * Defines the backup step for advanced grading methods attached to the activity module
2039 class backup_activity_grading_structure_step extends backup_structure_step {
2042 * Include the grading.xml only if the module supports advanced grading
2044 protected function execute_condition() {
2045 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2049 * Declares the gradable areas structures and data sources
2051 protected function define_structure() {
2053 // To know if we are including userinfo
2054 $userinfo = $this->get_setting_value('userinfo');
2056 // Define the elements
2058 $areas = new backup_nested_element('areas');
2060 $area = new backup_nested_element('area', array('id'), array(
2061 'areaname', 'activemethod'));
2063 $definitions = new backup_nested_element('definitions');
2065 $definition = new backup_nested_element('definition', array('id'), array(
2066 'method', 'name', 'description', 'descriptionformat', 'status',
2067 'timecreated', 'timemodified', 'options'));
2069 $instances = new backup_nested_element('instances');
2071 $instance = new backup_nested_element('instance', array('id'), array(
2072 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2073 'feedbackformat', 'timemodified'));
2075 // Build the tree including the method specific structures
2076 // (beware - the order of how gradingform plugins structures are attached is important)
2077 $areas->add_child($area);
2078 // attach local plugin stucture to $area element, multiple allowed
2079 $this->add_plugin_structure('local', $area, true);
2080 $area->add_child($definitions);
2081 $definitions->add_child($definition);
2082 $this->add_plugin_structure('gradingform', $definition, true);
2083 // attach local plugin stucture to $definition element, multiple allowed
2084 $this->add_plugin_structure('local', $definition, true);
2085 $definition->add_child($instances);
2086 $instances->add_child($instance);
2087 $this->add_plugin_structure('gradingform', $instance, false);
2088 // attach local plugin stucture to $instance element, multiple allowed
2089 $this->add_plugin_structure('local', $instance, true);
2091 // Define data sources
2093 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2094 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2096 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2098 if ($userinfo) {
2099 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2102 // Annotate references
2103 $definition->annotate_files('grading', 'description', 'id');
2104 $instance->annotate_ids('user', 'raterid');
2106 // Return the root element
2107 return $areas;
2113 * structure step in charge of constructing the grades.xml file for all the grade items
2114 * and letters related to one activity
2116 class backup_activity_grades_structure_step extends backup_structure_step {
2118 protected function define_structure() {
2120 // To know if we are including userinfo
2121 $userinfo = $this->get_setting_value('userinfo');
2123 // Define each element separated
2125 $book = new backup_nested_element('activity_gradebook');
2127 $items = new backup_nested_element('grade_items');
2129 $item = new backup_nested_element('grade_item', array('id'), array(
2130 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2131 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2132 'calculation', 'gradetype', 'grademax', 'grademin',
2133 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2134 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
2135 'decimals', 'hidden', 'locked', 'locktime',
2136 'needsupdate', 'timecreated', 'timemodified'));
2138 $grades = new backup_nested_element('grade_grades');
2140 $grade = new backup_nested_element('grade_grade', array('id'), array(
2141 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2142 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2143 'locked', 'locktime', 'exported', 'overridden',
2144 'excluded', 'feedback', 'feedbackformat', 'information',
2145 'informationformat', 'timecreated', 'timemodified'));
2147 $letters = new backup_nested_element('grade_letters');
2149 $letter = new backup_nested_element('grade_letter', 'id', array(
2150 'lowerboundary', 'letter'));
2152 // Build the tree
2154 $book->add_child($items);
2155 $items->add_child($item);
2157 $item->add_child($grades);
2158 $grades->add_child($grade);
2160 $book->add_child($letters);
2161 $letters->add_child($letter);
2163 // Define sources
2165 $item->set_source_sql("SELECT gi.*
2166 FROM {grade_items} gi
2167 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2168 WHERE bi.backupid = ?
2169 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2171 // This only happens if we are including user info
2172 if ($userinfo) {
2173 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2176 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2178 // Annotations
2180 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2181 $item->annotate_ids('outcome', 'outcomeid');
2183 $grade->annotate_ids('user', 'userid');
2184 $grade->annotate_ids('user', 'usermodified');
2186 // Return the root element (book)
2188 return $book;
2193 * Backups up the course completion information for the course.
2195 class backup_course_completion_structure_step extends backup_structure_step {
2197 protected function execute_condition() {
2198 // Check that all activities have been included
2199 if ($this->task->is_excluding_activities()) {
2200 return false;
2202 return true;
2206 * The structure of the course completion backup
2208 * @return backup_nested_element
2210 protected function define_structure() {
2212 // To know if we are including user completion info
2213 $userinfo = $this->get_setting_value('userscompletion');
2215 $cc = new backup_nested_element('course_completion');
2217 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2218 'course','criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod', 'timeend', 'gradepass', 'role'
2221 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2223 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2224 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2227 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2228 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2231 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2232 'course','criteriatype','method','value'
2235 $cc->add_child($criteria);
2236 $criteria->add_child($criteriacompletions);
2237 $criteriacompletions->add_child($criteriacomplete);
2238 $cc->add_child($coursecompletions);
2239 $cc->add_child($aggregatemethod);
2241 // We need to get the courseinstances shortname rather than an ID for restore
2242 $criteria->set_source_sql("SELECT ccc.*, c.shortname AS courseinstanceshortname
2243 FROM {course_completion_criteria} ccc
2244 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2245 WHERE ccc.course = ?", array(backup::VAR_COURSEID));
2248 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2250 if ($userinfo) {
2251 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2252 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2255 $criteria->annotate_ids('role', 'role');
2256 $criteriacomplete->annotate_ids('user', 'userid');
2257 $coursecompletions->annotate_ids('user', 'userid');
2259 return $cc;