Merge branch 'wip-mdl-52066-m28' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / backup / moodle2 / backup_stepslib.php
blobb1d07025e3d10a17056a275f3e8ce9da773ec7cb
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',
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', 'expirythreshold', '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 // Add enrol plugin structure.
551 $this->add_plugin_structure('enrol', $enrol, false);
553 return $enrolments;
558 * structure step that will generate the roles.xml file for the given context, observing
559 * the role_assignments setting to know if that part needs to be included
561 class backup_roles_structure_step extends backup_structure_step {
563 protected function define_structure() {
565 // To know if we are including role assignments
566 $roleassignments = $this->get_setting_value('role_assignments');
568 // Define each element separated
570 $roles = new backup_nested_element('roles');
572 $overrides = new backup_nested_element('role_overrides');
574 $override = new backup_nested_element('override', array('id'), array(
575 'roleid', 'capability', 'permission', 'timemodified',
576 'modifierid'));
578 $assignments = new backup_nested_element('role_assignments');
580 $assignment = new backup_nested_element('assignment', array('id'), array(
581 'roleid', 'userid', 'timemodified', 'modifierid', 'component', 'itemid',
582 'sortorder'));
584 // Build the tree
585 $roles->add_child($overrides);
586 $roles->add_child($assignments);
588 $overrides->add_child($override);
589 $assignments->add_child($assignment);
591 // Define sources
593 $override->set_source_table('role_capabilities', array('contextid' => backup::VAR_CONTEXTID));
595 // Assignments only added if specified
596 if ($roleassignments) {
597 $assignment->set_source_table('role_assignments', array('contextid' => backup::VAR_CONTEXTID));
600 // Define id annotations
601 $override->annotate_ids('role', 'roleid');
603 $assignment->annotate_ids('role', 'roleid');
605 $assignment->annotate_ids('user', 'userid');
607 //TODO: how do we annotate the itemid? the meaning depends on the content of component table (skodak)
609 return $roles;
614 * structure step that will generate the roles.xml containing the
615 * list of roles used along the whole backup process. Just raw
616 * list of used roles from role table
618 class backup_final_roles_structure_step extends backup_structure_step {
620 protected function define_structure() {
622 // Define elements
624 $rolesdef = new backup_nested_element('roles_definition');
626 $role = new backup_nested_element('role', array('id'), array(
627 'name', 'shortname', 'nameincourse', 'description',
628 'sortorder', 'archetype'));
630 // Build the tree
632 $rolesdef->add_child($role);
634 // Define sources
636 $role->set_source_sql("SELECT r.*, rn.name AS nameincourse
637 FROM {role} r
638 JOIN {backup_ids_temp} bi ON r.id = bi.itemid
639 LEFT JOIN {role_names} rn ON r.id = rn.roleid AND rn.contextid = ?
640 WHERE bi.backupid = ?
641 AND bi.itemname = 'rolefinal'", array(backup::VAR_CONTEXTID, backup::VAR_BACKUPID));
643 // Return main element (rolesdef)
644 return $rolesdef;
649 * structure step that will generate the scales.xml containing the
650 * list of scales used along the whole backup process.
652 class backup_final_scales_structure_step extends backup_structure_step {
654 protected function define_structure() {
656 // Define elements
658 $scalesdef = new backup_nested_element('scales_definition');
660 $scale = new backup_nested_element('scale', array('id'), array(
661 'courseid', 'userid', 'name', 'scale',
662 'description', 'descriptionformat', 'timemodified'));
664 // Build the tree
666 $scalesdef->add_child($scale);
668 // Define sources
670 $scale->set_source_sql("SELECT s.*
671 FROM {scale} s
672 JOIN {backup_ids_temp} bi ON s.id = bi.itemid
673 WHERE bi.backupid = ?
674 AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID));
676 // Annotate scale files (they store files in system context, so pass it instead of default one)
677 $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id);
679 // Return main element (scalesdef)
680 return $scalesdef;
685 * structure step that will generate the outcomes.xml containing the
686 * list of outcomes used along the whole backup process.
688 class backup_final_outcomes_structure_step extends backup_structure_step {
690 protected function define_structure() {
692 // Define elements
694 $outcomesdef = new backup_nested_element('outcomes_definition');
696 $outcome = new backup_nested_element('outcome', array('id'), array(
697 'courseid', 'userid', 'shortname', 'fullname',
698 'scaleid', 'description', 'descriptionformat', 'timecreated',
699 'timemodified','usermodified'));
701 // Build the tree
703 $outcomesdef->add_child($outcome);
705 // Define sources
707 $outcome->set_source_sql("SELECT o.*
708 FROM {grade_outcomes} o
709 JOIN {backup_ids_temp} bi ON o.id = bi.itemid
710 WHERE bi.backupid = ?
711 AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID));
713 // Annotate outcome files (they store files in system context, so pass it instead of default one)
714 $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id);
716 // Return main element (outcomesdef)
717 return $outcomesdef;
722 * structure step in charge of constructing the filters.xml file for all the filters found
723 * in activity
725 class backup_filters_structure_step extends backup_structure_step {
727 protected function define_structure() {
729 // Define each element separated
731 $filters = new backup_nested_element('filters');
733 $actives = new backup_nested_element('filter_actives');
735 $active = new backup_nested_element('filter_active', null, array('filter', 'active'));
737 $configs = new backup_nested_element('filter_configs');
739 $config = new backup_nested_element('filter_config', null, array('filter', 'name', 'value'));
741 // Build the tree
743 $filters->add_child($actives);
744 $filters->add_child($configs);
746 $actives->add_child($active);
747 $configs->add_child($config);
749 // Define sources
751 list($activearr, $configarr) = filter_get_all_local_settings($this->task->get_contextid());
753 $active->set_source_array($activearr);
754 $config->set_source_array($configarr);
756 // Return the root element (filters)
757 return $filters;
762 * structure step in charge of constructing the comments.xml file for all the comments found
763 * in a given context
765 class backup_comments_structure_step extends backup_structure_step {
767 protected function define_structure() {
769 // Define each element separated
771 $comments = new backup_nested_element('comments');
773 $comment = new backup_nested_element('comment', array('id'), array(
774 'commentarea', 'itemid', 'content', 'format',
775 'userid', 'timecreated'));
777 // Build the tree
779 $comments->add_child($comment);
781 // Define sources
783 $comment->set_source_table('comments', array('contextid' => backup::VAR_CONTEXTID));
785 // Define id annotations
787 $comment->annotate_ids('user', 'userid');
789 // Return the root element (comments)
790 return $comments;
795 * structure step in charge of constructing the badges.xml file for all the badges found
796 * in a given context
798 class backup_badges_structure_step extends backup_structure_step {
800 protected function execute_condition() {
801 // Check that all activities have been included.
802 if ($this->task->is_excluding_activities()) {
803 return false;
805 return true;
808 protected function define_structure() {
810 // Define each element separated.
812 $badges = new backup_nested_element('badges');
813 $badge = new backup_nested_element('badge', array('id'), array('name', 'description',
814 'timecreated', 'timemodified', 'usercreated', 'usermodified', 'issuername',
815 'issuerurl', 'issuercontact', 'expiredate', 'expireperiod', 'type', 'courseid',
816 'message', 'messagesubject', 'attachment', 'notification', 'status', 'nextcron'));
818 $criteria = new backup_nested_element('criteria');
819 $criterion = new backup_nested_element('criterion', array('id'), array('badgeid',
820 'criteriatype', 'method'));
822 $parameters = new backup_nested_element('parameters');
823 $parameter = new backup_nested_element('parameter', array('id'), array('critid',
824 'name', 'value', 'criteriatype'));
826 $manual_awards = new backup_nested_element('manual_awards');
827 $manual_award = new backup_nested_element('manual_award', array('id'), array('badgeid',
828 'recipientid', 'issuerid', 'issuerrole', 'datemet'));
830 // Build the tree.
832 $badges->add_child($badge);
833 $badge->add_child($criteria);
834 $criteria->add_child($criterion);
835 $criterion->add_child($parameters);
836 $parameters->add_child($parameter);
837 $badge->add_child($manual_awards);
838 $manual_awards->add_child($manual_award);
840 // Define sources.
842 $badge->set_source_table('badge', array('courseid' => backup::VAR_COURSEID));
843 $criterion->set_source_table('badge_criteria', array('badgeid' => backup::VAR_PARENTID));
845 $parametersql = 'SELECT cp.*, c.criteriatype
846 FROM {badge_criteria_param} cp JOIN {badge_criteria} c
847 ON cp.critid = c.id
848 WHERE critid = :critid';
849 $parameterparams = array('critid' => backup::VAR_PARENTID);
850 $parameter->set_source_sql($parametersql, $parameterparams);
852 $manual_award->set_source_table('badge_manual_award', array('badgeid' => backup::VAR_PARENTID));
854 // Define id annotations.
856 $badge->annotate_ids('user', 'usercreated');
857 $badge->annotate_ids('user', 'usermodified');
858 $criterion->annotate_ids('badge', 'badgeid');
859 $parameter->annotate_ids('criterion', 'critid');
860 $badge->annotate_files('badges', 'badgeimage', 'id');
861 $manual_award->annotate_ids('badge', 'badgeid');
862 $manual_award->annotate_ids('user', 'recipientid');
863 $manual_award->annotate_ids('user', 'issuerid');
864 $manual_award->annotate_ids('role', 'issuerrole');
866 // Return the root element ($badges).
867 return $badges;
872 * structure step in charge of constructing the calender.xml file for all the events found
873 * in a given context
875 class backup_calendarevents_structure_step extends backup_structure_step {
877 protected function define_structure() {
879 // Define each element separated
881 $events = new backup_nested_element('events');
883 $event = new backup_nested_element('event', array('id'), array(
884 'name', 'description', 'format', 'courseid', 'groupid', 'userid',
885 'repeatid', 'modulename', 'instance', 'eventtype', 'timestart',
886 'timeduration', 'visible', 'uuid', 'sequence', 'timemodified'));
888 // Build the tree
889 $events->add_child($event);
891 // Define sources
892 if ($this->name == 'course_calendar') {
893 $calendar_items_sql ="SELECT * FROM {event}
894 WHERE courseid = :courseid
895 AND (eventtype = 'course' OR eventtype = 'group')";
896 $calendar_items_params = array('courseid'=>backup::VAR_COURSEID);
897 $event->set_source_sql($calendar_items_sql, $calendar_items_params);
898 } else {
899 $event->set_source_table('event', array('courseid' => backup::VAR_COURSEID, 'instance' => backup::VAR_ACTIVITYID, 'modulename' => backup::VAR_MODNAME));
902 // Define id annotations
904 $event->annotate_ids('user', 'userid');
905 $event->annotate_ids('group', 'groupid');
906 $event->annotate_files('calendar', 'event_description', 'id');
908 // Return the root element (events)
909 return $events;
914 * structure step in charge of constructing the gradebook.xml file for all the gradebook config in the course
915 * NOTE: the backup of the grade items themselves is handled by backup_activity_grades_structure_step
917 class backup_gradebook_structure_step extends backup_structure_step {
920 * We need to decide conditionally, based on dynamic information
921 * about the execution of this step. Only will be executed if all
922 * the module gradeitems have been already included in backup
924 protected function execute_condition() {
925 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
928 protected function define_structure() {
929 global $CFG, $DB;
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', 'aggregationcoef2', 'weightoverride',
946 'sortorder', 'display', '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',
956 'aggregationstatus', 'aggregationweight'));
958 //grade_categories
959 $grade_categories = new backup_nested_element('grade_categories');
960 $grade_category = new backup_nested_element('grade_category', array('id'), array(
961 //'courseid',
962 'parent', 'depth', 'path', 'fullname', 'aggregation', 'keephigh',
963 'droplow', 'aggregateonlygraded', 'aggregateoutcomes',
964 'timecreated', 'timemodified', 'hidden'));
966 $letters = new backup_nested_element('grade_letters');
967 $letter = new backup_nested_element('grade_letter', 'id', array(
968 'lowerboundary', 'letter'));
970 $grade_settings = new backup_nested_element('grade_settings');
971 $grade_setting = new backup_nested_element('grade_setting', 'id', array(
972 'name', 'value'));
975 // Build the tree
976 $gradebook->add_child($grade_categories);
977 $grade_categories->add_child($grade_category);
979 $gradebook->add_child($grade_items);
980 $grade_items->add_child($grade_item);
981 $grade_item->add_child($grade_grades);
982 $grade_grades->add_child($grade_grade);
984 $gradebook->add_child($letters);
985 $letters->add_child($letter);
987 $gradebook->add_child($grade_settings);
988 $grade_settings->add_child($grade_setting);
990 // Add attribute with gradebook calculation freeze date if needed.
991 $gradebookcalculationfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
992 if ($gradebookcalculationfreeze) {
993 $gradebook->add_attributes(array('calculations_freeze'));
994 $gradebook->get_attribute('calculations_freeze')->set_value($gradebookcalculationfreeze);
997 // Define sources
999 //Include manual, category and the course grade item
1000 $grade_items_sql ="SELECT * FROM {grade_items}
1001 WHERE courseid = :courseid
1002 AND (itemtype='manual' OR itemtype='course' OR itemtype='category')";
1003 $grade_items_params = array('courseid'=>backup::VAR_COURSEID);
1004 $grade_item->set_source_sql($grade_items_sql, $grade_items_params);
1006 if ($userinfo) {
1007 $grade_grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
1010 $grade_category_sql = "SELECT gc.*, gi.sortorder
1011 FROM {grade_categories} gc
1012 JOIN {grade_items} gi ON (gi.iteminstance = gc.id)
1013 WHERE gc.courseid = :courseid
1014 AND (gi.itemtype='course' OR gi.itemtype='category')
1015 ORDER BY gc.parent ASC";//need parent categories before their children
1016 $grade_category_params = array('courseid'=>backup::VAR_COURSEID);
1017 $grade_category->set_source_sql($grade_category_sql, $grade_category_params);
1019 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
1021 // Set the grade settings source, forcing the inclusion of minmaxtouse if not present.
1022 $settings = array();
1023 $rs = $DB->get_recordset('grade_settings', array('courseid' => $this->get_courseid()));
1024 foreach ($rs as $record) {
1025 $settings[$record->name] = $record;
1027 $rs->close();
1028 if (!isset($settings['minmaxtouse'])) {
1029 $settings['minmaxtouse'] = (object) array('name' => 'minmaxtouse', 'value' => $CFG->grade_minmaxtouse);
1031 $grade_setting->set_source_array($settings);
1034 // Annotations (both as final as far as they are going to be exported in next steps)
1035 $grade_item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
1036 $grade_item->annotate_ids('outcomefinal', 'outcomeid');
1038 //just in case there are any users not already annotated by the activities
1039 $grade_grade->annotate_ids('userfinal', 'userid');
1041 // Return the root element
1042 return $gradebook;
1047 * Step in charge of constructing the grade_history.xml file containing the grade histories.
1049 class backup_grade_history_structure_step extends backup_structure_step {
1052 * Limit the execution.
1054 * This applies the same logic than the one applied to {@link backup_gradebook_structure_step},
1055 * because we do not want to save the history of items which are not backed up. At least for now.
1057 protected function execute_condition() {
1058 return backup_plan_dbops::require_gradebook_backup($this->get_courseid(), $this->get_backupid());
1061 protected function define_structure() {
1063 // Settings to use.
1064 $userinfo = $this->get_setting_value('users');
1065 $history = $this->get_setting_value('grade_histories');
1067 // Create the nested elements.
1068 $bookhistory = new backup_nested_element('grade_history');
1069 $grades = new backup_nested_element('grade_grades');
1070 $grade = new backup_nested_element('grade_grade', array('id'), array(
1071 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
1072 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
1073 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
1074 'excluded', 'feedback', 'feedbackformat', 'information',
1075 'informationformat', 'timemodified'));
1077 // Build the tree.
1078 $bookhistory->add_child($grades);
1079 $grades->add_child($grade);
1081 // This only happens if we are including user info and history.
1082 if ($userinfo && $history) {
1083 // Only keep the history of grades related to items which have been backed up, The query is
1084 // similar (but not identical) to the one used in backup_gradebook_structure_step::define_structure().
1085 $gradesql = "SELECT ggh.*
1086 FROM {grade_grades_history} ggh
1087 JOIN {grade_items} gi ON ggh.itemid = gi.id
1088 WHERE gi.courseid = :courseid
1089 AND (gi.itemtype = 'manual' OR gi.itemtype = 'course' OR gi.itemtype = 'category')";
1090 $grade->set_source_sql($gradesql, array('courseid' => backup::VAR_COURSEID));
1093 // Annotations. (Final annotations as this step is part of the final task).
1094 $grade->annotate_ids('scalefinal', 'rawscaleid');
1095 $grade->annotate_ids('userfinal', 'loggeduser');
1096 $grade->annotate_ids('userfinal', 'userid');
1097 $grade->annotate_ids('userfinal', 'usermodified');
1099 // Return the root element.
1100 return $bookhistory;
1106 * structure step in charge if constructing the completion.xml file for all the users completion
1107 * information in a given activity
1109 class backup_userscompletion_structure_step extends backup_structure_step {
1111 protected function define_structure() {
1113 // Define each element separated
1115 $completions = new backup_nested_element('completions');
1117 $completion = new backup_nested_element('completion', array('id'), array(
1118 'userid', 'completionstate', 'viewed', 'timemodified'));
1120 // Build the tree
1122 $completions->add_child($completion);
1124 // Define sources
1126 $completion->set_source_table('course_modules_completion', array('coursemoduleid' => backup::VAR_MODID));
1128 // Define id annotations
1130 $completion->annotate_ids('user', 'userid');
1132 // Return the root element (completions)
1133 return $completions;
1138 * structure step in charge of constructing the main groups.xml file for all the groups and
1139 * groupings information already annotated
1141 class backup_groups_structure_step extends backup_structure_step {
1143 protected function define_structure() {
1145 // To know if we are including users
1146 $users = $this->get_setting_value('users');
1148 // Define each element separated
1150 $groups = new backup_nested_element('groups');
1152 $group = new backup_nested_element('group', array('id'), array(
1153 'name', 'idnumber', 'description', 'descriptionformat', 'enrolmentkey',
1154 'picture', 'hidepicture', 'timecreated', 'timemodified'));
1156 $members = new backup_nested_element('group_members');
1158 $member = new backup_nested_element('group_member', array('id'), array(
1159 'userid', 'timeadded', 'component', 'itemid'));
1161 $groupings = new backup_nested_element('groupings');
1163 $grouping = new backup_nested_element('grouping', 'id', array(
1164 'name', 'idnumber', 'description', 'descriptionformat', 'configdata',
1165 'timecreated', 'timemodified'));
1167 $groupinggroups = new backup_nested_element('grouping_groups');
1169 $groupinggroup = new backup_nested_element('grouping_group', array('id'), array(
1170 'groupid', 'timeadded'));
1172 // Build the tree
1174 $groups->add_child($group);
1175 $groups->add_child($groupings);
1177 $group->add_child($members);
1178 $members->add_child($member);
1180 $groupings->add_child($grouping);
1181 $grouping->add_child($groupinggroups);
1182 $groupinggroups->add_child($groupinggroup);
1184 // Define sources
1186 $group->set_source_sql("
1187 SELECT g.*
1188 FROM {groups} g
1189 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1190 WHERE bi.backupid = ?
1191 AND bi.itemname = 'groupfinal'", array(backup::VAR_BACKUPID));
1193 // This only happens if we are including users
1194 if ($users) {
1195 $member->set_source_table('groups_members', array('groupid' => backup::VAR_PARENTID));
1198 $grouping->set_source_sql("
1199 SELECT g.*
1200 FROM {groupings} g
1201 JOIN {backup_ids_temp} bi ON g.id = bi.itemid
1202 WHERE bi.backupid = ?
1203 AND bi.itemname = 'groupingfinal'", array(backup::VAR_BACKUPID));
1205 $groupinggroup->set_source_table('groupings_groups', array('groupingid' => backup::VAR_PARENTID));
1207 // Define id annotations (as final)
1209 $member->annotate_ids('userfinal', 'userid');
1211 // Define file annotations
1213 $group->annotate_files('group', 'description', 'id');
1214 $group->annotate_files('group', 'icon', 'id');
1215 $grouping->annotate_files('grouping', 'description', 'id');
1217 // Return the root element (groups)
1218 return $groups;
1223 * structure step in charge of constructing the main users.xml file for all the users already
1224 * annotated (final). Includes custom profile fields, preferences, tags, role assignments and
1225 * overrides.
1227 class backup_users_structure_step extends backup_structure_step {
1229 protected function define_structure() {
1230 global $CFG;
1232 // To know if we are anonymizing users
1233 $anonymize = $this->get_setting_value('anonymize');
1234 // To know if we are including role assignments
1235 $roleassignments = $this->get_setting_value('role_assignments');
1237 // Define each element separated
1239 $users = new backup_nested_element('users');
1241 // Create the array of user fields by hand, as far as we have various bits to control
1242 // anonymize option, password backup, mnethostid...
1244 // First, the fields not needing anonymization nor special handling
1245 $normalfields = array(
1246 'confirmed', 'policyagreed', 'deleted',
1247 'lang', 'theme', 'timezone', 'firstaccess',
1248 'lastaccess', 'lastlogin', 'currentlogin',
1249 'mailformat', 'maildigest', 'maildisplay',
1250 'autosubscribe', 'trackforums', 'timecreated',
1251 'timemodified', 'trustbitmask');
1253 // Then, the fields potentially needing anonymization
1254 $anonfields = array(
1255 'username', 'idnumber', 'email', 'icq', 'skype',
1256 'yahoo', 'aim', 'msn', 'phone1',
1257 'phone2', 'institution', 'department', 'address',
1258 'city', 'country', 'lastip', 'picture',
1259 'url', 'description', 'descriptionformat', 'imagealt', 'auth');
1260 $anonfields = array_merge($anonfields, get_all_user_name_fields());
1262 // Add anonymized fields to $userfields with custom final element
1263 foreach ($anonfields as $field) {
1264 if ($anonymize) {
1265 $userfields[] = new anonymizer_final_element($field);
1266 } else {
1267 $userfields[] = $field; // No anonymization, normally added
1271 // mnethosturl requires special handling (custom final element)
1272 $userfields[] = new mnethosturl_final_element('mnethosturl');
1274 // password added conditionally
1275 if (!empty($CFG->includeuserpasswordsinbackup)) {
1276 $userfields[] = 'password';
1279 // Merge all the fields
1280 $userfields = array_merge($userfields, $normalfields);
1282 $user = new backup_nested_element('user', array('id', 'contextid'), $userfields);
1284 $customfields = new backup_nested_element('custom_fields');
1286 $customfield = new backup_nested_element('custom_field', array('id'), array(
1287 'field_name', 'field_type', 'field_data'));
1289 $tags = new backup_nested_element('tags');
1291 $tag = new backup_nested_element('tag', array('id'), array(
1292 'name', 'rawname'));
1294 $preferences = new backup_nested_element('preferences');
1296 $preference = new backup_nested_element('preference', array('id'), array(
1297 'name', 'value'));
1299 $roles = new backup_nested_element('roles');
1301 $overrides = new backup_nested_element('role_overrides');
1303 $override = new backup_nested_element('override', array('id'), array(
1304 'roleid', 'capability', 'permission', 'timemodified',
1305 'modifierid'));
1307 $assignments = new backup_nested_element('role_assignments');
1309 $assignment = new backup_nested_element('assignment', array('id'), array(
1310 'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
1311 'sortorder'));
1313 // Build the tree
1315 $users->add_child($user);
1317 $user->add_child($customfields);
1318 $customfields->add_child($customfield);
1320 $user->add_child($tags);
1321 $tags->add_child($tag);
1323 $user->add_child($preferences);
1324 $preferences->add_child($preference);
1326 $user->add_child($roles);
1328 $roles->add_child($overrides);
1329 $roles->add_child($assignments);
1331 $overrides->add_child($override);
1332 $assignments->add_child($assignment);
1334 // Define sources
1336 $user->set_source_sql('SELECT u.*, c.id AS contextid, m.wwwroot AS mnethosturl
1337 FROM {user} u
1338 JOIN {backup_ids_temp} bi ON bi.itemid = u.id
1339 LEFT JOIN {context} c ON c.instanceid = u.id AND c.contextlevel = ' . CONTEXT_USER . '
1340 LEFT JOIN {mnet_host} m ON m.id = u.mnethostid
1341 WHERE bi.backupid = ?
1342 AND bi.itemname = ?', array(
1343 backup_helper::is_sqlparam($this->get_backupid()),
1344 backup_helper::is_sqlparam('userfinal')));
1346 // All the rest on information is only added if we arent
1347 // in an anonymized backup
1348 if (!$anonymize) {
1349 $customfield->set_source_sql('SELECT f.id, f.shortname, f.datatype, d.data
1350 FROM {user_info_field} f
1351 JOIN {user_info_data} d ON d.fieldid = f.id
1352 WHERE d.userid = ?', array(backup::VAR_PARENTID));
1354 $customfield->set_source_alias('shortname', 'field_name');
1355 $customfield->set_source_alias('datatype', 'field_type');
1356 $customfield->set_source_alias('data', 'field_data');
1358 $tag->set_source_sql('SELECT t.id, t.name, t.rawname
1359 FROM {tag} t
1360 JOIN {tag_instance} ti ON ti.tagid = t.id
1361 WHERE ti.itemtype = ?
1362 AND ti.itemid = ?', array(
1363 backup_helper::is_sqlparam('user'),
1364 backup::VAR_PARENTID));
1366 $preference->set_source_table('user_preferences', array('userid' => backup::VAR_PARENTID));
1368 $override->set_source_table('role_capabilities', array('contextid' => '/users/user/contextid'));
1370 // Assignments only added if specified
1371 if ($roleassignments) {
1372 $assignment->set_source_table('role_assignments', array('contextid' => '/users/user/contextid'));
1375 // Define id annotations (as final)
1376 $override->annotate_ids('rolefinal', 'roleid');
1379 // Return root element (users)
1380 return $users;
1385 * structure step in charge of constructing the block.xml file for one
1386 * given block (instance and positions). If the block has custom DB structure
1387 * that will go to a separate file (different step defined in block class)
1389 class backup_block_instance_structure_step extends backup_structure_step {
1391 protected function define_structure() {
1392 global $DB;
1394 // Define each element separated
1396 $block = new backup_nested_element('block', array('id', 'contextid', 'version'), array(
1397 'blockname', 'parentcontextid', 'showinsubcontexts', 'pagetypepattern',
1398 'subpagepattern', 'defaultregion', 'defaultweight', 'configdata'));
1400 $positions = new backup_nested_element('block_positions');
1402 $position = new backup_nested_element('block_position', array('id'), array(
1403 'contextid', 'pagetype', 'subpage', 'visible',
1404 'region', 'weight'));
1406 // Build the tree
1408 $block->add_child($positions);
1409 $positions->add_child($position);
1411 // Transform configdata information if needed (process links and friends)
1412 $blockrec = $DB->get_record('block_instances', array('id' => $this->task->get_blockid()));
1413 if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
1414 $configdata = (array)unserialize(base64_decode($blockrec->configdata));
1415 foreach ($configdata as $attribute => $value) {
1416 if (in_array($attribute, $attrstotransform)) {
1417 $configdata[$attribute] = $this->contenttransformer->process($value);
1420 $blockrec->configdata = base64_encode(serialize((object)$configdata));
1422 $blockrec->contextid = $this->task->get_contextid();
1423 // Get the version of the block
1424 $blockrec->version = get_config('block_'.$this->task->get_blockname(), 'version');
1426 // Define sources
1428 $block->set_source_array(array($blockrec));
1430 $position->set_source_table('block_positions', array('blockinstanceid' => backup::VAR_PARENTID));
1432 // File anotations (for fileareas specified on each block)
1433 foreach ($this->task->get_fileareas() as $filearea) {
1434 $block->annotate_files('block_' . $this->task->get_blockname(), $filearea, null);
1437 // Return the root element (block)
1438 return $block;
1443 * structure step in charge of constructing the logs.xml file for all the log records found
1444 * in course. Note that we are sending to backup ALL the log records having cmid = 0. That
1445 * includes some records that won't be restoreable (like 'upload', 'calendar'...) but we do
1446 * that just in case they become restored some day in the future
1448 class backup_course_logs_structure_step extends backup_structure_step {
1450 protected function define_structure() {
1452 // Define each element separated
1454 $logs = new backup_nested_element('logs');
1456 $log = new backup_nested_element('log', array('id'), array(
1457 'time', 'userid', 'ip', 'module',
1458 'action', 'url', 'info'));
1460 // Build the tree
1462 $logs->add_child($log);
1464 // Define sources (all the records belonging to the course, having cmid = 0)
1466 $log->set_source_table('log', array('course' => backup::VAR_COURSEID, 'cmid' => backup_helper::is_sqlparam(0)));
1468 // Annotations
1469 // NOTE: We don't annotate users from logs as far as they MUST be
1470 // always annotated by the course (enrol, ras... whatever)
1472 // Return the root element (logs)
1474 return $logs;
1479 * structure step in charge of constructing the logs.xml file for all the log records found
1480 * in activity
1482 class backup_activity_logs_structure_step extends backup_structure_step {
1484 protected function define_structure() {
1486 // Define each element separated
1488 $logs = new backup_nested_element('logs');
1490 $log = new backup_nested_element('log', array('id'), array(
1491 'time', 'userid', 'ip', 'module',
1492 'action', 'url', 'info'));
1494 // Build the tree
1496 $logs->add_child($log);
1498 // Define sources
1500 $log->set_source_table('log', array('cmid' => backup::VAR_MODID));
1502 // Annotations
1503 // NOTE: We don't annotate users from logs as far as they MUST be
1504 // always annotated by the activity (true participants).
1506 // Return the root element (logs)
1508 return $logs;
1513 * structure in charge of constructing the inforef.xml file for all the items we want
1514 * to have referenced there (users, roles, files...)
1516 class backup_inforef_structure_step extends backup_structure_step {
1518 protected function define_structure() {
1520 // Items we want to include in the inforef file.
1521 $items = backup_helper::get_inforef_itemnames();
1523 // Build the tree
1525 $inforef = new backup_nested_element('inforef');
1527 // For each item, conditionally, if there are already records, build element
1528 foreach ($items as $itemname) {
1529 if (backup_structure_dbops::annotations_exist($this->get_backupid(), $itemname)) {
1530 $elementroot = new backup_nested_element($itemname . 'ref');
1531 $element = new backup_nested_element($itemname, array(), array('id'));
1532 $inforef->add_child($elementroot);
1533 $elementroot->add_child($element);
1534 $element->set_source_sql("
1535 SELECT itemid AS id
1536 FROM {backup_ids_temp}
1537 WHERE backupid = ?
1538 AND itemname = ?",
1539 array(backup::VAR_BACKUPID, backup_helper::is_sqlparam($itemname)));
1543 // We don't annotate anything there, but rely in the next step
1544 // (move_inforef_annotations_to_final) that will change all the
1545 // already saved 'inforref' entries to their 'final' annotations.
1546 return $inforef;
1551 * This step will get all the annotations already processed to inforef.xml file and
1552 * transform them into 'final' annotations.
1554 class move_inforef_annotations_to_final extends backup_execution_step {
1556 protected function define_execution() {
1558 // Items we want to include in the inforef file
1559 $items = backup_helper::get_inforef_itemnames();
1560 $progress = $this->task->get_progress();
1561 $progress->start_progress($this->get_name(), count($items));
1562 $done = 1;
1563 foreach ($items as $itemname) {
1564 // Delegate to dbops
1565 backup_structure_dbops::move_annotations_to_final($this->get_backupid(),
1566 $itemname, $progress);
1567 $progress->progress($done++);
1569 $progress->end_progress();
1574 * structure in charge of constructing the files.xml file with all the
1575 * annotated (final) files along the process. At, the same time, and
1576 * using one specialised nested_element, will copy them form moodle storage
1577 * to backup storage
1579 class backup_final_files_structure_step extends backup_structure_step {
1581 protected function define_structure() {
1583 // Define elements
1585 $files = new backup_nested_element('files');
1587 $file = new file_nested_element('file', array('id'), array(
1588 'contenthash', 'contextid', 'component', 'filearea', 'itemid',
1589 'filepath', 'filename', 'userid', 'filesize',
1590 'mimetype', 'status', 'timecreated', 'timemodified',
1591 'source', 'author', 'license', 'sortorder',
1592 'repositorytype', 'repositoryid', 'reference'));
1594 // Build the tree
1596 $files->add_child($file);
1598 // Define sources
1600 $file->set_source_sql("SELECT f.*, r.type AS repositorytype, fr.repositoryid, fr.reference
1601 FROM {files} f
1602 LEFT JOIN {files_reference} fr ON fr.id = f.referencefileid
1603 LEFT JOIN {repository_instances} ri ON ri.id = fr.repositoryid
1604 LEFT JOIN {repository} r ON r.id = ri.typeid
1605 JOIN {backup_ids_temp} bi ON f.id = bi.itemid
1606 WHERE bi.backupid = ?
1607 AND bi.itemname = 'filefinal'", array(backup::VAR_BACKUPID));
1609 return $files;
1614 * Structure step in charge of creating the main moodle_backup.xml file
1615 * where all the information related to the backup, settings, license and
1616 * other information needed on restore is added*/
1617 class backup_main_structure_step extends backup_structure_step {
1619 protected function define_structure() {
1621 global $CFG;
1623 $info = array();
1625 $info['name'] = $this->get_setting_value('filename');
1626 $info['moodle_version'] = $CFG->version;
1627 $info['moodle_release'] = $CFG->release;
1628 $info['backup_version'] = $CFG->backup_version;
1629 $info['backup_release'] = $CFG->backup_release;
1630 $info['backup_date'] = time();
1631 $info['backup_uniqueid']= $this->get_backupid();
1632 $info['mnet_remoteusers']=backup_controller_dbops::backup_includes_mnet_remote_users($this->get_backupid());
1633 $info['include_files'] = backup_controller_dbops::backup_includes_files($this->get_backupid());
1634 $info['include_file_references_to_external_content'] =
1635 backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1636 $info['original_wwwroot']=$CFG->wwwroot;
1637 $info['original_site_identifier_hash'] = md5(get_site_identifier());
1638 $info['original_course_id'] = $this->get_courseid();
1639 $originalcourseinfo = backup_controller_dbops::backup_get_original_course_info($this->get_courseid());
1640 $info['original_course_fullname'] = $originalcourseinfo->fullname;
1641 $info['original_course_shortname'] = $originalcourseinfo->shortname;
1642 $info['original_course_startdate'] = $originalcourseinfo->startdate;
1643 $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id;
1644 $info['original_system_contextid'] = context_system::instance()->id;
1646 // Get more information from controller
1647 list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information(
1648 $this->get_backupid(), $this->get_task()->get_progress());
1650 // Define elements
1652 $moodle_backup = new backup_nested_element('moodle_backup');
1654 $information = new backup_nested_element('information', null, array(
1655 'name', 'moodle_version', 'moodle_release', 'backup_version',
1656 'backup_release', 'backup_date', 'mnet_remoteusers', 'include_files', 'include_file_references_to_external_content', 'original_wwwroot',
1657 'original_site_identifier_hash', 'original_course_id',
1658 'original_course_fullname', 'original_course_shortname', 'original_course_startdate',
1659 'original_course_contextid', 'original_system_contextid'));
1661 $details = new backup_nested_element('details');
1663 $detail = new backup_nested_element('detail', array('backup_id'), array(
1664 'type', 'format', 'interactive', 'mode',
1665 'execution', 'executiontime'));
1667 $contents = new backup_nested_element('contents');
1669 $activities = new backup_nested_element('activities');
1671 $activity = new backup_nested_element('activity', null, array(
1672 'moduleid', 'sectionid', 'modulename', 'title',
1673 'directory'));
1675 $sections = new backup_nested_element('sections');
1677 $section = new backup_nested_element('section', null, array(
1678 'sectionid', 'title', 'directory'));
1680 $course = new backup_nested_element('course', null, array(
1681 'courseid', 'title', 'directory'));
1683 $settings = new backup_nested_element('settings');
1685 $setting = new backup_nested_element('setting', null, array(
1686 'level', 'section', 'activity', 'name', 'value'));
1688 // Build the tree
1690 $moodle_backup->add_child($information);
1692 $information->add_child($details);
1693 $details->add_child($detail);
1695 $information->add_child($contents);
1696 if (!empty($cinfo['activities'])) {
1697 $contents->add_child($activities);
1698 $activities->add_child($activity);
1700 if (!empty($cinfo['sections'])) {
1701 $contents->add_child($sections);
1702 $sections->add_child($section);
1704 if (!empty($cinfo['course'])) {
1705 $contents->add_child($course);
1708 $information->add_child($settings);
1709 $settings->add_child($setting);
1712 // Set the sources
1714 $information->set_source_array(array((object)$info));
1716 $detail->set_source_array($dinfo);
1718 $activity->set_source_array($cinfo['activities']);
1720 $section->set_source_array($cinfo['sections']);
1722 $course->set_source_array($cinfo['course']);
1724 $setting->set_source_array($sinfo);
1726 // Prepare some information to be sent to main moodle_backup.xml file
1727 return $moodle_backup;
1733 * Execution step that will generate the final zip (.mbz) file with all the contents
1735 class backup_zip_contents extends backup_execution_step implements file_progress {
1737 * @var bool True if we have started tracking progress
1739 protected $startedprogress;
1741 protected function define_execution() {
1743 // Get basepath
1744 $basepath = $this->get_basepath();
1746 // Get the list of files in directory
1747 $filestemp = get_directory_list($basepath, '', false, true, true);
1748 $files = array();
1749 foreach ($filestemp as $file) { // Add zip paths and fs paths to all them
1750 $files[$file] = $basepath . '/' . $file;
1753 // Add the log file if exists
1754 $logfilepath = $basepath . '.log';
1755 if (file_exists($logfilepath)) {
1756 $files['moodle_backup.log'] = $logfilepath;
1759 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1760 $zipfile = $basepath . '/backup.mbz';
1762 // Get the zip packer
1763 $zippacker = get_file_packer('application/vnd.moodle.backup');
1765 // Track overall progress for the 2 long-running steps (archive to
1766 // pathname, get backup information).
1767 $reporter = $this->task->get_progress();
1768 $reporter->start_progress('backup_zip_contents', 2);
1770 // Zip files
1771 $result = $zippacker->archive_to_pathname($files, $zipfile, true, $this);
1773 // If any sub-progress happened, end it.
1774 if ($this->startedprogress) {
1775 $this->task->get_progress()->end_progress();
1776 $this->startedprogress = false;
1777 } else {
1778 // No progress was reported, manually move it on to the next overall task.
1779 $reporter->progress(1);
1782 // Something went wrong.
1783 if ($result === false) {
1784 @unlink($zipfile);
1785 throw new backup_step_exception('error_zip_packing', '', 'An error was encountered while trying to generate backup zip');
1787 // Read to make sure it is a valid backup. Refer MDL-37877 . Delete it, if found not to be valid.
1788 try {
1789 backup_general_helper::get_backup_information_from_mbz($zipfile, $this);
1790 } catch (backup_helper_exception $e) {
1791 @unlink($zipfile);
1792 throw new backup_step_exception('error_zip_packing', '', $e->debuginfo);
1795 // If any sub-progress happened, end it.
1796 if ($this->startedprogress) {
1797 $this->task->get_progress()->end_progress();
1798 $this->startedprogress = false;
1799 } else {
1800 $reporter->progress(2);
1802 $reporter->end_progress();
1806 * Implementation for file_progress interface to display unzip progress.
1808 * @param int $progress Current progress
1809 * @param int $max Max value
1811 public function progress($progress = file_progress::INDETERMINATE, $max = file_progress::INDETERMINATE) {
1812 $reporter = $this->task->get_progress();
1814 // Start tracking progress if necessary.
1815 if (!$this->startedprogress) {
1816 $reporter->start_progress('extract_file_to_dir', ($max == file_progress::INDETERMINATE)
1817 ? \core\progress\base::INDETERMINATE : $max);
1818 $this->startedprogress = true;
1821 // Pass progress through to whatever handles it.
1822 $reporter->progress(($progress == file_progress::INDETERMINATE)
1823 ? \core\progress\base::INDETERMINATE : $progress);
1828 * This step will send the generated backup file to its final destination
1830 class backup_store_backup_file extends backup_execution_step {
1832 protected function define_execution() {
1834 // Get basepath
1835 $basepath = $this->get_basepath();
1837 // Calculate the zip fullpath (in OS temp area it's always backup.mbz)
1838 $zipfile = $basepath . '/backup.mbz';
1840 $has_file_references = backup_controller_dbops::backup_includes_file_references($this->get_backupid());
1841 // Perform storage and return it (TODO: shouldn't be array but proper result object)
1842 return array(
1843 'backup_destination' => backup_helper::store_backup_file($this->get_backupid(), $zipfile,
1844 $this->task->get_progress()),
1845 'include_file_references_to_external_content' => $has_file_references
1852 * This step will search for all the activity (not calculations, categories nor aggregations) grade items
1853 * and put them to the backup_ids tables, to be used later as base to backup them
1855 class backup_activity_grade_items_to_ids extends backup_execution_step {
1857 protected function define_execution() {
1859 // Fetch all activity grade items
1860 if ($items = grade_item::fetch_all(array(
1861 'itemtype' => 'mod', 'itemmodule' => $this->task->get_modulename(),
1862 'iteminstance' => $this->task->get_activityid(), 'courseid' => $this->task->get_courseid()))) {
1863 // Annotate them in backup_ids
1864 foreach ($items as $item) {
1865 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grade_item', $item->id);
1873 * This step allows enrol plugins to annotate custom fields.
1875 * @package core_backup
1876 * @copyright 2014 University of Wisconsin
1877 * @author Matt Petro
1878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1880 class backup_enrolments_execution_step extends backup_execution_step {
1883 * Function that will contain all the code to be executed.
1885 protected function define_execution() {
1886 global $DB;
1888 $plugins = enrol_get_plugins(true);
1889 $enrols = $DB->get_records('enrol', array(
1890 'courseid' => $this->task->get_courseid()));
1892 // Allow each enrol plugin to add annotations.
1893 foreach ($enrols as $enrol) {
1894 if (isset($plugins[$enrol->enrol])) {
1895 $plugins[$enrol->enrol]->backup_annotate_custom_fields($this, $enrol);
1901 * Annotate a single name/id pair.
1902 * This can be called from {@link enrol_plugin::backup_annotate_custom_fields()}.
1904 * @param string $itemname
1905 * @param int $itemid
1907 public function annotate_id($itemname, $itemid) {
1908 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), $itemname, $itemid);
1913 * This step will annotate all the groups and groupings belonging to the course
1915 class backup_annotate_course_groups_and_groupings extends backup_execution_step {
1917 protected function define_execution() {
1918 global $DB;
1920 // Get all the course groups
1921 if ($groups = $DB->get_records('groups', array(
1922 'courseid' => $this->task->get_courseid()))) {
1923 foreach ($groups as $group) {
1924 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->id);
1928 // Get all the course groupings
1929 if ($groupings = $DB->get_records('groupings', array(
1930 'courseid' => $this->task->get_courseid()))) {
1931 foreach ($groupings as $grouping) {
1932 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'grouping', $grouping->id);
1939 * This step will annotate all the groups belonging to already annotated groupings
1941 class backup_annotate_groups_from_groupings extends backup_execution_step {
1943 protected function define_execution() {
1944 global $DB;
1946 // Fetch all the annotated groupings
1947 if ($groupings = $DB->get_records('backup_ids_temp', array(
1948 'backupid' => $this->get_backupid(), 'itemname' => 'grouping'))) {
1949 foreach ($groupings as $grouping) {
1950 if ($groups = $DB->get_records('groupings_groups', array(
1951 'groupingid' => $grouping->itemid))) {
1952 foreach ($groups as $group) {
1953 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'group', $group->groupid);
1962 * This step will annotate all the scales belonging to already annotated outcomes
1964 class backup_annotate_scales_from_outcomes extends backup_execution_step {
1966 protected function define_execution() {
1967 global $DB;
1969 // Fetch all the annotated outcomes
1970 if ($outcomes = $DB->get_records('backup_ids_temp', array(
1971 'backupid' => $this->get_backupid(), 'itemname' => 'outcome'))) {
1972 foreach ($outcomes as $outcome) {
1973 if ($scale = $DB->get_record('grade_outcomes', array(
1974 'id' => $outcome->itemid))) {
1975 // Annotate as scalefinal because it's > 0
1976 backup_structure_dbops::insert_backup_ids_record($this->get_backupid(), 'scalefinal', $scale->scaleid);
1984 * This step will generate all the file annotations for the already
1985 * annotated (final) question_categories. It calculates the different
1986 * contexts that are being backup and, annotates all the files
1987 * on every context belonging to the "question" component. As far as
1988 * we are always including *complete* question banks it is safe and
1989 * optimal to do that in this (one pass) way
1991 class backup_annotate_all_question_files extends backup_execution_step {
1993 protected function define_execution() {
1994 global $DB;
1996 // Get all the different contexts for the final question_categories
1997 // annotated along the whole backup
1998 $rs = $DB->get_recordset_sql("SELECT DISTINCT qc.contextid
1999 FROM {question_categories} qc
2000 JOIN {backup_ids_temp} bi ON bi.itemid = qc.id
2001 WHERE bi.backupid = ?
2002 AND bi.itemname = 'question_categoryfinal'", array($this->get_backupid()));
2003 // To know about qtype specific components/fileareas
2004 $components = backup_qtype_plugin::get_components_and_fileareas();
2005 // Let's loop
2006 foreach($rs as $record) {
2007 // Backup all the file areas the are managed by the core question component.
2008 // That is, by the question_type base class. In particular, we don't want
2009 // to include files belonging to responses here.
2010 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'questiontext', null);
2011 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'generalfeedback', null);
2012 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answer', null);
2013 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'answerfeedback', null);
2014 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'hint', null);
2015 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'correctfeedback', null);
2016 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'partiallycorrectfeedback', null);
2017 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, 'question', 'incorrectfeedback', null);
2019 // For files belonging to question types, we make the leap of faith that
2020 // all the files belonging to the question type are part of the question definition,
2021 // so we can just backup all the files in bulk, without specifying each
2022 // file area name separately.
2023 foreach ($components as $component => $fileareas) {
2024 backup_structure_dbops::annotate_files($this->get_backupid(), $record->contextid, $component, null, null);
2027 $rs->close();
2032 * structure step in charge of constructing the questions.xml file for all the
2033 * question categories and questions required by the backup
2034 * and letters related to one activity
2036 class backup_questions_structure_step extends backup_structure_step {
2038 protected function define_structure() {
2040 // Define each element separated
2042 $qcategories = new backup_nested_element('question_categories');
2044 $qcategory = new backup_nested_element('question_category', array('id'), array(
2045 'name', 'contextid', 'contextlevel', 'contextinstanceid',
2046 'info', 'infoformat', 'stamp', 'parent',
2047 'sortorder'));
2049 $questions = new backup_nested_element('questions');
2051 $question = new backup_nested_element('question', array('id'), array(
2052 'parent', 'name', 'questiontext', 'questiontextformat',
2053 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty',
2054 'qtype', 'length', 'stamp', 'version',
2055 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby'));
2057 // attach qtype plugin structure to $question element, only one allowed
2058 $this->add_plugin_structure('qtype', $question, false);
2060 // attach local plugin stucture to $question element, multiple allowed
2061 $this->add_plugin_structure('local', $question, true);
2063 $qhints = new backup_nested_element('question_hints');
2065 $qhint = new backup_nested_element('question_hint', array('id'), array(
2066 'hint', 'hintformat', 'shownumcorrect', 'clearwrong', 'options'));
2068 $tags = new backup_nested_element('tags');
2070 $tag = new backup_nested_element('tag', array('id'), array('name', 'rawname'));
2072 // Build the tree
2074 $qcategories->add_child($qcategory);
2075 $qcategory->add_child($questions);
2076 $questions->add_child($question);
2077 $question->add_child($qhints);
2078 $qhints->add_child($qhint);
2080 $question->add_child($tags);
2081 $tags->add_child($tag);
2083 // Define the sources
2085 $qcategory->set_source_sql("
2086 SELECT gc.*, contextlevel, instanceid AS contextinstanceid
2087 FROM {question_categories} gc
2088 JOIN {backup_ids_temp} bi ON bi.itemid = gc.id
2089 JOIN {context} co ON co.id = gc.contextid
2090 WHERE bi.backupid = ?
2091 AND bi.itemname = 'question_categoryfinal'", array(backup::VAR_BACKUPID));
2093 $question->set_source_table('question', array('category' => backup::VAR_PARENTID));
2095 $qhint->set_source_sql('
2096 SELECT *
2097 FROM {question_hints}
2098 WHERE questionid = :questionid
2099 ORDER BY id',
2100 array('questionid' => backup::VAR_PARENTID));
2102 $tag->set_source_sql("SELECT t.id, t.name, t.rawname
2103 FROM {tag} t
2104 JOIN {tag_instance} ti ON ti.tagid = t.id
2105 WHERE ti.itemid = ?
2106 AND ti.itemtype = 'question'", array(backup::VAR_PARENTID));
2108 // don't need to annotate ids nor files
2109 // (already done by {@link backup_annotate_all_question_files}
2111 return $qcategories;
2118 * This step will generate all the file annotations for the already
2119 * annotated (final) users. Need to do this here because each user
2120 * has its own context and structure tasks only are able to handle
2121 * one context. Also, this step will guarantee that every user has
2122 * its context created (req for other steps)
2124 class backup_annotate_all_user_files extends backup_execution_step {
2126 protected function define_execution() {
2127 global $DB;
2129 // List of fileareas we are going to annotate
2130 $fileareas = array('profile', 'icon');
2132 // Fetch all annotated (final) users
2133 $rs = $DB->get_recordset('backup_ids_temp', array(
2134 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal'));
2135 $progress = $this->task->get_progress();
2136 $progress->start_progress($this->get_name());
2137 foreach ($rs as $record) {
2138 $userid = $record->itemid;
2139 $userctx = context_user::instance($userid, IGNORE_MISSING);
2140 if (!$userctx) {
2141 continue; // User has not context, sure it's a deleted user, so cannot have files
2143 // Proceed with every user filearea
2144 foreach ($fileareas as $filearea) {
2145 // We don't need to specify itemid ($userid - 5th param) as far as by
2146 // context we can get all the associated files. See MDL-22092
2147 backup_structure_dbops::annotate_files($this->get_backupid(), $userctx->id, 'user', $filearea, null);
2148 $progress->progress();
2151 $progress->end_progress();
2152 $rs->close();
2158 * Defines the backup step for advanced grading methods attached to the activity module
2160 class backup_activity_grading_structure_step extends backup_structure_step {
2163 * Include the grading.xml only if the module supports advanced grading
2165 protected function execute_condition() {
2166 return plugin_supports('mod', $this->get_task()->get_modulename(), FEATURE_ADVANCED_GRADING, false);
2170 * Declares the gradable areas structures and data sources
2172 protected function define_structure() {
2174 // To know if we are including userinfo
2175 $userinfo = $this->get_setting_value('userinfo');
2177 // Define the elements
2179 $areas = new backup_nested_element('areas');
2181 $area = new backup_nested_element('area', array('id'), array(
2182 'areaname', 'activemethod'));
2184 $definitions = new backup_nested_element('definitions');
2186 $definition = new backup_nested_element('definition', array('id'), array(
2187 'method', 'name', 'description', 'descriptionformat', 'status',
2188 'timecreated', 'timemodified', 'options'));
2190 $instances = new backup_nested_element('instances');
2192 $instance = new backup_nested_element('instance', array('id'), array(
2193 'raterid', 'itemid', 'rawgrade', 'status', 'feedback',
2194 'feedbackformat', 'timemodified'));
2196 // Build the tree including the method specific structures
2197 // (beware - the order of how gradingform plugins structures are attached is important)
2198 $areas->add_child($area);
2199 // attach local plugin stucture to $area element, multiple allowed
2200 $this->add_plugin_structure('local', $area, true);
2201 $area->add_child($definitions);
2202 $definitions->add_child($definition);
2203 $this->add_plugin_structure('gradingform', $definition, true);
2204 // attach local plugin stucture to $definition element, multiple allowed
2205 $this->add_plugin_structure('local', $definition, true);
2206 $definition->add_child($instances);
2207 $instances->add_child($instance);
2208 $this->add_plugin_structure('gradingform', $instance, false);
2209 // attach local plugin stucture to $instance element, multiple allowed
2210 $this->add_plugin_structure('local', $instance, true);
2212 // Define data sources
2214 $area->set_source_table('grading_areas', array('contextid' => backup::VAR_CONTEXTID,
2215 'component' => array('sqlparam' => 'mod_'.$this->get_task()->get_modulename())));
2217 $definition->set_source_table('grading_definitions', array('areaid' => backup::VAR_PARENTID));
2219 if ($userinfo) {
2220 $instance->set_source_table('grading_instances', array('definitionid' => backup::VAR_PARENTID));
2223 // Annotate references
2224 $definition->annotate_files('grading', 'description', 'id');
2225 $instance->annotate_ids('user', 'raterid');
2227 // Return the root element
2228 return $areas;
2234 * structure step in charge of constructing the grades.xml file for all the grade items
2235 * and letters related to one activity
2237 class backup_activity_grades_structure_step extends backup_structure_step {
2239 protected function define_structure() {
2241 // To know if we are including userinfo
2242 $userinfo = $this->get_setting_value('userinfo');
2244 // Define each element separated
2246 $book = new backup_nested_element('activity_gradebook');
2248 $items = new backup_nested_element('grade_items');
2250 $item = new backup_nested_element('grade_item', array('id'), array(
2251 'categoryid', 'itemname', 'itemtype', 'itemmodule',
2252 'iteminstance', 'itemnumber', 'iteminfo', 'idnumber',
2253 'calculation', 'gradetype', 'grademax', 'grademin',
2254 'scaleid', 'outcomeid', 'gradepass', 'multfactor',
2255 'plusfactor', 'aggregationcoef', 'aggregationcoef2', 'weightoverride',
2256 'sortorder', 'display', 'decimals', 'hidden', 'locked', 'locktime',
2257 'needsupdate', 'timecreated', 'timemodified'));
2259 $grades = new backup_nested_element('grade_grades');
2261 $grade = new backup_nested_element('grade_grade', array('id'), array(
2262 'userid', 'rawgrade', 'rawgrademax', 'rawgrademin',
2263 'rawscaleid', 'usermodified', 'finalgrade', 'hidden',
2264 'locked', 'locktime', 'exported', 'overridden',
2265 'excluded', 'feedback', 'feedbackformat', 'information',
2266 'informationformat', 'timecreated', 'timemodified',
2267 'aggregationstatus', 'aggregationweight'));
2269 $letters = new backup_nested_element('grade_letters');
2271 $letter = new backup_nested_element('grade_letter', 'id', array(
2272 'lowerboundary', 'letter'));
2274 // Build the tree
2276 $book->add_child($items);
2277 $items->add_child($item);
2279 $item->add_child($grades);
2280 $grades->add_child($grade);
2282 $book->add_child($letters);
2283 $letters->add_child($letter);
2285 // Define sources
2287 $item->set_source_sql("SELECT gi.*
2288 FROM {grade_items} gi
2289 JOIN {backup_ids_temp} bi ON gi.id = bi.itemid
2290 WHERE bi.backupid = ?
2291 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2293 // This only happens if we are including user info
2294 if ($userinfo) {
2295 $grade->set_source_table('grade_grades', array('itemid' => backup::VAR_PARENTID));
2298 $letter->set_source_table('grade_letters', array('contextid' => backup::VAR_CONTEXTID));
2300 // Annotations
2302 $item->annotate_ids('scalefinal', 'scaleid'); // Straight as scalefinal because it's > 0
2303 $item->annotate_ids('outcome', 'outcomeid');
2305 $grade->annotate_ids('user', 'userid');
2306 $grade->annotate_ids('user', 'usermodified');
2308 // Return the root element (book)
2310 return $book;
2315 * Structure step in charge of constructing the grade history of an activity.
2317 * This step is added to the task regardless of the setting 'grade_histories'.
2318 * The reason is to allow for a more flexible step in case the logic needs to be
2319 * split accross different settings to control the history of items and/or grades.
2321 class backup_activity_grade_history_structure_step extends backup_structure_step {
2323 protected function define_structure() {
2325 // Settings to use.
2326 $userinfo = $this->get_setting_value('userinfo');
2327 $history = $this->get_setting_value('grade_histories');
2329 // Create the nested elements.
2330 $bookhistory = new backup_nested_element('grade_history');
2331 $grades = new backup_nested_element('grade_grades');
2332 $grade = new backup_nested_element('grade_grade', array('id'), array(
2333 'action', 'oldid', 'source', 'loggeduser', 'itemid', 'userid',
2334 'rawgrade', 'rawgrademax', 'rawgrademin', 'rawscaleid',
2335 'usermodified', 'finalgrade', 'hidden', 'locked', 'locktime', 'exported', 'overridden',
2336 'excluded', 'feedback', 'feedbackformat', 'information',
2337 'informationformat', 'timemodified'));
2339 // Build the tree.
2340 $bookhistory->add_child($grades);
2341 $grades->add_child($grade);
2343 // This only happens if we are including user info and history.
2344 if ($userinfo && $history) {
2345 // Define sources. Only select the history related to existing activity items.
2346 $grade->set_source_sql("SELECT ggh.*
2347 FROM {grade_grades_history} ggh
2348 JOIN {backup_ids_temp} bi ON ggh.itemid = bi.itemid
2349 WHERE bi.backupid = ?
2350 AND bi.itemname = 'grade_item'", array(backup::VAR_BACKUPID));
2353 // Annotations.
2354 $grade->annotate_ids('scalefinal', 'rawscaleid'); // Straight as scalefinal because it's > 0.
2355 $grade->annotate_ids('user', 'loggeduser');
2356 $grade->annotate_ids('user', 'userid');
2357 $grade->annotate_ids('user', 'usermodified');
2359 // Return the root element.
2360 return $bookhistory;
2365 * Backups up the course completion information for the course.
2367 class backup_course_completion_structure_step extends backup_structure_step {
2369 protected function execute_condition() {
2370 // Check that all activities have been included
2371 if ($this->task->is_excluding_activities()) {
2372 return false;
2374 return true;
2378 * The structure of the course completion backup
2380 * @return backup_nested_element
2382 protected function define_structure() {
2384 // To know if we are including user completion info
2385 $userinfo = $this->get_setting_value('userscompletion');
2387 $cc = new backup_nested_element('course_completion');
2389 $criteria = new backup_nested_element('course_completion_criteria', array('id'), array(
2390 'course', 'criteriatype', 'module', 'moduleinstance', 'courseinstanceshortname', 'enrolperiod',
2391 'timeend', 'gradepass', 'role', 'roleshortname'
2394 $criteriacompletions = new backup_nested_element('course_completion_crit_completions');
2396 $criteriacomplete = new backup_nested_element('course_completion_crit_compl', array('id'), array(
2397 'criteriaid', 'userid', 'gradefinal', 'unenrolled', 'timecompleted'
2400 $coursecompletions = new backup_nested_element('course_completions', array('id'), array(
2401 'userid', 'course', 'timeenrolled', 'timestarted', 'timecompleted', 'reaggregate'
2404 $aggregatemethod = new backup_nested_element('course_completion_aggr_methd', array('id'), array(
2405 'course','criteriatype','method','value'
2408 $cc->add_child($criteria);
2409 $criteria->add_child($criteriacompletions);
2410 $criteriacompletions->add_child($criteriacomplete);
2411 $cc->add_child($coursecompletions);
2412 $cc->add_child($aggregatemethod);
2414 // We need some extra data for the restore.
2415 // - courseinstances shortname rather than an ID.
2416 // - roleshortname in case restoring on a different site.
2417 $sourcesql = "SELECT ccc.*, c.shortname AS courseinstanceshortname, r.shortname AS roleshortname
2418 FROM {course_completion_criteria} ccc
2419 LEFT JOIN {course} c ON c.id = ccc.courseinstance
2420 LEFT JOIN {role} r ON r.id = ccc.role
2421 WHERE ccc.course = ?";
2422 $criteria->set_source_sql($sourcesql, array(backup::VAR_COURSEID));
2424 $aggregatemethod->set_source_table('course_completion_aggr_methd', array('course' => backup::VAR_COURSEID));
2426 if ($userinfo) {
2427 $criteriacomplete->set_source_table('course_completion_crit_compl', array('criteriaid' => backup::VAR_PARENTID));
2428 $coursecompletions->set_source_table('course_completions', array('course' => backup::VAR_COURSEID));
2431 $criteria->annotate_ids('role', 'role');
2432 $criteriacomplete->annotate_ids('user', 'userid');
2433 $coursecompletions->annotate_ids('user', 'userid');
2435 return $cc;