Merge branch 'MDL-44620_master' of git://github.com/dmonllao/moodle into MOODLE_27_STABLE
[moodle.git] / backup / moodle2 / backup_stepslib.php
blob53cce2283561f3d865d8d6fa9622198b73c868f5
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,
32 * delete old directories and create temp ids table
34 class create_and_clean_temp_stuff extends backup_execution_step {
36 protected function define_execution() {
37 $progress = $this->task->get_progress();
38 $progress->start_progress('Deleting backup directories');
39 backup_helper::check_and_create_backup_dir($this->get_backupid());// Create backup temp dir
40 backup_helper::clear_backup_dir($this->get_backupid(), $progress); // Empty temp dir, just in case
41 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60), $progress); // Delete > 4 hours temp dirs
42 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
43 backup_controller_dbops::create_backup_ids_temp_table($this->get_backupid()); // Create ids temp table
44 $progress->end_progress();
48 /**
49 * delete the temp dir used by backup/restore (conditionally),
50 * delete old directories and drop tem ids table. Note we delete
51 * the directory but not the corresponding log file that will be
52 * there for, at least, 4 hours - only delete_old_backup_dirs()
53 * deletes log files (for easier access to them)
55 class drop_and_clean_temp_stuff extends backup_execution_step {
57 protected $skipcleaningtempdir = false;
59 protected function define_execution() {
60 global $CFG;
62 backup_controller_dbops::drop_backup_ids_temp_table($this->get_backupid()); // Drop ids temp table
63 backup_helper::delete_old_backup_dirs(time() - (4 * 60 * 60)); // Delete > 4 hours temp dirs
64 // Delete temp dir conditionally:
65 // 1) If $CFG->keeptempdirectoriesonbackup is not enabled
66 // 2) If backup temp dir deletion has been marked to be avoided
67 if (empty($CFG->keeptempdirectoriesonbackup) && !$this->skipcleaningtempdir) {
68 $progress = $this->task->get_progress();
69 $progress->start_progress('Deleting backup dir');
70 backup_helper::delete_backup_dir($this->get_backupid(), $progress); // Empty backup dir
71 $progress->end_progress();
75 public function skip_cleaning_temp_dir($skip) {
76 $this->skipcleaningtempdir = $skip;
80 /**
81 * Create the directory where all the task (activity/block...) information will be stored
83 class create_taskbasepath_directory extends backup_execution_step {
85 protected function define_execution() {
86 global $CFG;
87 $basepath = $this->task->get_taskbasepath();
88 if (!check_dir_exists($basepath, true, true)) {
89 throw new backup_step_exception('cannot_create_taskbasepath_directory', $basepath);
94 /**
95 * Abstract structure step, parent of all the activity structure steps. Used to wrap the
96 * activity structure definition within the main <activity ...> tag. Also provides
97 * subplugin support for activities (that must be properly declared)
99 abstract class backup_activity_structure_step extends backup_structure_step {
102 * Add subplugin structure to any element in the activity backup tree
104 * @param string $subplugintype type of subplugin as defined in activity db/subplugins.php
105 * @param backup_nested_element $element element in the activity backup tree that
106 * we are going to add subplugin information to
107 * @param bool $multiple to define if multiple subplugins can produce information
108 * for each instance of $element (true) or no (false)
109 * @return void
111 protected function add_subplugin_structure($subplugintype, $element, $multiple) {
113 global $CFG;
115 // Check the requested subplugintype is a valid one
116 $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php';
117 if (!file_exists($subpluginsfile)) {
118 throw new backup_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename());
120 include($subpluginsfile);
121 if (!array_key_exists($subplugintype, $subplugins)) {
122 throw new backup_step_exception('incorrect_subplugin_type', $subplugintype);
125 // Arrived here, subplugin is correct, let's create the optigroup
126 $optigroupname = $subplugintype . '_' . $element->get_name() . '_subplugin';
127 $optigroup = new backup_optigroup($optigroupname, null, $multiple);
128 $element->add_child($optigroup); // Add optigroup to stay connected since beginning
130 // Get all the optigroup_elements, looking across all the subplugin dirs
131 $subpluginsdirs = core_component::get_plugin_list($subplugintype);
132 foreach ($subpluginsdirs as $name => $subpluginsdir) {
133 $classname = 'backup_' . $subplugintype . '_' . $name . '_subplugin';
134 $backupfile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php';
135 if (file_exists($backupfile)) {
136 require_once($backupfile);
137 $backupsubplugin = new $classname($subplugintype, $name, $optigroup, $this);
138 // Add subplugin returned structure to optigroup
139 $backupsubplugin->define_subplugin_structure($element->get_name());
145 * As far as activity backup steps are implementing backup_subplugin stuff, they need to
146 * have the parent task available for wrapping purposes (get course/context....)
148 * @return backup_activity_task
150 public function get_task() {
151 return $this->task;
155 * Wraps any activity backup structure within the common 'activity' element
156 * that will include common to all activities information like id, context...
158 * @param backup_nested_element $activitystructure the element to wrap
159 * @return backup_nested_element the $activitystructure wrapped by the common 'activity' element
161 protected function prepare_activity_structure($activitystructure) {
163 // Create the wrap element
164 $activity = new backup_nested_element('activity', array('id', 'moduleid', 'modulename', 'contextid'), null);
166 // Build the tree
167 $activity->add_child($activitystructure);
169 // Set the source
170 $activityarr = array((object)array(
171 'id' => $this->task->get_activityid(),
172 'moduleid' => $this->task->get_moduleid(),
173 'modulename' => $this->task->get_modulename(),
174 'contextid' => $this->task->get_contextid()));
176 $activity->set_source_array($activityarr);
178 // Return the root element (activity)
179 return $activity;
184 * Abstract structure step, to be used by all the activities using core questions stuff
185 * (namely quiz module), supporting question plugins, states and sessions
187 abstract class backup_questions_activity_structure_step extends backup_activity_structure_step {
190 * Attach to $element (usually attempts) the needed backup structures
191 * for question_usages and all the associated data.
193 * @param backup_nested_element $element the element that will contain all the question_usages data.
194 * @param string $usageidname the name of the element that holds the usageid.
195 * This must be child of $element, and must be a final element.
196 * @param string $nameprefix this prefix is added to all the element names we create.
197 * Element names in the XML must be unique, so if you are using usages in
198 * two different ways, you must give a prefix to at least one of them. If
199 * you only use one sort of usage, then you can just use the default empty prefix.
200 * This should include a trailing underscore. For example "myprefix_"
202 protected function add_question_usages($element, $usageidname, $nameprefix = '') {
203 global $CFG;
204 require_once($CFG->dirroot . '/question/engine/lib.php');
206 // Check $element is one nested_backup_element
207 if (! $element instanceof backup_nested_element) {
208 throw new backup_step_exception('question_states_bad_parent_element', $element);
210 if (! $element->get_final_element($usageidname)) {
211 throw new backup_step_exception('question_states_bad_question_attempt_element', $usageidname);
214 $quba = new backup_nested_element($nameprefix . 'question_usage', array('id'),
215 array('component', 'preferredbehaviour'));
217 $qas = new backup_nested_element($nameprefix . 'question_attempts');
218 $qa = new backup_nested_element($nameprefix . 'question_attempt', array('id'), array(
219 'slot', 'behaviour', 'questionid', 'variant', 'maxmark', 'minfraction', 'maxfraction',
220 'flagged', 'questionsummary', 'rightanswer', 'responsesummary',
221 'timemodified'));
223 $steps = new backup_nested_element($nameprefix . 'steps');
224 $step = new backup_nested_element($nameprefix . 'step', array('id'), array(
225 'sequencenumber', 'state', 'fraction', 'timecreated', 'userid'));
227 $response = new backup_nested_element($nameprefix . 'response');
228 $variable = new backup_nested_element($nameprefix . 'variable', null, array('name', 'value'));
230 // Build the tree
231 $element->add_child($quba);
232 $quba->add_child($qas);
233 $qas->add_child($qa);
234 $qa->add_child($steps);
235 $steps->add_child($step);
236 $step->add_child($response);
237 $response->add_child($variable);
239 // Set the sources
240 $quba->set_source_table('question_usages',
241 array('id' => '../' . $usageidname));
242 $qa->set_source_table('question_attempts', array('questionusageid' => backup::VAR_PARENTID), 'slot ASC');
243 $step->set_source_table('question_attempt_steps', array('questionattemptid' => backup::VAR_PARENTID), 'sequencenumber ASC');
244 $variable->set_source_table('question_attempt_step_data', array('attemptstepid' => backup::VAR_PARENTID));
246 // Annotate ids
247 $qa->annotate_ids('question', 'questionid');
248 $step->annotate_ids('user', 'userid');
250 // Annotate files
251 $fileareas = question_engine::get_all_response_file_areas();
252 foreach ($fileareas as $filearea) {
253 $step->annotate_files('question', $filearea, 'id');
260 * backup structure step in charge of calculating the categories to be
261 * included in backup, based in the context being backuped (module/course)
262 * and the already annotated questions present in backup_ids_temp
264 class backup_calculate_question_categories extends backup_execution_step {
266 protected function define_execution() {
267 backup_question_dbops::calculate_question_categories($this->get_backupid(), $this->task->get_contextid());
272 * backup structure step in charge of deleting all the questions annotated
273 * in the backup_ids_temp table
275 class backup_delete_temp_questions extends backup_execution_step {
277 protected function define_execution() {
278 backup_question_dbops::delete_temp_questions($this->get_backupid());
283 * Abstract structure step, parent of all the block structure steps. Used to wrap the
284 * block structure definition within the main <block ...> tag
286 abstract class backup_block_structure_step extends backup_structure_step {
288 protected function prepare_block_structure($blockstructure) {
290 // Create the wrap element
291 $block = new backup_nested_element('block', array('id', 'blockname', 'contextid'), null);
293 // Build the tree
294 $block->add_child($blockstructure);
296 // Set the source
297 $blockarr = array((object)array(
298 'id' => $this->task->get_blockid(),
299 'blockname' => $this->task->get_blockname(),
300 'contextid' => $this->task->get_contextid()));
302 $block->set_source_array($blockarr);
304 // Return the root element (block)
305 return $block;
310 * structure step that will generate the module.xml file for the activity,
311 * accumulating various information about the activity, annotating groupings
312 * and completion/avail conf
314 class backup_module_structure_step extends backup_structure_step {
316 protected function define_structure() {
317 global $DB;
319 // Define each element separated
321 $module = new backup_nested_element('module', array('id', 'version'), array(
322 'modulename', 'sectionid', 'sectionnumber', 'idnumber',
323 'added', 'score', 'indent', 'visible',
324 'visibleold', 'groupmode', 'groupingid', 'groupmembersonly',
325 'completion', 'completiongradeitemnumber', 'completionview', 'completionexpected',
326 'availability', 'showdescription'));
328 // attach format plugin structure to $module element, only one allowed
329 $this->add_plugin_structure('format', $module, false);
331 // attach plagiarism plugin structure to $module element, there can be potentially
332 // many plagiarism plugins storing information about this course
333 $this->add_plugin_structure('plagiarism', $module, true);
335 // attach local plugin structure to $module, multiple allowed
336 $this->add_plugin_structure('local', $module, true);
338 // Set the sources
339 $concat = $DB->sql_concat("'mod_'", 'm.name');
340 $module->set_source_sql("
341 SELECT cm.*, cp.value AS version, m.name AS modulename, s.id AS sectionid, s.section AS sectionnumber
342 FROM {course_modules} cm
343 JOIN {modules} m ON m.id = cm.module
344 JOIN {config_plugins} cp ON cp.plugin = $concat AND cp.name = 'version'
345 JOIN {course_sections} s ON s.id = cm.section
346 WHERE cm.id = ?", array(backup::VAR_MODID));
348 // Define annotations
349 $module->annotate_ids('grouping', 'groupingid');
351 // Return the root element ($module)
352 return $module;
357 * structure step that will generate the section.xml file for the section
358 * annotating files
360 class backup_section_structure_step extends backup_structure_step {
362 protected function define_structure() {
364 // Define each element separated
366 $section = new backup_nested_element('section', array('id'), array(
367 'number', 'name', 'summary', 'summaryformat', 'sequence', 'visible',
368 'availabilityjson'));
370 // attach format plugin structure to $section element, only one allowed
371 $this->add_plugin_structure('format', $section, false);
373 // attach local plugin structure to $section element, multiple allowed
374 $this->add_plugin_structure('local', $section, true);
376 // Add nested elements for course_format_options table
377 $formatoptions = new backup_nested_element('course_format_options', array('id'), array(
378 'format', 'name', 'value'));
379 $section->add_child($formatoptions);
381 // Define sources.
382 $section->set_source_table('course_sections', array('id' => backup::VAR_SECTIONID));
383 $formatoptions->set_source_sql('SELECT cfo.id, cfo.format, cfo.name, cfo.value
384 FROM {course} c
385 JOIN {course_format_options} cfo
386 ON cfo.courseid = c.id AND cfo.format = c.format
387 WHERE c.id = ? AND cfo.sectionid = ?',
388 array(backup::VAR_COURSEID, backup::VAR_SECTIONID));
390 // Aliases
391 $section->set_source_alias('section', 'number');
392 // The 'availability' field needs to be renamed because it clashes with
393 // the old nested element structure for availability data.
394 $section->set_source_alias('availability', 'availabilityjson');
396 // Set annotations
397 $section->annotate_files('course', 'section', 'id');
399 return $section;
404 * structure step that will generate the course.xml file for the course, including
405 * course category reference, tags, modules restriction information
406 * and some annotations (files & groupings)
408 class backup_course_structure_step extends backup_structure_step {
410 protected function define_structure() {
411 global $DB;
413 // Define each element separated
415 $course = new backup_nested_element('course', array('id', 'contextid'), array(
416 'shortname', 'fullname', 'idnumber',
417 'summary', 'summaryformat', 'format', 'showgrades',
418 'newsitems', 'startdate',
419 'marker', 'maxbytes', 'legacyfiles', 'showreports',
420 'visible', 'groupmode', 'groupmodeforce',
421 'defaultgroupingid', 'lang', 'theme',
422 'timecreated', 'timemodified',
423 'requested',
424 'enablecompletion', 'completionstartonenrol', 'completionnotify'));
426 $category = new backup_nested_element('category', array('id'), array(
427 'name', 'description'));
429 $tags = new backup_nested_element('tags');
431 $tag = new backup_nested_element('tag', array('id'), array(
432 'name', 'rawname'));
434 // attach format plugin structure to $course element, only one allowed
435 $this->add_plugin_structure('format', $course, false);
437 // attach theme plugin structure to $course element; multiple themes can
438 // save course data (in case of user theme, legacy theme, etc)
439 $this->add_plugin_structure('theme', $course, true);
441 // attach general report plugin structure to $course element; multiple
442 // reports can save course data if required
443 $this->add_plugin_structure('report', $course, true);
445 // attach course report plugin structure to $course element; multiple
446 // course reports can save course data if required
447 $this->add_plugin_structure('coursereport', $course, true);
449 // attach plagiarism plugin structure to $course element, there can be potentially
450 // many plagiarism plugins storing information about this course
451 $this->add_plugin_structure('plagiarism', $course, true);
453 // attach local plugin structure to $course element; multiple local plugins
454 // can save course data if required
455 $this->add_plugin_structure('local', $course, true);
457 // Build the tree
459 $course->add_child($category);
461 $course->add_child($tags);
462 $tags->add_child($tag);
464 // Set the sources
466 $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
467 $courserec->contextid = $this->task->get_contextid();
469 $formatoptions = course_get_format($courserec)->get_format_options();
470 $course->add_final_elements(array_keys($formatoptions));
471 foreach ($formatoptions as $key => $value) {
472 $courserec->$key = $value;
475 $course->set_source_array(array($courserec));
477 $categoryrec = $DB->get_record('course_categories', array('id' => $courserec->category));
479 $category->set_source_array(array($categoryrec));
481 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
482 FROM {tag} t
483 JOIN {tag_instance} ti ON ti.tagid = t.id
484 WHERE ti.itemtype = ?
485 AND ti.itemid = ?', array(
486 backup_helper::is_sqlparam('course'),
487 backup::VAR_PARENTID));
489 // Some annotations
491 $course->annotate_ids('grouping', 'defaultgroupingid');
493 $course->annotate_files('course', 'summary', null);
494 $course->annotate_files('course', 'overviewfiles', null);
495 $course->annotate_files('course', 'legacy', null);
497 // Return root element ($course)
499 return $course;
504 * structure step that will generate the enrolments.xml file for the given course
506 class backup_enrolments_structure_step extends backup_structure_step {
508 protected function define_structure() {
510 // To know if we are including users
511 $users = $this->get_setting_value('users');
513 // Define each element separated
515 $enrolments = new backup_nested_element('enrolments');
517 $enrols = new backup_nested_element('enrols');
519 $enrol = new backup_nested_element('enrol', array('id'), array(
520 'enrol', 'status', 'name', 'enrolperiod', 'enrolstartdate',
521 'enrolenddate', 'expirynotify', 'expirytreshold', 'notifyall',
522 'password', 'cost', 'currency', 'roleid',
523 'customint1', 'customint2', 'customint3', 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
524 'customchar1', 'customchar2', 'customchar3',
525 'customdec1', 'customdec2',
526 'customtext1', 'customtext2', 'customtext3', 'customtext4',
527 'timecreated', 'timemodified'));
529 $userenrolments = new backup_nested_element('user_enrolments');
531 $enrolment = new backup_nested_element('enrolment', array('id'), array(
532 'status', 'userid', 'timestart', 'timeend', 'modifierid',
533 'timemodified'));
535 // Build the tree
536 $enrolments->add_child($enrols);
537 $enrols->add_child($enrol);
538 $enrol->add_child($userenrolments);
539 $userenrolments->add_child($enrolment);
541 // Define sources - the instances are restored using the same sortorder, we do not need to store it in xml and deal with it afterwards.
542 $enrol->set_source_table('enrol', array('courseid' => backup::VAR_COURSEID), 'sortorder ASC');
544 // User enrolments only added only if users included
545 if ($users) {
546 $enrolment->set_source_table('user_enrolments', array('enrolid' => backup::VAR_PARENTID));
547 $enrolment->annotate_ids('user', 'userid');
550 $enrol->annotate_ids('role', 'roleid');
552 //TODO: let plugins annotate custom fields too and add more children
554 return $enrolments;
559 * structure step that will generate the roles.xml file for the given context, observing
560 * the role_assignments setting to know if that part needs to be included
562 class backup_roles_structure_step extends backup_structure_step {
564 protected function define_structure() {
566 // To know if we are including role assignments
567 $roleassignments = $this->get_setting_value('role_assignments');
569 // Define each element separated
571 $roles = new backup_nested_element('roles');
573 $overrides = new backup_nested_element('role_overrides');
575 $override = new backup_nested_element('override', array('id'), array(
576 'roleid', 'capability', 'permission', 'timemodified',
577 'modifierid'));
579 $assignments = new backup_nested_element('role_assignments');
581 $assignment = new backup_nested_element('assignment', array('id'), array(
582 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
583 'sortorder'));
585 // Build the tree
586 $roles->add_child($overrides);
587 $roles->add_child($assignments);
589 $overrides->add_child($override);
590 $assignments->add_child($assignment);
592 // Define sources
594 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
596 // Assignments only added if specified
597 if ($roleassignments) {
598 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
601 // Define id annotations
602 $override->annotate_ids('role', 'roleid');
604 $assignment->annotate_ids('role', 'roleid');
606 $assignment->annotate_ids('user', 'userid');
608 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
610 return $roles;
615 * structure step that will generate the roles.xml containing the
616 * list of roles used along the whole backup process. Just raw
617 * list of used roles from role table
619 class backup_final_roles_structure_step extends backup_structure_step {
621 protected function define_structure() {
623 // Define elements
625 $rolesdef = new backup_nested_element('roles_definition');
627 $role = new backup_nested_element('role', array('id'), array(
628 'name', 'shortname', 'nameincourse', 'description',
629 'sortorder', 'archetype'));
631 // Build the tree
633 $rolesdef->add_child($role);
635 // Define sources
637 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
638 FROM {role} r
639 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
640 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
641 WHERE bi.backupid = ?
642 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
644 // Return main element (rolesdef)
645 return $rolesdef;
650 * structure step that will generate the scales.xml containing the
651 * list of scales used along the whole backup process.
653 class backup_final_scales_structure_step extends backup_structure_step {
655 protected function define_structure() {
657 // Define elements
659 $scalesdef = new backup_nested_element('scales_definition');
661 $scale = new backup_nested_element('scale', array('id'), array(
662 'courseid', 'userid', 'name', 'scale',
663 'description', 'descriptionformat', 'timemodified'));
665 // Build the tree
667 $scalesdef->add_child($scale);
669 // Define sources
671 $scale->set_source_sql("SELECT s.*
672 FROM {scale} s
673 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
674 WHERE bi.backupid = ?
675 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
677 // Annotate scale files (they store files in system context, so pass it instead of default one)
678 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
680 // Return main element (scalesdef)
681 return $scalesdef;
686 * structure step that will generate the outcomes.xml containing the
687 * list of outcomes used along the whole backup process.
689 class backup_final_outcomes_structure_step extends backup_structure_step {
691 protected function define_structure() {
693 // Define elements
695 $outcomesdef = new backup_nested_element('outcomes_definition');
697 $outcome = new backup_nested_element('outcome', array('id'), array(
698 'courseid', 'userid', 'shortname', 'fullname',
699 'scaleid', 'description', 'descriptionformat', 'timecreated',
700 'timemodified','usermodified'));
702 // Build the tree
704 $outcomesdef->add_child($outcome);
706 // Define sources
708 $outcome->set_source_sql("SELECT o.*
709 FROM {grade_outcomes} o
710 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
711 WHERE bi.backupid = ?
712 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
714 // Annotate outcome files (they store files in system context, so pass it instead of default one)
715 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
717 // Return main element (outcomesdef)
718 return $outcomesdef;
723 * structure step in charge of constructing the filters.xml file for all the filters found
724 * in activity
726 class backup_filters_structure_step extends backup_structure_step {
728 protected function define_structure() {
730 // Define each element separated
732 $filters = new backup_nested_element('filters');
734 $actives = new backup_nested_element('filter_actives');
736 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
738 $configs = new backup_nested_element('filter_configs');
740 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
742 // Build the tree
744 $filters->add_child($actives);
745 $filters->add_child($configs);
747 $actives->add_child($active);
748 $configs->add_child($config);
750 // Define sources
752 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
754 $active->set_source_array($activearr);
755 $config->set_source_array($configarr);
757 // Return the root element (filters)
758 return $filters;
763 * structure step in charge of constructing the comments.xml file for all the comments found
764 * in a given context
766 class backup_comments_structure_step extends backup_structure_step {
768 protected function define_structure() {
770 // Define each element separated
772 $comments = new backup_nested_element('comments');
774 $comment = new backup_nested_element('comment', array('id'), array(
775 'commentarea', 'itemid', 'content', 'format',
776 'userid', 'timecreated'));
778 // Build the tree
780 $comments->add_child($comment);
782 // Define sources
784 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
786 // Define id annotations
788 $comment->annotate_ids('user', 'userid');
790 // Return the root element (comments)
791 return $comments;
796 * structure step in charge of constructing the badges.xml file for all the badges found
797 * in a given context
799 class backup_badges_structure_step extends backup_structure_step {
801 protected function execute_condition() {
802 // Check that all activities have been included.
803 if ($this->task->is_excluding_activities()) {
804 return false;
806 return true;
809 protected function define_structure() {
811 // Define each element separated.
813 $badges = new backup_nested_element('badges');
814 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
815 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
816 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
817 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron'));
819 $criteria = new backup_nested_element('criteria');
820 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
821 'criteriatype', 'method'));
823 $parameters = new backup_nested_element('parameters');
824 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
825 'name', 'value', 'criteriatype'));
827 $manual_awards = new backup_nested_element('manual_awards');
828 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
829 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
831 // Build the tree.
833 $badges->add_child($badge);
834 $badge->add_child($criteria);
835 $criteria->add_child($criterion);
836 $criterion->add_child($parameters);
837 $parameters->add_child($parameter);
838 $badge->add_child($manual_awards);
839 $manual_awards->add_child($manual_award);
841 // Define sources.
843 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
844 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
846 $parametersql = 'SELECT cp.*, c.criteriatype
847 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
848 ON cp.critid = c.id
849 WHERE critid = :critid';
850 $parameterparams = array('critid' => backup::VAR_PARENTID);
851 $parameter->set_source_sql($parametersql, $parameterparams);
853 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
855 // Define id annotations.
857 $badge->annotate_ids('user', 'usercreated');
858 $badge->annotate_ids('user', 'usermodified');
859 $criterion->annotate_ids('badge', 'badgeid');
860 $parameter->annotate_ids('criterion', 'critid');
861 $badge->annotate_files('badges', 'badgeimage', 'id');
862 $manual_award->annotate_ids('badge', 'badgeid');
863 $manual_award->annotate_ids('user', 'recipientid');
864 $manual_award->annotate_ids('user', 'issuerid');
865 $manual_award->annotate_ids('role', 'issuerrole');
867 // Return the root element ($badges).
868 return $badges;
873 * structure step in charge of constructing the calender.xml file for all the events found
874 * in a given context
876 class backup_calendarevents_structure_step extends backup_structure_step {
878 protected function define_structure() {
880 // Define each element separated
882 $events = new backup_nested_element('events');
884 $event = new backup_nested_element('event', array('id'), array(
885 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
886 'repeatid', 'modulename', 'instance', 'eventtype', 'timestart',
887 'timeduration', 'visible', 'uuid', 'sequence', 'timemodified'));
889 // Build the tree
890 $events->add_child($event);
892 // Define sources
893 if ($this->name == 'course_calendar') {
894 $calendar_items_sql ="SELECT * FROM {event}
895 WHERE courseid = :courseid
896 AND (eventtype = 'course' OR eventtype = 'group')";
897 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
898 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
899 } else {
900 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
903 // Define id annotations
905 $event->annotate_ids('user', 'userid');
906 $event->annotate_ids('group', 'groupid');
907 $event->annotate_files('calendar', 'event_description', 'id');
909 // Return the root element (events)
910 return $events;
915 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
916 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
918 class backup_gradebook_structure_step extends backup_structure_step {
921 * We need to decide conditionally, based on dynamic information
922 * about the execution of this step. Only will be executed if all
923 * the module gradeitems have been already included in backup
925 protected function execute_condition() {
926 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
929 protected function define_structure() {
931 // are we including user info?
932 $userinfo = $this->get_setting_value('users');
934 $gradebook = new backup_nested_element('gradebook');
936 //grade_letters are done in backup_activity_grades_structure_step()
938 //calculated grade items
939 $grade_items = new backup_nested_element('grade_items');
940 $grade_item = new backup_nested_element('grade_item', array('id'), array(
941 'categoryid', 'itemname', 'itemtype', 'itemmodule',
942 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
943 'calculation', 'gradetype', 'grademax', 'grademin',
944 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
945 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
946 'decimals', 'hidden', 'locked', 'locktime',
947 'needsupdate', 'timecreated', 'timemodified'));
949 $grade_grades = new backup_nested_element('grade_grades');
950 $grade_grade = new backup_nested_element('grade_grade', array('id'), array(
951 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
952 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
953 'locked', 'locktime', 'exported', 'overridden',
954 'excluded', 'feedback', 'feedbackformat', 'information',
955 'informationformat', 'timecreated', 'timemodified'));
957 //grade_categories
958 $grade_categories = new backup_nested_element('grade_categories');
959 $grade_category = new backup_nested_element('grade_category', array('id'), array(
960 //'courseid',
961 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
962 'droplow', 'aggregateonlygraded', 'aggregateoutcomes', 'aggregatesubcats',
963 'timecreated', 'timemodified', 'hidden'));
965 $letters = new backup_nested_element('grade_letters');
966 $letter = new backup_nested_element('grade_letter', 'id', array(
967 'lowerboundary', 'letter'));
969 $grade_settings = new backup_nested_element('grade_settings');
970 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
971 'name', 'value'));
974 // Build the tree
975 $gradebook->add_child($grade_categories);
976 $grade_categories->add_child($grade_category);
978 $gradebook->add_child($grade_items);
979 $grade_items->add_child($grade_item);
980 $grade_item->add_child($grade_grades);
981 $grade_grades->add_child($grade_grade);
983 $gradebook->add_child($letters);
984 $letters->add_child($letter);
986 $gradebook->add_child($grade_settings);
987 $grade_settings->add_child($grade_setting);
989 // Define sources
991 //Include manual, category and the course grade item
992 $grade_items_sql ="SELECT * FROM {grade_items}
993 WHERE courseid = :courseid
994 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
995 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
996 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
998 if ($userinfo) {
999 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1002 $grade_category_sql = "SELECT gc.*, gi.sortorder
1003 FROM {grade_categories} gc
1004 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1005 WHERE gc.courseid = :courseid
1006 AND (gi.itemtype='course' OR gi.itemtype='category')
1007 ORDER BY gc.parent ASC";//need parent categories before their children
1008 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1009 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1011 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1013 $grade_setting->set_source_table('grade_settings', array('courseid' => backup::VAR_COURSEID));
1015 // Annotations (both as final as far as they are going to be exported in next steps)
1016 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1017 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1019 //just in case there are any users not already annotated by the activities
1020 $grade_grade->annotate_ids('userfinal', 'userid');
1022 // Return the root element
1023 return $gradebook;
1028 * structure step in charge if constructing the completion.xml file for all the users completion
1029 * information in a given activity
1031 class backup_userscompletion_structure_step extends backup_structure_step {
1033 protected function define_structure() {
1035 // Define each element separated
1037 $completions = new backup_nested_element('completions');
1039 $completion = new backup_nested_element('completion', array('id'), array(
1040 'userid', 'completionstate', 'viewed', 'timemodified'));
1042 // Build the tree
1044 $completions->add_child($completion);
1046 // Define sources
1048 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1050 // Define id annotations
1052 $completion->annotate_ids('user', 'userid');
1054 // Return the root element (completions)
1055 return $completions;
1060 * structure step in charge of constructing the main groups.xml file for all the groups and
1061 * groupings information already annotated
1063 class backup_groups_structure_step extends backup_structure_step {
1065 protected function define_structure() {
1067 // To know if we are including users
1068 $users = $this->get_setting_value('users');
1070 // Define each element separated
1072 $groups = new backup_nested_element('groups');
1074 $group = new backup_nested_element('group', array('id'), array(
1075 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1076 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1078 $members = new backup_nested_element('group_members');
1080 $member = new backup_nested_element('group_member', array('id'), array(
1081 'userid', 'timeadded', 'component', 'itemid'));
1083 $groupings = new backup_nested_element('groupings');
1085 $grouping = new backup_nested_element('grouping', 'id', array(
1086 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1087 'timecreated', 'timemodified'));
1089 $groupinggroups = new backup_nested_element('grouping_groups');
1091 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1092 'groupid', 'timeadded'));
1094 // Build the tree
1096 $groups->add_child($group);
1097 $groups->add_child($groupings);
1099 $group->add_child($members);
1100 $members->add_child($member);
1102 $groupings->add_child($grouping);
1103 $grouping->add_child($groupinggroups);
1104 $groupinggroups->add_child($groupinggroup);
1106 // Define sources
1108 $group->set_source_sql("
1109 SELECT g.*
1110 FROM {groups} g
1111 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1112 WHERE bi.backupid = ?
1113 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1115 // This only happens if we are including users
1116 if ($users) {
1117 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1120 $grouping->set_source_sql("
1121 SELECT g.*
1122 FROM {groupings} g
1123 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1124 WHERE bi.backupid = ?
1125 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1127 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1129 // Define id annotations (as final)
1131 $member->annotate_ids('userfinal', 'userid');
1133 // Define file annotations
1135 $group->annotate_files('group', 'description', 'id');
1136 $group->annotate_files('group', 'icon', 'id');
1137 $grouping->annotate_files('grouping', 'description', 'id');
1139 // Return the root element (groups)
1140 return $groups;
1145 * structure step in charge of constructing the main users.xml file for all the users already
1146 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1147 * overrides.
1149 class backup_users_structure_step extends backup_structure_step {
1151 protected function define_structure() {
1152 global $CFG;
1154 // To know if we are anonymizing users
1155 $anonymize = $this->get_setting_value('anonymize');
1156 // To know if we are including role assignments
1157 $roleassignments = $this->get_setting_value('role_assignments');
1159 // Define each element separated
1161 $users = new backup_nested_element('users');
1163 // Create the array of user fields by hand, as far as we have various bits to control
1164 // anonymize option, password backup, mnethostid...
1166 // First, the fields not needing anonymization nor special handling
1167 $normalfields = array(
1168 'confirmed', 'policyagreed', 'deleted',
1169 'lang', 'theme', 'timezone', 'firstaccess',
1170 'lastaccess', 'lastlogin', 'currentlogin',
1171 'mailformat', 'maildigest', 'maildisplay',
1172 'autosubscribe', 'trackforums', 'timecreated',
1173 'timemodified', 'trustbitmask');
1175 // Then, the fields potentially needing anonymization
1176 $anonfields = array(
1177 'username', 'idnumber', 'email', 'icq', 'skype',
1178 'yahoo', 'aim', 'msn', 'phone1',
1179 'phone2', 'institution', 'department', 'address',
1180 'city', 'country', 'lastip', 'picture',
1181 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1182 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1184 // Add anonymized fields to $userfields with custom final element
1185 foreach ($anonfields as $field) {
1186 if ($anonymize) {
1187 $userfields[] = new anonymizer_final_element($field);
1188 } else {
1189 $userfields[] = $field; // No anonymization, normally added
1193 // mnethosturl requires special handling (custom final element)
1194 $userfields[] = new mnethosturl_final_element('mnethosturl');
1196 // password added conditionally
1197 if (!empty($CFG->includeuserpasswordsinbackup)) {
1198 $userfields[] = 'password';
1201 // Merge all the fields
1202 $userfields = array_merge($userfields, $normalfields);
1204 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1206 $customfields = new backup_nested_element('custom_fields');
1208 $customfield = new backup_nested_element('custom_field', array('id'), array(
1209 'field_name', 'field_type', 'field_data'));
1211 $tags = new backup_nested_element('tags');
1213 $tag = new backup_nested_element('tag', array('id'), array(
1214 'name', 'rawname'));
1216 $preferences = new backup_nested_element('preferences');
1218 $preference = new backup_nested_element('preference', array('id'), array(
1219 'name', 'value'));
1221 $roles = new backup_nested_element('roles');
1223 $overrides = new backup_nested_element('role_overrides');
1225 $override = new backup_nested_element('override', array('id'), array(
1226 'roleid', 'capability', 'permission', 'timemodified',
1227 'modifierid'));
1229 $assignments = new backup_nested_element('role_assignments');
1231 $assignment = new backup_nested_element('assignment', array('id'), array(
1232 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1233 'sortorder'));
1235 // Build the tree
1237 $users->add_child($user);
1239 $user->add_child($customfields);
1240 $customfields->add_child($customfield);
1242 $user->add_child($tags);
1243 $tags->add_child($tag);
1245 $user->add_child($preferences);
1246 $preferences->add_child($preference);
1248 $user->add_child($roles);
1250 $roles->add_child($overrides);
1251 $roles->add_child($assignments);
1253 $overrides->add_child($override);
1254 $assignments->add_child($assignment);
1256 // Define sources
1258 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1259 FROM {user} u
1260 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1261 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1262 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1263 WHERE bi.backupid = ?
1264 AND bi.itemname = ?', array(
1265 backup_helper::is_sqlparam($this->get_backupid()),
1266 backup_helper::is_sqlparam('userfinal')));
1268 // All the rest on information is only added if we arent
1269 // in an anonymized backup
1270 if (!$anonymize) {
1271 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1272 FROM {user_info_field} f
1273 JOIN {user_info_data} d ON d.fieldid = f.id
1274 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1276 $customfield->set_source_alias('shortname', 'field_name');
1277 $customfield->set_source_alias('datatype', 'field_type');
1278 $customfield->set_source_alias('data', 'field_data');
1280 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1281 FROM {tag} t
1282 JOIN {tag_instance} ti ON ti.tagid = t.id
1283 WHERE ti.itemtype = ?
1284 AND ti.itemid = ?', array(
1285 backup_helper::is_sqlparam('user'),
1286 backup::VAR_PARENTID));
1288 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1290 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1292 // Assignments only added if specified
1293 if ($roleassignments) {
1294 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1297 // Define id annotations (as final)
1298 $override->annotate_ids('rolefinal', 'roleid');
1301 // Return root element (users)
1302 return $users;
1307 * structure step in charge of constructing the block.xml file for one
1308 * given block (instance and positions). If the block has custom DB structure
1309 * that will go to a separate file (different step defined in block class)
1311 class backup_block_instance_structure_step extends backup_structure_step {
1313 protected function define_structure() {
1314 global $DB;
1316 // Define each element separated
1318 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1319 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1320 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1322 $positions = new backup_nested_element('block_positions');
1324 $position = new backup_nested_element('block_position', array('id'), array(
1325 'contextid', 'pagetype', 'subpage', 'visible',
1326 'region', 'weight'));
1328 // Build the tree
1330 $block->add_child($positions);
1331 $positions->add_child($position);
1333 // Transform configdata information if needed (process links and friends)
1334 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1335 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1336 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1337 foreach ($configdata as $attribute => $value) {
1338 if (in_array($attribute, $attrstotransform)) {
1339 $configdata[$attribute] = $this->contenttransformer->process($value);
1342 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1344 $blockrec->contextid = $this->task->get_contextid();
1345 // Get the version of the block
1346 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1348 // Define sources
1350 $block->set_source_array(array($blockrec));
1352 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1354 // File anotations (for fileareas specified on each block)
1355 foreach ($this->task->get_fileareas() as $filearea) {
1356 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1359 // Return the root element (block)
1360 return $block;
1365 * structure step in charge of constructing the logs.xml file for all the log records found
1366 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1367 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1368 * that just in case they become restored some day in the future
1370 class backup_course_logs_structure_step extends backup_structure_step {
1372 protected function define_structure() {
1374 // Define each element separated
1376 $logs = new backup_nested_element('logs');
1378 $log = new backup_nested_element('log', array('id'), array(
1379 'time', 'userid', 'ip', 'module',
1380 'action', 'url', 'info'));
1382 // Build the tree
1384 $logs->add_child($log);
1386 // Define sources (all the records belonging to the course, having cmid = 0)
1388 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1390 // Annotations
1391 // NOTE: We don't annotate users from logs as far as they MUST be
1392 // always annotated by the course (enrol, ras... whatever)
1394 // Return the root element (logs)
1396 return $logs;
1401 * structure step in charge of constructing the logs.xml file for all the log records found
1402 * in activity
1404 class backup_activity_logs_structure_step extends backup_structure_step {
1406 protected function define_structure() {
1408 // Define each element separated
1410 $logs = new backup_nested_element('logs');
1412 $log = new backup_nested_element('log', array('id'), array(
1413 'time', 'userid', 'ip', 'module',
1414 'action', 'url', 'info'));
1416 // Build the tree
1418 $logs->add_child($log);
1420 // Define sources
1422 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1424 // Annotations
1425 // NOTE: We don't annotate users from logs as far as they MUST be
1426 // always annotated by the activity (true participants).
1428 // Return the root element (logs)
1430 return $logs;
1435 * structure in charge of constructing the inforef.xml file for all the items we want
1436 * to have referenced there (users, roles, files...)
1438 class backup_inforef_structure_step extends backup_structure_step {
1440 protected function define_structure() {
1442 // Items we want to include in the inforef file.
1443 $items = backup_helper::get_inforef_itemnames();
1445 // Build the tree
1447 $inforef = new backup_nested_element('inforef');
1449 // For each item, conditionally, if there are already records, build element
1450 foreach ($items as $itemname) {
1451 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1452 $elementroot = new backup_nested_element($itemname . 'ref');
1453 $element = new backup_nested_element($itemname, array(), array('id'));
1454 $inforef->add_child($elementroot);
1455 $elementroot->add_child($element);
1456 $element->set_source_sql("
1457 SELECT itemid AS id
1458 FROM {backup_ids_temp}
1459 WHERE backupid = ?
1460 AND itemname = ?",
1461 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1465 // We don't annotate anything there, but rely in the next step
1466 // (move_inforef_annotations_to_final) that will change all the
1467 // already saved 'inforref' entries to their 'final' annotations.
1468 return $inforef;
1473 * This step will get all the annotations already processed to inforef.xml file and
1474 * transform them into 'final' annotations.
1476 class move_inforef_annotations_to_final extends backup_execution_step {
1478 protected function define_execution() {
1480 // Items we want to include in the inforef file
1481 $items = backup_helper::get_inforef_itemnames();
1482 $progress = $this->task->get_progress();
1483 $progress->start_progress($this->get_name(), count($items));
1484 $done = 1;
1485 foreach ($items as $itemname) {
1486 // Delegate to dbops
1487 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1488 $itemname, $progress);
1489 $progress->progress($done++);
1491 $progress->end_progress();
1496 * structure in charge of constructing the files.xml file with all the
1497 * annotated (final) files along the process. At, the same time, and
1498 * using one specialised nested_element, will copy them form moodle storage
1499 * to backup storage
1501 class backup_final_files_structure_step extends backup_structure_step {
1503 protected function define_structure() {
1505 // Define elements
1507 $files = new backup_nested_element('files');
1509 $file = new file_nested_element('file', array('id'), array(
1510 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1511 'filepath', 'filename', 'userid', 'filesize',
1512 'mimetype', 'status', 'timecreated', 'timemodified',
1513 'source', 'author', 'license', 'sortorder',
1514 'repositorytype', 'repositoryid', 'reference'));
1516 // Build the tree
1518 $files->add_child($file);
1520 // Define sources
1522 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1523 FROM {files} f
1524 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1525 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1526 LEFT JOIN {repository} r ON r.id = ri.typeid
1527 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1528 WHERE bi.backupid = ?
1529 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1531 return $files;
1536 * Structure step in charge of creating the main moodle_backup.xml file
1537 * where all the information related to the backup, settings, license and
1538 * other information needed on restore is added*/
1539 class backup_main_structure_step extends backup_structure_step {
1541 protected function define_structure() {
1543 global $CFG;
1545 $info = array();
1547 $info['name'] = $this->get_setting_value('filename');
1548 $info['moodle_version'] = $CFG->version;
1549 $info['moodle_release'] = $CFG->release;
1550 $info['backup_version'] = $CFG->backup_version;
1551 $info['backup_release'] = $CFG->backup_release;
1552 $info['backup_date'] = time();
1553 $info['backup_uniqueid']= $this->get_backupid();
1554 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1555 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1556 $info['include_file_references_to_external_content'] =
1557 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1558 $info['original_wwwroot']=$CFG->wwwroot;
1559 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1560 $info['original_course_id'] = $this->get_courseid();
1561 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1562 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1563 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1564 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1565 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1566 $info['original_system_contextid'] = context_system::instance()->id;
1568 // Get more information from controller
1569 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
1570 $this->get_backupid(), $this->get_task()->get_progress());
1572 // Define elements
1574 $moodle_backup = new backup_nested_element('moodle_backup');
1576 $information = new backup_nested_element('information', null, array(
1577 'name', 'moodle_version', 'moodle_release', 'backup_version',
1578 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1579 'original_site_identifier_hash', 'original_course_id',
1580 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1581 'original_course_contextid', 'original_system_contextid'));
1583 $details = new backup_nested_element('details');
1585 $detail = new backup_nested_element('detail', array('backup_id'), array(
1586 'type', 'format', 'interactive', 'mode',
1587 'execution', 'executiontime'));
1589 $contents = new backup_nested_element('contents');
1591 $activities = new backup_nested_element('activities');
1593 $activity = new backup_nested_element('activity', null, array(
1594 'moduleid', 'sectionid', 'modulename', 'title',
1595 'directory'));
1597 $sections = new backup_nested_element('sections');
1599 $section = new backup_nested_element('section', null, array(
1600 'sectionid', 'title', 'directory'));
1602 $course = new backup_nested_element('course', null, array(
1603 'courseid', 'title', 'directory'));
1605 $settings = new backup_nested_element('settings');
1607 $setting = new backup_nested_element('setting', null, array(
1608 'level', 'section', 'activity', 'name', 'value'));
1610 // Build the tree
1612 $moodle_backup->add_child($information);
1614 $information->add_child($details);
1615 $details->add_child($detail);
1617 $information->add_child($contents);
1618 if (!empty($cinfo['activities'])) {
1619 $contents->add_child($activities);
1620 $activities->add_child($activity);
1622 if (!empty($cinfo['sections'])) {
1623 $contents->add_child($sections);
1624 $sections->add_child($section);
1626 if (!empty($cinfo['course'])) {
1627 $contents->add_child($course);
1630 $information->add_child($settings);
1631 $settings->add_child($setting);
1634 // Set the sources
1636 $information->set_source_array(array((object)$info));
1638 $detail->set_source_array($dinfo);
1640 $activity->set_source_array($cinfo['activities']);
1642 $section->set_source_array($cinfo['sections']);
1644 $course->set_source_array($cinfo['course']);
1646 $setting->set_source_array($sinfo);
1648 // Prepare some information to be sent to main moodle_backup.xml file
1649 return $moodle_backup;
1655 * Execution step that will generate the final zip (.mbz) file with all the contents
1657 class backup_zip_contents extends backup_execution_step implements file_progress {
1659 * @var bool True if we have started tracking progress
1661 protected $startedprogress;
1663 protected function define_execution() {
1665 // Get basepath
1666 $basepath = $this->get_basepath();
1668 // Get the list of files in directory
1669 $filestemp = get_directory_list($basepath, '', false, true, true);
1670 $files = array();
1671 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1672 $files[$file] = $basepath . '/' . $file;
1675 // Add the log file if exists
1676 $logfilepath = $basepath . '.log';
1677 if (file_exists($logfilepath)) {
1678 $files['moodle_backup.log'] = $logfilepath;
1681 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1682 $zipfile = $basepath . '/backup.mbz';
1684 // Get the zip packer
1685 $zippacker = get_file_packer('application/vnd.moodle.backup');
1687 // Zip files
1688 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1690 // Something went wrong.
1691 if ($result === false) {
1692 @unlink($zipfile);
1693 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
1695 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
1696 try {
1697 backup_general_helper::get_backup_information_from_mbz($zipfile);
1698 } catch (backup_helper_exception $e) {
1699 @unlink($zipfile);
1700 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
1703 // If any progress happened, end it.
1704 if ($this->startedprogress) {
1705 $this->task->get_progress()->end_progress();
1710 * Implementation for file_progress interface to display unzip progress.
1712 * @param int $progress Current progress
1713 * @param int $max Max value
1715 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
1716 $reporter = $this->task->get_progress();
1718 // Start tracking progress if necessary.
1719 if (!$this->startedprogress) {
1720 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
1721 ? \core\progress\base::INDETERMINATE : $max);
1722 $this->startedprogress = true;
1725 // Pass progress through to whatever handles it.
1726 $reporter->progress(($progress == file_progress::INDETERMINATE)
1727 ? \core\progress\base::INDETERMINATE : $progress);
1732 * This step will send the generated backup file to its final destination
1734 class backup_store_backup_file extends backup_execution_step {
1736 protected function define_execution() {
1738 // Get basepath
1739 $basepath = $this->get_basepath();
1741 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1742 $zipfile = $basepath . '/backup.mbz';
1744 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1745 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1746 return array(
1747 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
1748 $this->task->get_progress()),
1749 'include_file_references_to_external_content' => $has_file_references
1756 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1757 * and put them to the backup_ids tables, to be used later as base to backup them
1759 class backup_activity_grade_items_to_ids extends backup_execution_step {
1761 protected function define_execution() {
1763 // Fetch all activity grade items
1764 if ($items = grade_item::fetch_all(array(
1765 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1766 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1767 // Annotate them in backup_ids
1768 foreach ($items as $item) {
1769 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1776 * This step will annotate all the groups and groupings belonging to the course
1778 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1780 protected function define_execution() {
1781 global $DB;
1783 // Get all the course groups
1784 if ($groups = $DB->get_records('groups', array(
1785 'courseid' => $this->task->get_courseid()))) {
1786 foreach ($groups as $group) {
1787 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1791 // Get all the course groupings
1792 if ($groupings = $DB->get_records('groupings', array(
1793 'courseid' => $this->task->get_courseid()))) {
1794 foreach ($groupings as $grouping) {
1795 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1802 * This step will annotate all the groups belonging to already annotated groupings
1804 class backup_annotate_groups_from_groupings extends backup_execution_step {
1806 protected function define_execution() {
1807 global $DB;
1809 // Fetch all the annotated groupings
1810 if ($groupings = $DB->get_records('backup_ids_temp', array(
1811 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1812 foreach ($groupings as $grouping) {
1813 if ($groups = $DB->get_records('groupings_groups', array(
1814 'groupingid' => $grouping->itemid))) {
1815 foreach ($groups as $group) {
1816 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1825 * This step will annotate all the scales belonging to already annotated outcomes
1827 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1829 protected function define_execution() {
1830 global $DB;
1832 // Fetch all the annotated outcomes
1833 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1834 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1835 foreach ($outcomes as $outcome) {
1836 if ($scale = $DB->get_record('grade_outcomes', array(
1837 'id' => $outcome->itemid))) {
1838 // Annotate as scalefinal because it's > 0
1839 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1847 * This step will generate all the file annotations for the already
1848 * annotated (final) question_categories. It calculates the different
1849 * contexts that are being backup and, annotates all the files
1850 * on every context belonging to the "question" component. As far as
1851 * we are always including *complete* question banks it is safe and
1852 * optimal to do that in this (one pass) way
1854 class backup_annotate_all_question_files extends backup_execution_step {
1856 protected function define_execution() {
1857 global $DB;
1859 // Get all the different contexts for the final question_categories
1860 // annotated along the whole backup
1861 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1862 FROM {question_categories} qc
1863 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
1864 WHERE bi.backupid = ?
1865 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
1866 // To know about qtype specific components/fileareas
1867 $components = backup_qtype_plugin::get_components_and_fileareas();
1868 // Let's loop
1869 foreach($rs as $record) {
1870 // We don't need to specify filearea nor itemid as far as by
1871 // component and context it's enough to annotate the whole bank files
1872 // This backups "questiontext", "generalfeedback" and "answerfeedback" fileareas (all them
1873 // belonging to the "question" component
1874 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', null, null);
1875 // Again, it is enough to pick files only by context and component
1876 // Do it for qtype specific components
1877 foreach ($components as $component => $fileareas) {
1878 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
1881 $rs->close();
1886 * structure step in charge of constructing the questions.xml file for all the
1887 * question categories and questions required by the backup
1888 * and letters related to one activity
1890 class backup_questions_structure_step extends backup_structure_step {
1892 protected function define_structure() {
1894 // Define each element separated
1896 $qcategories = new backup_nested_element('question_categories');
1898 $qcategory = new backup_nested_element('question_category', array('id'), array(
1899 'name', 'contextid', 'contextlevel', 'contextinstanceid',
1900 'info', 'infoformat', 'stamp', 'parent',
1901 'sortorder'));
1903 $questions = new backup_nested_element('questions');
1905 $question = new backup_nested_element('question', array('id'), array(
1906 'parent', 'name', 'questiontext', 'questiontextformat',
1907 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
1908 'qtype', 'length', 'stamp', 'version',
1909 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
1911 // attach qtype plugin structure to $question element, only one allowed
1912 $this->add_plugin_structure('qtype', $question, false);
1914 // attach local plugin stucture to $question element, multiple allowed
1915 $this->add_plugin_structure('local', $question, true);
1917 $qhints = new backup_nested_element('question_hints');
1919 $qhint = new backup_nested_element('question_hint', array('id'), array(
1920 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
1922 $tags = new backup_nested_element('tags');
1924 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
1926 // Build the tree
1928 $qcategories->add_child($qcategory);
1929 $qcategory->add_child($questions);
1930 $questions->add_child($question);
1931 $question->add_child($qhints);
1932 $qhints->add_child($qhint);
1934 $question->add_child($tags);
1935 $tags->add_child($tag);
1937 // Define the sources
1939 $qcategory->set_source_sql("
1940 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
1941 FROM {question_categories} gc
1942 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
1943 JOIN {context} co ON co.id = gc.contextid
1944 WHERE bi.backupid = ?
1945 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
1947 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
1949 $qhint->set_source_sql('
1950 SELECT *
1951 FROM {question_hints}
1952 WHERE questionid = :questionid
1953 ORDER BY id',
1954 array('questionid' => backup::VAR_PARENTID));
1956 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
1957 FROM {tag} t
1958 JOIN {tag_instance} ti ON ti.tagid = t.id
1959 WHERE ti.itemid = ?
1960 AND ti.itemtype = 'question'", array(backup::VAR_PARENTID));
1962 // don't need to annotate ids nor files
1963 // (already done by {@link backup_annotate_all_question_files}
1965 return $qcategories;
1972 * This step will generate all the file annotations for the already
1973 * annotated (final) users. Need to do this here because each user
1974 * has its own context and structure tasks only are able to handle
1975 * one context. Also, this step will guarantee that every user has
1976 * its context created (req for other steps)
1978 class backup_annotate_all_user_files extends backup_execution_step {
1980 protected function define_execution() {
1981 global $DB;
1983 // List of fileareas we are going to annotate
1984 $fileareas = array('profile', 'icon');
1986 // Fetch all annotated (final) users
1987 $rs = $DB->get_recordset('backup_ids_temp', array(
1988 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
1989 $progress = $this->task->get_progress();
1990 $progress->start_progress($this->get_name());
1991 foreach ($rs as $record) {
1992 $userid = $record->itemid;
1993 $userctx = context_user::instance($userid, IGNORE_MISSING);
1994 if (!$userctx) {
1995 continue; // User has not context, sure it's a deleted user, so cannot have files
1997 // Proceed with every user filearea
1998 foreach ($fileareas as $filearea) {
1999 // We don't need to specify itemid ($userid - 5th param) as far as by
2000 // context we can get all the associated files. See MDL-22092
2001 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2002 $progress->progress();
2005 $progress->end_progress();
2006 $rs->close();
2012 * Defines the backup step for advanced grading methods attached to the activity module
2014 class backup_activity_grading_structure_step extends backup_structure_step {
2017 * Include the grading.xml only if the module supports advanced grading
2019 protected function execute_condition() {
2020 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2024 * Declares the gradable areas structures and data sources
2026 protected function define_structure() {
2028 // To know if we are including userinfo
2029 $userinfo = $this->get_setting_value('userinfo');
2031 // Define the elements
2033 $areas = new backup_nested_element('areas');
2035 $area = new backup_nested_element('area', array('id'), array(
2036 'areaname', 'activemethod'));
2038 $definitions = new backup_nested_element('definitions');
2040 $definition = new backup_nested_element('definition', array('id'), array(
2041 'method', 'name', 'description', 'descriptionformat', 'status',
2042 'timecreated', 'timemodified', 'options'));
2044 $instances = new backup_nested_element('instances');
2046 $instance = new backup_nested_element('instance', array('id'), array(
2047 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2048 'feedbackformat', 'timemodified'));
2050 // Build the tree including the method specific structures
2051 // (beware - the order of how gradingform plugins structures are attached is important)
2052 $areas->add_child($area);
2053 // attach local plugin stucture to $area element, multiple allowed
2054 $this->add_plugin_structure('local', $area, true);
2055 $area->add_child($definitions);
2056 $definitions->add_child($definition);
2057 $this->add_plugin_structure('gradingform', $definition, true);
2058 // attach local plugin stucture to $definition element, multiple allowed
2059 $this->add_plugin_structure('local', $definition, true);
2060 $definition->add_child($instances);
2061 $instances->add_child($instance);
2062 $this->add_plugin_structure('gradingform', $instance, false);
2063 // attach local plugin stucture to $instance element, multiple allowed
2064 $this->add_plugin_structure('local', $instance, true);
2066 // Define data sources
2068 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2069 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2071 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2073 if ($userinfo) {
2074 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2077 // Annotate references
2078 $definition->annotate_files('grading', 'description', 'id');
2079 $instance->annotate_ids('user', 'raterid');
2081 // Return the root element
2082 return $areas;
2088 * structure step in charge of constructing the grades.xml file for all the grade items
2089 * and letters related to one activity
2091 class backup_activity_grades_structure_step extends backup_structure_step {
2093 protected function define_structure() {
2095 // To know if we are including userinfo
2096 $userinfo = $this->get_setting_value('userinfo');
2098 // Define each element separated
2100 $book = new backup_nested_element('activity_gradebook');
2102 $items = new backup_nested_element('grade_items');
2104 $item = new backup_nested_element('grade_item', array('id'), array(
2105 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2106 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2107 'calculation', 'gradetype', 'grademax', 'grademin',
2108 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2109 'plusfactor', 'aggregationcoef', 'sortorder', 'display',
2110 'decimals', 'hidden', 'locked', 'locktime',
2111 'needsupdate', 'timecreated', 'timemodified'));
2113 $grades = new backup_nested_element('grade_grades');
2115 $grade = new backup_nested_element('grade_grade', array('id'), array(
2116 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2117 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2118 'locked', 'locktime', 'exported', 'overridden',
2119 'excluded', 'feedback', 'feedbackformat', 'information',
2120 'informationformat', 'timecreated', 'timemodified'));
2122 $letters = new backup_nested_element('grade_letters');
2124 $letter = new backup_nested_element('grade_letter', 'id', array(
2125 'lowerboundary', 'letter'));
2127 // Build the tree
2129 $book->add_child($items);
2130 $items->add_child($item);
2132 $item->add_child($grades);
2133 $grades->add_child($grade);
2135 $book->add_child($letters);
2136 $letters->add_child($letter);
2138 // Define sources
2140 $item->set_source_sql("SELECT gi.*
2141 FROM {grade_items} gi
2142 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2143 WHERE bi.backupid = ?
2144 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2146 // This only happens if we are including user info
2147 if ($userinfo) {
2148 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2151 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2153 // Annotations
2155 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2156 $item->annotate_ids('outcome', 'outcomeid');
2158 $grade->annotate_ids('user', 'userid');
2159 $grade->annotate_ids('user', 'usermodified');
2161 // Return the root element (book)
2163 return $book;
2168 * Backups up the course completion information for the course.
2170 class backup_course_completion_structure_step extends backup_structure_step {
2172 protected function execute_condition() {
2173 // Check that all activities have been included
2174 if ($this->task->is_excluding_activities()) {
2175 return false;
2177 return true;
2181 * The structure of the course completion backup
2183 * @return backup_nested_element
2185 protected function define_structure() {
2187 // To know if we are including user completion info
2188 $userinfo = $this->get_setting_value('userscompletion');
2190 $cc = new backup_nested_element('course_completion');
2192 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2193 'course','criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod', 'timeend', 'gradepass', 'role'
2196 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2198 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2199 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2202 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2203 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2206 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2207 'course','criteriatype','method','value'
2210 $cc->add_child($criteria);
2211 $criteria->add_child($criteriacompletions);
2212 $criteriacompletions->add_child($criteriacomplete);
2213 $cc->add_child($coursecompletions);
2214 $cc->add_child($aggregatemethod);
2216 // We need to get the courseinstances shortname rather than an ID for restore
2217 $criteria->set_source_sql("SELECT ccc.*, c.shortname AS courseinstanceshortname
2218 FROM {course_completion_criteria} ccc
2219 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2220 WHERE ccc.course = ?", array(backup::VAR_COURSEID));
2223 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2225 if ($userinfo) {
2226 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2227 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2230 $criteria->annotate_ids('role', 'role');
2231 $criteriacomplete->annotate_ids('user', 'userid');
2232 $coursecompletions->annotate_ids('user', 'userid');
2234 return $cc;