From bb41dadd29e24ab3546f7e7b116628ad9fb59ce2 Mon Sep 17 00:00:00 2001 From: Eloy Lafuente Date: Fri, 6 Aug 2010 16:09:28 +0000 Subject: [PATCH] MDL-22164 backup - clean important parts of old code. Leaving rest for reference --- backup/restore_check.html | 45 - backup/restore_form.html | 230 ---- backup/restorelib.php | 2315 +------------------------------------ 3 files changed, 26 insertions(+), 2564 deletions(-) diff --git a/backup/restore_check.html b/backup/restore_check.html index 7ffff213f5d..1711025f520 100644 --- a/backup/restore_check.html +++ b/backup/restore_check.html @@ -20,31 +20,6 @@ //Detect if we are coming from the restore form $fromform = optional_param ('fromform', 0, PARAM_INT); - if ($form1 = data_submitted()) { - $currentcourseshortname = $course_header->course_shortname; //"store_ShortName"; - $course_header->course_shortname = !empty($form1->shortname) ? $form1->shortname : ''; //"update_ShortName"; - $course_header->course_fullname = !empty($form1->fullname) ? $form1->fullname : ''; //"update_FullName"; - /// Roll dates only if the backup course has a start date - /// (some formats like main page, social..., haven't it and rolling dates - /// from 0 produces crazy dates. MDL-10125 and we have passed some custom startyear/month/day. MDL-12922 - if ($course_header->course_startdate && !empty($form1->startyear)) { - $form1->startdate = make_timestamp($form1->startyear, $form1->startmonth, $form1->startday); - $currentcoursestartdate = $course_header->course_startdate; - $coursestartdatedateoffset = $form1->startdate - $currentcoursestartdate; - $restore->course_startdateoffset = $coursestartdatedateoffset; //change to restore - // Only apply rolling of dates if differences are bigger than one day - // that should solve current problems with daylight changes between - // backup and restore - if (abs($restore->course_startdateoffset) < 24 * 60 * 60) { - $coursestartdatedateoffset = 0; - $restore->course_startdateoffset = 0; - } - } else { // don't roll if the course hasn't start date - $coursestartdatedateoffset = 0; - $restore->course_startdateoffset = 0; - } - } - ///Enforce SESSION->course_header rewrite (PHP 4.x needed because assigns are by value) MDL-8298 $SESSION->course_header = $course_header; @@ -277,26 +252,6 @@ } } - // If we have selected to roll dates on restore and the user is missing - // such capability (moodle/restore:rolldates) in the target course/category, - // disable roll of dates and warn - if ($restore->course_startdateoffset != 0) { - $canrolldates = false; // init to false - - // if we know the target course, check the capability on it - if (!empty($restore->course_id)) { - $canrolldates = has_capability('moodle/restore:rolldates', get_context_instance(CONTEXT_COURSE, $restore->course_id)); - // if we know the target category, check capability on it - } else if (!empty($restore->restore_restorecatto)) { - $canrolldates = has_capability('moodle/restore:rolldates', get_context_instance(CONTEXT_COURSECAT, $restore->restore_restorecatto)); - } - - if (!$canrolldates) { - $messages[] = get_string ("noteusercannotrolldatesoncontext"); - $restore->course_startdateoffset = 0; - } - } - //Check if we've selected any mod's user info and restore->users //is set to none. Change it to course and inform. if ($restore->users == 2) { diff --git a/backup/restore_form.html b/backup/restore_form.html index 9d8a5b76a69..0e29385e97b 100644 --- a/backup/restore_form.html +++ b/backup/restore_form.html @@ -572,233 +572,3 @@ function selectItemInCheckboxByName(formId, checkName, checked ) { ?> -
-heading(get_string('rolemappings')); - $xml_file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml"; - - $info = restore_read_xml_info($xml_file); - - // fix for MDL-9068, front page course is just a normal course - $siterolesarray = get_assignable_roles (get_context_instance(CONTEXT_COURSE, $course->id), "shortname", ROLENAME_ORIGINAL); - $siterolesnamearray = get_assignable_roles (get_context_instance(CONTEXT_COURSE, $course->id), "name", ROLENAME_ORIGINAL); - $allroles = get_records('role'); - - echo (''); - - if ($info->backup_moodle_version < 2006092801) { - echo (''); - - // 1.6 and below backup - - /// Editting teacher - echo (''); - - /// Non-editting teacher - echo (''); - - - /// Student - echo (''); - - } else { - // 1.7 and above backup - $roles = restore_read_xml_roles($xml_file); - - // Calculate if any role can be mapped - $str_new = ''; - $canmaproles = false; - if (has_capability('moodle/role:manage', get_context_instance(CONTEXT_SYSTEM))) { - $str_new = 'new role'; - $canmaproles = true; - } else if (!empty($siterolesarray)) { - $canmaproles = true; - } - - if ($canmaproles) { - echo (''); - } - - if (!empty($roles->roles)) { // possible to have course with no roles - foreach ($siterolesarray as $siteroleid=>$siteroleshortname) { - $siteroleschoicearray[$siteroleid] = $siterolesnamearray[$siteroleid]." (". $siterolesarray[$siteroleid].")"; - } - - foreach ($roles->roles as $roleid=>$role) { - - if (!$canmaproles) { // User cannot map roles at all, add hidden element and continue - echo ""; - continue; - } - - $mappableroles = !empty($siteroleschoicearray) ? $siteroleschoicearray : array(); - - echo (''); - } - } - - } // end else - echo ('
'.get_string('sourcerole').''.get_string('targetrole').'
'); - echo ''; - echo (''); - - // get the first teacheredit legacy - $roles = get_archetype_roles('editingteacher'); - - $editteacher = reset($roles); - echo html_writer::select($siterolesarray, "defaultteacheredit", $editteacher->id, array(''=>'new role')); - echo ('
'); - echo ''; - print_string('noneditingteacher'); - echo (''); - - // get the first teacheredit legacy - $roles = get_archetype_roles('teacher'); - $teacher = reset($roles); - - echo html_writer::select($siterolesarray, "defaultteacher", $teacher->id, array(''=>'new role')); - echo ('
'); - echo ''; - echo (''); - - // get the first teacheredit legacy - $roles = get_archetype_roles('student'); - $studentrole = array_shift($roles); - - echo html_writer::select($siterolesarray, "defaultstudent", $studentrole->id, array(''=>'new role')); - echo ('
'.get_string('sourcerole').''.get_string('targetrole').'
'); - echo ''; - echo (''); - - /// first, we see if any exact role definition is found - /// if found, that is the only option of restoring to - - if ($samerole = restore_samerole($roleid, $role)) { - $matchrole = $samerole->id; - // if an exact role is found, it does not matter whether this user can assign this role or not, - // this will be presented as a valid option regardless - $mappableroles[$samerole->id] = format_string($allroles[$samerole->id]->name)." (". $allroles[$samerole->id]->shortname.")"; - } else { - // no exact role found, let's try to match shortname - // this is useful in situations where basic roles differ slightly in definition - $matchrole = 0; - foreach ($siterolesarray as $siteroleid=>$siteroleshortname) { - if ($siteroleshortname == $role->shortname) { - $matchrole = $siteroleid; - break; - } - } - // Hack a bit, so, if role continues unmatched, and was "editingteacher", and "teacher" is available - // preselect it as fallback matching (can happen a lot) - if ($matchrole == 0 && $role->shortname == 'editingteacher' && in_array('teacher', $siterolesarray)) { - $matchrole = array_search('teacher', $siterolesarray); - } - - // If arrived here, role continues unmatched and the user lacks the 'moodle/role:manage' capability - // perform automatic matching to site defaultcourseroleid (only if available in the list) - if ($matchrole == 0 && !has_capability('moodle/role:manage', get_context_instance(CONTEXT_SYSTEM))) { - if (array_key_exists($CFG->defaultcourseroleid, $siterolesarray)) { - $matchrole = $CFG->defaultcourseroleid; - } - } - } - echo html_writer::select($mappableroles, "roles_".$roleid, $matchrole, array('' => $str_new)); - echo ('
'); // end of role mappings table -} - -?> -
-
- - - - -" /> -" /> -
- - - -get_record('role', array('id'=>$roleid)); - } - - // Second guess, try the shortname - $testroleid = $DB->get_field('role', 'id', array('shortname'=>$rolefromxml->shortname)); - if ($testroleid && restore_is_samerole($testroleid, $rolefromxml)) { - return $DB->get_record('role', array('id'=>$testroleid)); - } - - // Finally, search all other roles. In orter to speed things up, we exclude the ones we have - // already tested, and we only search roles with the same number of capabilities set in their - // definition. - $extracondition = ''; - if ($testroleid) { - $extracondition = "AND roleid <> $testroleid"; - } - $candidateroleids = $DB->get_records_sql( - "SELECT roleid - FROM {role_capabilities} - WHERE roleid <> $roleid $extracondition - GROUP BY roleid - HAVING COUNT(capability) = ".count($rolefromxml->capabilities)); - if (!empty($candidateroleids)) { - foreach ($candidateroleids as $testroleid => $notused) { - if (restore_is_samerole($testroleid, $rolefromxml)) { - return $DB->get_record('role', array('id'=>$testroleid)); - } - } - } - - return false; -} - -/** - * Compare a role in the database with one loaded from the backup file, and determine whether - * they have identical permissions for each capability. - * @param integer $testroleid the id of the role from the database to test against. - * @param object $rolefromxml the role definition loaded from the backup file. - * @return boolean true if the two roles are identical. - */ -function restore_is_samerole($testroleid, $rolefromxml) { - global $DB; - - // Load the role definition from the databse. - $rolefromdb = $DB->get_records('role_capabilities', array('roleid'=>$testroleid), '', 'capability,permission'); - if (!$rolefromdb) { - return false; - } - - // Quick check, do they have the permissions on the same number of capabilities? - if (count($rolefromdb) != count($rolefromxml->capabilities)) { - return false; - } - - // If they do, check each one. - foreach ($rolefromdb as $capability => $permissions) { - if (!isset($rolefromxml->capabilities[$capability]) || - $permissions->permission != $rolefromxml->capabilities[$capability]->permission) { - return false; - } - } - return true; -} diff --git a/backup/restorelib.php b/backup/restorelib.php index ef34acd2cdb..4051a2ef2b0 100644 --- a/backup/restorelib.php +++ b/backup/restorelib.php @@ -248,69 +248,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); return $content; } - //This function converts all the wiki texts in the restored course - //to the Markdown format. Used only for backup files prior 2005041100. - //It calls every module xxxx_convert_wiki2markdown function - function restore_convert_wiki2markdown($restore) { - - $status = true; - - if (!defined('RESTORE_SILENTLY')) { - echo ""; - } - return $status; - } - - //This function receives a wiki text in the restore process and - //return it with every link to modules " modulename:moduleid" - //converted if possible. See the space before modulename!! - function restore_decode_wiki_content($content,$restore) { - global $CFG; - - $result = $content; - - $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/'; - //We look for it - preg_match_all($searchstring,$content,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (course id) - $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id); - //Personalize the searchstring - $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/'; - //If it is a link to this course, update the link to its new location - if($rec->new_id) { - //Now replace it - $result= preg_replace($searchstring,' $1:'.$rec->new_id.'($2)',$result); - } else { - //It's a foreign link so redirect it to its original URL - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/$1/view.php?id='.$old_id.'($2)',$result); - } - } - } - return $result; - } - //This function read the xml file and store it data from the info zone in an object function restore_read_xml_info ($xml_file) { @@ -1010,58 +947,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); function restore_create_new_course($restore,&$course_header) { global $CFG, $DB; - $status = true; - - $fullname = $course_header->course_fullname; - $shortname = $course_header->course_shortname; - $currentfullname = ""; - $currentshortname = ""; - $counter = 0; - //Iteratere while the name exists - do { - if ($counter) { - $suffixfull = " ".get_string("copyasnoun")." ".$counter; - $suffixshort = "_".$counter; - } else { - $suffixfull = ""; - $suffixshort = ""; - } - $currentfullname = $fullname.$suffixfull; - // Limit the size of shortname - database column accepts <= 100 chars - $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; - $coursefull = $DB->get_record("course", array("fullname"=>$currentfullname)); - $courseshort = $DB->get_record("course", array("shortname"=>$currentshortname)); - $counter++; - } while ($coursefull || $courseshort); - - //New name = currentname - $course_header->course_fullname = $currentfullname; - $course_header->course_shortname = $currentshortname; - - // first try to get it from restore - if ($restore->restore_restorecatto) { - $category = $DB->get_record('course_categories', array('id'=>$restore->restore_restorecatto)); - } - - // else we try to get it from the xml file - //Now calculate the category - if (empty($category)) { - $category = $DB->get_record("course_categories",array("id"=>$course_header->category->id, - "name"=>$course_header->category->name)); - } - - //If no exists, try by name only - if (!$category) { - $category = $DB->get_record("course_categories", array("name"=>$course_header->category->name)); - } - - //If no exists, get default category - if (!$category) { - $category = get_course_category(); - } - - $course_header->category->id = $category->id; - $course_header->category->name = $category->name; //Create the course_object if ($status) { @@ -1154,398 +1039,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } - - //This function creates all the block stuff when restoring courses - //It calls selectively to restore_create_block_instances() for 1.5 - //and above backups. Upwards compatible with old blocks. - function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) { - global $CFG, $DB; - $status = true; - - blocks_delete_all_on_page(PAGE_COURSE_VIEW, $restore->course_id); - if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5 - if (empty($blockinfo)) { - // Looks like it's from Moodle < 1.3. Let's give the course default blocks... - blocks_add_default_course_blocks($DB->get_record('course', array('id' => $restore->course_id))); - } else { - // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup - $blockrecords = $DB->get_records('block', null, '', 'name, id'); - $temp_blocks_l = array(); - $temp_blocks_r = array(); - @list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo); - $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r)); - foreach($temp_blocks as $blockposition => $blocks) { - $blockweight = 0; - foreach($blocks as $blockname) { - if(!isset($blockrecords[$blockname])) { - // We don't know anything about this block! - continue; - } - $blockinstance = new stdClass; - // Remove any - prefix before doing the name-to-id mapping - if(substr($blockname, 0, 1) == '-') { - $blockname = substr($blockname, 1); - $blockinstance->visible = 0; - } else { - $blockinstance->visible = 1; - } - $blockinstance->blockid = $blockrecords[$blockname]->id; - $blockinstance->pageid = $restore->course_id; - $blockinstance->pagetype = PAGE_COURSE_VIEW; - $blockinstance->position = $blockposition; - $blockinstance->weight = $blockweight; - $DB->insert_record('block_instance', $blockinstance); - ++$blockweight; - } - } - } - } else if($backup_block_format == 'instances') { - $status = restore_create_block_instances($restore,$xml_file); - } - - return $status; - - } - - //This function creates all the block_instances from xml when restoring in a - //new course - function restore_create_block_instances($restore,$xml_file) { - global $CFG, $DB; - $status = true; - - //Check it exists - if (!file_exists($xml_file)) { - $status = false; - } - //Get info from xml - if ($status) { - $info = restore_read_xml_blocks($restore,$xml_file); - } - - if(empty($info->instances)) { - return $status; - } - - // First of all, iterate over the blocks to see which distinct pages we have - // in our hands and arrange the blocks accordingly. - $pageinstances = array(); - foreach($info->instances as $instance) { - - //pagetype and pageid black magic, we have to handle the case of blocks for the - //course, blocks from other pages in that course etc etc etc. - - if($instance->pagetype == PAGE_COURSE_VIEW) { - // This one's easy... - $instance->pageid = $restore->course_id; - - } else { - // restore activity blocks - $parts = explode('-', $instance->pagetype); - if($parts[0] == 'mod') { - if(!$restore->mods[$parts[1]]->restore) { - continue; - } - $getid = backup_getid($restore->backup_unique_code, $parts[1], $instance->pageid); - - if (empty($getid->new_id)) { - // Failed, perhaps the module was not included in the restore MDL-13554 - continue; - } - $instance->pageid = $getid->new_id; - } - else { - // Not invented here ;-) - continue; - } - - } - - if(!isset($pageinstances[$instance->pagetype])) { - $pageinstances[$instance->pagetype] = array(); - } - if(!isset($pageinstances[$instance->pagetype][$instance->pageid])) { - $pageinstances[$instance->pagetype][$instance->pageid] = array(); - } - - $pageinstances[$instance->pagetype][$instance->pageid][] = $instance; - } - - $blocks = $DB->get_records('block', array('visible'=>1), '', 'name, id, multiple'); - - // For each type of page we have restored - foreach($pageinstances as $thistypeinstances) { - - // For each page id of that type - foreach($thistypeinstances as $thisidinstances) { - - $addedblocks = array(); - $maxweights = array(); - - // For each block instance in that page - foreach($thisidinstances as $instance) { - - if(!isset($blocks[$instance->name])) { - //We are trying to restore a block we don't have... - continue; - } - - //If we have already added this block once and multiples aren't allowed, disregard it - if(!$blocks[$instance->name]->multiple && isset($addedblocks[$instance->name])) { - continue; - } - - //If its the first block we add to a new position, start weight counter equal to 0. - if(empty($maxweights[$instance->position])) { - $maxweights[$instance->position] = 0; - } - - //If the instance weight is greater than the weight counter (we skipped some earlier - //blocks most probably), bring it back in line. - if($instance->weight > $maxweights[$instance->position]) { - $instance->weight = $maxweights[$instance->position]; - } - - //Add this instance - $instance->blockid = $blocks[$instance->name]->id; - - // This will only be set if we come from 1.7 and above backups - // Also, must do this before insert ($DB->insert_record unsets id) - if (!empty($instance->id)) { - $oldid = $instance->id; - } else { - $oldid = 0; - } - - if ($instance->id = $DB->insert_record('block_instance', $instance)) { - // Create block instance - if (!$blockobj = block_instance($instance->name, $instance)) { - $status = false; - break; - } - // Run the block restore if needed - if ($blockobj->backuprestore_instancedata_used()) { - // Get restore information - $data = backup_getid($restore->backup_unique_code,'block_instance',$oldid); - $data->new_id = $instance->id; // For completeness - if (!$blockobj->instance_restore($restore, $data)) { - $status = false; - break; - } - } - // Save oldid after block restore process because info will be over-written with blank string - if ($oldid) { - backup_putid ($restore->backup_unique_code,"block_instance",$oldid,$instance->id); - } - - } else { - $status = false; - break; - } - - //Get an object for the block and tell it it's been restored so it can update dates - //etc. if necessary - if ($blockobj = block_instance($instance->name,$instance)) { - $blockobj->after_restore($restore); - } - - //Now we can increment the weight counter - ++$maxweights[$instance->position]; - - //Keep track of block types we have already added - $addedblocks[$instance->name] = true; - - } - } - } - - return $status; - } - - //This function creates all the course_sections and course_modules from xml - //when restoring in a new course or simply checks sections and create records - //in backup_ids when restoring in a existing course - function restore_create_sections(&$restore, $xml_file) { - global $CFG, $DB; - - $status = true; - //Check it exists - if (!file_exists($xml_file)) { - $status = false; - } - //Get info from xml - if ($status) { - $info = restore_read_xml_sections($xml_file); - } - //Put the info in the DB, recoding ids and saving the in backup tables - - $sequence = ""; - - if ($info) { - //For each, section, save it to db - foreach ($info->sections as $key => $sect) { - $sequence = ""; - $section = new object(); - $section->course = $restore->course_id; - $section->section = $sect->number; - $section->summary = backup_todb($sect->summary); - $section->visible = $sect->visible; - $section->sequence = ""; - //Now calculate the section's newid - $newid = 0; - if ($restore->restoreto == RESTORETO_NEW_COURSE) { - //Save it to db (only if restoring to new course) - $newid = $DB->insert_record("course_sections",$section); - } else { - //Get section id when restoring in existing course - $rec = $DB->get_record("course_sections", array("course"=>$restore->course_id, - "section"=>$section->section)); - //If section exists, has empty summary and backup has some summary, use it. MDL-8848 - if ($rec && empty($rec->summary) && !empty($section->summary)) { - $rec->summary = $section->summary; - $DB->update_record("course_sections", $rec); - } - //If that section doesn't exist, get section 0 (every mod will be - //asigned there - if(!$rec) { - $rec = $DB->get_record("course_sections", array("course"=>$restore->course_id, - "section"=>"0")); - } - //New check. If section 0 doesn't exist, insert it here !! - //Teorically this never should happen but, in practice, some users - //have reported this issue. - if(!$rec) { - $zero_sec = new object(); - $zero_sec->course = $restore->course_id; - $zero_sec->section = 0; - $zero_sec->summary = ""; - $zero_sec->sequence = ""; - $newid = $DB->insert_record("course_sections",$zero_sec); - $rec->id = $newid; - $rec->sequence = ""; - } - $newid = $rec->id; - $sequence = $rec->sequence; - } - if ($newid) { - //save old and new section id - backup_putid ($restore->backup_unique_code,"course_sections",$key,$newid); - } else { - $status = false; - } - //If all is OK, go with associated mods - if ($status) { - //If we have mods in the section - if (!empty($sect->mods)) { - //For each mod inside section - foreach ($sect->mods as $keym => $mod) { - // Yu: This part is called repeatedly for every instance, - // so it is necessary to set the granular flag and check isset() - // when the first instance of this type of mod is processed. - - //if (!isset($restore->mods[$mod->type]->granular) && isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) { - - if (!isset($restore->mods[$mod->type]->granular)) { - if (isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) { - // This defines whether we want to restore specific - // instances of the modules (granular restore), or - // whether we don't care and just want to restore - // all module instances (non-granular). - $restore->mods[$mod->type]->granular = true; - } else { - $restore->mods[$mod->type]->granular = false; - } - } - - //Check if we've to restore this module (and instance) - if (!empty($restore->mods[$mod->type]->restore)) { - if (empty($restore->mods[$mod->type]->granular) // we don't care about per instance - || (array_key_exists($mod->instance,$restore->mods[$mod->type]->instances) - && !empty($restore->mods[$mod->type]->instances[$mod->instance]->restore))) { - - //Get the module id from modules - $module = $DB->get_record("modules", array("name"=>$mod->type)); - if ($module) { - $course_module = new object(); - $course_module->course = $restore->course_id; - $course_module->module = $module->id; - $course_module->section = $newid; - $course_module->added = $mod->added; - $course_module->score = $mod->score; - $course_module->indent = $mod->indent; - $course_module->visible = $mod->visible; - $course_module->groupmode = $mod->groupmode; - if ($mod->groupingid and $grouping = restore_grouping_getid($restore, $mod->groupingid)) { - $course_module->groupingid = $grouping->new_id; - } else { - $course_module->groupingid = 0; - } - $course_module->groupmembersonly = $mod->groupmembersonly; - $course_module->instance = 0; - //NOTE: The instance (new) is calculated and updated in db in the - // final step of the restore. We don't know it yet. - //print_object($course_module); //Debug - //Save it to db - if ($mod->idnumber) { - $mod->idnumber=backup_todb($mod->idnumber); - if (grade_verify_idnumber($mod->idnumber, $restore->course_id)) { - $course_module->idnumber = $mod->idnumber; - } - } - - $course_module->completion=$mod->completion; - $course_module->completiongradeitemnumber=backup_todb($mod->completiongradeitemnumber); - $course_module->completionview=$mod->completionview; - $course_module->completionexpected=$mod->completionexpected; - - $course_module->availablefrom=$mod->availablefrom; - if($mod->availablefrom!=0) { - $course_module->availablefrom+=$restore->course_startdateoffset; - } - $course_module->availableuntil=$mod->availableuntil; - if($mod->availableuntil!=0) { - $course_module->availableuntil+=$restore->course_startdateoffset; - } - $course_module->showavailability=$mod->showavailability; - - $newidmod = $DB->insert_record("course_modules", $course_module); - if ($newidmod) { - //save old and new module id - //In the info field, we save the original instance of the module - //to use it later - backup_putid ($restore->backup_unique_code,"course_modules", - $keym,$newidmod,$mod->instance); - - $restore->mods[$mod->type]->instances[$mod->instance]->restored_as_course_module = $newidmod; - } else { - $status = false; - } - //Now, calculate the sequence field - if ($status) { - if ($sequence) { - $sequence .= ",".$newidmod; - } else { - $sequence = $newidmod; - } - } - } else { - $status = false; - } - } - } - } - } - } - //If all is OK, update sequence field in course_sections - if ($status) { - if (isset($sequence)) { - $update_rec = new object(); - $update_rec->id = $newid; - $update_rec->sequence = $sequence; - $status = $DB->update_record("course_sections",$update_rec); - } - } - } - // Now that we have IDs for everything, store any completion data if($status && !empty($info->completiondata) && count($info->completiondata)>0) { // Get list of users who can view course (& hence have @@ -1669,104 +1162,11 @@ define('RESTORE_GROUPS_GROUPINGS', 3); return true; } - //This function creates all the metacourse data from xml, notifying - //about each incidence - function restore_create_metacourse($restore,$xml_file) { - global $CFG, $DB; - - $status = true; - //Check it exists - if (!file_exists($xml_file)) { - $status = false; - } - //Get info from xml - if ($status) { - //Load data from XML to info - $info = restore_read_xml_metacourse($xml_file); - } - - //Process info about metacourse - if ($status and $info) { - //Process child records - if (!empty($info->childs)) { - foreach ($info->childs as $child) { - $dbcourse = false; - $dbmetacourse = false; - //Check if child course exists in destination server - //(by id in the same server or by idnumber and shortname in other server) - if (backup_is_same_site($restore)) { - //Same server, lets see by id - $dbcourse = $DB->get_record('course', array('id'=>$child->id)); - } else { - //Different server, lets see by idnumber and shortname, and only ONE record - $dbcount = $DB->count_records('course', array('idnumber'=>$child->idnumber, 'shortname'=>$child->shortname)); - if ($dbcount == 1) { - $dbcourse = $DB->get_record('course', array('idnumber'=>$child->idnumber, 'shortname'=>$child->shortname)); - } - } - //If child course has been found, insert data - if ($dbcourse) { - $dbmetacourse->child_course = $dbcourse->id; - $dbmetacourse->parent_course = $restore->course_id; - $status = $DB->insert_record('course_meta',$dbmetacourse); - } else { - //Child course not found, notice! - if (!defined('RESTORE_SILENTLY')) { - echo ''; - } - } - } - //Now, recreate student enrolments... - sync_metacourse($restore->course_id); - } - //Process parent records - if (!empty($info->parents)) { - foreach ($info->parents as $parent) { - $dbcourse = false; - $dbmetacourse = false; - //Check if parent course exists in destination server - //(by id in the same server or by idnumber and shortname in other server) - if (backup_is_same_site($restore)) { - //Same server, lets see by id - $dbcourse = $DB->get_record('course', array('id'=>$parent->id)); - } else { - //Different server, lets see by idnumber and shortname, and only ONE record - $dbcount = $DB->count_records('course', array('idnumber'=>$parent->idnumber, 'shortname'=>$parent->shortname)); - if ($dbcount == 1) { - $dbcourse = $DB->get_record('course', array('idnumber'=>$parent->idnumber, 'shortname'=>$parent->shortname)); - } - } - //If parent course has been found, insert data if it is a metacourse - if ($dbcourse) { - if ($dbcourse->metacourse) { - $dbmetacourse->parent_course = $dbcourse->id; - $dbmetacourse->child_course = $restore->course_id; - $status = $DB->insert_record ('course_meta',$dbmetacourse); - //Now, recreate student enrolments in parent course - sync_metacourse($dbcourse->id); - } else { - //Parent course isn't metacourse, notice! - if (!defined('RESTORE_SILENTLY')) { - echo ''; - } - } - } else { - //Parent course not found, notice! - if (!defined('RESTORE_SILENTLY')) { - echo ''; - } - } - } - } - - } - return $status; - } /** - * This function migrades all the pre 1.9 gradebook data from xml + * This function creates all the gradebook data from xml */ - function restore_migrate_old_gradebook($restore,$xml_file) { + function restore_create_gradebook($restore,$xml_file) { global $CFG, $DB; $status = true; @@ -1784,6 +1184,12 @@ define('RESTORE_GROUPS_GROUPINGS', 3); return $status; } + if (empty($CFG->disablegradehistory) and isset($info->gradebook_histories) and $info->gradebook_histories == "true") { + $restore_histories = true; + } else { + $restore_histories = false; + } + // make sure top course category exists $course_category = grade_category::fetch_course_category($restore->course_id); $course_category->load_grade_item(); @@ -1792,8 +1198,8 @@ define('RESTORE_GROUPS_GROUPINGS', 3); // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type // i.e. the aggregated grades of that category - $restoreall = true; // set to false if any grade_item is not selected/restored - $importing = !empty($SESSION->restore->importing); // there should not be a way to import old backups, but anyway ;-) + $restoreall = true; // set to false if any grade_item is not selected/restored or already exist + $importing = !empty($SESSION->restore->importing); if ($importing) { $restoreall = false; @@ -1802,212 +1208,21 @@ define('RESTORE_GROUPS_GROUPINGS', 3); $prev_grade_items = grade_item::fetch_all(array('courseid'=>$restore->course_id)); $prev_grade_cats = grade_category::fetch_all(array('courseid'=>$restore->course_id)); - // if any categories already present, skip restore of categories from backup + // if any categories already present, skip restore of categories from backup - course item or category already exist if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) { $restoreall = false; } unset($prev_grade_items); unset($prev_grade_cats); - } - // force creation of all grade_items - the course_modules already exist - grade_force_full_regrading($restore->course_id); - grade_grab_course_grades($restore->course_id); + if ($restoreall) { + if ($recs = $DB->get_records("backup_ids", array('table_name'=>'grade_items', 'backup_code'=>$restore->backup_unique_code), "", "old_id")) { + foreach ($recs as $rec) { + if ($data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id)) { - // Start ul - if (!defined('RESTORE_SILENTLY')) { - echo ''; - } - - return $status; - } - - /** - * This function creates all the gradebook data from xml - */ - function restore_create_gradebook($restore,$xml_file) { - global $CFG, $DB; - - $status = true; - //Check it exists - if (!file_exists($xml_file)) { - return false; - } - - // Get info from xml - // info will contain the number of record to process - $info = restore_read_xml_gradebook($restore, $xml_file); - - // If we have info, then process - if (empty($info)) { - return $status; - } - - if (empty($CFG->disablegradehistory) and isset($info->gradebook_histories) and $info->gradebook_histories == "true") { - $restore_histories = true; - } else { - $restore_histories = false; - } - - // make sure top course category exists - $course_category = grade_category::fetch_course_category($restore->course_id); - $course_category->load_grade_item(); - - // we need to know if all grade items that were backed up are being restored - // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type - // i.e. the aggregated grades of that category - - $restoreall = true; // set to false if any grade_item is not selected/restored or already exist - $importing = !empty($SESSION->restore->importing); - - if ($importing) { - $restoreall = false; - - } else { - $prev_grade_items = grade_item::fetch_all(array('courseid'=>$restore->course_id)); - $prev_grade_cats = grade_category::fetch_all(array('courseid'=>$restore->course_id)); - - // if any categories already present, skip restore of categories from backup - course item or category already exist - if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) { - $restoreall = false; - } - unset($prev_grade_items); - unset($prev_grade_cats); - - if ($restoreall) { - if ($recs = $DB->get_records("backup_ids", array('table_name'=>'grade_items', 'backup_code'=>$restore->backup_unique_code), "", "old_id")) { - foreach ($recs as $rec) { - if ($data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id)) { - - $info = $data->info; - // do not restore if this grade_item is a mod, and - $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']); + $info = $data->info; + // do not restore if this grade_item is a mod, and + $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']); if ($itemtype == 'mod') { $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']); @@ -2064,76 +1279,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - /// Preprocess outcomes - do not store them yet! - if ($status and !$importing and $restoreall) { - if (!defined('RESTORE_SILENTLY')) { - echo '
  • '.get_string('gradeoutcomes','grades').'
  • '; - } - $recs = $DB->get_records("backup_ids", array('table_name'=>'grade_outcomes', 'backup_code'=>$restore->backup_unique_code), - "", - "old_id"); - if ($recs) { - foreach ($recs as $rec) { - //Get the full record from backup_ids - $data = backup_getid($restore->backup_unique_code,'grade_outcomes',$rec->old_id); - if ($data) { - $info = $data->info; - - //first find out if outcome already exists - $shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']); - - if ($candidates = $DB->get_records_sql("SELECT * - FROM {grade_outcomes} - WHERE (courseid IS NULL OR courseid = ?) - AND shortname = ? - ORDER BY courseid ASC, id ASC", array($restore->course_id, $shortname))) { - $grade_outcome = reset($candidates); - $outcomes[$rec->old_id] = $grade_outcome; - continue; - } - - $dbrec = new object(); - - if (has_capability('moodle/grade:manageoutcomes', get_context_instance(CONTEXT_SYSTEM))) { - $oldoutcome = backup_todb($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']); - if (empty($oldoutcome)) { - //site wide - $dbrec->courseid = null; - } else { - //course only - $dbrec->courseid = $restore->course_id; - } - } else { - // no permission to add site outcomes - $dbrec->courseid = $restore->course_id; - } - - //Get the fields - $dbrec->shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#'], false); - $dbrec->fullname = backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#'], false); - $dbrec->scaleid = backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#'], false); - $dbrec->description = backup_todb($info['GRADE_OUTCOME']['#']['DESCRIPTION']['0']['#'], false); - $dbrec->timecreated = backup_todb($info['GRADE_OUTCOME']['#']['TIMECREATED']['0']['#'], false); - $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME']['#']['TIMEMODIFIED']['0']['#'], false); - $dbrec->usermodified = backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#'], false); - - //Need to recode the scaleid - if ($scale = backup_getid($restore->backup_unique_code, 'scale', $dbrec->scaleid)) { - $dbrec->scaleid = $scale->new_id; - } - - //Need to recode the usermodified - if ($modifier = backup_getid($restore->backup_unique_code, 'user', $dbrec->usermodified)) { - $dbrec->usermodified = $modifier->new_id; - } - - $grade_outcome = new grade_outcome($dbrec, false); - $outcomes[$rec->old_id] = $grade_outcome; - } - } - } - } - /// Process grade items and grades if ($status) { if (!defined('RESTORE_SILENTLY')) { @@ -2822,422 +1967,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); return $status; } - //This function creates all the user, user_students, user_teachers - //user_course_creators and user_admins from xml - function restore_create_users($restore,$xml_file) { - global $CFG, $DB; - require_once ($CFG->dirroot.'/tag/lib.php'); - - $authcache = array(); // Cache to get some bits from authentication plugins - - $status = true; - - // Users have already been checked by restore_precheck_users() so they are loaded - // in backup_ids table. They don't need to be loaded (parsed) from XML again. Also, note - // the same function has performed the needed modifications in the $user->mnethostid field - // so we don't need to do it again here at all. Just some checks. - - // Get users ids from backup_ids table - $userids = $DB->get_fieldset_select('backup_ids', 'old_id', 'backup_code = ? AND table_name = ?', array($restore->backup_unique_code, 'user')); - - // Have users to process, proceed with them - if (!empty($userids)) { - - /// Get languages for quick search later - $languages = get_string_manager()->get_list_of_translations(); - - /// Iterate over all users loaded from xml - $counter = 0; - - /// Init trailing messages - $messages = array(); - foreach ($userids as $userid) { - // Defaults - $user_exists = false; // By default user does not exist - $newid = null; // By default, there is not newid - - // Get record from backup_ids - $useridsdbrec = backup_getid($restore->backup_unique_code, 'user', $userid); - - // Based in restore_precheck_users() calculations, if the user exists - // new_id must contain the id of the matching user - if (!empty($useridsdbrec->new_id)) { - $user_exists = true; - $newid = $useridsdbrec->new_id; - } - - $user = $useridsdbrec->info; - foreach (array_keys(get_object_vars($user)) as $field) { - if (!is_array($user->$field)) { - $user->$field = backup_todb($user->$field); - if (is_null($user->$field)) { - $user->$field = ''; - } - } - } - - //Now, recode some languages (Moodle 1.5) - if ($user->lang == 'ma_nt') { - $user->lang = 'mi_nt'; - } - - //Country list updates - MDL-13060 - //Any user whose country code has been deleted or modified needs to be assigned a valid one. - $country_update_map = array( - 'ZR' => 'CD', - 'TP' => 'TL', - 'FX' => 'FR', - 'KO' => 'RS', - 'CS' => 'RS', - 'WA' => 'GB'); - if (array_key_exists($user->country, $country_update_map)) { - $user->country = $country_update_map[$user->country]; - } - - //If language does not exist here - use site default - if (!array_key_exists($user->lang, $languages)) { - $user->lang = $CFG->lang; - } - - //Check if it's admin and coursecreator - $is_admin = !empty($user->roles['admin']); - $is_coursecreator = !empty($user->roles['coursecreator']); - - //Check if it's teacher and student - $is_teacher = !empty($user->roles['teacher']); - $is_student = !empty($user->roles['student']); - - //Check if it's needed - $is_needed = !empty($user->roles['needed']); - - //Calculate if it is a course user - //Has role teacher or student or needed - $is_course_user = ($is_teacher or $is_student or $is_needed); - - // Only try to perform mnethost/auth modifications if restoring to another server - // or if, while restoring to same server, the user doesn't exists yet (rebuilt site) - // - // So existing user data in same server *won't be modified by restore anymore*, - // under any circumpstance. If somehting is wrong with existing data, it's server fault. - if (!backup_is_same_site($restore) || (backup_is_same_site($restore) && !$user_exists)) { - //Arriving here, any user with mnet auth and using $CFG->mnet_localhost_id is wrong - //as own server cannot be accesed over mnet. Change auth to manual and inform about the switch - if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) { - // Respect registerauth - if ($CFG->registerauth == 'email') { - $user->auth = 'email'; - } else { - $user->auth = 'manual'; - } - // inform about the automatic switch of authentication/host - if(empty($user->mnethosturl)) { - $user->mnethosturl = '----'; - } - $messages[] = get_string('mnetrestore_extusers_switchuserauth', 'admin', $user); - } - } - unset($user->mnethosturl); - - //Flags to see what parts are we going to restore - $create_user = true; - $create_roles = true; - $create_custom_profile_fields = true; - $create_tags = true; - $create_preferences = true; - - //If we are restoring course users and it isn't a course user - if ($restore->users == 1 and !$is_course_user) { - //If only restoring course_users and user isn't a course_user, inform to $backup_ids - $status = backup_putid($restore->backup_unique_code,"user",$userid,null,'notincourse'); - $create_user = false; - $create_roles = false; - $create_custom_profile_fields = false; - $create_tags = false; - $create_preferences = false; - } - - if ($user_exists and $create_user) { - //If user exists mark its newid in backup_ids (the same than old) - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,'exists'); - $create_user = false; - $create_custom_profile_fields = false; - $create_tags = false; - $create_preferences = false; - } - - //Here, if create_user, do it - if ($create_user) { - //Unset the id because it's going to be inserted with a new one - unset ($user->id); - - /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties) - if (!empty($CFG->disableuserimages) || empty($user->picture)) { - $user->picture = 0; - } - - //We need to analyse the AUTH field to recode it: - // - if the field isn't set, we are in a pre 1.4 backup and $CFG->registerauth will decide - // - if the auth isn't enabled in target site, $CFG->registerauth will decide - // - finally, if the auth resulting isn't enabled, default to 'manual' - if (empty($user->auth) || !is_enabled_auth($user->auth)) { - if ($CFG->registerauth == 'email') { - $user->auth = 'email'; - } else { - $user->auth = 'manual'; - } - } - if (!is_enabled_auth($user->auth)) { // Final auth check verify, default to manual if not enabled - $user->auth = 'manual'; - } - - // Now that we know the auth method, for users to be created without pass - // if password handling is internal and reset password is available - // we set the password to "restored" (plain text), so the login process - // will know how to handle that situation in order to allow the user to - // recover the password. MDL-20846 - if (empty($user->password)) { // Only if restore comes without password - if (!array_key_exists($user->auth, $authcache)) { // Not in cache - $userauth = new stdClass(); - $authplugin = get_auth_plugin($user->auth); - $userauth->preventpassindb = $authplugin->prevent_local_passwords(); - $userauth->isinternal = $authplugin->is_internal(); - $userauth->canresetpwd = $authplugin->can_reset_password(); - $authcache[$user->auth] = $userauth; - } else { - $userauth = $authcache[$user->auth]; // Get from cache - } - - // Most external plugins do not store passwords locally - if (!empty($userauth->preventpassindb)) { - $user->password = 'not cached'; - - // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark - } else if ($userauth->isinternal and $userauth->canresetpwd) { - $user->password = 'restored'; - } - } - - //We need to process the POLICYAGREED field to recalculate it: - // - if the destination site is different (by wwwroot) reset it. - // - if the destination site is the same (by wwwroot), leave it unmodified - - if (!backup_is_same_site($restore)) { - $user->policyagreed = 0; - } else { - //Nothing to do, we are in the same server - } - - //Check if the theme exists in destination server - $themes = get_list_of_themes(); - if (!in_array($user->theme, $themes)) { - $user->theme = ''; - } - - //set time created - if (empty($user->timecreated)) { - $user->timecreated = time(); - } - - //We are going to create the user - //The structure is exactly as we need - - $newid = $DB->insert_record("user", $user); - //Put the new id - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new"); - } - - ///TODO: This seccion is to support pre 1.7 course backups, using old roles - /// teacher, coursecreator, student.... providing a basic mapping to new ones. - /// Someday we'll drop support for them and this section will be safely deleted (2.0?) - //Here, if create_roles, do it as necessary - if ($create_roles) { - //Get the newid and current info from backup_ids - $data = backup_getid($restore->backup_unique_code,"user",$userid); - $newid = $data->new_id; - $currinfo = $data->info.","; - - //Now, depending of the role, create records in user_studentes and user_teacher - //and/or mark it in backup_ids - - if ($is_admin) { - //If the record (user_admins) doesn't exists - //Only put status in backup_ids - $currinfo = $currinfo."admin,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - } - if ($is_coursecreator) { - //If the record (user_coursecreators) doesn't exists - //Only put status in backup_ids - $currinfo = $currinfo."coursecreator,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - } - if ($is_needed) { - //Only put status in backup_ids - $currinfo = $currinfo."needed,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - } - if ($is_teacher) { - //If the record (teacher) doesn't exists - //Put status in backup_ids - $currinfo = $currinfo."teacher,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - //Set course and user - $user->roles['teacher']->course = $restore->course_id; - $user->roles['teacher']->userid = $newid; - - //Need to analyse the enrol field - // - if it isn't set, set it to $CFG->enrol - // - if we are in a different server (by wwwroot), set it to $CFG->enrol - // - if we are in the same server (by wwwroot), maintain it unmodified. - if (empty($user->roles['teacher']->enrol)) { - $user->roles['teacher']->enrol = $CFG->enrol; - } else if (!backup_is_same_site($restore)) { - $user->roles['teacher']->enrol = $CFG->enrol; - } else { - //Nothing to do. Leave it unmodified - } - - $rolesmapping = $restore->rolesmapping; - $context = get_context_instance(CONTEXT_COURSE, $restore->course_id); - if ($user->roles['teacher']->editall) { - role_assign($rolesmapping['defaultteacheredit'], - $newid, - 0, - $context->id, - $user->roles['teacher']->timestart, - $user->roles['teacher']->timeend, - 0, - $user->roles['teacher']->enrol); - - // editting teacher - } else { - // non editting teacher - role_assign($rolesmapping['defaultteacher'], - $newid, - 0, - $context->id, - $user->roles['teacher']->timestart, - $user->roles['teacher']->timeend, - 0, - $user->roles['teacher']->enrol); - } - } - if ($is_student) { - - //Put status in backup_ids - $currinfo = $currinfo."student,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - //Set course and user - $user->roles['student']->course = $restore->course_id; - $user->roles['student']->userid = $newid; - - //Need to analyse the enrol field - // - if it isn't set, set it to $CFG->enrol - // - if we are in a different server (by wwwroot), set it to $CFG->enrol - // - if we are in the same server (by wwwroot), maintain it unmodified. - if (empty($user->roles['student']->enrol)) { - $user->roles['student']->enrol = $CFG->enrol; - } else if (!backup_is_same_site($restore)) { - $user->roles['student']->enrol = $CFG->enrol; - } else { - //Nothing to do. Leave it unmodified - } - $rolesmapping = $restore->rolesmapping; - $context = get_context_instance(CONTEXT_COURSE, $restore->course_id); - - role_assign($rolesmapping['defaultstudent'], - $newid, - 0, - $context->id, - $user->roles['student']->timestart, - $user->roles['student']->timeend, - 0, - $user->roles['student']->enrol); - - } - if (!$is_course_user) { - //If the record (user) doesn't exists - if (!$DB->record_exists("user", array("id"=>$newid))) { - //Put status in backup_ids - $currinfo = $currinfo."user,"; - $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo); - } - } - } - - /// Here, if create_custom_profile_fields, do it as necessary - if ($create_custom_profile_fields) { - if (isset($user->user_custom_profile_fields)) { - foreach($user->user_custom_profile_fields as $udata) { - /// If the profile field has data and the profile shortname-datatype is defined in server - if ($udata->field_data) { - if ($field = $DB->get_record('user_info_field', array('shortname'=>$udata->field_name, 'datatype'=>$udata->field_type))) { - /// Insert the user_custom_profile_field - $rec = new object(); - $rec->userid = $newid; - $rec->fieldid = $field->id; - $rec->data = $udata->field_data; - $DB->insert_record('user_info_data', $rec); - } - } - } - } - } - - /// Here, if create_tags, do it as necessary - if ($create_tags) { - /// if tags are enabled and there are user tags - if (!empty($CFG->usetags) && isset($user->user_tags)) { - $tags = array(); - foreach($user->user_tags as $user_tag) { - $tags[] = $user_tag->rawname; - } - tag_set('user', $newid, $tags); - } - } - - //Here, if create_preferences, do it as necessary - if ($create_preferences) { - if (isset($user->user_preferences)) { - foreach($user->user_preferences as $user_preference) { - //We check if that user_preference exists in DB - if (!$DB->record_exists("user_preferences", array("userid"=>$newid, "name"=>$user_preference->name))) { - //Prepare the record and insert it - $user_preference->userid = $newid; - $status = $DB->insert_record("user_preferences",$user_preference); - } - } - } - } - - //Do some output - $counter++; - if ($counter % 10 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if ($counter % 200 == 0) { - echo "
    "; - } - } - backup_flush(300); - } - } /// End of loop over all the users loaded from backup_ids table - - /// Inform about all the messages geerated while restoring users - if (!defined('RESTORE_SILENTLY')) { - if ($messages) { - echo ''; - } - } - } - - return $status; - } - //This function creates all the structures messages and contacts function restore_create_messages($restore,$xml_file) { global $CFG, $DB; @@ -3620,9 +2349,11 @@ define('RESTORE_GROUPS_GROUPINGS', 3); return $status; } - //This function creates all the scales - function restore_create_scales($restore,$xml_file) { - global $CFG, $USER, $DB; + //This function creates all the course events + function restore_create_events($restore,$xml_file) { + global $DB; + + global $CFG, $SESSION; $status = true; //Check it exists @@ -3631,397 +2362,10 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } //Get info from xml if ($status) { - //scales will contain the old_id of every scale + //events will contain the old_id of every event //in backup_ids->info will be the real info (serialized) - $scales = restore_read_xml_scales($restore,$xml_file); - } - //Now, if we have anything in scales, we have to restore that - //scales - if ($scales) { - if ($scales !== true) { - //Iterate over each scale - foreach ($scales as $scale) { - //Get record from backup_ids - $data = backup_getid($restore->backup_unique_code,"scale",$scale->id); - - if ($data) { - //Now get completed xmlized object - $info = $data->info; - //traverse_xmlize($info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //Now build the SCALE record structure - $sca = new object(); - $sca->courseid = backup_todb($info['SCALE']['#']['COURSEID']['0']['#']); - $sca->userid = backup_todb($info['SCALE']['#']['USERID']['0']['#']); - $sca->name = backup_todb($info['SCALE']['#']['NAME']['0']['#']); - $sca->scale = backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']); - $sca->description = backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']); - $sca->timemodified = backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']); - - // Look for scale (by 'scale' both in standard (course=0) and current course - // with priority to standard scales (ORDER clause) - // scale is not course unique, use get_record_sql to suppress warning - // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides. - $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc'); - $params = array('courseid'=>$restore->course_id, 'scaledesc'=>$sca->scale); - // Scale doesn't exist, create it - if (!$sca_db = $DB->get_record_sql("SELECT * - FROM {scale} - WHERE courseid IN (0, :courseid) - AND $compare_scale_clause - ORDER BY courseid", $params, true)) { - - // Try to recode the user field, defaulting to current user if not found - $user = backup_getid($restore->backup_unique_code,"user",$sca->userid); - if ($user) { - $sca->userid = $user->new_id; - } else { - $sca->userid = $USER->id; - } - // If course scale, recode the course field - if ($sca->courseid != 0) { - $sca->courseid = $restore->course_id; - } - // If scale is standard, if user lacks perms to manage standar scales - // 'downgrade' them to course scales - if ($sca->courseid == 0 and !has_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM), $sca->userid)) { - $sca->courseid = $restore->course_id; - } - //The structure is equal to the db, so insert the scale - $newid = $DB->insert_record ("scale",$sca); - - // Scale exists, reuse it - } else { - $newid = $sca_db->id; - } - - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,"scale", $scale->id, $newid); - } - } - } - } - } else { - $status = false; - } - return $status; - } - - /** - * Recode group ID field, and set group ID based on restore options. - * @return object Group object with new_id field. - */ - function restore_group_getid($restore, $groupid) { - //We have to recode the groupid field - $group = backup_getid($restore->backup_unique_code, 'groups', $groupid); - - if ($restore->groups == RESTORE_GROUPS_NONE or $restore->groups == RESTORE_GROUPINGS_ONLY) { - $group->new_id = 0; - } - return $group; - } - - /** - * Recode grouping ID field, and set grouping ID based on restore options. - * @return object Group object with new_id field. - */ - function restore_grouping_getid($restore, $groupingid) { - //We have to recode the groupid field - $grouping = backup_getid($restore->backup_unique_code, 'groupings', $groupingid); - - if ($restore->groups != RESTORE_GROUPS_GROUPINGS and $restore->groups != RESTORE_GROUPINGS_ONLY) { - $grouping->new_id = 0; - } - return $grouping; - } - - //This function creates all the groups - function restore_create_groups($restore,$xml_file) { - global $CFG, $DB; - - //Check it exists - if (!file_exists($xml_file)) { - return false; - } - //Get info from xml - if (!$groups = restore_read_xml_groups($restore,$xml_file)) { - //groups will contain the old_id of every group - //in backup_ids->info will be the real info (serialized) - return false; - - } else if ($groups === true) { - return true; - } - - $status = true; - - //Iterate over each group - foreach ($groups as $group) { - //Get record from backup_ids - $data = backup_getid($restore->backup_unique_code,"groups",$group->id); - - if ($data) { - //Now get completed xmlized object - $info = $data->info; - //traverse_xmlize($info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - //Now build the GROUP record structure - $gro = new Object(); - $gro->courseid = $restore->course_id; - $gro->name = backup_todb($info['GROUP']['#']['NAME']['0']['#']); - $gro->description = backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']); - if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) { - $gro->enrolmentkey = backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']); - } else { - $gro->enrolmentkey = backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']); - } - $gro->picture = backup_todb($info['GROUP']['#']['PICTURE']['0']['#']); - $gro->hidepicture = backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']); - $gro->timecreated = backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']); - $gro->timemodified = backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']); - - //Now search if that group exists (by name and description field) in - //restore->course_id course - //Going to compare LOB columns so, use the cross-db $DB->sql_compare_text() in both sides. - $description_clause = ''; - $params = array('courseid'=>$restore->course_id, 'grname'=>$gro->name); - if (!empty($gro->description)) { /// Only for groups having a description - $description_clause = " AND " . - $DB->sql_compare_text('description') . " = " . - $DB->sql_compare_text(':desc'); - $params['desc'] = $gro->description; - } - if (!$gro_db = $DB->get_record_sql("SELECT * - FROM {groups} - WHERE courseid = :courseid AND - name = :grname $description_clause", $params, true)) { - //If it doesn't exist, create - $newid = $DB->insert_record('groups', $gro); - - } else { - //get current group id - $newid = $gro_db->id; - } - - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,"groups", $group->id, $newid); - } else { - - $status = false; - continue; - } - - //Now restore members in the groups_members, only if - //users are included - if ($restore->users != 2) { - if (!restore_create_groups_members($newid,$info,$restore)) { - $status = false; - } - } - } - } - - //Now, restore group_files - if ($status) { - $status = restore_group_files($restore); - } - - return $status; - } - - //This function restores the groups_members - function restore_create_groups_members($group_id,$info,$restore) { - global $DB; - - if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) { - //OK, some groups have no members. - return true; - } - //Get the members array - $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER']; - - $status = true; - - //Iterate over members - for($i = 0; $i < sizeof($members); $i++) { - $mem_info = $members[$i]; - //traverse_xmlize($mem_info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //Now, build the GROUPS_MEMBERS record structure - $group_member = new Object(); - $group_member->groupid = $group_id; - $group_member->userid = backup_todb($mem_info['#']['USERID']['0']['#']); - $group_member->timeadded = backup_todb($mem_info['#']['TIMEADDED']['0']['#']); - - $newid = false; - - //We have to recode the userid field - if (!$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid)) { - debugging("group membership can not be restored, user id $group_member->userid not present in backup"); - // do not not block the restore - continue; - } - - $group_member->userid = $user->new_id; - - //The structure is equal to the db, so insert the groups_members - if ($DB->record_exists("groups_members", array('groupid'=>$group_member->groupid, 'userid'=>$group_member->userid))) { - // user already member - } else { - $DB->insert_record ("groups_members", $group_member); - } - - //Do some output - if (($i+1) % 50 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 1000 == 0) { - echo "
    "; - } - } - backup_flush(300); - } - } - - return $status; - } - - //This function creates all the groupings - function restore_create_groupings($restore,$xml_file) { - global $DB; - - //Check it exists - if (!file_exists($xml_file)) { - return false; - } - //Get info from xml - if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) { - return false; - - } else if ($groupings === true) { - return true; - } - - $status = true; - - //Iterate over each group - foreach ($groupings as $grouping) { - if ($data = backup_getid($restore->backup_unique_code,"groupings",$grouping->id)) { - //Now get completed xmlized object - $info = $data->info; - //Now build the GROUPING record structure - $gro = new Object(); - ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']); - $gro->courseid = $restore->course_id; - $gro->name = backup_todb($info['GROUPING']['#']['NAME']['0']['#']); - $gro->description = backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']); - $gro->configdata = backup_todb($info['GROUPING']['#']['CONFIGDATA']['0']['#']); - $gro->timecreated = backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']); - - //Now search if that group exists (by name and description field) in - if ($gro_db = $DB->get_record('groupings', array('courseid'=>$restore->course_id, 'name'=>$gro->name, 'description'=>$gro->description))) { - //get current group id - $newid = $gro_db->id; - - } else { - //The structure is equal to the db, so insert the grouping - $newid = $DB->insert_record('groupings', $gro); - } - - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,"groupings", - $grouping->id, $newid); - } - } - - - // now fix the defaultgroupingid in course - $course = $DB->get_record('course', array('id'=>$restore->course_id)); - if ($course->defaultgroupingid) { - if ($grouping = restore_grouping_getid($restore, $course->defaultgroupingid)) { - $DB->set_field('course', 'defaultgroupingid', $grouping->new_id, array('id'=>$course->id)); - } else { - $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$course->id)); - } - } - - return $status; - } - - //This function creates all the groupingsgroups - function restore_create_groupings_groups($restore,$xml_file) { - global $DB; - - //Check it exists - if (!file_exists($xml_file)) { - return false; - } - //Get info from xml - if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) { - return false; - - } else if ($groupingsgroups === true) { - return true; - } - - $status = true; - - //Iterate over each group - foreach ($groupingsgroups as $groupinggroup) { - if ($data = backup_getid($restore->backup_unique_code,"groupingsgroups",$groupinggroup->id)) { - //Now get completed xmlized object - $info = $data->info; - //Now build the GROUPING record structure - $gro_member = new Object(); - $gro_member->groupingid = backup_todb($info['GROUPINGGROUP']['#']['GROUPINGID']['0']['#']); - $gro_member->groupid = backup_todb($info['GROUPINGGROUP']['#']['GROUPID']['0']['#']); - $gro_member->timeadded = backup_todb($info['GROUPINGGROUP']['#']['TIMEADDED']['0']['#']); - - if (!$grouping = backup_getid($restore->backup_unique_code,"groupings",$gro_member->groupingid)) { - $status = false; - continue; - } - - if (!$group = backup_getid($restore->backup_unique_code,"groups",$gro_member->groupid)) { - $status = false; - continue; - } - - $gro_member->groupid = $group->new_id; - $gro_member->groupingid = $grouping->new_id; - if (!$DB->get_record('groupings_groups', array('groupid'=>$gro_member->groupid, 'groupingid'=>$gro_member->groupingid))) { - $DB->insert_record('groupings_groups', $gro_member); - } - } - } - - return $status; - } - - //This function creates all the course events - function restore_create_events($restore,$xml_file) { - global $DB; - - global $CFG, $SESSION; - - $status = true; - //Check it exists - if (!file_exists($xml_file)) { - $status = false; - } - //Get info from xml - if ($status) { - //events will contain the old_id of every event - //in backup_ids->info will be the real info (serialized) - $events = restore_read_xml_events($restore,$xml_file); - } + $events = restore_read_xml_events($restore,$xml_file); + } //Get admin->id for later use $admin = get_admin(); @@ -8402,75 +6746,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); $status = true; - //Checks for the required files/functions to restore every module - //and include them - if ($allmods = $DB->get_records("modules") ) { - foreach ($allmods as $mod) { - $modname = $mod->name; - $modfile = "$CFG->dirroot/mod/$modname/restorelib.php"; - //If file exists and we have selected to restore that type of module - if ((file_exists($modfile)) and !empty($restore->mods[$modname]) and ($restore->mods[$modname]->restore)) { - include_once($modfile); - } - } - } - - if (!defined('RESTORE_SILENTLY')) { - //Start the main table - echo ""; - echo "
    "; - - //Start the main ul - echo "
      "; - } - - //Location of the xml file - $xml_file = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml"; - - // Re-assure xml file is in place before any further process - if (! $status = restore_check_moodle_file($xml_file)) { - if (!is_file($xml_file)) { - $errorstr = 'Error checking backup file. moodle.xml not found. Session problem?'; - } else { - $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted. Session problem?'; - } - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification($errorstr); - } - return false; - } - - //Preprocess the moodle.xml file spliting into smaller chucks (modules, users, logs...) - //for optimal parsing later in the restore process. - if (!empty($CFG->experimentalsplitrestore)) { - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '.get_string('preprocessingbackupfile') . '
    • '; - } - //First of all, split moodle.xml into handy files - if (!restore_split_xml ($xml_file, $restore)) { - $errorstr = "Error proccessing moodle.xml file. Process ended."; - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification($errorstr); - } - return false; - } - } - - // Precheck the users section, detecting various situations that can lead to problems, so - // we stop restore before performing any further action - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '.get_string('restoreusersprecheck').'
    • '; - } - if (!restore_precheck_users($xml_file, $restore, $problems)) { - $errorstr = get_string('restoreusersprecheckerror'); - if (!empty($problems)) { - $errorstr .= ' (' . implode(', ', $problems) . ')'; - } - if (!defined('RESTORE_SILENTLY')) { - notify($errorstr); - } - return false; - } //If we've selected to restore into new course //create it (course) @@ -8556,98 +6831,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - //Now create users as needed - if ($status and ($restore->users == 0 or $restore->users == 1)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingusers")."
      "; - } - if (!$status = restore_create_users($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore users."); - } else { - $errorstr = "Could not restore users."; - return false; - } - } - - //Now print info about the work done - if ($status) { - $recs = $DB->get_records_sql("select old_id, new_id from {backup_ids} - where backup_code = ? and - table_name = 'user'", array($restore->backup_unique_code)); - //We've records - if ($recs) { - $new_count = 0; - $exists_count = 0; - $student_count = 0; - $teacher_count = 0; - $counter = 0; - //Iterate, filling counters - foreach ($recs as $rec) { - //Get full record, using backup_getids - $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id); - if (strpos($record->info,"new") !== false) { - $new_count++; - } - if (strpos($record->info,"exists") !== false) { - $exists_count++; - } - if (strpos($record->info,"student") !== false) { - $student_count++; - } else if (strpos($record->info,"teacher") !== false) { - $teacher_count++; - } - //Do some output - $counter++; - if ($counter % 10 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if ($counter % 200 == 0) { - echo "
      "; - } - } - backup_flush(300); - } - } - if (!defined('RESTORE_SILENTLY')) { - //Now print information gathered - echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")"; - echo "
        "; - echo "
      • ".get_string("students").": ".$student_count.'
      • '; - echo "
      • ".get_string("teachers").": ".$teacher_count.'
      • '; - echo "
      "; - } - } else { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("No users were found!"); - } // no need to return false here, it's recoverable. - } - } - - if (!defined('RESTORE_SILENTLY')) { - echo "
    • "; - } - } - - - //Now create groups as needed - if ($status and ($restore->groups == RESTORE_GROUPS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatinggroups"); - } - if (!$status = restore_create_groups($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore groups!"); - } else { - $errorstr = "Could not restore groups!"; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '; - } - } - //Now create groupings as needed if ($status and ($restore->groups == RESTORE_GROUPINGS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) { if (!defined('RESTORE_SILENTLY')) { @@ -8732,28 +6915,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - //Now create metacourse info - if ($status and $restore->metacourse) { - //Only to new courses! - if ($restore->restoreto == RESTORETO_NEW_COURSE) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingmetacoursedata"); - } - if (!$status = restore_create_metacourse($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Error creating metacourse in the course."); - } else { - $errorstr = "Error creating metacourse in the course."; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '; - } - } - } - - //Now create categories and questions as needed if ($status) { include_once("$CFG->dirroot/question/restorelib.php"); @@ -8774,32 +6935,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - //Now create user_files as needed - if ($status and ($restore->user_files)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("copyinguserfiles"); - } - if (!$status = restore_user_files($restore)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore user files!"); - } else { - $errorstr = "Could not restore user files!"; - return false; - } - } - //If all is ok (and we have a counter) - if ($status and ($status !== true)) { - //Inform about user dirs created from backup - if (!defined('RESTORE_SILENTLY')) { - echo "
        "; - echo "
      • ".get_string("userzones").": ".$status; - echo "
      "; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '; - } - } //Now create course files as needed if ($status and ($restore->course_files)) { @@ -8828,88 +6963,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - - //Now create site files as needed - if ($status and ($restore->site_files)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string('copyingsitefiles'); - } - if (!$status = restore_site_files($restore)) { - if (empty($status)) { - echo $OUTPUT->notification("Could not restore site files!"); - } else { - $errorstr = "Could not restore site files!"; - return false; - } - } - //If all is ok (and we have a counter) - if ($status and ($status !== true)) { - //Inform about user dirs created from backup - if (!defined('RESTORE_SILENTLY')) { - echo "
        "; - echo "
      • ".get_string("filesfolders").": ".$status.'
      • '; - echo "
      "; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo "
    • "; - } - } - - //Now create messages as needed - if ($status and ($restore->messages)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingmessagesinfo"); - } - if (!$status = restore_create_messages($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore messages!"); - } else { - $errorstr = "Could not restore messages!"; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo "
    • "; - } - } - - //Now create blogs as needed - if ($status and ($restore->blogs)) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingblogsinfo"); - } - if (!$status = restore_create_blogs($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore blogs!"); - } else { - $errorstr = "Could not restore blogs!"; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo "
    • "; - } - } - - //Now create scales as needed - if ($status) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingscales"); - } - if (!$status = restore_create_scales($restore,$xml_file)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not restore custom scales!"); - } else { - $errorstr = "Could not restore custom scales!"; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '; - } - } - //Now create events as needed if ($status) { if (!defined('RESTORE_SILENTLY')) { @@ -9067,25 +7120,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3); } } - //Now, with backup files prior to version 2005041100, - //convert all the wiki texts in the course to markdown - if ($status && $restore->backup_version < 2005041100) { - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("convertingwikitomarkdown"); - } - if (!$status = restore_convert_wiki2markdown($restore)) { - if (!defined('RESTORE_SILENTLY')) { - echo $OUTPUT->notification("Could not convert wiki texts to markdown!"); - } else { - $errorstr = "Could not convert wiki texts to markdown!"; - return false; - } - } - if (!defined('RESTORE_SILENTLY')) { - echo '
    • '; - } - } - //Now create gradebook as needed -- AFTER modules and blocks!!! if ($status) { if ($restore->backup_version > 2007090500) { @@ -9310,145 +7344,6 @@ WHERE /********************** Roles and Capabilities Related Functions *******************************/ - /* Yu: Note recovering of role assignments/overrides need to take place after - users have been recovered, i.e. after we get their new_id, and after all - roles have been recreated or mapped. Contexts can be created on the fly. - The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides - the order of restore among different contexts, i.e. course, mod, blocks, users should not matter - once roles and users have been restored. - */ - - /** - * This function restores all the needed roles for this course - * i.e. roles with an assignment in any of the mods or blocks, - * roles assigned on any user (e.g. parent role) and roles - * assigned at course levle - * This function should check for duplicate roles first - * It isn't now, just overwriting - */ - function restore_create_roles($restore, $xmlfile) { - global $DB, $CFG; - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingrolesdefinitions").'
    • '; - } - $info = restore_read_xml_roles($xmlfile); - - $sitecontext = get_context_instance(CONTEXT_SYSTEM); - - // the following code creates new roles - // but we could use more intelligent detection, and role mapping - // get role mapping info from $restore - $rolemappings = array(); - - if (!empty($restore->rolesmapping)) { - $rolemappings = $restore->rolesmapping; - } - // $info->roles will be empty for backups pre 1.7 - if (isset($info->roles) && $info->roles) { - - foreach ($info->roles as $oldroleid=>$roledata) { - - if (empty($restore->rolesmapping)) { - // if this is empty altogether, we came from import or there's no roles used in course at all - // in this case, write the same oldid as this is the same site - // no need to do mapping - $status = backup_putid($restore->backup_unique_code,"role",$oldroleid, - $oldroleid); // adding a new id - continue; // do not create additonal roles; - } - // first we check if the roles are in the mappings - // if so, we just do a mapping i.e. update oldids table - if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) { - $status = backup_putid($restore->backup_unique_code,"role",$oldroleid, - $rolemappings[$oldroleid]); // adding a new id - - // check for permissions before create new roles - } else if (has_capability('moodle/role:manage', get_context_instance(CONTEXT_SYSTEM))) { - - // code to make new role name/short name if same role name or shortname exists - $fullname = $roledata->name; - $shortname = $roledata->shortname; - $currentfullname = ""; - $currentshortname = ""; - $counter = 0; - - do { - if ($counter) { - $suffixfull = " ".get_string("copyasnoun")." ".$counter; - $suffixshort = "_".$counter; - } else { - $suffixfull = ""; - $suffixshort = ""; - } - $currentfullname = $fullname.$suffixfull; - // Limit the size of shortname - database column accepts <= 100 chars - $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort; - $coursefull = $DB->get_record("role", array("name"=>$currentfullname)); - $courseshort = $DB->get_record("role", array("shortname"=>$currentshortname)); - $counter++; - } while ($coursefull || $courseshort); - - $roledata->name = $currentfullname; - $roledata->shortname= $currentshortname; - - // done finding a unique name - - $newroleid = create_role($roledata->name, $roledata->shortname, ''); - $status = backup_putid($restore->backup_unique_code,"role",$oldroleid, - $newroleid); // adding a new id - - /// Restore the role contextlevels. - if (isset($roledata->contextlevels)) { - set_role_contextlevels($newroleid, $roledata->contextlevels); - } else { - // Data was not in the backup file (must be a pre-2.0 backup). - // Allow this role to be assigned at all levels, which is - // Which is what would have been possible where the backup - // was made. - set_role_contextlevels($newroleid, array(CONTEXT_SYSTEM, - CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, - CONTEXT_MODULE, CONTEXT_BLOCK)); - } - - /// Restore all the role capabiltites. - foreach ($roledata->capabilities as $capability) { - - $roleinfo = new object(); - $roleinfo = (object)$capability; - $roleinfo->contextid = $sitecontext->id; - $roleinfo->capability = $capability->name; - $roleinfo->roleid = $newroleid; - - $DB->insert_record('role_capabilities', $roleinfo); - } - } else { - // map the new role to course default role - if (!$default_role = get_field("course", "defaultrole", "id", $restore->course_id)) { - $default_role = $CFG->defaultcourseroleid; - } - $status = backup_putid($restore->backup_unique_code, "role", $oldroleid, $default_role); - } - - /// Now, restore role nameincourse (only if the role had nameincourse in backup) - if (!empty($roledata->nameincourse)) { - $newrole = backup_getid($restore->backup_unique_code, 'role', $oldroleid); /// Look for target role - $coursecontext = get_context_instance(CONTEXT_COURSE, $restore->course_id); /// Look for target context - if (!empty($newrole->new_id) && !empty($coursecontext) && !empty($roledata->nameincourse)) { - /// Check the role hasn't any custom name in context - if (!$DB->record_exists('role_names', array('roleid'=>$newrole->new_id, 'contextid'=>$coursecontext->id))) { - $rolename = new object(); - $rolename->roleid = $newrole->new_id; - $rolename->contextid = $coursecontext->id; - $rolename->name = $roledata->nameincourse; - - $DB->insert_record('role_names', $rolename); - } - } - } - } - } - return true; - } /** * this function restores role assignments and role overrides @@ -9472,122 +7367,9 @@ WHERE $isimport = false; // course restore with role assignments } - $newcoursecontext = restore_get_new_context($restore, 'course', CONTEXT_COURSE, $course->course_id); - if (!empty($course->roleassignments) && !$isimport) { - $courseassignments = $course->roleassignments; - - foreach ($courseassignments as $oldroleid => $courseassignment) { - restore_write_roleassignments($restore, $courseassignment->assignments, $newcoursecontext, $oldroleid); - } - } - /***************************************************** - * Restoring from course level overrides * - *****************************************************/ - - if (!empty($course->roleoverrides) && !$isimport) { - $courseoverrides = $course->roleoverrides; - foreach ($courseoverrides as $oldroleid => $courseoverride) { - // if not importing into exiting course, or creating new role, we are ok - // local course overrides to be respected (i.e. restored course overrides ignored) - if (($restore->restoreto != RESTORETO_CURRENT_ADDING && $restore->restoreto != RESTORETO_EXISTING_ADDING) || empty($restore->rolesmapping[$oldroleid])) { - restore_write_roleoverrides($restore, $courseoverride->overrides, $newcoursecontext, $oldroleid); - } - } - } - // Per-context filter settings. restore_write_local_filter_settings($restore, $course, $newcoursecontext); - /******************************************************* - * Restoring role assignments/overrdies * - * from module level assignments * - *******************************************************/ - - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingmodroles").'
    • '; - } - $sections = restore_read_xml_sections($xmlfile); - $secs = $sections->sections; - - foreach ($secs as $section) { - if (isset($section->mods)) { - foreach ($section->mods as $modid=>$mod) { - $newmodcontext = restore_get_new_context($restore, 'course_modules', CONTEXT_MODULE, $modid); - if (isset($mod->roleassignments) && !$isimport) { - foreach ($mod->roleassignments as $oldroleid=>$modassignment) { - restore_write_roleassignments($restore, $modassignment->assignments, $newmodcontext, $oldroleid); - } - } - // role overrides always applies, in import or backup/restore - if (isset($mod->roleoverrides)) { - foreach ($mod->roleoverrides as $oldroleid=>$modoverride) { - restore_write_roleoverrides($restore, $modoverride->overrides, $newmodcontext, $oldroleid); - } - } - // Per-context filter settings. - restore_write_local_filter_settings($restore, $mod, $newmodcontext); - } - } - } - - /************************************************* - * Restoring assignments from blocks level * - * role assignments/overrides * - *************************************************/ - - if ($restore->restoreto != RESTORETO_CURRENT_ADDING && $restore->restoreto != RESTORETO_EXISTING_ADDING) { // skip altogether if restoring to exisitng course by adding - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatingblocksroles").'
    • '; - } - $blocks = restore_read_xml_blocks($restore, $xmlfile); - if (isset($blocks->instances)) { - foreach ($blocks->instances as $instance) { - $newblockcontext = restore_get_new_context($restore, 'block_instance', CONTEXT_BLOCK, $instance->id); - if (isset($instance->roleassignments) && !$isimport) { - foreach ($instance->roleassignments as $oldroleid=>$blockassignment) { - restore_write_roleassignments($restore, $blockassignment->assignments, $newblockcontext, $oldroleid); - - } - } - // likewise block overrides should always be restored like mods - if (isset($instance->roleoverrides)) { - foreach ($instance->roleoverrides as $oldroleid=>$blockoverride) { - restore_write_roleoverrides($restore, $blockoverride->overrides, $newblockcontext, $oldroleid); - } - } - } - } - } - - /************************************************ - * Restoring assignments from userid level * - * role assignments/overrides * - ************************************************/ - if (!defined('RESTORE_SILENTLY')) { - echo "
    • ".get_string("creatinguserroles").'
    • '; - } - $info = restore_read_xml_users($restore, $xmlfile); - if (!empty($info->users) && !$isimport) { // no need to restore user assignments for imports (same course) - //For each user, take its info from backup_ids - foreach ($info->users as $userid) { - $rec = backup_getid($restore->backup_unique_code,"user",$userid); - $newusercontext = restore_get_new_context($restore, 'user', CONTEXT_USER, $userid); - if (isset($rec->info->roleassignments)) { - foreach ($rec->info->roleassignments as $oldroleid=>$userassignment) { - restore_write_roleassignments($restore, $userassignment->assignments, $newusercontext, $oldroleid); - } - } - if (isset($rec->info->roleoverrides)) { - foreach ($rec->info->roleoverrides as $oldroleid=>$useroverride) { - restore_write_roleoverrides($restore, $useroverride->overrides, $newusercontext, $oldroleid); - } - } - } - } - - return true; - } - /** * Get the context object from the site we are restoring to that corresponds * to a particular context on the site we backed up from. @@ -9610,51 +7392,6 @@ WHERE return $newcontext; } - // auxillary function to write role assignments read from xml to db - function restore_write_roleassignments($restore, $assignments, $newcontext, $oldroleid) { - - $role = backup_getid($restore->backup_unique_code, "role", $oldroleid); - - foreach ($assignments as $assignment) { - - $olduser = backup_getid($restore->backup_unique_code,"user",$assignment->userid); - //Oh dear, $olduser... can be an object, $obj->string or bool! - if (!$olduser || (is_string($olduser->info) && $olduser->info == "notincourse")) { // it's possible that user is not in the course - continue; - } - $assignment->userid = $olduser->new_id; // new userid here - $oldmodifier = backup_getid($restore->backup_unique_code,"user",$assignment->modifierid); - $assignment->modifierid = !empty($oldmodifier->new_id) ? $oldmodifier->new_id : 0; // new modifier id here - $assignment->roleid = $role->new_id; // restored new role id - - $assignment->contextid = $newcontext->id; // new context id - // might already have same assignment - role_assign($assignment->roleid, $assignment->userid, 0, $assignment->contextid, $assignment->timestart, $assignment->timeend, $assignment->hidden, $assignment->enrol, $assignment->timemodified); - - } - } - - // auxillary function to write role assignments read from xml to db - function restore_write_roleoverrides($restore, $overrides, $newcontext, $oldroleid) { - - // it is possible to have an override not relevant to this course context. - // should be ignored(?) - if (!$role = backup_getid($restore->backup_unique_code, "role", $oldroleid)) { - return null; - } - - foreach ($overrides as $override) { - $override->capability = $override->name; - $oldmodifier = backup_getid($restore->backup_unique_code,"user",$override->modifierid); - $override->modifierid = !empty($oldmodifier->new_id)?$oldmodifier->new_id:0; // new modifier id here - $override->roleid = $role->new_id; // restored new role id - - $override->contextid = $newcontext->id; // new context id - // use assign capability instead so we can add context to context_rel - assign_capability($override->capability, $override->permission, $override->roleid, $override->contextid); - } - } - /** * Write any per-context filter settings from the backup XML to the DB. * @param object $restore the restore we are part of. -- 2.43.0