/** * Roll over an existing Moodle course into a new one using a customized backup * and restore routine * * @param int $courseid Id of the course we are copying * @param int $categoryid * @return int|boolean Id of the newly created course */ function course_rollover($courseid, $categoryid = null) { global $DB; if ($course = $DB->get_record('course', array('id' => $courseid))) { //figure out the category if ($categoryid === null) { $categoryid = $course->category; } //make sure the category is valid if (!$DB->record_exists('course_categories', array('id' => $categoryid))) { //invalid category return false; } //perform backup without including user info $controller = new rollover_backup_controller($courseid); $controller->get_plan()->get_setting('users')->set_value(false); $controller->execute_plan(); //get directory name for use in restore $backupid = $controller->get_backupid(); //start a database transaction to make sure restore is atomic, etc $transaction = $DB->start_delegated_transaction(); //create the new course $result = restore_dbops::create_new_course($course->fullname, $course->shortname, $categoryid); //restore the content into it within the current transaction without including user information $controller = new rollover_restore_controller($backupid, $result); $controller->get_plan()->get_setting('users')->set_value(false); $controller->execute_precheck(); $controller->execute_plan(); //make sure the sort order is defined as expected fix_course_sortorder(); try { //try to finalize $transaction->allow_commit(); } catch (dml_transaction_exception $e) { //failure $result = false; } return $result; } else { //invalid course specified return false; } }
public function test_mod_jclic_backup_restore() { 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)); // Turn off file logging, otherwise it can't delete the file (Windows). $CFG->backup_file_logger_level = backup::LOG_NONE; // Do backup with default settings. MODE_IMPORT means it will just // create the directory and not zip it. $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); $backupid = $bc->get_backupid(); $bc->execute_plan(); $bc->destroy(); // Do restore to new course with default settings. $newcourseid = restore_dbops::create_new_course($course->fullname, $course->shortname . '_2', $course->category); $rc = new restore_controller($backupid, $newcourseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, backup::TARGET_NEW_COURSE); $this->assertTrue($rc->execute_precheck()); $rc->execute_plan(); $rc->destroy(); // Check settings in new course. $modinfo = get_fast_modinfo($newcourseid); $jclics = array_values($modinfo->get_instances_of('jclic')); $newjclic = new jclic(context_module::instance($jclics[0]->id), 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); }
/** * Duplicate a course * * @param int $courseid * @param string $fullname Duplicated course fullname * @param string $shortname Duplicated course shortname * @param int $categoryid Duplicated course parent category id * @param int $visible Duplicated course availability * @param array $options List of backup options * @return array New course info * @since Moodle 2.3 */ public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) { global $CFG, $USER, $DB; require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php'); require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php'); // Parameter validation. $params = self::validate_parameters( self::duplicate_course_parameters(), array( 'courseid' => $courseid, 'fullname' => $fullname, 'shortname' => $shortname, 'categoryid' => $categoryid, 'visible' => $visible, 'options' => $options ) ); // Context validation. if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) { throw new moodle_exception('invalidcourseid', 'error'); } // Category where duplicated course is going to be created. $categorycontext = context_coursecat::instance($params['categoryid']); self::validate_context($categorycontext); // Course to be duplicated. $coursecontext = context_course::instance($course->id); self::validate_context($coursecontext); $backupdefaults = array( 'activities' => 1, 'blocks' => 1, 'filters' => 1, 'users' => 0, 'role_assignments' => 0, 'comments' => 0, 'userscompletion' => 0, 'logs' => 0, 'grade_histories' => 0 ); $backupsettings = array(); // Check for backup and restore options. if (!empty($params['options'])) { foreach ($params['options'] as $option) { // Strict check for a correct value (allways 1 or 0, true or false). $value = clean_param($option['value'], PARAM_INT); if ($value !== 0 and $value !== 1) { throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); } if (!isset($backupdefaults[$option['name']])) { throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); } $backupsettings[$option['name']] = $value; } } // Capability checking. // The backup controller check for this currently, this may be redundant. require_capability('moodle/course:create', $categorycontext); require_capability('moodle/restore:restorecourse', $categorycontext); require_capability('moodle/backup:backupcourse', $coursecontext); if (!empty($backupsettings['users'])) { require_capability('moodle/backup:userinfo', $coursecontext); require_capability('moodle/restore:userinfo', $categorycontext); } // Check if the shortname is used. if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) { foreach ($foundcourses as $foundcourse) { $foundcoursenames[] = $foundcourse->fullname; } $foundcoursenamestring = implode(',', $foundcoursenames); throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring); } // Backup the course. $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id); foreach ($backupsettings as $name => $value) { $bc->get_plan()->get_setting($name)->set_value($value); } $backupid = $bc->get_backupid(); $backupbasepath = $bc->get_plan()->get_basepath(); $bc->execute_plan(); $results = $bc->get_results(); $file = $results['backup_destination']; $bc->destroy(); // Restore the backup immediately. // Check if we need to unzip the file because the backup temp dir does not contains backup files. if (!file_exists($backupbasepath . "/moodle_backup.xml")) { $file->extract_to_pathname(get_file_packer(), $backupbasepath); } // Create new course. $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']); $rc = new restore_controller($backupid, $newcourseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE); foreach ($backupsettings as $name => $value) { $setting = $rc->get_plan()->get_setting($name); if ($setting->get_status() == backup_setting::NOT_LOCKED) { $setting->set_value($value); } } if (!$rc->execute_precheck()) { $precheckresults = $rc->get_precheck_results(); if (is_array($precheckresults) && !empty($precheckresults['errors'])) { if (empty($CFG->keeptempdirectoriesonbackup)) { fulldelete($backupbasepath); } $errorinfo = ''; foreach ($precheckresults['errors'] as $error) { $errorinfo .= $error; } if (array_key_exists('warnings', $precheckresults)) { foreach ($precheckresults['warnings'] as $warning) { $errorinfo .= $warning; } } throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo); } } $rc->execute_plan(); $rc->destroy(); $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST); $course->fullname = $params['fullname']; $course->shortname = $params['shortname']; $course->visible = $params['visible']; // Set shortname and fullname back. $DB->update_record('course', $course); if (empty($CFG->keeptempdirectoriesonbackup)) { fulldelete($backupbasepath); } // Delete the course backup file created by this WebService. Originally located in the course backups area. $file->delete(); return array('id' => $course->id, 'shortname' => $course->shortname); }
/** * Processes the destination stage. * @return bool * @throws coding_exception * @throws restore_ui_exception */ public function process() { global $CFG, $DB; if (!file_exists("{$CFG->tempdir}/backup/" . $this->filepath) || !is_dir("{$CFG->tempdir}/backup/" . $this->filepath)) { throw new restore_ui_exception('invalidrestorepath'); } if (optional_param('searchcourses', false, PARAM_BOOL)) { return false; } $this->target = optional_param('target', backup::TARGET_NEW_COURSE, PARAM_INT); $targetid = optional_param('targetid', null, PARAM_INT); if (!is_null($this->target) && !is_null($targetid) && confirm_sesskey()) { if ($this->target == backup::TARGET_NEW_COURSE) { list($fullname, $shortname) = restore_dbops::calculate_course_names(0, get_string('restoringcourse', 'backup'), get_string('restoringcourseshortname', 'backup')); $this->courseid = restore_dbops::create_new_course($fullname, $shortname, $targetid); } else { $this->courseid = $targetid; } return $DB->record_exists('course', array('id' => $this->courseid)); } return false; }
<?php define('CLI_SCRIPT', true); chdir('/var/www/ae.ket.org'); require_once 'config.php'; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; // Transaction $transaction = $DB->start_delegated_transaction(); // Create new course $folder = '9706ff11ee909cc426e66fff74926faa'; // as found in: $CFG->dataroot . '/temp/backup/' $categoryid = 1; // e.g. 1 == Miscellaneous $user_doing_the_restore = 4; // e.g. 2 == admin $courseid = restore_dbops::create_new_course('Z', 'Z', $categoryid); // Restore backup into course $controller = new restore_controller($folder, $courseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $user_doing_the_restore, backup::TARGET_NEW_COURSE); $controller->execute_precheck(); $controller->execute_plan(); // Commit $transaction->allow_commit();
/** * Backs a course up and restores it. * * @param stdClass $course Course object to backup * @param int $newdate If non-zero, specifies custom date for new course * @return int ID of newly restored course */ protected function backup_and_restore($course, $newdate = 0) { global $USER, $CFG; // Turn off file logging, otherwise it can't delete the file (Windows). $CFG->backup_file_logger_level = backup::LOG_NONE; // Do backup with default settings. MODE_IMPORT means it will just // create the directory and not zip it. $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); $backupid = $bc->get_backupid(); $bc->execute_plan(); $bc->destroy(); // Do restore to new course with default settings. $newcourseid = restore_dbops::create_new_course($course->fullname, $course->shortname . '_2', $course->category); $rc = new restore_controller($backupid, $newcourseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, backup::TARGET_NEW_COURSE); if ($newdate) { $rc->get_plan()->get_setting('course_startdate')->set_value($newdate); } $this->assertTrue($rc->execute_precheck()); $rc->execute_plan(); $rc->destroy(); return $newcourseid; }
/** * Restore a course. * * @param int $backupid The backup ID. * @param int $courseid The course ID to restore in, or 0. * @param int $userid The ID of the user performing the restore. * @return stdClass The updated course object. */ protected function restore_course($backupid, $courseid, $userid) { global $DB; $target = backup::TARGET_CURRENT_ADDING; if (!$courseid) { $target = backup::TARGET_NEW_COURSE; $categoryid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}"); $courseid = restore_dbops::create_new_course('Tmp', 'tmp', $categoryid); } $rc = new restore_controller($backupid, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $userid, $target); $target == backup::TARGET_NEW_COURSE ?: $rc->get_plan()->get_setting('overwrite_conf')->set_value(true); $rc->execute_precheck(); $rc->execute_plan(); $course = $DB->get_record('course', array('id' => $rc->get_courseid())); $rc->destroy(); unset($rc); return $course; }
<?php define('CLI_SCRIPT', 1); require_once '../../../config.php'; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; $folder = '06199f4ab82d075d19672f3bb42a285a'; // home=06199f4ab82d075d19672f3bb42a285a :: work=b5dbb55e2e834b3132e915395ed6917f $userid = 2; $fullname = 'JClic restore'; $shortname = 'jclic_restore'; $categoryid = 1; $courseid = 100; // Transaction $transaction = $DB->start_delegated_transaction(); // Create new course $courseid = restore_dbops::create_new_course($fullname, $shortname, $categoryid); // Restore backup into course $controller = new restore_controller($folder, $courseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $userid, backup::TARGET_NEW_COURSE); $controller->execute_precheck(); $controller->execute_plan(); // Commit $transaction->allow_commit();
/** * Execute scheduled task * * @return boolean */ public function execute() { global $CFG, $DB; require_once $CFG->libdir . '/moodlelib.php'; require_once $CFG->libdir . '/filestorage/zip_packer.php'; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; // Get plugin config $local_sandbox_config = get_config('local_sandbox'); // Counter for restored courses $count = 0; // Do only when sandbox directory is configured if ($local_sandbox_config->coursebackupsdirectory != '') { // Do only when sandbox directory exists if (is_dir($local_sandbox_config->coursebackupsdirectory)) { // Open directory and get all .mbz files if ($handle = @opendir($local_sandbox_config->coursebackupsdirectory)) { while (false !== ($file = readdir($handle))) { if (substr($file, -4) == '.mbz' && $file != '.' && $file != '..') { // Get course shortname from filename $shortname = substr($file, 0, -4); echo "\n\t" . get_string('nowprocessing', 'local_sandbox', $shortname) . "\n"; // Get existing course information if ($oldcourse = $DB->get_record('course', array('shortname' => $shortname))) { $oldcourseid = $oldcourse->id; $categoryid = $oldcourse->category; $fullname = $oldcourse->fullname; } else { // Output error message for cron listing echo "\n\t" . get_string('skippingnocourse', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingnocourse', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Delete existing course if (!delete_course($oldcourseid, false)) { // Output error message for cron listing echo "\n\t" . get_string('skippingdeletionfailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingdeletionfailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Unzip course backup file to temp directory $filepacker = get_file_packer('application/vnd.moodle.backup'); check_dir_exists($CFG->dataroot . '/temp/backup'); if (!$filepacker->extract_to_pathname($local_sandbox_config->coursebackupsdirectory . '/' . $file, $CFG->dataroot . '/temp/backup/' . $shortname)) { // Output error message for cron listing echo "\n\t" . get_string('skippingunzipfailed', 'local_sandbox', $file) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingunzipfailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Create new course if (!($newcourseid = \restore_dbops::create_new_course($shortname, $shortname, $categoryid))) { // Output error message for cron listing echo "\n\t" . get_string('skippingcreatefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingcreatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Get admin user for restore $admin = get_admin(); $restoreuser = $admin->id; // Restore course backup file into new course if ($controller = new \restore_controller($shortname, $newcourseid, \backup::INTERACTIVE_NO, \backup::MODE_SAMESITE, $restoreuser, \backup::TARGET_NEW_COURSE)) { $controller->get_logger()->set_next(new \output_indented_logger(\backup::LOG_INFO, false, true)); $controller->execute_precheck(); $controller->execute_plan(); } else { // Output error message for cron listing echo "\n\t" . get_string('skippingrestorefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingrestorefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Adjust course start date if ($local_sandbox_config->adjustcoursestartdate == true) { if (!$DB->update_record('course', (object) array('id' => $newcourseid, 'startdate' => time()))) { // Output error message for cron listing echo "\n\t" . get_string('skippingadjuststartdatefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingadjuststartdatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } } // Set shortname and fullname back if ($DB->update_record('course', (object) array('id' => $newcourseid, 'shortname' => $shortname, 'fullname' => $fullname))) { // Output info message for cron listing echo "\n\t" . get_string('successrestored', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('successrestored', 'local_sandbox', $shortname), SANDBOX_LEVEL_NOTICE); // Log the event $logevent = \local_sandbox\event\course_restored::create(array('objectid' => $newcourseid, 'context' => \context_course::instance($newcourseid))); $logevent->trigger(); // Fire course_updated event $course = $DB->get_record('course', array('id' => $newcourseid)); $ccevent = \core\event\course_created::create(array('objectid' => $course->id, 'context' => \context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname))); $ccevent->trigger(); // Count successfully restored course $count++; } else { // Output error message for cron listing echo "\n\t" . get_string('skippingdbupdatedfailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingdbupdatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } } } closedir($handle); // Output info message for cron listing echo "\n\t" . get_string('noticerestorecount', 'local_sandbox', $count) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('noticerestorecount', 'local_sandbox', $count), SANDBOX_LEVEL_NOTICE); return true; } else { // Output error message for cron listing echo "\n\t" . get_string('errordirectorynotreadable', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('errordirectorynotreadable', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory), SANDBOX_LEVEL_ERROR); return false; } } else { // Output error message for cron listing echo "\n\t" . get_string('errordirectorynotexist', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('errordirectorynotexist', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory), SANDBOX_LEVEL_ERROR); return false; } } else { // Output info message for cron listing echo "\n\t" . get_string('noticedirectorynotconfigured', 'local_sandbox') . "\n"; // Inform admin local_sandbox_inform_admin(get_string('noticedirectorynotconfigured', 'local_sandbox'), SANDBOX_LEVEL_NOTICE); return true; } }
/** * https://github.com/tmuras/moosh/blob/master/Moosh/Command/Moodle23/Course/CourseRestore.php * @param $bkpfile * @param $categoryId */ public static function execute($bkpfile, $categoryId) { global $CFG, $DB, $USER; require_once $CFG->dirroot . "/backup/util/includes/backup_includes.php"; require_once $CFG->dirroot . "/backup/util/includes/restore_includes.php"; if (empty($CFG->tempdir)) { $CFG->tempdir = $CFG->dataroot . DIRECTORY_SEPARATOR . 'temp'; } //unzip into $CFG->tempdir / "backup" / "auto_restore_" . $split[1]; $backupdir = "moosh_restore_" . uniqid(); $path = $CFG->tempdir . DIRECTORY_SEPARATOR . "backup" . DIRECTORY_SEPARATOR . $backupdir; /** @var $fp file_packer */ $fp = get_file_packer('application/vnd.moodle.backup'); $fp->extract_to_pathname($bkpfile, $path); //extract original full & short names $xmlfile = $path . DIRECTORY_SEPARATOR . "course" . DIRECTORY_SEPARATOR . "course.xml"; // Different XML file in Moodle 1.9 backup if (!file_exists($xmlfile)) { $xmlfile = $path . DIRECTORY_SEPARATOR . "moodle.xml"; } $xml = simplexml_load_file($xmlfile); $fullname = $xml->xpath('/course/fullname'); if (!$fullname) { $fullname = $xml->xpath('/MOODLE_BACKUP/COURSE/HEADER/FULLNAME'); } $shortname = $xml->xpath('/course/shortname'); if (!$shortname) { $shortname = $xml->xpath('/MOODLE_BACKUP/COURSE/HEADER/SHORTNAME'); } $fullname = (string) $fullname[0]; $shortname = (string) $shortname[0]; if (!$shortname) { cli_error('No shortname in the backup file.'); } if (!$fullname) { $fullname = $shortname; } $courseid = \restore_dbops::create_new_course($fullname, $shortname, $categoryId); $rc = new \restore_controller($backupdir, $courseid, \backup::INTERACTIVE_NO, \backup::MODE_GENERAL, 2, \backup::TARGET_NEW_COURSE); echo "Restoring (new course id,shortname,destination category): {$courseid}, {$shortname}," . $categoryId . "\n"; if ($rc->get_status() == \backup::STATUS_REQUIRE_CONV) { $rc->convert(); } $plan = $rc->get_plan(); //TODO: valider les options réquises. $restopt = array('activities' => 1, 'blocks' => 1, 'filters' => 1, 'users' => 0, 'role_assignments' => 1, 'comments' => 0, 'logs' => 0, 'grade_histories' => 0); foreach ($restopt as $name => $value) { $setting = $plan->get_setting($name); if ($setting->get_status() == \backup_setting::NOT_LOCKED) { $setting->set_value($value); } } $rc->execute_precheck(); $rc->execute_plan(); $rc->destroy(); echo "New course ID for '{$shortname}': {$courseid} in {$categoryId}\n"; // Ajouter le idnumber dans le nouveau cours. $c = $DB->get_record('course', array('id' => $courseid)); $c->idnumber = self::get_idnumber($shortname); $DB->update_record('course', $c); }
<?php define('CLI_SCRIPT', true); require_once __DIR__ . '/config.php'; # Restore a course require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; require_once $CFG->dirroot . '/grade/querylib.php'; require_once $CFG->libdir . '/completionlib.php'; if (isset($argv[1])) { $backupfile = $argv[1]; } else { $backupfile = '/opt/AllFeaturesBackup.mbz'; } $backupid = 'abc'; $backuppath = $CFG->tempdir . '/backup/' . $backupid; check_dir_exists($backuppath); get_file_packer('application/vnd.moodle.backup')->extract_to_pathname($backupfile, $backuppath); $course = $DB->get_record_select('course', 'shortname = ?', array("Features Demo")); // If course is not present then create it. if (!$course) { $newcourseid = restore_dbops::create_new_course('Moodle Features Demo', 'Features Demo', 1); $rc = new restore_controller($backupid, $newcourseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, 2, backup::TARGET_NEW_COURSE); if ($rc->execute_precheck()) { $rc->execute_plan(); $rc->destroy(); } }
function create_cwsp_course($fullname, $shortname, $categoryid = 2) { global $CFG, $USER, $DB; //need this // $CFG->keeptempdirectoriesonbackup = true; // in config.php to keep the directory available //$backupdir = 'fde3a9c54543ef236d60ba0fa4aba028'; //CWSP $backupdir = 'ef521c9d85221eac4b596380655f0918'; //departmental $backupdir = 'e993969ee7787cdc1c5cd4f309c1902d'; //bi-weekly $transaction = $DB->start_delegated_transaction(); echo $fullname . ' ' . $shortname . "\n"; // Create new course $courseid = restore_dbops::create_new_course($fullname, $shortname, $categoryid); // Restore backup into course $controller = new restore_controller($backupdir, $courseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, 2, backup::TARGET_NEW_COURSE); $controller->execute_precheck(); $controller->execute_plan(); // Commit $transaction->allow_commit(); return $courseid; }
require_capability('moodle/restore:restorecourse', $context); if ($stage & restore_ui::STAGE_CONFIRM + restore_ui::STAGE_DESTINATION) { $restore = restore_ui::engage_independent_stage($stage, $contextid); } else { if ($_POST['searchcourses'] || !$_POST['targetid']) { // $restore = restore_ui::engage_independent_stage($stage, $contextid); $restore = restore_ui::engage_independent_stage(restore_ui::STAGE_DESTINATION, $contextid); $restore->process(); } else { $target = required_param('target', PARAM_INT); $filepath = $_SESSION['filepath']; if ($target == backup::TARGET_NEW_COURSE) { $transaction = $DB->start_delegated_transaction(); $targetid = required_param('targetid', PARAM_INT); list($fullname, $shortname) = restore_dbops::calculate_course_names($course->id, get_string('restoringcourse', 'backup'), get_string('restoringcourseshortname', 'backup')); $courseid = restore_dbops::create_new_course($fullname, $shortname, $targetid); $controller = new restore_controller($filepath, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, $target); $controller->execute_precheck(); $controller->execute_plan(); $transaction->allow_commit(); } elseif ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_CURRENT_ADDING) { $transaction = $DB->start_delegated_transaction(); $courseid = $course->id; if ($target == backup::TARGET_CURRENT_DELETING) { $options = array(); $options['keep_roles_and_enrolments'] = new restore_course_generic_setting('keep_roles_and_enrolments', base_setting::IS_BOOLEAN, true); $options['keep_groups_and_groupings'] = new restore_course_generic_setting('keep_groups_and_groupings', base_setting::IS_BOOLEAN, true); restore_dbops::delete_course_content($courseid, $options); } $controller = new restore_controller($filepath, $courseid, backup::INTERACTIVE_NO, backup::MODE_GENERAL, $USER->id, $target); $controller->execute_precheck();
///*** it's not working well /// try to chage to behat define('CLI_SCRIPT', true); require_once '../../../config.php'; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; // Transaction. $transaction = $DB->start_delegated_transaction(); // Create new course. $srcfolder = $CFG->dirroot . '/mod/simplecertificate/tests/other/backup-test-v2.1-with-issued-certs'; $folder = $CFG->dataroot . '/temp/backup/7af1bcb7cf5c268130c23e5947efbcc3'; $categoryid = 1; // e.g. 1 == Miscellaneous $userdoingrestore = 2; // e.g. 2 == admin $courseid = restore_dbops::create_new_course('restore teste', 'rt', $categoryid); // Restore backup into course. if (!is_file($folder . '/' . basename($srcfolder))) { xcopy($srcfolder, $folder); } $controller = new restore_controller($folder, $courseid, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $userdoingrestore, backup::TARGET_NEW_COURSE); $controller->execute_precheck(); $controller->execute_plan(); // Commit. $transaction->allow_commit(); // rmdir($folder); function xcopy($src, $dst) { $dir = opendir($src); @mkdir($dst); while (false !== ($file = readdir($dir))) {