本文整理汇总了PHP中backup_controller::execute_plan方法的典型用法代码示例。如果您正苦于以下问题:PHP backup_controller::execute_plan方法的具体用法?PHP backup_controller::execute_plan怎么用?PHP backup_controller::execute_plan使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类backup_controller
的用法示例。
在下文中一共展示了backup_controller::execute_plan方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: backup_course
/**
* Backup a course and return its backup ID.
*
* @param int $courseid The course ID.
* @param int $userid The user doing the backup.
* @return string
*/
protected function backup_course($courseid, $userid = 2)
{
global $CFG;
$packer = get_file_packer('application/vnd.moodle.backup');
$bc = new backup_controller(backup::TYPE_1COURSE, $courseid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $userid);
$bc->execute_plan();
$results = $bc->get_results();
$results['backup_destination']->extract_to_pathname($packer, "{$CFG->tempdir}/backup/core_course_testcase");
$bc->destroy();
unset($bc);
return 'core_course_testcase';
}
示例2: execute
/**
* C'est une copie de la commande moosh
* https://github.com/tmuras/moosh/blob/master/Moosh/Command/Moodle23/Course/CourseBackup.php
* @param $shortname
* @param $savepath
*/
public static function execute($shortname, $savepath)
{
global $CFG, $DB, $USER;
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
error_reporting(E_ALL);
ini_set('display_errors', true);
//check if course id exists
$course = $DB->get_record('course', array('shortname' => $shortname), '*', MUST_EXIST);
$shortname = str_replace(' ', '_', $course->shortname);
$filename = $savepath . '/backup_' . str_replace('/', '_', $shortname) . '_' . date('Y.m.d') . '.mbz';
//check if destination file does not exist and can be created
if (file_exists($filename)) {
cli_error("File '{$filename}' already exists, I will not over-write it.");
}
$bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id, \backup::FORMAT_MOODLE, \backup::INTERACTIVE_YES, \backup::MODE_GENERAL, 2);
// 2 correspond à user admin!
$tasks = $bc->get_plan()->get_tasks();
foreach ($tasks as &$task) {
if ($task instanceof \backup_root_task) {
$setting = $task->get_setting('users');
$setting->set_value('0');
$setting = $task->get_setting('anonymize');
$setting->set_value('1');
$setting = $task->get_setting('role_assignments');
$setting->set_value('1');
$setting = $task->get_setting('filters');
$setting->set_value('1');
$setting = $task->get_setting('comments');
$setting->set_value('0');
$setting = $task->get_setting('logs');
$setting->set_value('0');
$setting = $task->get_setting('grade_histories');
$setting->set_value('0');
}
}
$bc->set_status(\backup::STATUS_AWAITING);
$bc->execute_plan();
$result = $bc->get_results();
if (isset($result['backup_destination']) && $result['backup_destination']) {
$file = $result['backup_destination'];
/** @var $file stored_file */
if (!$file->copy_content_to($filename)) {
cli_error("Problems copying final backup to '" . $filename . "'");
} else {
printf("%s\n", $filename);
}
} else {
echo $bc->get_backupid();
}
}
示例3: test_backup_restore
public function test_backup_restore()
{
// TODO this test does not check if userids are correctly mapped
global $CFG, $DB;
core_php_time_limit::raise();
// Set to admin user.
$this->setAdminUser();
$gen_mod = new mod_ratingallocate_generated_module($this);
$course1 = $gen_mod->course;
// Create backup file and save it to the backup location.
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $gen_mod->mod_db->cmid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2);
$bc->execute_plan();
$results = $bc->get_results();
$file = $results['backup_destination'];
//TODO: Necessary to ensure backward compatibility
if (tgz_packer::is_tgz_file($file)) {
$fp = get_file_packer('application/x-gzip');
} else {
$fp = get_file_packer();
}
$filepath = $CFG->dataroot . '/temp/backup/test-restore-course';
$file->extract_to_pathname($fp, $filepath);
$bc->destroy();
unset($bc);
// Create a course that we are going to restore the other course to.
$course2 = $this->getDataGenerator()->create_course();
// Now restore the course.
$rc = new restore_controller('test-restore-course', $course2->id, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2, backup::TARGET_NEW_COURSE);
$rc->execute_precheck();
$rc->execute_plan();
$unset_values = function ($elem1, $elem2, $varname) {
$this->assertNotEquals($elem1->{$varname}, $elem2->{$varname});
$result = array($elem1->{$varname}, $elem2->{$varname});
unset($elem1->{$varname});
unset($elem2->{$varname});
return $result;
};
$ratingallocate1 = $DB->get_record(this_db\ratingallocate::TABLE, array(this_db\ratingallocate::COURSE => $course1->id));
$ratingallocate2 = $DB->get_record(this_db\ratingallocate::TABLE, array(this_db\ratingallocate::COURSE => $course2->id));
list($rating_id1, $rating_id2) = $unset_values($ratingallocate1, $ratingallocate2, this_db\ratingallocate::ID);
$unset_values($ratingallocate1, $ratingallocate2, this_db\ratingallocate::COURSE);
$this->assertEquals($ratingallocate1, $ratingallocate2);
$choices1 = $DB->get_records(this_db\ratingallocate_choices::TABLE, array(this_db\ratingallocate_choices::RATINGALLOCATEID => $rating_id1), this_db\ratingallocate_choices::TITLE);
$choices2 = $DB->get_records(this_db\ratingallocate_choices::TABLE, array(this_db\ratingallocate_choices::RATINGALLOCATEID => $rating_id2), this_db\ratingallocate_choices::TITLE);
$this->assertCount(2, $choices1);
$this->assertCount(2, array_values($choices2));
$choice2_copy = $choices2;
foreach ($choices1 as $choice1) {
//work with copies
$choice2 = json_decode(json_encode(array_shift($choice2_copy)));
$choice1 = json_decode(json_encode($choice1));
list($choiceid1, $choiceid2) = $unset_values($choice1, $choice2, this_db\ratingallocate_choices::ID);
$unset_values($choice1, $choice2, this_db\ratingallocate_choices::RATINGALLOCATEID);
$this->assertEquals($choice1, $choice2);
// compare ratings for this choice
$ratings1 = array_values($DB->get_records(this_db\ratingallocate_ratings::TABLE, array(this_db\ratingallocate_ratings::CHOICEID => $choiceid1), this_db\ratingallocate_ratings::USERID));
$ratings2 = array_values($DB->get_records(this_db\ratingallocate_ratings::TABLE, array(this_db\ratingallocate_ratings::CHOICEID => $choiceid2), this_db\ratingallocate_ratings::USERID));
$this->assertEquals(count($ratings1), count($ratings2));
$ratings2_copy = $ratings2;
foreach ($ratings1 as $rating1) {
$rating2 = json_decode(json_encode(array_shift($ratings2_copy)));
$rating1 = json_decode(json_encode($rating1));
$unset_values($rating1, $rating2, this_db\ratingallocate_ratings::CHOICEID);
$unset_values($rating1, $rating2, this_db\ratingallocate_ratings::ID);
$this->assertEquals($rating1, $rating2);
}
}
// compare allocations
$allocations1 = $DB->get_records(this_db\ratingallocate_allocations::TABLE, array(this_db\ratingallocate_allocations::RATINGALLOCATEID => $rating_id1), this_db\ratingallocate_allocations::USERID);
$allocations2 = $DB->get_records(this_db\ratingallocate_allocations::TABLE, array(this_db\ratingallocate_allocations::RATINGALLOCATEID => $rating_id2), this_db\ratingallocate_allocations::USERID);
// number of allocations is equal
//$this->assertCount(count($allocations1), $allocations2);
$this->assertCount(count($gen_mod->allocations), $allocations2);
// create function that can be used to replace
$map_allocation_to_choice_title = function (&$alloc, $choices) {
$alloc->{'choice_title'} = $choices[$alloc->{this_db\ratingallocate_allocations::CHOICEID}]->{this_db\ratingallocate_choices::TITLE};
};
// compare allocations in detail!
$alloc2 = reset($allocations2);
foreach ($allocations1 as &$alloc1) {
$map_allocation_to_choice_title($alloc1, $choices1);
$map_allocation_to_choice_title($alloc2, $choices2);
$unset_values($alloc1, $alloc2, this_db\ratingallocate_allocations::RATINGALLOCATEID);
$unset_values($alloc1, $alloc2, this_db\ratingallocate_allocations::CHOICEID);
$unset_values($alloc1, $alloc2, this_db\ratingallocate_allocations::ID);
$alloc2 = next($allocations2);
}
$this->assertEquals(array_values($allocations1), array_values($allocations2));
}
示例4: test_altering_tag_instance_context
/**
* This function tests that the functions responsible for moving questions to
* different contexts also updates the tag instances associated with the questions.
*/
public function test_altering_tag_instance_context()
{
global $CFG, $DB;
// Set to admin user.
$this->setAdminUser();
// Create two course categories - we are going to delete one of these later and will expect
// all the questions belonging to the course in the deleted category to be moved.
$coursecat1 = $this->getDataGenerator()->create_category();
$coursecat2 = $this->getDataGenerator()->create_category();
// Create a couple of categories and questions.
$context1 = context_coursecat::instance($coursecat1->id);
$context2 = context_coursecat::instance($coursecat2->id);
$questiongenerator = $this->getDataGenerator()->get_plugin_generator('core_question');
$questioncat1 = $questiongenerator->create_question_category(array('contextid' => $context1->id));
$questioncat2 = $questiongenerator->create_question_category(array('contextid' => $context2->id));
$question1 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat1->id));
$question2 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat1->id));
$question3 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat2->id));
$question4 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat2->id));
// Now lets tag these questions.
core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $context1, array('tag 1', 'tag 2'));
core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $context1, array('tag 3', 'tag 4'));
core_tag_tag::set_item_tags('core_question', 'question', $question3->id, $context2, array('tag 5', 'tag 6'));
core_tag_tag::set_item_tags('core_question', 'question', $question4->id, $context2, array('tag 7', 'tag 8'));
// Test moving the questions to another category.
question_move_questions_to_category(array($question1->id, $question2->id), $questioncat2->id);
// Test that all tag_instances belong to one context.
$this->assertEquals(8, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat2->contextid)));
// Test moving them back.
question_move_questions_to_category(array($question1->id, $question2->id), $questioncat1->id);
// Test that all tag_instances are now reset to how they were initially.
$this->assertEquals(4, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat1->contextid)));
$this->assertEquals(4, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat2->contextid)));
// Now test moving a whole question category to another context.
question_move_category_to_context($questioncat1->id, $questioncat1->contextid, $questioncat2->contextid);
// Test that all tag_instances belong to one context.
$this->assertEquals(8, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat2->contextid)));
// Now test moving them back.
question_move_category_to_context($questioncat1->id, $questioncat2->contextid, context_coursecat::instance($coursecat1->id)->id);
// Test that all tag_instances are now reset to how they were initially.
$this->assertEquals(4, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat1->contextid)));
$this->assertEquals(4, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat2->contextid)));
// Now we want to test deleting the course category and moving the questions to another category.
question_delete_course_category($coursecat1, $coursecat2, false);
// Test that all tag_instances belong to one context.
$this->assertEquals(8, $DB->count_records('tag_instance', array('component' => 'core_question', 'contextid' => $questioncat2->contextid)));
// Create a course.
$course = $this->getDataGenerator()->create_course();
// Create some question categories and questions in this course.
$coursecontext = context_course::instance($course->id);
$questioncat = $questiongenerator->create_question_category(array('contextid' => $coursecontext->id));
$question1 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat->id));
$question2 = $questiongenerator->create_question('shortanswer', null, array('category' => $questioncat->id));
// Add some tags to these questions.
core_tag_tag::set_item_tags('core_question', 'question', $question1->id, $coursecontext, array('tag 1', 'tag 2'));
core_tag_tag::set_item_tags('core_question', 'question', $question2->id, $coursecontext, array('tag 1', 'tag 2'));
// Create a course that we are going to restore the other course to.
$course2 = $this->getDataGenerator()->create_course();
// Create backup file and save it to the backup location.
$bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2);
$bc->execute_plan();
$results = $bc->get_results();
$file = $results['backup_destination'];
$fp = get_file_packer('application/vnd.moodle.backup');
$filepath = $CFG->dataroot . '/temp/backup/test-restore-course';
$file->extract_to_pathname($fp, $filepath);
$bc->destroy();
// Now restore the course.
$rc = new restore_controller('test-restore-course', $course2->id, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2, backup::TARGET_NEW_COURSE);
$rc->execute_precheck();
$rc->execute_plan();
// Get the created question category.
$restoredcategory = $DB->get_record('question_categories', array('contextid' => context_course::instance($course2->id)->id), '*', MUST_EXIST);
// Check that there are two questions in the restored to course's context.
$this->assertEquals(2, $DB->count_records('question', array('category' => $restoredcategory->id)));
$rc->destroy();
}
示例5: array
$PAGE->set_heading($course->fullname);
$PAGE->set_url(new moodle_url('/course/modduplicate.php', array('cmid' => $cm->id, 'courseid' => $course->id)));
$PAGE->set_pagelayout('incourse');
$output = $PAGE->get_renderer('core', 'backup');
$a = new stdClass();
$a->modtype = get_string('modulename', $cm->modname);
$a->modname = format_string($cm->name);
if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
$url = course_get_url($course, $cm->sectionnum, array('sr' => $sectionreturn));
print_error('duplicatenosupport', 'error', $url, $a);
}
// backup the activity
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
$backupid = $bc->get_backupid();
$backupbasepath = $bc->get_plan()->get_basepath();
$bc->execute_plan();
$bc->destroy();
// restore the backup immediately
$rc = new restore_controller($backupid, $courseid, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
if (!$rc->execute_precheck()) {
$precheckresults = $rc->get_precheck_results();
if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete($backupbasepath);
}
echo $output->header();
echo $output->precheck_notices($precheckresults);
$url = course_get_url($course, $cm->sectionnum, array('sr' => $sectionreturn));
echo $output->continue_button($url);
echo $output->footer();
die;
示例6: test_course_restored_event
/**
* Test that triggering a course_restored event works as expected.
*/
public function test_course_restored_event()
{
global $CFG;
// Get the necessary files to perform backup and restore.
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php';
$this->resetAfterTest();
// Set to admin user.
$this->setAdminUser();
// The user id is going to be 2 since we are the admin user.
$userid = 2;
// Create a course.
$course = $this->getDataGenerator()->create_course();
// Create backup file and save it to the backup location.
$bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $userid);
$bc->execute_plan();
$results = $bc->get_results();
$file = $results['backup_destination'];
$fp = get_file_packer('application/vnd.moodle.backup');
$filepath = $CFG->dataroot . '/temp/backup/test-restore-course-event';
$file->extract_to_pathname($fp, $filepath);
$bc->destroy();
unset($bc);
// Now we want to catch the restore course event.
$sink = $this->redirectEvents();
// Now restore the course to trigger the event.
$rc = new restore_controller('test-restore-course-event', $course->id, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $userid, backup::TARGET_NEW_COURSE);
$rc->execute_precheck();
$rc->execute_plan();
// Capture the event.
$events = $sink->get_events();
$sink->close();
// Validate the event.
$event = array_pop($events);
$this->assertInstanceOf('\\core\\event\\course_restored', $event);
$this->assertEquals('course', $event->objecttable);
$this->assertEquals($rc->get_courseid(), $event->objectid);
$this->assertEquals(context_course::instance($rc->get_courseid())->id, $event->contextid);
$this->assertEquals('course_restored', $event->get_legacy_eventname());
$legacydata = (object) array('courseid' => $rc->get_courseid(), 'userid' => $rc->get_userid(), 'type' => $rc->get_type(), 'target' => $rc->get_target(), 'mode' => $rc->get_mode(), 'operation' => $rc->get_operation(), 'samesite' => $rc->is_samesite());
$url = new moodle_url('/course/view.php', array('id' => $event->objectid));
$this->assertEquals($url, $event->get_url());
$this->assertEventLegacyData($legacydata, $event);
$this->assertEventContextNotUsed($event);
// Destroy the resource controller since we are done using it.
$rc->destroy();
unset($rc);
}
示例7: test_get_restore_content_dir
public function test_get_restore_content_dir()
{
global $CFG;
$this->resetAfterTest(true);
$this->setAdminUser();
$c1 = $this->getDataGenerator()->create_course();
$c2 = $this->getDataGenerator()->create_course((object) array('shortname' => 'Yay'));
// Creating backup file.
$bc = new backup_controller(backup::TYPE_1COURSE, $c1->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2);
$bc->execute_plan();
$result = $bc->get_results();
$this->assertTrue(isset($result['backup_destination']));
$c1backupfile = $result['backup_destination']->copy_content_to_temp();
$bc->destroy();
unset($bc);
// File logging is a mess, we can only try to rely on gc to close handles.
// Creating backup file.
$bc = new backup_controller(backup::TYPE_1COURSE, $c2->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2);
$bc->execute_plan();
$result = $bc->get_results();
$this->assertTrue(isset($result['backup_destination']));
$c2backupfile = $result['backup_destination']->copy_content_to_temp();
$bc->destroy();
unset($bc);
// File logging is a mess, we can only try to rely on gc to close handles.
$oldcfg = isset($CFG->keeptempdirectoriesonbackup) ? $CFG->keeptempdirectoriesonbackup : false;
$CFG->keeptempdirectoriesonbackup = true;
// Checking restore dir.
$dir = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
$bcinfo = backup_general_helper::get_backup_information($dir);
$this->assertEquals($bcinfo->original_course_id, $c1->id);
$this->assertEquals($bcinfo->original_course_fullname, $c1->fullname);
// Do it again, it should be the same directory.
$dir2 = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
$this->assertEquals($dir, $dir2);
// Get the second course.
$dir = tool_uploadcourse_helper::get_restore_content_dir($c2backupfile, null);
$bcinfo = backup_general_helper::get_backup_information($dir);
$this->assertEquals($bcinfo->original_course_id, $c2->id);
$this->assertEquals($bcinfo->original_course_fullname, $c2->fullname);
// Checking with a shortname.
$dir = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
$bcinfo = backup_general_helper::get_backup_information($dir);
$this->assertEquals($bcinfo->original_course_id, $c1->id);
$this->assertEquals($bcinfo->original_course_fullname, $c1->fullname);
// Do it again, it should be the same directory.
$dir2 = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
$this->assertEquals($dir, $dir2);
// Get the second course.
$dir = tool_uploadcourse_helper::get_restore_content_dir(null, $c2->shortname);
$bcinfo = backup_general_helper::get_backup_information($dir);
$this->assertEquals($bcinfo->original_course_id, $c2->id);
$this->assertEquals($bcinfo->original_course_fullname, $c2->fullname);
// Get a course that does not exist.
$errors = array();
$dir = tool_uploadcourse_helper::get_restore_content_dir(null, 'DoesNotExist', $errors);
$this->assertFalse($dir);
$this->assertArrayHasKey('coursetorestorefromdoesnotexist', $errors);
// Trying again without caching. $CFG->keeptempdirectoriesonbackup is required for caching.
$CFG->keeptempdirectoriesonbackup = false;
// Checking restore dir.
$dir = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
$dir2 = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
$this->assertNotEquals($dir, $dir2);
// Checking with a shortname.
$dir = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
$dir2 = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
$this->assertNotEquals($dir, $dir2);
// Get a course that does not exist.
$errors = array();
$dir = tool_uploadcourse_helper::get_restore_content_dir(null, 'DoesNotExist', $errors);
$this->assertFalse($dir);
$this->assertArrayHasKey('coursetorestorefromdoesnotexist', $errors);
$dir2 = tool_uploadcourse_helper::get_restore_content_dir(null, 'DoesNotExist', $errors);
$this->assertEquals($dir, $dir2);
$CFG->keeptempdirectoriesonbackup = $oldcfg;
}
示例8: duplicate_module
/**
* Api to duplicate a module.
*
* @param object $course course object.
* @param object $cm course module object to be duplicated.
* @since Moodle 2.8
*
* @throws Exception
* @throws coding_exception
* @throws moodle_exception
* @throws restore_controller_exception
*
* @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
*/
function duplicate_module($course, $cm)
{
global $CFG, $DB, $USER;
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php';
require_once $CFG->libdir . '/filelib.php';
$a = new stdClass();
$a->modtype = get_string('modulename', $cm->modname);
$a->modname = format_string($cm->name);
if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
throw new moodle_exception('duplicatenosupport', 'error', '', $a);
}
// Backup the activity.
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
$backupid = $bc->get_backupid();
$backupbasepath = $bc->get_plan()->get_basepath();
$bc->execute_plan();
$bc->destroy();
// Restore the backup immediately.
$rc = new restore_controller($backupid, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
$cmcontext = context_module::instance($cm->id);
if (!$rc->execute_precheck()) {
$precheckresults = $rc->get_precheck_results();
if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete($backupbasepath);
}
}
}
$rc->execute_plan();
// Now a bit hacky part follows - we try to get the cmid of the newly
// restored copy of the module.
$newcmid = null;
$tasks = $rc->get_plan()->get_tasks();
foreach ($tasks as $task) {
if (is_subclass_of($task, 'restore_activity_task')) {
if ($task->get_old_contextid() == $cmcontext->id) {
$newcmid = $task->get_moduleid();
break;
}
}
}
// If we know the cmid of the new course module, let us move it
// right below the original one. otherwise it will stay at the
// end of the section.
if ($newcmid) {
$info = get_fast_modinfo($course);
$newcm = $info->get_cm($newcmid);
$section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
moveto_module($newcm, $section, $cm);
moveto_module($cm, $section, $newcm);
// Update calendar events with the duplicated module.
$refresheventsfunction = $newcm->modname . '_refresh_events';
if (function_exists($refresheventsfunction)) {
call_user_func($refresheventsfunction, $newcm->course);
}
// Trigger course module created event. We can trigger the event only if we know the newcmid.
$event = \core\event\course_module_created::create_from_cm($newcm);
$event->trigger();
}
rebuild_course_cache($cm->course);
$rc->destroy();
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete($backupbasepath);
}
return isset($newcm) ? $newcm : null;
}
示例9: store_item
/**
* Store a course module in the recycle bin.
*
* @param \stdClass $cm Course module
* @throws \moodle_exception
*/
public function store_item($cm)
{
global $CFG, $DB;
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
// Get more information.
$modinfo = get_fast_modinfo($cm->course);
if (!isset($modinfo->cms[$cm->id])) {
return;
// Can't continue without the module information.
}
$cminfo = $modinfo->cms[$cm->id];
// Check backup/restore support.
if (!plugin_supports('mod', $cminfo->modname, FEATURE_BACKUP_MOODLE2)) {
return;
}
// Backup the activity.
$user = get_admin();
$controller = new \backup_controller(\backup::TYPE_1ACTIVITY, $cm->id, \backup::FORMAT_MOODLE, \backup::INTERACTIVE_NO, \backup::MODE_GENERAL, $user->id);
$controller->execute_plan();
// Grab the result.
$result = $controller->get_results();
if (!isset($result['backup_destination'])) {
throw new \moodle_exception('Failed to backup activity prior to deletion.');
}
// Have finished with the controller, let's destroy it, freeing mem and resources.
$controller->destroy();
// Grab the filename.
$file = $result['backup_destination'];
if (!$file->get_contenthash()) {
throw new \moodle_exception('Failed to backup activity prior to deletion (invalid file).');
}
// Record the activity, get an ID.
$activity = new \stdClass();
$activity->courseid = $cm->course;
$activity->section = $cm->section;
$activity->module = $cm->module;
$activity->name = $cminfo->name;
$activity->timecreated = time();
$binid = $DB->insert_record('tool_recyclebin_course', $activity);
// Create the location we want to copy this file to.
$filerecord = array('contextid' => \context_course::instance($this->_courseid)->id, 'component' => 'tool_recyclebin', 'filearea' => TOOL_RECYCLEBIN_COURSE_BIN_FILEAREA, 'itemid' => $binid, 'timemodified' => time());
// Move the file to our own special little place.
$fs = get_file_storage();
if (!$fs->create_file_from_storedfile($filerecord, $file)) {
// Failed, cleanup first.
$DB->delete_records('tool_recyclebin_course', array('id' => $binid));
throw new \moodle_exception("Failed to copy backup file to recyclebin.");
}
// Delete the old file.
$file->delete();
// Fire event.
$event = \tool_recyclebin\event\course_bin_item_created::create(array('objectid' => $binid, 'context' => \context_course::instance($cm->course)));
$event->trigger();
}
示例10: foreach
function backup_template($courseid_from,$settings,$config,$admin) {
$bc = new backup_controller(backup::TYPE_1COURSE, $courseid_from, backup::FORMAT_MOODLE,
backup::INTERACTIVE_YES, backup::MODE_IMPORT,$admin->id);
$backupid = $bc->get_backupid();
$bc->get_plan()->get_setting('users')->set_status(backup_setting::LOCKED_BY_CONFIG);
foreach ($settings as $setting => $configsetting) {
if ($bc->get_plan()->setting_exists($setting)) {
$bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
}
}
$bc->finish_ui();
$bc->execute_plan();
$bc->destroy();
unset($bc);
return $backupid;
}
示例11: test_mod_jclic_duplicate
public function test_mod_jclic_duplicate()
{
global $USER, $DB, $CFG;
require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php';
$this->resetAfterTest(true);
$this->setUser(2);
// Admin user.
// Create a course with some availability data set.
$generator = $this->getDataGenerator();
$course = $generator->create_course(array('format' => 'topics', 'numsections' => 3, 'enablecompletion' => COMPLETION_ENABLED), array('createsections' => true));
$jclic = $generator->create_module('jclic', array('course' => $course->id));
$cmid = $jclic->cmid;
// Do backup.
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $cmid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
$backupid = $bc->get_backupid();
$bc->execute_plan();
$bc->destroy();
// Do restore.
$rc = new restore_controller($backupid, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
$this->assertTrue($rc->execute_precheck());
$rc->execute_plan();
// Find cmid.
$tasks = $rc->get_plan()->get_tasks();
$cmcontext = context_module::instance($cmid);
$newcmid = 0;
foreach ($tasks as $task) {
if (is_subclass_of($task, 'restore_activity_task')) {
if ($task->get_old_contextid() == $cmcontext->id) {
$newcmid = $task->get_moduleid();
break;
}
}
}
$rc->destroy();
if (!$newcmid) {
throw new coding_exception('Unexpected: failure to find restored cmid');
}
// Check settings in new course.
$newjclic = new jclic(context_module::instance($newcmid), false, false);
$newjclicmodule = $newjclic->get_instance();
$this->assertNotEmpty($newjclic);
$jclic = new jclic(context_module::instance($jclic->cmid), false, false);
$jclicmodule = $jclic->get_instance();
$fields = (array) $jclicmodule;
unset($fields['id']);
unset($fields['course']);
foreach ($fields as $key => $unused) {
$this->assertEquals($newjclicmodule->{$key}, $jclicmodule->{$key}, "Failed on field {$key}");
}
// Avoid errors...
ini_set('max_execution_time', 0);
}
示例12: test_restore_controller_is_executing
/**
* Tests the restore_controller.
*/
public function test_restore_controller_is_executing()
{
global $CFG;
// Make a backup.
check_dir_exists($CFG->tempdir . '/backup');
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->moduleid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $this->userid);
$backupid = $bc->get_backupid();
$bc->execute_plan();
$bc->destroy();
// The progress class will get called during restore, so we can use that
// to check the executing flag is true.
$progress = new core_backup_progress_restore_is_executing();
// Set up restore.
$rc = new restore_controller($backupid, $this->courseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $this->userid, backup::TARGET_EXISTING_ADDING);
$this->assertTrue($rc->execute_precheck());
// Check restore is NOT executing.
$this->assertFalse(restore_controller::is_executing());
// Execute restore.
$rc->set_progress($progress);
$rc->execute_plan();
// Check restore is NOT executing afterward either.
$this->assertFalse(restore_controller::is_executing());
$rc->destroy();
// During restore, check that executing was true.
$this->assertTrue(count($progress->executing) > 0);
$alltrue = true;
foreach ($progress->executing as $executing) {
if (!$executing) {
$alltrue = false;
break;
}
}
$this->assertTrue($alltrue);
}
示例13: get_restore_content_dir
/**
* Get the restore content tempdir.
*
* The tempdir is the sub directory in which the backup has been extracted.
*
* This caches the result for better performance, but $CFG->keeptempdirectoriesonbackup
* needs to be enabled, otherwise the cache is ignored.
*
* @param string $backupfile path to a backup file.
* @param string $shortname shortname of a course.
* @param array $errors will be populated with errors found.
* @return string|false false when the backup couldn't retrieved.
*/
public static function get_restore_content_dir($backupfile = null, $shortname = null, &$errors = array())
{
global $CFG, $DB, $USER;
$cachekey = null;
if (!empty($backupfile)) {
$backupfile = realpath($backupfile);
if (empty($backupfile) || !is_readable($backupfile)) {
$errors['cannotreadbackupfile'] = new lang_string('cannotreadbackupfile', 'tool_uploadcourse');
return false;
}
$cachekey = 'backup_path:' . $backupfile;
} else {
if (!empty($shortname) || is_numeric($shortname)) {
$cachekey = 'backup_sn:' . $shortname;
}
}
if (empty($cachekey)) {
return false;
}
// If $CFG->keeptempdirectoriesonbackup is not set to true, any restore happening would
// automatically delete the backup directory... causing the cache to return an unexisting directory.
$usecache = !empty($CFG->keeptempdirectoriesonbackup);
if ($usecache) {
$cache = cache::make('tool_uploadcourse', 'helper');
}
// If we don't use the cache, or if we do and not set, or the directory doesn't exist any more.
if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir("{$CFG->tempdir}/backup/{$backupid}"))) {
// Use null instead of false because it would consider that the cache key has not been set.
$backupid = null;
if (!empty($backupfile)) {
// Extracting the backup file.
$packer = get_file_packer('application/vnd.moodle.backup');
$backupid = restore_controller::get_tempdir_name(SITEID, $USER->id);
$path = "{$CFG->tempdir}/backup/{$backupid}/";
$result = $packer->extract_to_pathname($backupfile, $path);
if (!$result) {
$errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse');
}
} else {
if (!empty($shortname) || is_numeric($shortname)) {
// Creating restore from an existing course.
$courseid = $DB->get_field('course', 'id', array('shortname' => $shortname), IGNORE_MISSING);
if (!empty($courseid)) {
$bc = new backup_controller(backup::TYPE_1COURSE, $courseid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
$bc->execute_plan();
$backupid = $bc->get_backupid();
$bc->destroy();
} else {
$errors['coursetorestorefromdoesnotexist'] = new lang_string('coursetorestorefromdoesnotexist', 'tool_uploadcourse');
}
}
}
if ($usecache) {
$cache->set($cachekey, $backupid);
}
}
if ($backupid === null) {
$backupid = false;
}
return $backupid;
}
示例14: execute
public function execute()
{
global $USER;
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $this->cm_id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id);
$bc->execute_plan();
$results = $bc->get_results();
$file = $results["backup_destination"];
$this->contextid = $file->get_contextid();
$this->fileid = $file->get_id();
$bc->destroy();
// $this->debug->trace();
// $this->prepareDir();
// $this->createXml();
// $temp_dir = $this->getTempDir().'/';
// moodle.xml 内を検索し、本体未対応や取りこぼしたリンクを
// 独自形式に書き換え、バックアップ一時ディレクトリへコピー
// $xml = file_get_contents($temp_dir.'moodle.xml');
// $xml = $this->encodeLinksAndBackupTargets($xml);
// file_put_contents($temp_dir.'moodle.xml', $xml);
// ユーザ指定のデータおよびファイルをZIPに追加
// foreach ($this->zip_userdata as $filename => $data) {
// file_put_contents($temp_dir.$filename, $data);
// }
// foreach ($this->zip_userfile as $filename => $path) {
// copy($path, $temp_dir.$filename);
// }
// $this->createZip();
// $this->cleanupDir();
// if (defined('BACKUP_SILENTLY')) {
// if (empty($this->message_output)) {
// if (is_callable('header_remove', FALSE, $header_remove)) {
// 可能であれば出力済みのHTTPヘッダを除去し、
// 直接リダイレクトできる状態にする (PHP 5.3.x)
// $header_remove();
// }
// (進捗以外の)メッセージが出力されていなければ、成功フラグを立てる
// $this->execute_succeeded = TRUE;
// }
// } else {
// 非サイレントモードでは成功かどうかの判定が困難なのでHTTPヘッダで簡易判定する
// if (!headers_sent()) {
// $this->execute_succeeded = TRUE;
// }
// }
$this->execute_succeeded = TRUE;
}
示例15: create_preset_from_backup
/**
*
*/
public function create_preset_from_backup($userdata)
{
global $CFG, $USER, $SESSION;
require_once "{$CFG->dirroot}/backup/util/includes/backup_includes.php";
$df = mod_dataform_dataform::instance($this->_dataformid);
$users = 0;
$anon = 0;
switch ($userdata) {
case 'dataanon':
$anon = 1;
case 'data':
$users = 1;
}
// Store preset settings in $SESSION.
$SESSION->{"dataform_{$df->cm->id}_preset"} = "{$users} {$anon}";
$bc = new backup_controller(backup::TYPE_1ACTIVITY, $df->cm->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id);
// Clear preset settings from $SESSION.
unset($SESSION->{"dataform_{$df->cm->id}_preset"});
// Set users and anon in plan.
$bc->get_plan()->get_setting('users')->set_value($users);
$bc->get_plan()->get_setting('anonymize')->set_value($anon);
$bc->set_status(backup::STATUS_AWAITING);
$bc->execute_plan();
$bc->destroy();
$fs = get_file_storage();
if ($users and !$anon) {
$contextid = $df->context->id;
$files = $fs->get_area_files($contextid, 'backup', 'activity', 0, 'timemodified', false);
} else {
$usercontext = context_user::instance($USER->id);
$contextid = $usercontext->id;
$files = $fs->get_area_files($contextid, 'user', 'backup', 0, 'timemodified', false);
}
if (!empty($files)) {
$coursecontext = context_course::instance($df->course->id);
foreach ($files as $file) {
if ($file->get_contextid() != $contextid) {
continue;
}
$preset = new object();
$preset->contextid = $coursecontext->id;
$preset->component = 'mod_dataform';
$preset->filearea = self::PRESET_COURSEAREA;
$preset->filepath = '/';
$preset->filename = clean_filename(str_replace(' ', '_', $df->name) . '-dataform-preset-' . gmdate("Ymd_Hi") . '-' . str_replace(' ', '-', get_string("preset{$userdata}", 'dataform')) . '.mbz');
$fs->create_file_from_storedfile($preset, $file);
$file->delete();
return true;
}
}
return false;
}