/**
 *
 * @since 2.0
 * @package blocks
 * @copyright 2011 Dustin Durand
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_block_roomscheduler_upgrade($oldversion)
{
    global $DB;
    $dbman = $DB->get_manager();
    if ($oldversion < 2011150301) {
        $timenow = time();
        $sysctx = get_context_instance(CONTEXT_SYSTEM);
        /// Fully setup the Elluminate Moderator role.
        if (!($mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager')))) {
            if ($rid = create_role(get_string('roomschedulermanager', 'block_roomscheduler'), 'roomschedulemanager', get_string('roomschedulermanagerdescription', 'block_roomscheduler'))) {
                $mrole = $DB->get_record('role', array('id' => $rid));
                assign_capability('block/roomscheduler:manage', CAP_ALLOW, $mrole->id, $sysctx->id);
                set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
            } else {
                $mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager'));
                set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
            }
        }
        upgrade_block_savepoint(true, 2011150301, 'roomscheduler');
    }
    if ($oldversion < 2011140315) {
        // Define field reservable to be added to roomscheduler_rooms
        $table = new xmldb_table('roomscheduler_rooms');
        $field = new xmldb_field('reservable', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'active');
        // Conditionally launch add field reservable
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        upgrade_block_savepoint(true, 2011140315, 'roomscheduler');
    }
    return true;
}
/**
 * @package block
 * @subpackage demostudent
 * @author Dominik Royko royko@ualberta.ca
 */
function xmldb_block_demostudent_install()
{
    global $DB;
    $result = true;
    $systemcontext = context_system::instance();
    // Create DemoStudent role.
    $contextlevels = array(CONTEXT_COURSE, CONTEXT_MODULE);
    if (!($demostudentrole = $DB->get_record('role', array('shortname' => 'demostudent')))) {
        if ($roleid = create_role(get_string('roledemostudentname', 'block_demostudent'), 'demostudent', get_string('roledemostudentdescription', 'block_demostudent'), 'student')) {
            $newrole = new stdClass();
            $newrole->id = $roleid;
            // Set the capabilities to the archetype (student).
            // Caution: new capabilities un/set here can get clobbered by 'clonepermissionsfrom',
            // defined in access.php.
            reset_role_capabilities($roleid);
            // DemoStudent needs to see the DemoStudent block.
            $result = $result && assign_capability('block/demostudent:seedemostudentblock', CAP_ALLOW, $newrole->id, $systemcontext->id);
            // DemoStudent should be able to see hidden courses to facilitate testing.
            $result = $result && assign_capability('moodle/course:viewhiddencourses', CAP_ALLOW, $newrole->id, $systemcontext->id);
            // DemoStudent should NOT be able to add more demostudents!
            $result = $result && unassign_capability('block/demostudent:addinstance', $newrole->id);
            $systemcontext->mark_dirty();
            set_role_contextlevels($newrole->id, $contextlevels);
        } else {
            $result = false;
        }
    }
    return $result;
}
 /**
  * Create a test role
  *
  * @param string $name The role's display name
  * @param string $shortname The role's shortname
  * @param string $description The role's description
  * @param array $contexts The contexts at which the role should be assignable (defaults to course.
  * @return int The created role's id
  */
 private static function create_test_role($name = 'coursename', $shortname = 'courseshortname', $description = 'coursedescription', $contexts = null)
 {
     if ($contexts === null) {
         // Use default of course context.
         $contexts = array(CONTEXT_COURSE);
     }
     $roleid = create_role($name, $shortname, $description);
     set_role_contextlevels($roleid, $contexts);
     return $roleid;
 }
Example #4
0
 /**
  * Test block_elisadmin_load_menu_children_course function.
  */
 public function test_block_elisadmin_load_menu_children_course()
 {
     global $DB, $USER;
     accesslib_clear_all_caches(true);
     // Create test user - ensure the returned user is NOT a site admin. if they are, our capability restrictions won't work.
     $testuser = new user();
     $testuser->username = '******';
     $testuser->idnumber = 'testELIS4093';
     $testuser->firstname = 'testELIS4093';
     $testuser->lastname = 'testELIS4093';
     $testuser->email = '*****@*****.**';
     $testuser->country = 'CA';
     $testuser->save();
     $testmuser = $testuser->get_moodleuser();
     // Create role with cap: 'local/elisprogram:class_view'.
     $testrole = new stdClass();
     $testrole->name = 'ELIS Class View';
     $testrole->shortname = '_test_ELIS_4093';
     $testrole->description = 'ELIS Class View';
     $testrole->archetype = '';
     $testrole->id = create_role($testrole->name, $testrole->shortname, $testrole->description, $testrole->archetype);
     // Ensure our new role is assignable to ELIS class contexts.
     set_role_contextlevels($testrole->id, array(CONTEXT_ELIS_CLASS));
     // Ensure the role has our required capability assigned.
     $sitecontext = context_system::instance();
     assign_capability('local/elisprogram:class_view', CAP_ALLOW, $testrole->id, $sitecontext->id, true);
     $sitecontext->mark_dirty();
     // Create ELIS Course Description.
     $testcrs = new course(array('name' => 'CD-ELIS-4093', 'idnumber' => 'CDELIS4093', 'syllabus' => ''));
     $testcrs->save();
     $testcrs->load();
     // Create three(3) Class Instances for Course Descrption.
     $testcls1 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.1'));
     $testcls1->save();
     $testcls1->load();
     $testcls2 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.2'));
     $testcls2->save();
     $testcls2->load();
     $testcls3 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.3'));
     $testcls3->save();
     $testcls3->load();
     // Assign testuser new role in one Class Instance.
     $context = \local_elisprogram\context\pmclass::instance($testcls2->id);
     role_assign($testrole->id, $testmuser->id, $context->id);
     // Switch to testuser.
     $USER = $testmuser;
     $this->setUser($testmuser);
     $items = block_elisadmin_load_menu_children_course($testcrs->id, 0, 0, 5, '');
     $this->assertEquals(1, count($items));
     $this->assertTrue($items[0]->name == 'pmclass_2');
 }
function xmldb_block_roomscheduler_install()
{
    global $DB;
    $timenow = time();
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    /// Fully setup the Elluminate Moderator role.
    if (!($mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager')))) {
        if ($rid = create_role(get_string('roomschedulermanager', 'block_roomscheduler'), 'roomschedulemanager', get_string('roomschedulermanagerdescription', 'block_roomscheduler'))) {
            $mrole = $DB->get_record('role', array('id' => $rid));
            assign_capability('block/roomscheduler:manage', CAP_ALLOW, $mrole->id, $sysctx->id);
            //Only assignable at system level
            set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
        } else {
            $mrole = $DB->get_record('role', array('shortname' => 'roomschedulermanager'));
            set_role_contextlevels($mrole->id, array(CONTEXT_SYSTEM));
        }
    }
}
Example #6
0
function xmldb_enrol_category_install()
{
    global $CFG, $DB;
    if (!$DB->record_exists_select('role_assignments', "contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array(CONTEXT_COURSECAT))) {
        // fresh install or nobody used category enrol
        return;
    }
    // existing sites need a way to keep category role enrols, but we do not want to encourage that on new sites
    // extremely ugly hack, the sync depends on the capabilities so we unfortunately force update of caps here
    // note: this is not officially supported and should not be copied elsewhere! :-(
    update_capabilities('enrol_category');
    $syscontext = get_context_instance(CONTEXT_SYSTEM);
    $archetypes = array('student', 'teacher', 'editingteacher');
    $enableplugin = false;
    foreach ($archetypes as $archetype) {
        $roles = get_archetype_roles($archetype);
        foreach ($roles as $role) {
            if (!$DB->record_exists_select('role_assignments', "roleid = ? AND contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array($role->id, CONTEXT_COURSECAT))) {
                continue;
            }
            assign_capability('enrol/category:synchronised', CAP_ALLOW, $role->id, $syscontext->id, true);
            $levels = get_role_contextlevels($role->id);
            $levels[] = CONTEXT_COURSECAT;
            set_role_contextlevels($role->id, $levels);
            $enableplugin = true;
        }
    }
    if (!$enableplugin) {
        return;
    }
    // enable this plugin
    $enabledplugins = explode(',', $CFG->enrol_plugins_enabled);
    $enabledplugins[] = 'category';
    $enabledplugins = array_unique($enabledplugins);
    set_config('enrol_plugins_enabled', implode(',', $enabledplugins));
    // brute force course resync, this may take a while
    require_once "{$CFG->dirroot}/enrol/category/locallib.php";
    enrol_category_sync_full();
}
/**
 * @package mod
 * @subpackage adobeconnect
 * @author Akinsaya Delamarre (adelamarre@remote-learner.net)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_adobeconnect_install()
{
    global $DB;
    // The commented out code is waiting for a fix for MDL-25709
    $result = true;
    $timenow = time();
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    $mrole = new stdClass();
    $levels = array(CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE);
    $param = array('shortname' => 'coursecreator');
    $coursecreatorrid = $DB->get_record('role', $param);
    $param = array('shortname' => 'editingteacher');
    $editingteacherrid = $DB->get_record('role', $param);
    $param = array('shortname' => 'teacher');
    $teacherrid = $DB->get_record('role', $param);
    /// Fully setup the Adobe Connect Presenter role.
    $param = array('shortname' => 'adobeconnectpresenter');
    if (!($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnectpresenter', 'adobeconnect'), 'adobeconnectpresenter', get_string('adobeconnectpresenterdescription', 'adobeconnect'), 'adobeconnectpresenter')) {
            $mrole->id = $rid;
            $result = assign_capability('mod/adobeconnect:meetingpresenter', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($coursecreatorrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($editingteacherrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($teacherrid->id, $mrole->id);
    }
    /// Fully setup the Adobe Connect Participant role.
    $param = array('shortname' => 'adobeconnectparticipant');
    if (!($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnectparticipant', 'adobeconnect'), 'adobeconnectparticipant', get_string('adobeconnectparticipantdescription', 'adobeconnect'), 'adobeconnectparticipant')) {
            $mrole->id = $rid;
            $result = assign_capability('mod/adobeconnect:meetingparticipant', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($coursecreatorrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($editingteacherrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($teacherrid->id, $mrole->id);
    }
    /// Fully setup the Adobe Connect Host role.
    $param = array('shortname' => 'adobeconnecthost');
    if (!($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnecthost', 'adobeconnect'), 'adobeconnecthost', get_string('adobeconnecthostdescription', 'adobeconnect'), 'adobeconnecthost')) {
            $mrole->id = $rid;
            $result = assign_capability('mod/adobeconnect:meetinghost', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($coursecreatorrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($editingteacherrid->id, $mrole->id);
    }
    $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
    if (!$DB->get_record('role_allow_assign', $param)) {
        $result = allow_assign($teacherrid->id, $mrole->id);
    }
    return $result;
}
 /**
  * Creates a test role, assignable at all necessary context levels
  *
  * @param string $fullname The new role's fullname
  * @param string $shortname The new role's shortname
  * @param string $description The new role's description
  * @return int The database record id of the created course
  */
 private function create_test_role($fullname = 'rlipfullname', $shortname = 'rlipshortname', $description = 'rlipdescription')
 {
     // Create the role.
     $roleid = create_role($fullname, $shortname, $description);
     // Make it assignable at all necessary contexts.
     $contexts = array(CONTEXT_COURSE, CONTEXT_COURSECAT, CONTEXT_USER, CONTEXT_SYSTEM);
     set_role_contextlevels($roleid, $contexts);
     return $roleid;
 }
 /**
  * Validate that when the "create or update" flag is enabled, update
  * actions can not create enrolments
  */
 public function test_version1createorupdatedoesnotcreateenrolmentfromupdateaction()
 {
     global $DB;
     // Set up initial conditions.
     set_config('createorupdate', 1, 'dhimport_version1');
     // Initial data setup.
     $userid = $this->create_test_user();
     $courseid = $this->create_test_course();
     $context = context_course::instance($courseid);
     $roleid = create_role('rlipname', 'rlipshortname', 'rlipdescription');
     set_role_contextlevels($roleid, array(CONTEXT_COURSE));
     // Validate that updates are not converted to creates for enrolments.
     $importdata = array('entity' => 'enrolment', 'action' => 'update', 'username' => 'rlipusername', 'context' => 'course', 'instance' => 'rlipshortname', 'role' => 'rlipshortname');
     $this->run_core_enrolment_import($importdata);
     $this->assertEquals($DB->count_records('role_assignments'), 0);
 }
Example #10
0
 /**
  * Method to test function /local/elisprogram/lib/lib.php::pm_get_select_roles_for_contexts()
  * part of ELIS-8341
  * @param array $testroles array of role 'objects' to create
  * @param array $passedcontexts  array of contexts to pass to function under  test
  * @param array $expectedresults associative array of selectable roles: roleshortname => rolename
  * @uses $DB
  * @dataProvider pm_get_select_roles_data_provider
  */
 public function test_pm_get_select_roles($testroles, $passedcontexts, $expectedresults)
 {
     global $DB;
     $id2shortname = array();
     // Create specified roles.
     foreach ($testroles as $testrole) {
         $roleid = create_role($testrole['name'], $testrole['shortname'], 'Default role description');
         // Assign role capabilities.
         foreach ($testrole['caps'] as $cap => $perm) {
             assign_capability($cap, $perm, $roleid, 1, true);
         }
         // Create assignable contexts array & assign.
         $contexts = array();
         foreach ($testrole['contexts'] as $contextlevel) {
             $contexts[$contextlevel] = $contextlevel;
         }
         set_role_contextlevels($roleid, $contexts);
         // Save roleid for later conversion.
         $id2shortname[$roleid] = $testrole['shortname'];
     }
     // Call test function.
     $results = array();
     pm_get_select_roles_for_contexts($results, $passedcontexts);
     // Convert roleid to roleshortname to validate.
     foreach ($results as $id => $name) {
         if (isset($id2shortname[$id])) {
             $results[$id2shortname[$id]] = $name;
         }
         unset($results[$id]);
     }
     $this->assertEquals($expectedresults, $results);
 }
Example #11
0
function xmldb_main_upgrade($oldversion)
{
    global $CFG, $THEME, $USER, $DB, $OUTPUT;
    require_once $CFG->libdir . '/db/upgradelib.php';
    // Core Upgrade-related functions
    $result = true;
    $dbman = $DB->get_manager();
    // loads ddl manager and xmldb classes
    ////////////////////////////////////////
    ///upgrade supported only from 1.9.x ///
    ////////////////////////////////////////
    if ($result && $oldversion < 2008030600) {
        //NOTE: this table was added much later, that is why this step is repeated later in this file
        /// Define table upgrade_log to be created
        $table = new xmldb_table('upgrade_log');
        /// Adding fields to table upgrade_log
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('type', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('plugin', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('version', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('details', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('backtrace', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table upgrade_log
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table upgrade_log
        $table->add_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        $table->add_index('type-timemodified', XMLDB_INDEX_NOTUNIQUE, array('type', 'timemodified'));
        /// Create table for upgrade_log
        $dbman->create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008030600);
    }
    if ($result && $oldversion < 2008030700) {
        upgrade_set_timeout(60 * 20);
        // this may take a while
        /// Define index contextid-lowerboundary (not unique) to be dropped form grade_letters
        $table = new xmldb_table('grade_letters');
        $index = new xmldb_index('contextid-lowerboundary', XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
        /// Launch drop index contextid-lowerboundary
        $dbman->drop_index($table, $index);
        /// Define index contextid-lowerboundary-letter (unique) to be added to grade_letters
        $table = new xmldb_table('grade_letters');
        $index = new xmldb_index('contextid-lowerboundary-letter', XMLDB_INDEX_UNIQUE, array('contextid', 'lowerboundary', 'letter'));
        /// Launch add index contextid-lowerboundary-letter
        $dbman->add_index($table, $index);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008030700);
    }
    if ($result && $oldversion < 2008050100) {
        // Update courses that used weekscss to weeks
        $result = $DB->set_field('course', 'format', 'weeks', array('format' => 'weekscss'));
        upgrade_main_savepoint($result, 2008050100);
    }
    if ($result && $oldversion < 2008050200) {
        // remove unused config options
        unset_config('statsrolesupgraded');
        upgrade_main_savepoint($result, 2008050200);
    }
    if ($result && $oldversion < 2008050700) {
        upgrade_set_timeout(60 * 20);
        // this may take a while
        /// Fix minor problem caused by MDL-5482.
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_fix_random_question_parents();
        upgrade_main_savepoint($result, 2008050700);
    }
    if ($result && $oldversion < 2008051200) {
        // if guest role used as default user role unset it and force admin to choose new setting
        if (!empty($CFG->defaultuserroleid)) {
            if ($role = $DB->get_record('role', array('id' => $CFG->defaultuserroleid))) {
                if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
                    if (isset($guestroles[$role->id])) {
                        set_config('defaultuserroleid', null);
                        echo $OUTPUT->notification('Guest role removed from "Default role for all users" setting, please select another role.', 'notifysuccess');
                    }
                }
            } else {
                set_config('defaultuserroleid', null);
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008051200);
    }
    if ($result && $oldversion < 2008051201) {
        echo $OUTPUT->notification('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
        upgrade_set_timeout(60 * 20);
        // this may take a while
        /// Under MySQL and Postgres... detect old NULL contents and change them by correct empty string. MDL-14859
        $dbfamily = $DB->get_dbfamily();
        if ($dbfamily === 'mysql' || $dbfamily === 'postgres') {
            $DB->execute("UPDATE {user} SET idnumber = '' WHERE idnumber IS NULL");
        }
        /// Define index idnumber (not unique) to be dropped form user
        $table = new xmldb_table('user');
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        /// Changing precision of field idnumber on table user to (255)
        $table = new xmldb_table('user');
        $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'password');
        /// Launch change of precision for field idnumber
        $dbman->change_field_precision($table, $field);
        /// Launch add index idnumber again
        $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        $dbman->add_index($table, $index);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008051201);
    }
    if ($result && $oldversion < 2008051202) {
        $log_action = new object();
        $log_action->module = 'course';
        $log_action->action = 'unenrol';
        $log_action->mtable = 'course';
        $log_action->field = 'fullname';
        if (!$DB->record_exists('log_display', array('action' => 'unenrol', 'module' => 'course'))) {
            $result = $result && $DB->insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2008051202);
    }
    if ($result && $oldversion < 2008051203) {
        $table = new xmldb_table('mnet_enrol_course');
        $field = new xmldb_field('sortorder', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0);
        $dbman->change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2008051203);
    }
    if ($result && $oldversion < 2008063001) {
        upgrade_set_timeout(60 * 20);
        // this may take a while
        // table to be modified
        $table = new xmldb_table('tag_instance');
        // add field
        $field = new xmldb_field('tiuserid');
        if (!$dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0, 'itemid');
            $dbman->add_field($table, $field);
        }
        // modify index
        $index = new xmldb_index('itemtype-itemid-tagid');
        $index->set_attributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid'));
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        $index = new xmldb_index('itemtype-itemid-tagid-tiuserid');
        $index->set_attributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid', 'tiuserid'));
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008063001);
    }
    if ($result && $oldversion < 2008070300) {
        $result = $DB->delete_records_select('role_names', $DB->sql_isempty('role_names', 'name', false, false));
        upgrade_main_savepoint($result, 2008070300);
    }
    if ($result && $oldversion < 2008070700) {
        if (isset($CFG->defaultuserroleid) and isset($CFG->guestroleid) and $CFG->defaultuserroleid == $CFG->guestroleid) {
            // guest can not be selected in defaultuserroleid!
            unset_config('defaultuserroleid');
        }
        upgrade_main_savepoint($result, 2008070700);
    }
    if ($result && $oldversion < 2008070701) {
        /// Define table portfolio_instance to be created
        $table = new xmldb_table('portfolio_instance');
        /// Adding fields to table portfolio_instance
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('plugin', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1');
        /// Adding keys to table portfolio_instance
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for portfolio_instance
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Define table portfolio_instance_config to be created
        $table = new xmldb_table('portfolio_instance_config');
        /// Adding fields to table portfolio_instance_config
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        /// Adding keys to table portfolio_instance_config
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('instance', XMLDB_KEY_FOREIGN, array('instance'), 'portfolio_instance', array('id'));
        /// Adding indexes to table portfolio_instance_config
        $table->add_index('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        /// Conditionally launch create table for portfolio_instance_config
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Define table portfolio_instance_user to be created
        $table = new xmldb_table('portfolio_instance_user');
        /// Adding fields to table portfolio_instance_user
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
        $table->add_field('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        /// Adding keys to table portfolio_instance_user
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('instancefk', XMLDB_KEY_FOREIGN, array('instance'), 'portfolio_instance', array('id'));
        $table->add_key('userfk', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Conditionally launch create table for portfolio_instance_user
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008070701);
    }
    if ($result && $oldversion < 2008072400) {
        /// Create the database tables for message_processors
        $table = new xmldb_table('message_processors');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null);
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $dbman->create_table($table);
        /// delete old and create new fields
        $table = new xmldb_table('message');
        $field = new xmldb_field('messagetype');
        $dbman->drop_field($table, $field);
        /// fields to rename
        $field = new xmldb_field('message');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->rename_field($table, $field, 'fullmessage');
        $field = new xmldb_field('format');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, '0', null);
        $dbman->rename_field($table, $field, 'fullmessageformat');
        /// new message fields
        $field = new xmldb_field('subject');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->add_field($table, $field);
        $field = new xmldb_field('fullmessagehtml');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null);
        $dbman->add_field($table, $field);
        $field = new xmldb_field('smallmessage');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->add_field($table, $field);
        $table = new xmldb_table('message_read');
        $field = new xmldb_field('messagetype');
        $dbman->drop_field($table, $field);
        $field = new xmldb_field('mailed');
        $dbman->drop_field($table, $field);
        /// fields to rename
        $field = new xmldb_field('message');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->rename_field($table, $field, 'fullmessage');
        $field = new xmldb_field('format');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, '0', null);
        $dbman->rename_field($table, $field, 'fullmessageformat');
        /// new message fields
        $field = new xmldb_field('subject');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->add_field($table, $field);
        $field = new xmldb_field('fullmessagehtml');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null);
        $dbman->add_field($table, $field);
        $field = new xmldb_field('smallmessage');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null);
        $dbman->add_field($table, $field);
        /// new table
        $table = new xmldb_table('message_working');
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('unreadmessageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('processorid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $dbman->create_table($table);
        upgrade_main_savepoint($result, 2008072400);
    }
    if ($result && $oldversion < 2008072800) {
        /// Define field enablecompletion to be added to course
        $table = new xmldb_table('course');
        $field = new xmldb_field('enablecompletion');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'defaultrole');
        /// Launch add field enablecompletion
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field completion to be added to course_modules
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('completion');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'groupmembersonly');
        /// Launch add field completion
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field completiongradeitemnumber to be added to course_modules
        $field = new xmldb_field('completiongradeitemnumber');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'completion');
        /// Launch add field completiongradeitemnumber
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field completionview to be added to course_modules
        $field = new xmldb_field('completionview');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completiongradeitemnumber');
        /// Launch add field completionview
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field completionexpected to be added to course_modules
        $field = new xmldb_field('completionexpected');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completionview');
        /// Launch add field completionexpected
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define table course_modules_completion to be created
        $table = new xmldb_table('course_modules_completion');
        if (!$dbman->table_exists($table)) {
            /// Adding fields to table course_modules_completion
            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
            $table->add_field('coursemoduleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
            $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
            $table->add_field('completionstate', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
            $table->add_field('viewed', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null);
            $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
            /// Adding keys to table course_modules_completion
            $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
            /// Adding indexes to table course_modules_completion
            $table->add_index('coursemoduleid', XMLDB_INDEX_NOTUNIQUE, array('coursemoduleid'));
            $table->add_index('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
            /// Launch create table for course_modules_completion
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008072800);
    }
    if ($result && $oldversion < 2008073000) {
        /// Define table portfolio_log to be created
        $table = new xmldb_table('portfolio_log');
        /// Adding fields to table portfolio_log
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('portfolio', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('caller_class', XMLDB_TYPE_CHAR, '150', null, XMLDB_NOTNULL, null, null);
        $table->add_field('caller_file', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('caller_sha1', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        /// Adding keys to table portfolio_log
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userfk', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->add_key('portfoliofk', XMLDB_KEY_FOREIGN, array('portfolio'), 'portfolio_instance', array('id'));
        /// Conditionally launch create table for portfolio_log
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008073000);
    }
    if ($result && $oldversion < 2008073104) {
        /// Drop old table that might exist for some people
        $table = new xmldb_table('message_providers');
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        /// Define table message_providers to be created
        $table = new xmldb_table('message_providers');
        /// Adding fields to table message_providers
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('component', XMLDB_TYPE_CHAR, '200', null, XMLDB_NOTNULL, null, null);
        $table->add_field('capability', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        /// Adding keys to table message_providers
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table message_providers
        $table->add_index('componentname', XMLDB_INDEX_UNIQUE, array('component', 'name'));
        /// Create table for message_providers
        $dbman->create_table($table);
        upgrade_main_savepoint($result, 2008073104);
    }
    if ($result && $oldversion < 2008073111) {
        /// Define table files to be created
        $table = new xmldb_table('files');
        /// Adding fields to table files
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('contenthash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
        $table->add_field('pathnamehash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('filearea', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, null, null);
        $table->add_field('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('filepath', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('filename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('filesize', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('mimetype', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('status', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table files
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table files
        $table->add_index('filearea-contextid-itemid', XMLDB_INDEX_NOTUNIQUE, array('filearea', 'contextid', 'itemid'));
        $table->add_index('contenthash', XMLDB_INDEX_NOTUNIQUE, array('contenthash'));
        $table->add_index('pathnamehash', XMLDB_INDEX_UNIQUE, array('pathnamehash'));
        /// Conditionally launch create table for files
        $dbman->create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008073111);
    }
    if ($result && $oldversion < 2008073113) {
        /// move all course, backup and other files to new filepool based storage
        upgrade_migrate_files_courses();
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008073113);
    }
    if ($result && $oldversion < 2008073114) {
        /// move all course, backup and other files to new filepool based storage
        upgrade_migrate_files_blog();
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008073114);
    }
    if ($result && $oldversion < 2008080400) {
        // Add field ssl_jump_url to mnet application, and populate existing default applications
        $table = new xmldb_table('mnet_application');
        $field = new xmldb_field('sso_jump_url');
        if (!$dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
            $dbman->add_field($table, $field);
            $result = $DB->set_field('mnet_application', 'sso_jump_url', '/auth/mnet/jump.php', array('name' => 'moodle'));
            $result = $result && $DB->set_field('mnet_application', 'sso_jump_url', '/auth/xmlrpc/jump.php', array('name' => 'mahara'));
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008080400);
    }
    if ($result && $oldversion < 2008080500) {
        /// Define table portfolio_tempdata to be created
        $table = new xmldb_table('portfolio_tempdata');
        /// Adding fields to table portfolio_tempdata
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('data', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        /// Adding keys to table portfolio_tempdata
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for portfolio_tempdata
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008080500);
    }
    if ($result && $oldversion < 2008080600) {
        $DB->delete_records('portfolio_tempdata');
        // there shouldnt' be any, and it will cause problems with this upgrade.
        /// Define field expirytime to be added to portfolio_tempdata
        $table = new xmldb_table('portfolio_tempdata');
        $field = new xmldb_field('expirytime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, 'data');
        /// Conditionally launch add field expirytime
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008080600);
    }
    if ($result && $oldversion < 2008081500) {
        /// Changing the type of all the columns that the question bank uses to store grades to be NUMBER(12, 7).
        $table = new xmldb_table('question');
        $field = new xmldb_field('defaultgrade', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'generalfeedback');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081500);
    }
    if ($result && $oldversion < 2008081501) {
        $table = new xmldb_table('question');
        $field = new xmldb_field('penalty', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'defaultgrade');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081501);
    }
    if ($result && $oldversion < 2008081502) {
        $table = new xmldb_table('question_answers');
        $field = new xmldb_field('fraction', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'answer');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081502);
    }
    if ($result && $oldversion < 2008081503) {
        $table = new xmldb_table('question_sessions');
        $field = new xmldb_field('sumpenalty', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'newgraded');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081503);
    }
    if ($result && $oldversion < 2008081504) {
        $table = new xmldb_table('question_states');
        $field = new xmldb_field('grade', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'event');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081504);
    }
    if ($result && $oldversion < 2008081505) {
        $table = new xmldb_table('question_states');
        $field = new xmldb_field('raw_grade', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'grade');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081505);
    }
    if ($result && $oldversion < 2008081506) {
        $table = new xmldb_table('question_states');
        $field = new xmldb_field('penalty', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null, 'raw_grade');
        $dbman->change_field_type($table, $field);
        upgrade_main_savepoint($result, 2008081506);
    }
    if ($result && $oldversion < 2008081600) {
        /// all 1.9 sites and fresh installs must already be unicode, not needed anymore
        unset_config('unicodedb');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008081600);
    }
    if ($result && $oldversion < 2008081900) {
        /// Define field userid to be added to portfolio_tempdata
        $table = new xmldb_table('portfolio_tempdata');
        $field = new xmldb_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'expirytime');
        /// Conditionally launch add field userid
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        $DB->set_field('portfolio_tempdata', 'userid', 0);
        /// now change it to be notnull
        /// Changing nullability of field userid on table portfolio_tempdata to not null
        $field = new xmldb_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, 'expirytime');
        /// Launch change of nullability for field userid
        $dbman->change_field_notnull($table, $field);
        /// Define key userfk (foreign) to be added to portfolio_tempdata
        $table = new xmldb_table('portfolio_tempdata');
        $key = new xmldb_key('userfk', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch add key userfk
        $dbman->add_key($table, $key);
        upgrade_main_savepoint($result, 2008081900);
    }
    if ($result && $oldversion < 2008082602) {
        /// Define table repository to be dropped
        $table = new xmldb_table('repository');
        /// Conditionally launch drop table for repository
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        /// Define table repository to be created
        $table = new xmldb_table('repository');
        /// Adding fields to table repository
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('type', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, '1');
        $table->add_field('sortorder', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        /// Adding keys to table repository
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for repository
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Define table repository_instances to be created
        $table = new xmldb_table('repository_instances');
        /// Adding fields to table repository_instances
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('typeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('username', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('password', XMLDB_TYPE_CHAR, '255', null, null, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        /// Adding keys to table repository_instances
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for repository_instances
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Define table repository_instance_config to be created
        $table = new xmldb_table('repository_instance_config');
        /// Adding fields to table repository_instance_config
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('instanceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        /// Adding keys to table repository_instance_config
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for repository_instance_config
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008082602);
    }
    if ($result && $oldversion < 2008082700) {
        /// Add a new column to the question sessions table to record whether a
        /// question has been flagged.
        /// Define field flagged to be added to question_sessions
        $table = new xmldb_table('question_sessions');
        $field = new xmldb_field('flagged', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'manualcomment');
        /// Conditionally launch add field flagged
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008082700);
    }
    if ($result && $oldversion < 2008082900) {
        /// Changing precision of field parent_type on table mnet_rpc to (20)
        $table = new xmldb_table('mnet_rpc');
        $field = new xmldb_field('parent_type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, 'xmlrpc_path');
        /// Launch change of precision for field parent_type
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008082900);
    }
    if ($result && $oldversion < 2008090108) {
        $repo = new object();
        $repo->type = 'upload';
        $repo->visible = 1;
        $repo->sortorder = 1;
        if (!$DB->record_exists('repository', array('type' => 'upload'))) {
            $typeid = $DB->insert_record('repository', $repo);
        } else {
            $record = $DB->get_record('repository', array('type' => 'upload'));
            $typeid = $record->id;
        }
        if (!$DB->record_exists('repository_instances', array('typeid' => $typeid))) {
            $instance = new object();
            $instance->name = get_string('repositoryname', 'repository_upload');
            $instance->typeid = $typeid;
            $instance->userid = 0;
            $instance->contextid = SITEID;
            $instance->timecreated = time();
            $instance->timemodified = time();
            $result = $result && $DB->insert_record('repository_instances', $instance);
        }
        $repo->type = 'local';
        $repo->visible = 1;
        $repo->sortorder = 1;
        if (!$DB->record_exists('repository', array('type' => 'local'))) {
            $typeid = $DB->insert_record('repository', $repo);
        } else {
            $record = $DB->get_record('repository', array('type' => 'local'));
            $typeid = $record->id;
        }
        if (!$DB->record_exists('repository_instances', array('typeid' => $typeid))) {
            $instance = new object();
            $instance->name = get_string('repositoryname', 'repository_local');
            $instance->typeid = $typeid;
            $instance->userid = 0;
            $instance->contextid = SITEID;
            $instance->timecreated = time();
            $instance->timemodified = time();
            $result = $result && $DB->insert_record('repository_instances', $instance);
        }
        upgrade_main_savepoint($result, 2008090108);
    }
    // MDL-16411 Move all plugintype_pluginname_version values from config to config_plugins.
    if ($result && $oldversion < 2008091000) {
        foreach (get_object_vars($CFG) as $name => $value) {
            if (substr($name, strlen($name) - 8) !== '_version') {
                continue;
            }
            $pluginname = substr($name, 0, strlen($name) - 8);
            if (!strpos($pluginname, '_')) {
                // Skip things like backup_version that don't contain an extra _
                continue;
            }
            if ($pluginname == 'enrol_ldap_version') {
                // Special case - this is something different from a plugin version number.
                continue;
            }
            if (!preg_match('/^\\d{10}$/', $value)) {
                // Extra safety check, skip anything that does not look like a Moodle
                // version number (10 digits).
                continue;
            }
            $result = $result && set_config('version', $value, $pluginname);
            $result = $result && unset_config($name);
        }
        upgrade_main_savepoint($result, 2008091000);
    }
    //Add a readonly field to the repository_instances table
    //in order to support instance created automatically by a repository plugin
    if ($result && $oldversion < 2008091611) {
        /// Define field readonly to be added to repository_instances
        $table = new xmldb_table('repository_instances');
        $field = new xmldb_field('readonly', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'timemodified');
        /// Conditionally launch add field readonly
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008091611);
    }
    if ($result && $oldversion < 2008092300) {
        unset_config('editorspelling');
        unset_config('editordictionary');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008092300);
    }
    if ($result && $oldversion < 2008101000) {
        /// Changing the default of field lang on table user to en_utf8
        $table = new xmldb_table('user');
        $field = new xmldb_field('lang', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'en_utf8', 'country');
        /// Launch change of default for field lang
        $dbman->change_field_default($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008101000);
    }
    if ($result && $oldversion < 2008101300) {
        if (!get_config(NULL, 'statsruntimedays')) {
            set_config('statsruntimedays', '31');
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008101300);
    }
    /// New table for storing which roles can be assigned in which contexts.
    if ($result && $oldversion < 2008110601) {
        /// Define table role_context_levels to be created
        $table = new xmldb_table('role_context_levels');
        /// Adding fields to table role_context_levels
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('contextlevel', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table role_context_levels
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('contextlevel-roleid', XMLDB_KEY_UNIQUE, array('contextlevel', 'roleid'));
        $table->add_key('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        /// Conditionally launch create table for role_context_levels
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008110601);
    }
    /// Now populate the role_context_levels table with the defaults that match
    /// moodle_install_roles, and any other combinations that exist in this system.
    if ($result && $oldversion < 2008110602) {
        $roleids = $DB->get_records_menu('role', array(), '', 'shortname,id');
        /// Defaults, should match moodle_install_roles.
        $rolecontextlevels = array();
        if (isset($roleids['admin'])) {
            $rolecontextlevels[$roleids['admin']] = get_default_contextlevels('admin');
        }
        if (isset($roleids['coursecreator'])) {
            $rolecontextlevels[$roleids['coursecreator']] = get_default_contextlevels('coursecreator');
        }
        if (isset($roleids['editingteacher'])) {
            $rolecontextlevels[$roleids['editingteacher']] = get_default_contextlevels('editingteacher');
        }
        if (isset($roleids['teacher'])) {
            $rolecontextlevels[$roleids['teacher']] = get_default_contextlevels('teacher');
        }
        if (isset($roleids['student'])) {
            $rolecontextlevels[$roleids['student']] = get_default_contextlevels('student');
        }
        if (isset($roleids['guest'])) {
            $rolecontextlevels[$roleids['guest']] = get_default_contextlevels('guest');
        }
        if (isset($roleids['user'])) {
            $rolecontextlevels[$roleids['user']] = get_default_contextlevels('user');
        }
        /// See what other role assignments are in this database, extend the allowed
        /// lists to allow them too.
        $existingrolecontextlevels = $DB->get_recordset_sql('SELECT DISTINCT ra.roleid, con.contextlevel FROM
                {role_assignments} ra JOIN {context} con ON ra.contextid = con.id');
        foreach ($existingrolecontextlevels as $rcl) {
            if (!isset($rolecontextlevels[$rcl->roleid])) {
                $rolecontextlevels[$rcl->roleid] = array($rcl->contextlevel);
            } else {
                if (!in_array($rcl->contextlevel, $rolecontextlevels[$rcl->roleid])) {
                    $rolecontextlevels[$rcl->roleid][] = $rcl->contextlevel;
                }
            }
        }
        /// Put the data into the database.
        foreach ($rolecontextlevels as $roleid => $contextlevels) {
            set_role_contextlevels($roleid, $contextlevels);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008110602);
    }
    /// Remove any role overrides for moodle/site:doanything, or any permissions
    /// for it in a role without legacy:admin.
    if ($result && $oldversion < 2008110603) {
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        // Remove all overrides.
        $DB->delete_records_select('role_capabilities', 'capability = ? AND contextid <> ?', array('moodle/site:doanything', $systemcontext->id));
        // Get the ids of all the roles that are moodle/legacy:admin.
        $adminroleids = $DB->get_records_menu('role_capabilities', array('capability' => 'moodle/legacy:admin', 'permission' => 1, 'contextid' => $systemcontext->id), '', 'id, roleid');
        // Remove moodle/site:doanything from all other roles.
        list($notroletest, $params) = $DB->get_in_or_equal($adminroleids, SQL_PARAMS_QM, '', false);
        $DB->delete_records_select('role_capabilities', "roleid {$notroletest} AND capability = ? AND contextid = ?", array_merge($params, array('moodle/site:doanything', $systemcontext->id)));
        // Ensure that for all admin-y roles, the permission for moodle/site:doanything is 1
        list($isroletest, $params) = $DB->get_in_or_equal($adminroleids);
        $DB->set_field_select('role_capabilities', 'permission', 1, "roleid {$isroletest} AND capability = ? AND contextid = ?", array_merge($params, array('moodle/site:doanything', $systemcontext->id)));
        // And for any admin-y roles where moodle/site:doanything is not set, set it.
        $doanythingroleids = $DB->get_records_menu('role_capabilities', array('capability' => 'moodle/site:doanything', 'permission' => 1, 'contextid' => $systemcontext->id), '', 'id, roleid');
        foreach ($adminroleids as $roleid) {
            if (!in_array($roleid, $doanythingroleids)) {
                $rc = new stdClass();
                $rc->contextid = $systemcontext->id;
                $rc->roleid = $roleid;
                $rc->capability = 'moodle/site:doanything';
                $rc->permission = 1;
                $rc->timemodified = time();
                $DB->insert_record('role_capabilities', $rc);
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008110603);
    }
    /// Drop the deprecated teacher, teachers, student and students columns from the course table.
    if ($result && $oldversion < 2008111200) {
        $table = new xmldb_table('course');
        /// Conditionally launch drop field teacher
        $field = new xmldb_field('teacher');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Conditionally launch drop field teacher
        $field = new xmldb_field('teachers');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Conditionally launch drop field teacher
        $field = new xmldb_field('student');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Conditionally launch drop field teacher
        $field = new xmldb_field('students');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008111200);
    }
    /// Add a unique index to the role.name column.
    if ($result && $oldversion < 2008111800) {
        /// Define index name (unique) to be added to role
        $table = new xmldb_table('role');
        $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name'));
        /// Conditionally launch add index name
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008111800);
    }
    /// Add a unique index to the role.shortname column.
    if ($result && $oldversion < 2008111801) {
        /// Define index shortname (unique) to be added to role
        $table = new xmldb_table('role');
        $index = new xmldb_index('shortname', XMLDB_INDEX_UNIQUE, array('shortname'));
        /// Conditionally launch add index shortname
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008111801);
    }
    if ($result && $oldversion < 2008120700) {
        /// Changing precision of field shortname on table course_request to (100)
        $table = new xmldb_table('course_request');
        $field = new xmldb_field('shortname', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'fullname');
        /// Before changing the field, drop dependent indexes
        /// Define index shortname (not unique) to be dropped form course_request
        $index = new xmldb_index('shortname', XMLDB_INDEX_NOTUNIQUE, array('shortname'));
        /// Conditionally launch drop index shortname
        if ($dbman->index_exists($table, $index)) {
            $dbman->drop_index($table, $index);
        }
        /// Launch change of precision for field shortname
        $dbman->change_field_precision($table, $field);
        /// After changing the field, recreate dependent indexes
        /// Define index shortname (not unique) to be added to course_request
        $index = new xmldb_index('shortname', XMLDB_INDEX_NOTUNIQUE, array('shortname'));
        /// Conditionally launch add index shortname
        if (!$dbman->index_exists($table, $index)) {
            $dbman->add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008120700);
    }
    /// For MDL-17501. Ensure that any role that has moodle/course:update also
    /// has moodle/course:visibility.
    if ($result && $oldversion < 2008120800) {
        /// Get the roles with 'moodle/course:update'.
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
        /// Give those roles 'moodle/course:visibility'.
        foreach ($roles as $role) {
            assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
        }
        /// Force all sessions to refresh access data.
        mark_context_dirty($systemcontext->path);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008120800);
    }
    if ($result && $oldversion < 2008120801) {
        /// Changing precision of field shortname on table mnet_enrol_course to (100)
        $table = new xmldb_table('mnet_enrol_course');
        $field = new xmldb_field('shortname', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'fullname');
        /// Launch change of precision for field shortname
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008120801);
    }
    if ($result && $oldversion < 2008121701) {
        /// Define field availablefrom to be added to course_modules
        $table = new xmldb_table('course_modules');
        $field = new xmldb_field('availablefrom', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'completionexpected');
        /// Conditionally launch add field availablefrom
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field availableuntil to be added to course_modules
        $field = new xmldb_field('availableuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'availablefrom');
        /// Conditionally launch add field availableuntil
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field showavailability to be added to course_modules
        $field = new xmldb_field('showavailability', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'availableuntil');
        /// Conditionally launch add field showavailability
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define table course_modules_availability to be created
        $table = new xmldb_table('course_modules_availability');
        /// Adding fields to table course_modules_availability
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('coursemoduleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('sourcecmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('requiredcompletion', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('gradeitemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
        $table->add_field('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        $table->add_field('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
        /// Adding keys to table course_modules_availability
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('coursemoduleid', XMLDB_KEY_FOREIGN, array('coursemoduleid'), 'course_modules', array('id'));
        $table->add_key('sourcecmid', XMLDB_KEY_FOREIGN, array('sourcecmid'), 'course_modules', array('id'));
        $table->add_key('gradeitemid', XMLDB_KEY_FOREIGN, array('gradeitemid'), 'grade_items', array('id'));
        /// Conditionally launch create table for course_modules_availability
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Changes to modinfo mean we need to rebuild course cache
        require_once $CFG->dirroot . '/course/lib.php';
        rebuild_course_cache(0, true);
        /// For developer upgrades, turn on the conditional activities and completion
        /// features automatically (to gain more testing)
        //TODO: remove before 2.0 final!
        if (debugging('', DEBUG_DEVELOPER)) {
            set_config('enableavailability', 1);
            set_config('enablecompletion', 1);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2008121701);
    }
    if ($result && $oldversion < 2009010500) {
        /// clean up config table a bit
        unset_config('session_error_counter');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010500);
    }
    if ($result && $oldversion < 2009010600) {
        /// Define field originalquestion to be dropped from question_states
        $table = new xmldb_table('question_states');
        $field = new xmldb_field('originalquestion');
        /// Conditionally launch drop field originalquestion
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010600);
    }
    if ($result && $oldversion < 2009010601) {
        /// Changing precision of field ip on table log to (45)
        $table = new xmldb_table('log');
        $field = new xmldb_field('ip', XMLDB_TYPE_CHAR, '45', null, XMLDB_NOTNULL, null, null, 'userid');
        /// Launch change of precision for field ip
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010601);
    }
    if ($result && $oldversion < 2009010602) {
        /// Changing precision of field lastip on table user to (45)
        $table = new xmldb_table('user');
        $field = new xmldb_field('lastip', XMLDB_TYPE_CHAR, '45', null, XMLDB_NOTNULL, null, null, 'currentlogin');
        /// Launch change of precision for field lastip
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010602);
    }
    if ($result && $oldversion < 2009010603) {
        /// Changing precision of field ip_address on table mnet_host to (45)
        $table = new xmldb_table('mnet_host');
        $field = new xmldb_field('ip_address', XMLDB_TYPE_CHAR, '45', null, XMLDB_NOTNULL, null, null, 'wwwroot');
        /// Launch change of precision for field ip_address
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010603);
    }
    if ($result && $oldversion < 2009010604) {
        /// Changing precision of field ip on table mnet_log to (45)
        $table = new xmldb_table('mnet_log');
        $field = new xmldb_field('ip', XMLDB_TYPE_CHAR, '45', null, XMLDB_NOTNULL, null, null, 'userid');
        /// Launch change of precision for field ip
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010604);
    }
    if ($result && $oldversion < 2009010800) {
        /// Update the notifyloginfailures setting.
        if ($CFG->notifyloginfailures == 'mainadmin') {
            set_config('notifyloginfailures', get_admin()->username);
        } else {
            if ($CFG->notifyloginfailures == 'alladmins') {
                set_config('notifyloginfailures', '$@ALL@$');
            } else {
                set_config('notifyloginfailures', '');
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009010800);
    }
    if ($result && $oldversion < 2009011000) {
        /// Changing nullability of field configdata on table block_instance to null
        $table = new xmldb_table('block_instance');
        $field = new xmldb_field('configdata');
        $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'visible');
        /// Launch change of nullability for field configdata
        $dbman->change_field_notnull($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009011000);
    }
    if ($result && $oldversion < 2009011100) {
        /// Remove unused settings
        unset_config('zip');
        unset_config('unzip');
        unset_config('adminblocks_initialised');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009011100);
    }
    if ($result && $oldversion < 2009011101) {
        /// Migrate backup settings to core plugin config table
        $configs = $DB->get_records('backup_config');
        foreach ($configs as $config) {
            set_config($config->name, $config->value, 'backup');
        }
        /// Define table to be dropped
        $table = new xmldb_table('backup_config');
        /// Launch drop table for old backup config
        $dbman->drop_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009011101);
    }
    if ($result && $oldversion < 2009011303) {
        /// Define table config_log to be created
        $table = new xmldb_table('config_log');
        /// Adding fields to table config_log
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('plugin', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('oldvalue', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        /// Adding keys to table config_log
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table config_log
        $table->add_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch create table for config_log
        $dbman->create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009011303);
    }
    if ($result && $oldversion < 2009011900) {
        /// Define table sessions2 to be dropped
        $table = new xmldb_table('sessions2');
        /// Conditionally launch drop table for sessions
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        /// Define table sessions to be dropped
        $table = new xmldb_table('sessions');
        /// Conditionally launch drop table for sessions
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        /// Define table sessions to be created
        $table = new xmldb_table('sessions');
        /// Adding fields to table sessions
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('state', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('sid', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('sessdata', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('firstip', XMLDB_TYPE_CHAR, '45', null, null, null, null);
        $table->add_field('lastip', XMLDB_TYPE_CHAR, '45', null, null, null, null);
        /// Adding keys to table sessions
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table sessions
        $table->add_index('state', XMLDB_INDEX_NOTUNIQUE, array('state'));
        $table->add_index('sid', XMLDB_INDEX_UNIQUE, array('sid'));
        $table->add_index('timecreated', XMLDB_INDEX_NOTUNIQUE, array('timecreated'));
        $table->add_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch create table for sessions
        $dbman->create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009011900);
    }
    if ($result && $oldversion < 2009012901) {
        // NOTE: this table may already exist, see beginning of this file ;-)
        /// Define table upgrade_log to be created
        $table = new xmldb_table('upgrade_log');
        /// Adding fields to table upgrade_log
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('type', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('plugin', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('version', XMLDB_TYPE_CHAR, '100', null, null, null, null);
        $table->add_field('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('details', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('backtrace', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table upgrade_log
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table upgrade_log
        $table->add_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        $table->add_index('type-timemodified', XMLDB_INDEX_NOTUNIQUE, array('type', 'timemodified'));
        /// Conditionally launch create table for upgrade_log
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009012901);
    }
    if ($result && $oldversion < 2009021800) {
        // Converting format of grade conditions, if any exist, to percentages.
        $DB->execute("\nUPDATE {course_modules_availability} SET grademin=(\n    SELECT 100.0*({course_modules_availability}.grademin-gi.grademin)\n        /(gi.grademax-gi.grademin)\n    FROM {grade_items} gi\n    WHERE gi.id={course_modules_availability}.gradeitemid)\nWHERE gradeitemid IS NOT NULL AND grademin IS NOT NULL");
        $DB->execute("\nUPDATE {course_modules_availability} SET grademax=(\n    SELECT 100.0*({course_modules_availability}.grademax-gi.grademin)\n        /(gi.grademax-gi.grademin)\n    FROM {grade_items} gi\n    WHERE gi.id={course_modules_availability}.gradeitemid)\nWHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009021800);
    }
    if ($result && $oldversion < 2009021801) {
        /// Define field backuptype to be added to backup_log
        $table = new xmldb_table('backup_log');
        $field = new xmldb_field('backuptype', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, null, null, 'info');
        /// Conditionally Launch add field backuptype and set all old records as 'scheduledbackup' records.
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
            $DB->execute("UPDATE {backup_log} SET backuptype='scheduledbackup'");
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009021801);
    }
    /// Add default sort order for question types.
    if ($result && $oldversion < 2009030300) {
        set_config('multichoice_sortorder', 1, 'question');
        set_config('truefalse_sortorder', 2, 'question');
        set_config('shortanswer_sortorder', 3, 'question');
        set_config('numerical_sortorder', 4, 'question');
        set_config('calculated_sortorder', 5, 'question');
        set_config('essay_sortorder', 6, 'question');
        set_config('match_sortorder', 7, 'question');
        set_config('randomsamatch_sortorder', 8, 'question');
        set_config('multianswer_sortorder', 9, 'question');
        set_config('description_sortorder', 10, 'question');
        set_config('random_sortorder', 11, 'question');
        set_config('missingtype_sortorder', 12, 'question');
        upgrade_main_savepoint($result, 2009030300);
    }
    if ($result && $oldversion < 2009030501) {
        /// setup default repository plugins
        require_once $CFG->dirroot . '/repository/lib.php';
        repository_setup_default_plugins();
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009030501);
    }
    /// MDL-18132 replace the use a new Role allow switch settings page, instead of
    /// $CFG->allowuserswitchrolestheycantassign
    if ($result && $oldversion < 2009032000) {
        /// First create the new table.
        $table = new xmldb_table('role_allow_switch');
        /// Adding fields to table role_allow_switch
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('allowswitch', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table role_allow_switch
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        $table->add_key('allowswitch', XMLDB_KEY_FOREIGN, array('allowswitch'), 'role', array('id'));
        /// Adding indexes to table role_allow_switch
        $table->add_index('roleid-allowoverride', XMLDB_INDEX_UNIQUE, array('roleid', 'allowswitch'));
        /// Conditionally launch create table for role_allow_switch
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009032000);
    }
    if ($result && $oldversion < 2009032001) {
        /// Copy from role_allow_assign into the new table.
        $DB->execute('INSERT INTO {role_allow_switch} (roleid, allowswitch)
                SELECT roleid, allowassign FROM {role_allow_assign}');
        /// Unset the config variable used in 1.9.
        unset_config('allowuserswitchrolestheycantassign');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009032001);
    }
    if ($result && $oldversion < 2009033100) {
        require_once "{$CFG->dirroot}/filter/tex/lib.php";
        filter_tex_updatedcallback(null);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009033100);
    }
    if ($result && $oldversion < 2009040300) {
        /// Define table filter_active to be created
        $table = new xmldb_table('filter_active');
        /// Adding fields to table filter_active
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('filter', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null);
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('active', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
        /// Adding keys to table filter_active
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table filter_active
        $table->add_index('contextid-filter', XMLDB_INDEX_UNIQUE, array('contextid', 'filter'));
        /// Conditionally launch create table for filter_active
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009040300);
    }
    if ($result && $oldversion < 2009040301) {
        /// Define table filter_config to be created
        $table = new xmldb_table('filter_config');
        /// Adding fields to table filter_config
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('filter', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null);
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        /// Adding keys to table filter_config
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table filter_config
        $table->add_index('contextid-filter-name', XMLDB_INDEX_UNIQUE, array('contextid', 'filter', 'name'));
        /// Conditionally launch create table for filter_config
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009040301);
    }
    if ($result && $oldversion < 2009040302) {
        /// Transfer current settings from $CFG->textfilters
        $disabledfilters = filter_get_all_installed();
        if (empty($CFG->textfilters)) {
            $activefilters = array();
        } else {
            $activefilters = explode(',', $CFG->textfilters);
        }
        $syscontext = get_context_instance(CONTEXT_SYSTEM);
        $sortorder = 1;
        foreach ($activefilters as $filter) {
            filter_set_global_state($filter, TEXTFILTER_ON, $sortorder);
            $sortorder += 1;
            unset($disabledfilters[$filter]);
        }
        foreach ($disabledfilters as $filter => $notused) {
            filter_set_global_state($filter, TEXTFILTER_DISABLED, $sortorder);
            $sortorder += 1;
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009040302);
    }
    if ($result && $oldversion < 2009040600) {
        /// Ensure that $CFG->stringfilters is set.
        if (empty($CFG->stringfilters)) {
            if (!empty($CFG->filterall)) {
                set_config('stringfilters', $CFG->textfilters);
            } else {
                set_config('stringfilters', '');
            }
        }
        set_config('filterall', !empty($CFG->stringfilters));
        unset_config('textfilters');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009040600);
    }
    if ($result && $oldversion < 2009041700) {
        /// To ensure the UI remains consistent with no behaviour change, any
        /// 'until' date in an activity condition should have 1 second subtracted
        /// (to go from 0:00 on the following day to 23:59 on the previous one).
        $DB->execute('UPDATE {course_modules} SET availableuntil = availableuntil - 1 WHERE availableuntil <> 0');
        require_once $CFG->dirroot . '/course/lib.php';
        rebuild_course_cache(0, true);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009041700);
    }
    if ($result && $oldversion < 2009042600) {
        /// Deleting orphaned messages from deleted users.
        require_once $CFG->dirroot . '/message/lib.php';
        /// Detect deleted users with messages sent(useridfrom) and not read
        if ($deletedusers = $DB->get_records_sql('SELECT DISTINCT u.id
                                                    FROM {user} u
                                                    JOIN {message} m ON m.useridfrom = u.id
                                                   WHERE u.deleted = ?', array(1))) {
            foreach ($deletedusers as $deleteduser) {
                message_move_userfrom_unread2read($deleteduser->id);
                // move messages
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009042600);
    }
    /// Dropping all enums/check contraints from core. MDL-18577
    if ($result && $oldversion < 2009042700) {
        /// Changing list of values (enum) of field stattype on table stats_daily to none
        $table = new xmldb_table('stats_daily');
        $field = new xmldb_field('stattype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'activity', 'roleid');
        /// Launch change of list of values for field stattype
        $dbman->drop_enum_from_field($table, $field);
        /// Changing list of values (enum) of field stattype on table stats_weekly to none
        $table = new xmldb_table('stats_weekly');
        $field = new xmldb_field('stattype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'activity', 'roleid');
        /// Launch change of list of values for field stattype
        $dbman->drop_enum_from_field($table, $field);
        /// Changing list of values (enum) of field stattype on table stats_monthly to none
        $table = new xmldb_table('stats_monthly');
        $field = new xmldb_field('stattype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'activity', 'roleid');
        /// Launch change of list of values for field stattype
        $dbman->drop_enum_from_field($table, $field);
        /// Changing list of values (enum) of field publishstate on table post to none
        $table = new xmldb_table('post');
        $field = new xmldb_field('publishstate', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, 'draft', 'attachment');
        /// Launch change of list of values for field publishstate
        $dbman->drop_enum_from_field($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009042700);
    }
    if ($result && $oldversion < 2009043000) {
        unset_config('grade_report_showgroups');
        upgrade_main_savepoint($result, 2009043000);
    }
    if ($result && $oldversion < 2009050600) {
        /// Site front page blocks need to be moved due to page name change.
        $DB->set_field('block_instance', 'pagetype', 'site-index', array('pagetype' => 'course-view', 'pageid' => SITEID));
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050600);
    }
    if ($result && $oldversion < 2009050601) {
        /// Define table block_instance to be renamed to block_instances
        $table = new xmldb_table('block_instance');
        /// Launch rename table for block_instance
        $dbman->rename_table($table, 'block_instances');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050601);
    }
    if ($result && $oldversion < 2009050602) {
        /// Define table block_instance to be renamed to block_instance_old
        $table = new xmldb_table('block_pinned');
        /// Launch rename table for block_instance
        $dbman->rename_table($table, 'block_pinned_old');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050602);
    }
    if ($result && $oldversion < 2009050603) {
        /// Define table block_instance_old to be created
        $table = new xmldb_table('block_instance_old');
        /// Adding fields to table block_instance_old
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('blockid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('pagetype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
        $table->add_field('position', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('weight', XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
        $table->add_field('configdata', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        /// Adding keys to table block_instance_old
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('blockid', XMLDB_KEY_FOREIGN, array('blockid'), 'block', array('id'));
        /// Adding indexes to table block_instance_old
        $table->add_index('pageid', XMLDB_INDEX_NOTUNIQUE, array('pageid'));
        $table->add_index('pagetype', XMLDB_INDEX_NOTUNIQUE, array('pagetype'));
        /// Conditionally launch create table for block_instance_old
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050603);
    }
    if ($result && $oldversion < 2009050604) {
        /// Copy current blocks data from block_instances to block_instance_old
        $DB->execute('INSERT INTO {block_instance_old} (oldid, blockid, pageid, pagetype, position, weight, visible, configdata)
            SELECT id, blockid, pageid, pagetype, position, weight, visible, configdata FROM {block_instances} ORDER BY id');
        upgrade_main_savepoint($result, 2009050604);
    }
    if ($result && $oldversion < 2009050605) {
        /// Define field multiple to be dropped from block
        $table = new xmldb_table('block');
        $field = new xmldb_field('multiple');
        /// Conditionally launch drop field multiple
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050605);
    }
    if ($result && $oldversion < 2009050606) {
        $table = new xmldb_table('block_instances');
        /// Rename field weight on table block_instances to defaultweight
        $field = new xmldb_field('weight', XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, '0', 'position');
        $dbman->rename_field($table, $field, 'defaultweight');
        /// Rename field position on table block_instances to defaultregion
        $field = new xmldb_field('position', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, 'pagetype');
        $dbman->rename_field($table, $field, 'defaultregion');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050606);
    }
    if ($result && $oldversion < 2009050607) {
        /// Changing precision of field defaultregion on table block_instances to (16)
        $table = new xmldb_table('block_instances');
        $field = new xmldb_field('defaultregion', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null, 'pagetype');
        /// Launch change of precision for field defaultregion
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050607);
    }
    if ($result && $oldversion < 2009050608) {
        /// Change regions to the new notation
        $DB->set_field('block_instances', 'defaultregion', 'side-pre', array('defaultregion' => 'l'));
        $DB->set_field('block_instances', 'defaultregion', 'side-post', array('defaultregion' => 'r'));
        $DB->set_field('block_instances', 'defaultregion', 'course-view-top', array('defaultregion' => 'c'));
        // This third one is a custom value from contrib/patches/center_blocks_position_patch and the
        // flex page course format. Hopefully this new value is an adequate alternative.
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050608);
    }
    if ($result && $oldversion < 2009050609) {
        /// Define key blockname (unique) to be added to block
        $table = new xmldb_table('block');
        $key = new xmldb_key('blockname', XMLDB_KEY_UNIQUE, array('name'));
        /// Launch add key blockname
        $dbman->add_key($table, $key);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050609);
    }
    if ($result && $oldversion < 2009050610) {
        $table = new xmldb_table('block_instances');
        /// Define field blockname to be added to block_instances
        $field = new xmldb_field('blockname', XMLDB_TYPE_CHAR, '40', null, null, null, null, 'blockid');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field contextid to be added to block_instances
        $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'blockname');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field showinsubcontexts to be added to block_instances
        $field = new xmldb_field('showinsubcontexts', XMLDB_TYPE_INTEGER, '4', null, null, null, null, 'contextid');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Define field subpagepattern to be added to block_instances
        $field = new xmldb_field('subpagepattern', XMLDB_TYPE_CHAR, '16', null, null, null, null, 'pagetype');
        if (!$dbman->field_exists($table, $field)) {
            $dbman->add_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050610);
    }
    if ($result && $oldversion < 2009050611) {
        $table = new xmldb_table('block_instances');
        /// Fill in blockname from blockid
        $DB->execute("UPDATE {block_instances} SET blockname = (SELECT name FROM {block} WHERE id = blockid)");
        /// Set showinsubcontexts = 0 for all rows.
        $DB->execute("UPDATE {block_instances} SET showinsubcontexts = 0");
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050611);
    }
    if ($result && $oldversion < 2009050612) {
        /// Rename field pagetype on table block_instances to pagetypepattern
        $table = new xmldb_table('block_instances');
        $field = new xmldb_field('pagetype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, 'pageid');
        /// Launch rename field pagetype
        $dbman->rename_field($table, $field, 'pagetypepattern');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050612);
    }
    if ($result && $oldversion < 2009050613) {
        /// fill in contextid and subpage, and update pagetypepattern from pagetype and pageid
        /// site-index
        $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
        $DB->execute("UPDATE {block_instances} SET contextid = " . $frontpagecontext->id . ",\n                                                   pagetypepattern = 'site-index',\n                                                   subpagepattern = NULL\n                      WHERE pagetypepattern = 'site-index'");
        /// course-view
        $DB->execute("UPDATE {block_instances} SET\n                        contextid = (\n                            SELECT {context}.id\n                            FROM {context}\n                            JOIN {course} ON instanceid = {course}.id AND contextlevel = " . CONTEXT_COURSE . "\n                            WHERE {course}.id = pageid\n                        ),\n                       pagetypepattern = 'course-view-*',\n                       subpagepattern = NULL\n                      WHERE pagetypepattern = 'course-view'");
        /// admin
        $syscontext = get_context_instance(CONTEXT_SYSTEM);
        $DB->execute("UPDATE {block_instances} SET\n                        contextid = " . $syscontext->id . ",\n                        pagetypepattern = 'admin-*',\n                        subpagepattern = NULL\n                      WHERE pagetypepattern = 'admin'");
        /// my-index
        $DB->execute("UPDATE {block_instances} SET\n                        contextid = (\n                            SELECT {context}.id\n                            FROM {context}\n                            JOIN {user} ON instanceid = {user}.id AND contextlevel = " . CONTEXT_USER . "\n                            WHERE {user}.id = pageid\n                        ),\n                        pagetypepattern = 'my-index',\n                        subpagepattern = NULL\n                      WHERE pagetypepattern = 'my-index'");
        /// tag-index
        $DB->execute("UPDATE {block_instances} SET\n                        contextid = " . $syscontext->id . ",\n                        pagetypepattern = 'tag-index',\n                        subpagepattern = pageid\n                      WHERE pagetypepattern = 'tag-index'");
        /// blog-view
        $DB->execute("UPDATE {block_instances} SET\n                        contextid = (\n                            SELECT {context}.id\n                            FROM {context}\n                            JOIN {user} ON instanceid = {user}.id AND contextlevel = " . CONTEXT_USER . "\n                            WHERE {user}.id = pageid\n                        ),\n                        pagetypepattern = 'blog-index',\n                        subpagepattern = NULL\n                      WHERE pagetypepattern = 'blog-view'");
        /// mod-xxx-view
        $moduleswithblocks = array('chat', 'data', 'lesson', 'quiz', 'dimdim', 'game', 'wiki', 'oublog');
        foreach ($moduleswithblocks as $modname) {
            if (!$dbman->table_exists($modname)) {
                continue;
            }
            $DB->execute("UPDATE {block_instances} SET\n                            contextid = (\n                                SELECT {context}.id\n                                FROM {context}\n                                JOIN {course_modules} ON instanceid = {course_modules}.id AND contextlevel = " . CONTEXT_MODULE . "\n                                JOIN {modules} ON {modules}.id = {course_modules}.module AND {modules}.name = '{$modname}'\n                                JOIN {{$modname}} ON {course_modules}.instance = {{$modname}}.id\n                                WHERE {{$modname}}.id = pageid\n                            ),\n                            pagetypepattern = 'blog-index',\n                            subpagepattern = NULL\n                          WHERE pagetypepattern = 'blog-view'");
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050613);
    }
    if ($result && $oldversion < 2009050614) {
        /// fill in any missing contextids with a dummy value, so we can add the not-null constraint.
        $DB->execute("UPDATE {block_instances} SET contextid = -1 WHERE contextid IS NULL");
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050614);
    }
    if ($result && $oldversion < 2009050615) {
        $table = new xmldb_table('block_instances');
        /// Changing nullability of field blockname on table block_instances to not null
        $field = new xmldb_field('blockname', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'id');
        $dbman->change_field_notnull($table, $field);
        /// Changing nullability of field contextid on table block_instances to not null
        $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, 'blockname');
        $dbman->change_field_notnull($table, $field);
        /// Changing nullability of field showinsubcontexts on table block_instances to not null
        $field = new xmldb_field('showinsubcontexts', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, 'contextid');
        $dbman->change_field_notnull($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050615);
    }
    if ($result && $oldversion < 2009050616) {
        /// Add exiting sticky blocks.
        $blocks = $DB->get_records('block');
        $syscontext = get_context_instance(CONTEXT_SYSTEM);
        $newregions = array('l' => 'side-pre', 'r' => 'side-post', 'c' => 'course-view-top');
        $stickyblocks = $DB->get_recordset('block_pinned_old');
        foreach ($stickyblocks as $stickyblock) {
            $newblock = stdClass;
            $newblock->blockname = $blocks[$stickyblock]->name;
            $newblock->contextid = $syscontext->id;
            $newblock->showinsubcontexts = 1;
            switch ($stickyblock->pagetype) {
                case 'course-view':
                    $newblock->pagetypepattern = 'course-view-*';
                    break;
                default:
                    $newblock->pagetypepattern = $stickyblock->pagetype;
            }
            $newblock->defaultregion = $newregions[$stickyblock->position];
            $newblock->defaultweight = $stickyblock->weight;
            $newblock->configdata = $stickyblock->configdata;
            $DB->insert_record('block_instances', $newblock);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050616);
    }
    if ($result && $oldversion < 2009050617) {
        /// Define table block_positions to be created
        $table = new xmldb_table('block_positions');
        /// Adding fields to table block_positions
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('blockinstanceid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('pagetype', XMLDB_TYPE_CHAR, '64', null, XMLDB_NOTNULL, null, null);
        $table->add_field('subpage', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null);
        $table->add_field('visible', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '1');
        $table->add_field('region', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null);
        $table->add_field('weight', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
        /// Adding keys to table block_positions
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->add_key('blockinstanceid', XMLDB_KEY_FOREIGN, array('blockinstanceid'), 'block_instances', array('id'));
        $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table block_positions
        $table->add_index('blockinstanceid-contextid-pagetype-subpage', XMLDB_INDEX_UNIQUE, array('blockinstanceid', 'contextid', 'pagetype', 'subpage'));
        /// Conditionally launch create table for block_positions
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050617);
    }
    if ($result && $oldversion < 2009050618) {
        /// And block instances with visible = 0, copy that information to block_positions
        $DB->execute("INSERT INTO {block_positions} (blockinstanceid, contextid, pagetype, subpage, visible, region, weight)\n                SELECT id, contextid,\n                CASE WHEN pagetypepattern = 'course-view-*' THEN\n                        (SELECT " . $DB->sql_concat("'course-view-'", 'format') . "\n                        FROM {course}\n                        JOIN {context} ON {course}.id = {context}.instanceid\n                        WHERE {context}.id = contextid)\n                    ELSE pagetypepattern END,\n                CASE WHEN subpagepattern IS NULL THEN ''\n                    ELSE subpagepattern END,\n                0, defaultregion, defaultweight\n                FROM {block_instances} WHERE visible = 0 AND pagetypepattern <> 'admin-*'");
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050618);
    }
    if ($result && $oldversion < 2009050619) {
        $table = new xmldb_table('block_instances');
        /// Define field blockid to be dropped from block_instances
        $field = new xmldb_field('blockid');
        if ($dbman->field_exists($table, $field)) {
            /// Before dropping the field, drop dependent indexes
            $index = new xmldb_index('blockid', XMLDB_INDEX_NOTUNIQUE, array('blockid'));
            if ($dbman->index_exists($table, $index)) {
                /// Launch drop index blockid
                $dbman->drop_index($table, $index);
            }
            $dbman->drop_field($table, $field);
        }
        /// Define field pageid to be dropped from block_instances
        $field = new xmldb_field('pageid');
        if ($dbman->field_exists($table, $field)) {
            /// Before dropping the field, drop dependent indexes
            $index = new xmldb_index('pageid', XMLDB_INDEX_NOTUNIQUE, array('pageid'));
            if ($dbman->index_exists($table, $index)) {
                /// Launch drop index pageid
                $dbman->drop_index($table, $index);
            }
            $dbman->drop_field($table, $field);
        }
        /// Define field visible to be dropped from block_instances
        $field = new xmldb_field('visible');
        if ($dbman->field_exists($table, $field)) {
            $dbman->drop_field($table, $field);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009050619);
    }
    if ($result && $oldversion < 2009051200) {
        /// Let's check the status of mandatory mnet_host records, fixing them
        /// and moving "orphan" users to default localhost record. MDL-16879
        echo $OUTPUT->notification('Fixing mnet records, this may take a while...', 'notifysuccess');
        upgrade_fix_incorrect_mnethostids();
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009051200);
    }
    if ($result && $oldversion < 2009051700) {
        /// migrate editor settings
        if (empty($CFG->htmleditor)) {
            set_config('texteditors', 'textarea');
        } else {
            set_config('texteditors', 'tinymce,textarea');
        }
        unset_config('htmleditor');
        unset_config('defaulthtmleditor');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009051700);
    }
    if ($result && $oldversion < 2009060200) {
        /// Define table files_cleanup to be dropped - not needed
        $table = new xmldb_table('files_cleanup');
        /// Conditionally launch drop table for files_cleanup
        if ($dbman->table_exists($table)) {
            $dbman->drop_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009060200);
    }
    if ($result && $oldversion < 2009061300) {
        //TODO: copy this to the very beginning of this upgrade script so that we may log upgrade queries
        /// Define table log_queries to be created
        $table = new xmldb_table('log_queries');
        /// Adding fields to table log_queries
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('qtype', XMLDB_TYPE_INTEGER, '5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('sqltext', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null);
        $table->add_field('sqlparams', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
        $table->add_field('error', XMLDB_TYPE_INTEGER, '5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('info', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('backtrace', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
        $table->add_field('exectime', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null);
        $table->add_field('timelogged', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table log_queries
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for log_queries
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009061300);
    }
    /// Repeat 2009050607 upgrade step, which Petr commented out becuase of XMLDB
    /// stupidity, so lots of peopel will have missed.
    if ($result && $oldversion < 2009061600) {
        /// Changing precision of field defaultregion on table block_instances to (16)
        $table = new xmldb_table('block_instances');
        $field = new xmldb_field('defaultregion', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null, 'configdata');
        /// Launch change of precision for field defaultregion
        $dbman->change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009061600);
    }
    if ($result && $oldversion < 2009061702) {
        // standardizing plugin names
        if ($configs = $DB->get_records_select('config_plugins', "plugin LIKE 'quizreport_%'")) {
            foreach ($configs as $config) {
                $result = $result && unset_config($config->name, $config->plugin);
                /// unset old config
                $config->plugin = str_replace('quizreport_', 'quiz_', $config->plugin);
                $result = $result && set_config($config->name, $config->value, $config->plugin);
                /// set new config
            }
        }
        unset($configs);
        upgrade_main_savepoint($result, 2009061702);
    }
    if ($result && $oldversion < 2009061703) {
        // standardizing plugin names
        if ($configs = $DB->get_records_select('config_plugins', "plugin LIKE 'assignment_type_%'")) {
            foreach ($configs as $config) {
                $result = $result && unset_config($config->name, $config->plugin);
                /// unset old config
                $config->plugin = str_replace('assignment_type_', 'assignment_', $config->plugin);
                $result = $result && set_config($config->name, $config->value, $config->plugin);
                /// set new config
            }
        }
        unset($configs);
        upgrade_main_savepoint($result, 2009061703);
    }
    if ($result && $oldversion < 2009061704) {
        // change component string in capability records to new "_" format
        if ($caps = $DB->get_records('capabilities')) {
            foreach ($caps as $cap) {
                $cap->component = str_replace('/', '_', $cap->component);
                $DB->update_record('capabilities', $cap);
            }
        }
        unset($caps);
        upgrade_main_savepoint($result, 2009061704);
    }
    if ($result && $oldversion < 2009061705) {
        // change component string in events_handlers records to new "_" format
        if ($handlers = $DB->get_records('events_handlers')) {
            foreach ($handlers as $handler) {
                $handler->handlermodule = str_replace('/', '_', $handler->handlermodule);
                $DB->update_record('events_handlers', $handler);
            }
        }
        unset($handlers);
        upgrade_main_savepoint($result, 2009061705);
    }
    if ($result && $oldversion < 2009061706) {
        // change component string in message_providers records to new "_" format
        if ($mps = $DB->get_records('message_providers')) {
            foreach ($mps as $mp) {
                $mp->component = str_replace('/', '_', $mp->component);
                $DB->update_record('message_providers', $cap);
            }
        }
        unset($caps);
        upgrade_main_savepoint($result, 2009061706);
    }
    if ($result && $oldversion < 2009063000) {
        // upgrade format of _with_advanced settings - quiz only
        // note: this can be removed later, not needed for upgrades from 1.9.x
        if ($quiz = get_config('quiz')) {
            foreach ($quiz as $name => $value) {
                if (strpos($name, 'fix_') !== 0) {
                    continue;
                }
                $newname = substr($name, 4) . '_adv';
                set_config($newname, $value, 'quiz');
                unset_config($name, 'quiz');
            }
        }
        upgrade_main_savepoint($result, 2009063000);
    }
    if ($result && $oldversion < 2009070100) {
        // MDL-19677 Change $CFG->bloglevel to BLOG_SITE_LEVEL if BLOG_COURSE_LEVEL or BLOG_GROUP_LEVEL
        $current_bloglevel = get_config(null, 'bloglevel');
        if ($current_bloglevel == BLOG_GROUP_LEVEL || $current_bloglevel == BLOG_COURSE_LEVEL) {
            set_config('bloglevel', BLOG_SITE_LEVEL);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009070100);
    }
    if ($result && $oldversion < 2009071000) {
        /// Rename field contextid on table block_instances to parentcontextid
        $table = new xmldb_table('block_instances');
        $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, 'blockname');
        /// Launch rename field parentcontextid
        $dbman->rename_field($table, $field, 'parentcontextid');
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009071000);
    }
    if ($result && $oldversion < 2009071300) {
        /// Create contexts for every block. In the past, only non-sticky course block had contexts.
        /// This is a copy of the code in create_contexts.
        $sql = "INSERT INTO {context} (contextlevel, instanceid)\n                SELECT " . CONTEXT_BLOCK . ", bi.id\n                  FROM {block_instances} bi\n                 WHERE NOT EXISTS (SELECT 'x'\n                                     FROM {context} ctx\n                                    WHERE bi.id = ctx.instanceid AND ctx.contextlevel=" . CONTEXT_BLOCK . ")";
        $DB->execute($sql);
        /// TODO MDL-19776 We should not really use API funcitons in upgrade.
        /// If MDL-19776 is done, we can remove this whole upgrade block.
        build_context_path();
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009071300);
    }
    if ($result && $oldversion < 2009072400) {
        /// Define table comments to be created
        $table = new xmldb_table('comments');
        /// Adding fields to table comments
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('commentarea', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
        $table->add_field('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('content', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null);
        $table->add_field('format', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0');
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
        /// Adding keys to table comments
        $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Conditionally launch create table for comments
        if (!$dbman->table_exists($table)) {
            $dbman->create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2009072400);
    }
    return $result;
}
Example #12
0
$user = $DB->get_record('user', array('username' => 'testtete'));
if (!$user) {
    $user = new stdClass();
    $user->username = '******';
    $user->firstname = 'Web';
    $user->lastname = 'Service';
    $user->password = '******';
    $dg = new testing_data_generator();
    $user = $dg->create_user($user);
}
// Create a role for Web Services with all permissions.
if (!($roleid = $DB->get_field('role', 'id', array('shortname' => 'testtete')))) {
    $roleid = create_role('Web Service', 'testtete', 'MDK: All permissions given by default.', '');
}
$context = context_system::instance();
set_role_contextlevels($roleid, array($context->contextlevel));
role_assign($roleid, $user->id, $context->id);
if (method_exists($context, 'get_capabilities')) {
    $capabilities = $context->get_capabilities();
} else {
    $capabilities = fetch_context_capabilities($context);
}
foreach ($capabilities as $capability) {
    assign_capability($capability->name, CAP_ALLOW, $roleid, $context->id, true);
}
$context->mark_dirty();
// Create a new service with all functions for the user.
$webservicemanager = new webservice();
if (!($service = $DB->get_record('external_services', array('shortname' => 'mdk_all')))) {
    $service = new stdClass();
    $service->name = 'MDK: All functions';
Example #13
0
 public function save_changes()
 {
     global $DB;
     if (!$this->roleid) {
         // Creating role
         $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $this->role->archetype);
         $this->roleid = $this->role->id;
         // Needed to make the parent::save_changes(); call work.
     } else {
         // Updating role
         $DB->update_record('role', $this->role);
     }
     // Assignable contexts.
     set_role_contextlevels($this->role->id, $this->contextlevels);
     // Permissions.
     parent::save_changes();
 }
Example #14
0
/**
* When called resets all custom roles as per definition set down in /local/roles.php
*
* Note that this uses the non-core role.custom field to isolate roles to remove.
*
* Utilise the $path parameter to allow for localisation (i.e. different roles defintion than core).
*
* Sort order is reset based on the order listed in the defintion.
*
* WARNING: as long as you retain the same shortname existing user role assigments will
*             be retained.  if you change the shortname they will be lost.
*
* KNOWN ISSUE: we rely on shortname being unique, but this is not enforced by the db.
*                       this is more a problem with moodle.
*
* @param text $path
*
*/
function tao_reset_custom_roles($path = 'local')
{
    global $CFG;
    if (!get_site()) {
        // not finished installing, skip
        return true;
    }
    // get latest role definition from roles file
    $rolespath = $CFG->dirroot . '/' . $path . '/roles.php';
    if (!file_exists($rolespath)) {
        debugging("Local caps reassignment called with invalid path {$path}");
        return false;
    }
    require_once $rolespath;
    if (!isset($customroles)) {
        return true;
        // nothing to do.
    }
    $undeletableroles = array();
    $undeletableroles[$CFG->notloggedinroleid] = 1;
    $undeletableroles[$CFG->guestroleid] = 1;
    $undeletableroles[$CFG->defaultuserroleid] = 1;
    $undeletableroles[$CFG->defaultcourseroleid] = 1;
    // If there is only one admin role, add that to $undeletableroles too.
    $adminroles = get_admin_roles();
    if (count($adminroles) == 1) {
        $undeletableroles[reset($adminroles)->id] = 1;
    }
    // get recordset of existing custom roles
    $sql = "SELECT id, name, shortname, description, sortorder, custom\n              FROM {$CFG->prefix}role\n              WHERE custom IS NOT NULL";
    $roles = get_records_sql($sql);
    // remove custom roles that are not in the latest definition
    foreach ($roles as $role) {
        // check whether this role is in the latest definition
        if (array_key_exists($role->shortname, $customroles)) {
            continue;
        }
        // extra safety: check undeletable roles
        if (isset($undeletableroles[$role->id])) {
            continue;
        }
        delete_role($role->id);
    }
    // hack to avoid sortorder unique constraint
    execute_sql("UPDATE {$CFG->prefix}role SET sortorder = (sortorder+1000) WHERE custom IS NOT NULL");
    // set sortorder to current highest value
    $sortorder = get_field_sql("SELECT " . sql_max('sortorder') . " FROM {$CFG->prefix}role WHERE custom IS NULL");
    // now loop through the new settings
    foreach ($customroles as $shortname => $role) {
        $sortorder++;
        // get the roleid
        $roleid = get_field('role', 'id', 'shortname', $shortname);
        // if exists then make updates
        if (!empty($roleid)) {
            // only update fields that have been set
            if (isset($role['name'])) {
                set_field('role', 'name', $role['name'], 'shortname', $shortname);
            }
            if (isset($role['description'])) {
                set_field('role', 'description', $role['description'], 'shortname', $shortname);
            }
            // reset sortorder
            set_field('role', 'sortorder', $sortorder, 'shortname', $shortname);
            // else create record
        } else {
            $newrole = new stdclass();
            $newrole->name = $role['name'];
            $newrole->shortname = $shortname;
            $newrole->description = $role['description'];
            $newrole->sortorder = $sortorder;
            $newrole->custom = 1;
            $roleid = insert_record('role', $newrole);
        }
        // remove any previously set legacy roles
        $legacyroles = get_legacy_roles();
        foreach ($legacyroles as $ltype => $lcap) {
            unassign_capability($lcap, $roleid);
        }
        // reset legacy role
        if (isset($role['legacy'])) {
            $legacycap = $legacyroles[$role['legacy']];
            $context = get_context_instance(CONTEXT_SYSTEM);
            assign_capability($legacycap, CAP_ALLOW, $roleid, $context->id);
        }
        // update the context settings
        set_role_contextlevels($roleid, $role['context']);
        //  e.g. array(CONTEXT_SYSTEM, CONTEXT_COURSECAT)
        // set allow assigns
        if (is_array($role['canassign'])) {
            // delete existing
            delete_records('role_allow_assign', 'allowassign', $roleid);
            foreach ($role['canassign'] as $canassign) {
                $canassignid = get_field('role', 'id', 'shortname', $canassign);
                allow_assign($canassignid, $roleid);
            }
        }
    }
    // reset custom capabilities to keep up with changes
    return tao_reset_capabilities();
}
Example #15
0
/**
 * Main post-install tasks to be executed after the BD schema is available
 *
 * This function is automatically executed after Moodle core DB has been
 * created at initial install. It's in charge of perform the initial tasks
 * not covered by the {@link install.xml} file, like create initial users,
 * roles, templates, moving stuff from other plugins...
 *
 * Note that the function is only invoked once, at install time, so if new tasks
 * are needed in the future, they will need to be added both here (for new sites)
 * and in the corresponding {@link upgrade.php} file (for existing sites).
 *
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
 * their own install.php file, using the "Frankenstyle" component name as
 * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
 *     - {@link xmldb_page_install()}. (modules don't require the plugintype ("mod_") to be used.
 *     - {@link xmldb_enrol_meta_install()}.
 *     - {@link xmldb_workshopform_accumulative_install()}.
 *     - ....
 *
 * Finally, note that it's also supported to have one uninstall.php file that is
 * executed also once, each time one plugin is uninstalled (before the DB schema is
 * deleted). Those uninstall files will contain one function, using the "Frankenstyle"
 * naming conventions, like {@link xmldb_enrol_meta_uninstall()} or {@link xmldb_workshop_uninstall()}.
 */
function xmldb_main_install()
{
    global $CFG, $DB, $SITE, $OUTPUT;
    // Make sure system context exists
    $syscontext = context_system::instance(0, MUST_EXIST, false);
    if ($syscontext->id != SYSCONTEXTID) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new system context id!');
    }
    // Create site course
    if ($DB->record_exists('course', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create frontpage course, courses already exist.');
    }
    $newsite = new stdClass();
    $newsite->fullname = '';
    $newsite->shortname = '';
    $newsite->summary = NULL;
    $newsite->newsitems = 3;
    $newsite->numsections = 1;
    $newsite->category = 0;
    $newsite->format = 'site';
    // Only for this course
    $newsite->timecreated = time();
    $newsite->timemodified = $newsite->timecreated;
    if (defined('SITEID')) {
        $newsite->id = SITEID;
        $DB->import_record('course', $newsite);
        $DB->get_manager()->reset_sequence('course');
    } else {
        $newsite->id = $DB->insert_record('course', $newsite);
        define('SITEID', $newsite->id);
    }
    // set the field 'numsections'. We can not use format_site::update_format_options() because
    // the file is not loaded
    $DB->insert_record('course_format_options', array('courseid' => SITEID, 'format' => 'site', 'sectionid' => 0, 'name' => 'numsections', 'value' => $newsite->numsections));
    $SITE = get_site();
    if ($newsite->id != $SITE->id) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new site course id!');
    }
    // Make sure site course context exists
    context_course::instance($SITE->id);
    // Update the global frontpage cache
    $SITE = $DB->get_record('course', array('id' => $newsite->id), '*', MUST_EXIST);
    // Create default course category
    if ($DB->record_exists('course_categories', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default course category, categories already exist.');
    }
    $cat = new stdClass();
    $cat->name = get_string('miscellaneous');
    $cat->depth = 1;
    $cat->sortorder = MAX_COURSES_IN_CATEGORY;
    $cat->timemodified = time();
    $catid = $DB->insert_record('course_categories', $cat);
    $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid));
    // Make sure category context exists
    context_coursecat::instance($catid);
    $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol_plugins_enabled' => 'manual,guest,self,cohort', 'theme' => theme_config::DEFAULT_THEME, 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'atto,tinymce,textarea', 'upgrade_minmaxgradestepignored' => 1, 'upgrade_extracreditweightsstepignored' => 1, 'upgrade_calculatedgradeitemsignored' => 1);
    foreach ($defaults as $key => $value) {
        set_config($key, $value);
    }
    // Bootstrap mnet
    $mnethost = new stdClass();
    $mnethost->wwwroot = $CFG->wwwroot;
    $mnethost->name = '';
    $mnethost->name = '';
    $mnethost->public_key = '';
    if (empty($_SERVER['SERVER_ADDR'])) {
        // SERVER_ADDR is only returned by Apache-like webservers
        preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches);
        $my_hostname = $matches[1];
        $my_ip = gethostbyname($my_hostname);
        // Returns unmodified hostname on failure. DOH!
        if ($my_ip == $my_hostname) {
            $mnethost->ip_address = 'UNKNOWN';
        } else {
            $mnethost->ip_address = $my_ip;
        }
    } else {
        $mnethost->ip_address = $_SERVER['SERVER_ADDR'];
    }
    $mnetid = $DB->insert_record('mnet_host', $mnethost);
    set_config('mnet_localhost_id', $mnetid);
    // Initial insert of mnet applications info
    $mnet_app = new stdClass();
    $mnet_app->name = 'moodle';
    $mnet_app->display_name = 'Moodle';
    $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/mnet/land.php';
    $mnet_app->sso_jump_url = '/auth/mnet/jump.php';
    $moodleapplicationid = $DB->insert_record('mnet_application', $mnet_app);
    $mnet_app = new stdClass();
    $mnet_app->name = 'mahara';
    $mnet_app->display_name = 'Mahara';
    $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/xmlrpc/land.php';
    $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php';
    $DB->insert_record('mnet_application', $mnet_app);
    // Set up the probably-to-be-removed-soon 'All hosts' record
    $mnetallhosts = new stdClass();
    $mnetallhosts->wwwroot = '';
    $mnetallhosts->ip_address = '';
    $mnetallhosts->public_key = '';
    $mnetallhosts->public_key_expires = 0;
    $mnetallhosts->last_connect_time = 0;
    $mnetallhosts->last_log_id = 0;
    $mnetallhosts->deleted = 0;
    $mnetallhosts->name = 'All Hosts';
    $mnetallhosts->applicationid = $moodleapplicationid;
    $mnetallhosts->id = $DB->insert_record('mnet_host', $mnetallhosts, true);
    set_config('mnet_all_hosts_id', $mnetallhosts->id);
    // Create guest record - do not assign any role, guest user gets the default guest role automatically on the fly
    if ($DB->record_exists('user', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default users, users already exist.');
    }
    $guest = new stdClass();
    $guest->auth = 'manual';
    $guest->username = '******';
    $guest->password = hash_internal_user_password('guest');
    $guest->firstname = get_string('guestuser');
    $guest->lastname = ' ';
    $guest->email = 'root@localhost';
    $guest->description = get_string('guestuserinfo');
    $guest->mnethostid = $CFG->mnet_localhost_id;
    $guest->confirmed = 1;
    $guest->lang = $CFG->lang;
    $guest->timemodified = time();
    $guest->id = $DB->insert_record('user', $guest);
    if ($guest->id != 1) {
        echo $OUTPUT->notification('Unexpected id generated for the Guest account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    // Store guest id
    set_config('siteguest', $guest->id);
    // Make sure user context exists
    context_user::instance($guest->id);
    // Now create admin user
    $admin = new stdClass();
    $admin->auth = 'manual';
    $admin->firstname = get_string('admin');
    $admin->lastname = get_string('user');
    $admin->username = '******';
    $admin->password = '******';
    $admin->email = '';
    $admin->confirmed = 1;
    $admin->mnethostid = $CFG->mnet_localhost_id;
    $admin->lang = $CFG->lang;
    $admin->maildisplay = 1;
    $admin->timemodified = time();
    $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr();
    // installation hijacking prevention
    $admin->id = $DB->insert_record('user', $admin);
    if ($admin->id != 2) {
        echo $OUTPUT->notification('Unexpected id generated for the Admin account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    if ($admin->id != $guest->id + 1) {
        echo $OUTPUT->notification('Nonconsecutive id generated for the Admin account. Your database configuration or clustering setup may not be fully supported.', 'notifyproblem');
    }
    // Store list of admins
    set_config('siteadmins', $admin->id);
    // Make sure user context exists
    context_user::instance($admin->id);
    // Install the roles system.
    $managerrole = create_role('', 'manager', '', 'manager');
    $coursecreatorrole = create_role('', 'coursecreator', '', 'coursecreator');
    $editteacherrole = create_role('', 'editingteacher', '', 'editingteacher');
    $noneditteacherrole = create_role('', 'teacher', '', 'teacher');
    $studentrole = create_role('', 'student', '', 'student');
    $guestrole = create_role('', 'guest', '', 'guest');
    $userrole = create_role('', 'user', '', 'user');
    $frontpagerole = create_role('', 'frontpage', '', 'frontpage');
    // Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    update_capabilities('moodle');
    // Default allow role matrices.
    foreach ($DB->get_records('role') as $role) {
        foreach (array('assign', 'override', 'switch') as $type) {
            $function = 'allow_' . $type;
            $allows = get_default_role_archetype_allows($type, $role->archetype);
            foreach ($allows as $allowid) {
                $function($role->id, $allowid);
            }
        }
    }
    // Set up the context levels where you can assign each role.
    set_role_contextlevels($managerrole, get_default_contextlevels('manager'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
    // Init theme and JS revisions
    set_config('themerev', time());
    set_config('jsrev', time());
    // No admin setting for this any more, GD is now required, remove in Moodle 2.6.
    set_config('gdversion', 2);
    // Install licenses
    require_once $CFG->libdir . '/licenselib.php';
    license_manager::install_licenses();
    // Init profile pages defaults
    if ($DB->record_exists('my_pages', array())) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default profile pages, records already exist.');
    }
    $mypage = new stdClass();
    $mypage->userid = NULL;
    $mypage->name = '__default';
    $mypage->private = 0;
    $mypage->sortorder = 0;
    $DB->insert_record('my_pages', $mypage);
    $mypage->private = 1;
    $DB->insert_record('my_pages', $mypage);
    // Set a sensible default sort order for the most-used question types.
    set_config('multichoice_sortorder', 1, 'question');
    set_config('truefalse_sortorder', 2, 'question');
    set_config('match_sortorder', 3, 'question');
    set_config('shortanswer_sortorder', 4, 'question');
    set_config('numerical_sortorder', 5, 'question');
    set_config('essay_sortorder', 6, 'question');
}
 /**
  * Validates that the version 1 update ignores empty values and does not
  * blank out fields for enrolments
  */
 public function test_version1enrolmentcreateanddeleteignoreemptyvalues()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     require_once $CFG->dirroot . '/lib/enrollib.php';
     set_config('createorupdate', 0, 'dhimport_version1');
     set_config('gradebookroles', '');
     set_config('defaultenrol', 1, 'enrol_manual');
     set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
     // Create category.
     $category = new stdClass();
     $category->name = 'rlipcategory';
     $category->id = $DB->insert_record('course_categories', $category);
     // Create course.
     $course = new stdClass();
     $course->shortname = 'rlipshortname';
     $course->fullname = 'rlipfullname';
     $course->category = $category->id;
     $course = create_course($course);
     // Create user.
     $user = new stdClass();
     $user->username = '******';
     $user->mnethostid = $CFG->mnet_localhost_id;
     $user->idnumber = 'rlipidnumber';
     $user->email = '*****@*****.**';
     $user->password = '******';
     $user->idnumber = 'rlipidnumber';
     $user->id = user_create_user($user);
     set_config('siteguest', 99999);
     // Create role.
     $context = context_course::instance($course->id);
     $roleid = create_role('rliprole', 'rliprole', 'rliprole');
     set_role_contextlevels($roleid, array(CONTEXT_COURSE));
     $syscontext = context_system::instance();
     assign_capability('moodle/course:view', CAP_ALLOW, $roleid, $syscontext->id);
     // Create an enrolment.
     $data = array(array('entity' => 'enrolment', 'action' => 'create', 'username' => 'rlipusername', 'email' => '', 'idnumber' => '', 'context' => 'course', 'instance' => 'rlipshortname', 'role' => 'rliprole'));
     $provider = new rlipimport_version1_importprovider_emptyenrolment($data);
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1', $provider);
     $importplugin->run();
     $this->assert_record_exists('role_assignments', array('userid' => $user->id, 'contextid' => $context->id, 'roleid' => $roleid));
     // Delete an enrolment.
     $data[0]['action'] = 'delete';
     $provider = new rlipimport_version1_importprovider_emptyenrolment($data);
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1', $provider);
     $importplugin->run();
     // Validation.
     $exists = $DB->record_exists('role_assignments', array('userid' => $user->id, 'contextid' => $context->id, 'roleid' => $roleid));
     $this->assertFalse($exists);
 }
Example #17
0
    /**
     * Test moodle_enrol_manual_enrol_users web service function
     * This test will:
     * 1- create a user (core call)
     * 2- enrol this user in the courses supporting enrolment
     * 3- unenrol this user (core call)
     *
     * @param webservice_rest_client|webservice_soap_client|webservice_xmlrpc_client $client the protocol test client
     */
    private function moodle_enrol_manual_enrol_users($client) {
        global $DB, $CFG;

        require_once($CFG->dirroot . "/user/lib.php");
        require_once($CFG->dirroot . "/user/profile/lib.php");
        require_once($CFG->dirroot . "/lib/enrollib.php");

        // Delete some previous test data
        if ($user = $DB->get_record('user', array('username' => 'veryimprobabletestusername2'))) {
            $DB->delete_records('user', array('id' => $user->id));
        }
        if ($role = $DB->get_record('role', array('shortname' => 'role1thatshouldnotexist'))) {
            set_role_contextlevels($role->id, array(CONTEXT_COURSE));
            delete_role($role->id);
        }

        // create a user
        $user = new stdClass();
        $user->username = '******';
        $user->password = '******';
        $user->firstname = 'testfirstname2';
        $user->lastname = 'testlastname2';
        $user->email = '*****@*****.**';
        $user->id = user_create_user($user);

        $roleid = create_role('role1thatshouldnotexist', 'role1thatshouldnotexist', '');
        set_role_contextlevels($roleid, array(CONTEXT_COURSE));

        $enrolments = array();
        $courses = $DB->get_records('course');

        foreach ($courses as $course) {
            if ($course->id > 1) {
                $enrolments[] = array('roleid' => $roleid,
                    'userid' => $user->id, 'courseid' => $course->id);
                $enrolledcourses[] = $course;
            }
        }

        // web service call
        $function = 'moodle_enrol_manual_enrol_users';
        $wsparams = array('enrolments' => $enrolments);
        $enrolmentsresult = $client->call($function, $wsparams);

        // get instance that can unenrol
        $enrols = enrol_get_plugins(true);
        $enrolinstances = enrol_get_instances($course->id, true);
        $unenrolled = false;
        foreach ($enrolinstances as $instance) {
            if (!$unenrolled and $enrols[$instance->enrol]->allow_unenrol($instance)) {
                $unenrolinstance = $instance;
                $unenrolled = true;
            }
        }

        // test and unenrol the user
        $enrolledusercourses = enrol_get_users_courses($user->id);
        foreach ($enrolledcourses as $course) {
            // test
            $this->assertEqual(true, isset($enrolledusercourses[$course->id]));

            // unenrol the user
            $enrols[$unenrolinstance->enrol]->unenrol_user($unenrolinstance, $user->id, $roleid);
        }

        // delete user
        $DB->delete_records('user', array('id' => $user->id));

        // delete the context level
        set_role_contextlevels($roleid, array(CONTEXT_COURSE));

        // delete role
        delete_role($roleid);
    }
Example #18
0
            $a->name = $roles[$roleid]->name;
            $a->shortname = $roles[$roleid]->shortname;
            $a->legacytype = get_legacy_type($roleid);
            if (empty($a->legacytype)) {
                $warning = get_string('resetrolesurenolegacy', 'role', $a);
            } else {
                $warning = get_string('resetrolesure', 'role', $a);
            }
            notice_yesno($warning, 'manage.php', 'manage.php', $optionsyes, $optionsno, 'post', 'get');
            admin_externalpage_print_footer();
            die;
        }
        // Do the reset.
        $legacytype = get_legacy_type($roleid);
        if ($legacytype) {
            set_role_contextlevels($roleid, get_default_contextlevels($legacytype));
        }
        reset_role_capabilities($roleid);
        // Mark context dirty, log and redirect.
        mark_context_dirty($systemcontext->path);
        add_to_log(SITEID, 'role', 'reset', 'admin/roles/manage.php?action=reset&roleid=' . $roleid, $roles[$roleid]->localname, '', $USER->id);
        redirect($defineurl . '?action=view&amp;roleid=' . $roleid);
        break;
}
/// Print the page header and tabs.
admin_externalpage_print_header();
$currenttab = 'manage';
include_once 'managetabs.php';
/// Initialise table.
$table = new object();
$table->tablealign = 'center';
Example #19
0
function xmldb_main_install()
{
    global $CFG, $DB, $SITE;
    /// make sure system context exists
    $syscontext = get_system_context(false);
    if ($syscontext->id != 1) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected system context id created!');
    }
    // create site course
    $newsite = new object();
    $newsite->fullname = "";
    $newsite->shortname = "";
    $newsite->summary = NULL;
    $newsite->newsitems = 3;
    $newsite->numsections = 0;
    $newsite->category = 0;
    $newsite->format = 'site';
    // Only for this course
    $newsite->teacher = get_string("defaultcourseteacher");
    $newsite->teachers = get_string("defaultcourseteachers");
    $newsite->student = get_string("defaultcoursestudent");
    $newsite->students = get_string("defaultcoursestudents");
    $newsite->timemodified = time();
    $DB->insert_record('course', $newsite);
    $SITE = get_site();
    if ($SITE->id != 1) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected site course id created!');
    }
    /// make sure site course context exists
    get_context_instance(CONTEXT_COURSE, $SITE->id);
    /// create default course category
    $cat = get_course_category();
    $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol' => 'manual', 'enrol_plugins_enabled' => 'manual', 'style' => 'default', 'template' => 'default', 'theme' => 'standardwhite', 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'blocks_version' => 2007081300, 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'tinymce,textarea');
    foreach ($defaults as $key => $value) {
        set_config($key, $value);
    }
    /// bootstrap mnet
    $mnethost = new object();
    $mnethost->wwwroot = $CFG->wwwroot;
    $mnethost->name = '';
    $mnethost->name = '';
    $mnethost->public_key = '';
    if (empty($_SERVER['SERVER_ADDR'])) {
        // SERVER_ADDR is only returned by Apache-like webservers
        preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches);
        $my_hostname = $matches[1];
        $my_ip = gethostbyname($my_hostname);
        // Returns unmodified hostname on failure. DOH!
        if ($my_ip == $my_hostname) {
            $mnethost->ip_address = 'UNKNOWN';
        } else {
            $mnethost->ip_address = $my_ip;
        }
    } else {
        $mnethost->ip_address = $_SERVER['SERVER_ADDR'];
    }
    $mnetid = $DB->insert_record('mnet_host', $mnethost);
    set_config('mnet_localhost_id', $mnetid);
    // Initial insert of mnet applications info
    $mnet_app = new object();
    $mnet_app->name = 'moodle';
    $mnet_app->display_name = 'Moodle';
    $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/mnet/land.php';
    $mnet_app->sso_jump_url = '/auth/mnet/land.php';
    $DB->insert_record('mnet_application', $mnet_app);
    $mnet_app = new object();
    $mnet_app->name = 'mahara';
    $mnet_app->display_name = 'Mahara';
    $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/xmlrpc/land.php';
    $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php';
    $DB->insert_record('mnet_application', $mnet_app);
    /// insert log entries - replaces statements section in install.xml
    update_log_display_entry('user', 'view', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('course', 'user report', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('course', 'view', 'course', 'fullname');
    update_log_display_entry('course', 'update', 'course', 'fullname');
    update_log_display_entry('course', 'enrol', 'course', 'fullname');
    update_log_display_entry('course', 'unenrol', 'course', 'fullname');
    update_log_display_entry('course', 'report log', 'course', 'fullname');
    update_log_display_entry('course', 'report live', 'course', 'fullname');
    update_log_display_entry('course', 'report outline', 'course', 'fullname');
    update_log_display_entry('course', 'report participation', 'course', 'fullname');
    update_log_display_entry('course', 'report stats', 'course', 'fullname');
    update_log_display_entry('message', 'write', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('message', 'read', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('message', 'add contact', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('message', 'remove contact', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('message', 'block contact', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('message', 'unblock contact', 'user', 'CONCAT(firstname,\' \',lastname)');
    update_log_display_entry('group', 'view', 'groups', 'name');
    /// Create guest record
    $guest = new object();
    $guest->auth = 'manual';
    $guest->username = '******';
    $guest->password = hash_internal_user_password('guest');
    $guest->firstname = get_string('guestuser');
    $guest->lastname = ' ';
    $guest->email = 'root@localhost';
    $guest->description = get_string('guestuserinfo');
    $guest->mnethostid = $CFG->mnet_localhost_id;
    $guest->confirmed = 1;
    $guest->lang = $CFG->lang;
    $guest->timemodified = time();
    $guest->id = $DB->insert_record('user', $guest);
    /// Now create admin user
    $admin = new object();
    $admin->auth = 'manual';
    $admin->firstname = get_string('admin');
    $admin->lastname = get_string('user');
    $admin->username = '******';
    $admin->password = '******';
    $admin->email = '';
    $admin->confirmed = 1;
    $admin->mnethostid = $CFG->mnet_localhost_id;
    $admin->lang = $CFG->lang;
    $admin->maildisplay = 1;
    $admin->timemodified = time();
    $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr();
    // installation hijacking prevention
    $admin->id = $DB->insert_record('user', $admin);
    /// Install the roles system.
    $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
    $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
    $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
    $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
    $studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
    $guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'moodle/legacy:guest');
    $userrole = create_role(get_string('authenticateduser'), 'user', get_string('authenticateduserdescription'), 'moodle/legacy:user');
    /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
    update_capabilities('moodle');
    /// assign default roles
    role_assign($guestrole, $guest->id, 0, $syscontext->id);
    role_assign($adminrole, $admin->id, 0, $syscontext->id);
    /// Default allow assign/override/switch.
    $defaultallows = array($coursecreatorrole => $noneditteacherrole, $coursecreatorrole => $editteacherrole, $coursecreatorrole => $studentrole, $coursecreatorrole => $guestrole, $editteacherrole => $noneditteacherrole, $editteacherrole => $studentrole, $editteacherrole => $guestrole);
    foreach ($defaultallows as $fromroleid => $toroleid) {
        allow_assign($fromroleid, $toroleid);
        allow_override($fromroleid, $toroleid);
        // There is a rant about this in MDL-15841.
        allow_switch($fromroleid, $toroleid);
    }
    allow_switch($noneditteacherrole, $studentrole);
    /// Set up the context levels where you can assign each role.
    set_role_contextlevels($adminrole, get_default_contextlevels('admin'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
}
Example #20
0
    public function test_can_be_edited_by_user() {
        $this->resetAfterTest(true);

        $syscontext = context_system::instance();
        $course = $this->getDataGenerator()->create_course();
        $coursecontext = context_course::instance($course->id);
        $roleid = create_role('A role', 'arole', 'A role', '');
        set_role_contextlevels($roleid, array($syscontext->contextlevel, $coursecontext->contextlevel));
        $user = $this->getDataGenerator()->create_user();
        $this->setUser($user);

        $plugintype = new repository_type('flickr_public');
        $plugintype->create(true);
        $params = array(
            'name' => 'Flickr Public'
        );

        // Instance on a site level.
        $repoid = repository::static_function('flickr_public', 'create', 'flickr_public', 0, $syscontext, $params);
        $systemrepo = repository::get_repository_by_id($repoid, $syscontext);

        role_assign($roleid, $user->id, $syscontext->id);
        assign_capability('moodle/site:config', CAP_ALLOW, $roleid, $syscontext, true);
        assign_capability('repository/flickr_public:view', CAP_ALLOW, $roleid, $syscontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertTrue($systemrepo->can_be_edited_by_user());

        assign_capability('repository/flickr_public:view', CAP_PROHIBIT, $roleid, $syscontext, true);
        assign_capability('moodle/site:config', CAP_PROHIBIT, $roleid, $syscontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertFalse($systemrepo->can_be_edited_by_user());

        assign_capability('repository/flickr_public:view', CAP_ALLOW, $roleid, $syscontext, true);
        assign_capability('moodle/site:config', CAP_PROHIBIT, $roleid, $syscontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertFalse($systemrepo->can_be_edited_by_user());

        role_unassign($roleid, $user->id, $syscontext->id);
        accesslib_clear_all_caches_for_unit_testing();

        // Instance on a course level.
        $this->getDataGenerator()->enrol_user($user->id, $course->id, $roleid);

        $repoid = repository::static_function('flickr_public', 'create', 'flickr_public', 0, $coursecontext, $params);
        $courserepo = repository::get_repository_by_id($repoid, $coursecontext);

        assign_capability('moodle/course:update', CAP_ALLOW, $roleid, $coursecontext, true);
        assign_capability('repository/flickr_public:view', CAP_ALLOW, $roleid, $coursecontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertTrue($courserepo->can_be_edited_by_user());

        assign_capability('repository/flickr_public:view', CAP_PROHIBIT, $roleid, $coursecontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertFalse($courserepo->can_be_edited_by_user());

        assign_capability('moodle/course:update', CAP_ALLOW, $roleid, $coursecontext, true);
        assign_capability('repository/flickr_public:view', CAP_PROHIBIT, $roleid, $coursecontext, true);
        accesslib_clear_all_caches_for_unit_testing();
        $this->assertFalse($courserepo->can_be_edited_by_user());

        role_unassign($roleid, $user->id, $coursecontext->id);
        accesslib_clear_all_caches_for_unit_testing();

        // Instance on a user level.
        $otheruser = $this->getDataGenerator()->create_user();
        $otherusercontext = context_user::instance($otheruser->id);
        role_assign($roleid, $user->id, $syscontext->id);
        assign_capability('repository/flickr_public:view', CAP_ALLOW, $roleid, $syscontext, true);
        accesslib_clear_all_caches_for_unit_testing();

        // Editing someone else's instance.
        $repoid = repository::static_function('flickr_public', 'create', 'flickr_public', 0, $otherusercontext, $params);
        $userrepo = repository::get_repository_by_id($repoid, $syscontext);
        $this->assertFalse($userrepo->can_be_edited_by_user());

        // Editing my own instance.
        $usercontext = context_user::instance($user->id);
        $repoid = repository::static_function('flickr_public', 'create', 'flickr_public', 0, $usercontext, $params);
        $userrepo = repository::get_repository_by_id($repoid, $syscontext);
        $this->assertTrue($userrepo->can_be_edited_by_user());

    }
Example #21
0
    /**
     * Creates a new role in the system.
     *
     * You can fill $record with the role 'name',
     * 'shortname', 'description' and 'archetype'.
     *
     * If an archetype is specified it's capabilities,
     * context where the role can be assigned and
     * all other properties are copied from the archetype;
     * if no archetype is specified it will create an
     * empty role.
     *
     * @param array|stdClass $record
     * @return int The new role id
     */
    public function create_role($record=null) {
        global $DB;

        $this->rolecount++;
        $i = $this->rolecount;

        $record = (array)$record;

        if (empty($record['shortname'])) {
            $record['shortname'] = 'role-' . $i;
        }

        if (empty($record['name'])) {
            $record['name'] = 'Test role ' . $i;
        }

        if (empty($record['description'])) {
            $record['description'] = 'Test role ' . $i . ' description';
        }

        if (empty($record['archetype'])) {
            $record['archetype'] = '';
        } else {
            $archetypes = get_role_archetypes();
            if (empty($archetypes[$record['archetype']])) {
                throw new coding_exception('\'role\' requires the field \'archetype\' to specify a ' .
                    'valid archetype shortname (editingteacher, student...)');
            }
        }

        // Creates the role.
        if (!$newroleid = create_role($record['name'], $record['shortname'], $record['description'], $record['archetype'])) {
            throw new coding_exception('There was an error creating \'' . $record['shortname'] . '\' role');
        }

        // If no archetype was specified we allow it to be added to all contexts,
        // otherwise we allow it in the archetype contexts.
        if (!$record['archetype']) {
            $contextlevels = array_keys(context_helper::get_all_levels());
        } else {
            // Copying from the archetype default rol.
            $archetyperoleid = $DB->get_field(
                'role',
                'id',
                array('shortname' => $record['archetype'], 'archetype' => $record['archetype'])
            );
            $contextlevels = get_role_contextlevels($archetyperoleid);
        }
        set_role_contextlevels($newroleid, $contextlevels);

        if ($record['archetype']) {

            // We copy all the roles the archetype can assign, override and switch to.
            if ($record['archetype']) {
                $types = array('assign', 'override', 'switch');
                foreach ($types as $type) {
                    $rolestocopy = get_default_role_archetype_allows($type, $record['archetype']);
                    foreach ($rolestocopy as $tocopy) {
                        $functionname = 'allow_' . $type;
                        $functionname($newroleid, $tocopy);
                    }
                }
            }

            // Copying the archetype capabilities.
            $sourcerole = $DB->get_record('role', array('id' => $archetyperoleid));
            role_cap_duplicate($sourcerole, $newroleid);
        }

        return $newroleid;
    }
Example #22
0
function upgrade_to_new_roles_ui()
{
    global $CFG;
    /// New table for storing which roles can be assigned in which contexts.
    /// Define table role_context_levels to be created
    $table = new XMLDBTable('role_context_levels');
    /// Adding fields to table role_context_levels
    $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
    $table->addFieldInfo('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
    $table->addFieldInfo('contextlevel', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
    /// Adding keys to table role_context_levels
    $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
    $table->addKeyInfo('contextlevel-roleid', XMLDB_KEY_UNIQUE, array('contextlevel', 'roleid'));
    $table->addKeyInfo('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
    /// Conditionally launch create table for role_context_levels
    if (!table_exists($table)) {
        create_table($table);
    }
    /// Now populate the role_context_levels table with the defaults that match
    /// moodle_install_roles, and any other combinations that exist in this system.
    $roleids = get_records_menu('role', '', '', '', 'shortname,id');
    /// Defaults, should match moodle_install_roles.
    $rolecontextlevels = array();
    if (isset($roleids['admin'])) {
        $rolecontextlevels[$roleids['admin']] = get_default_contextlevels('admin');
    }
    if (isset($roleids['coursecreator'])) {
        $rolecontextlevels[$roleids['coursecreator']] = get_default_contextlevels('coursecreator');
    }
    if (isset($roleids['editingteacher'])) {
        $rolecontextlevels[$roleids['editingteacher']] = get_default_contextlevels('editingteacher');
    }
    if (isset($roleids['teacher'])) {
        $rolecontextlevels[$roleids['teacher']] = get_default_contextlevels('teacher');
    }
    if (isset($roleids['student'])) {
        $rolecontextlevels[$roleids['student']] = get_default_contextlevels('student');
    }
    if (isset($roleids['guest'])) {
        $rolecontextlevels[$roleids['guest']] = get_default_contextlevels('guest');
    }
    if (isset($roleids['user'])) {
        $rolecontextlevels[$roleids['user']] = get_default_contextlevels('user');
    }
    /// See what other role assignments are in this database, extend the allowed
    /// lists to allow them too.
    $existingrolecontextlevels = get_recordset_sql('SELECT DISTINCT ra.roleid, con.contextlevel FROM
            {role_assignments} ra JOIN {context} con ON ra.contextid = con.id');
    foreach ($existingrolecontextlevels as $rcl) {
        $rcl = (object) $rcl;
        if (!isset($rolecontextlevels[$rcl->roleid])) {
            $rolecontextlevels[$rcl->roleid] = array($rcl->contextlevel);
        } else {
            if (!in_array($rcl->contextlevel, $rolecontextlevels[$rcl->roleid])) {
                $rolecontextlevels[$rcl->roleid][] = $rcl->contextlevel;
            }
        }
    }
    /// Put the data into the database.
    foreach ($rolecontextlevels as $roleid => $contextlevels) {
        set_role_contextlevels($roleid, $contextlevels);
    }
    /// Remove any role overrides for moodle/site:doanything, or any permissions
    /// for it in a role without legacy:admin.
    $systemcontext = get_context_instance(CONTEXT_SYSTEM);
    // Remove all overrides.
    delete_records_select('role_capabilities', "capability = 'moodle/site:doanything'\n        AND contextid <> {$systemcontext->id}");
    $roletest = '';
    // Get the ids of all the roles that are moodle/legacy:admin.
    if ($adminroleids = get_records_select_menu('role_capabilities', "capability = 'moodle/legacy:admin' AND permission = 1 AND contextid = {$systemcontext->id}", '', 'id, roleid')) {
        $roletest = 'IN ( ' . implode(',', $adminroleids) . ')';
    } else {
        $adminroleids = array();
    }
    delete_records_select('role_capabilities', "roleid NOT {$roletest}\n        AND capability = 'moodle/site:doanything'AND contextid = {$systemcontext->id}");
    set_field_select('role_capabilities', 'permission', 1, "roleid {$roletest} AND capability = 'moodle/site:doanything' AND contextid = {$systemcontext->id}");
    // And for any admin-y roles where moodle/site:doanything is not set, set it.
    $doanythingroleids = get_records_select_menu('role_capabilities', "capability = 'moodle/site:doanything' AND permission = 1 AND contextid = {$systemcontext->id}", '', 'id, roleid');
    foreach ($adminroleids as $roleid) {
        if (!in_array($roleid, $doanythingroleids)) {
            $rc = new stdClass();
            $rc->contextid = $systemcontext->id;
            $rc->roleid = $roleid;
            $rc->capability = 'moodle/site:doanything';
            $rc->permission = 1;
            $rc->timemodified = time();
            insert_record('role_capabilities', $rc);
        }
    }
    set_config('roles_ui_backport_upgraded', 1);
}
Example #23
0
            $a->shortname = $roles[$roleid]->shortname;
            $a->legacytype = $roles[$roleid]->archetype;
            if (empty($a->legacytype)) {
                $warning = get_string('resetrolesurenolegacy', 'role', $a);
            } else {
                $warning = get_string('resetrolesure', 'role', $a);
            }
            $formcontinue = new single_button(new moodle_url('manage.php', $optionsyes), get_string('yes'));
            $formcancel = new single_button(new moodle_url('manage.php', $optionsno), get_string('no'), 'get');
            echo $OUTPUT->confirm($warning, $formcontinue, $formcancel);
            echo $OUTPUT->footer();
            die;
        }
        // Reset context levels for standard archetypes
        if ($roles[$roleid]->archetype) {
            set_role_contextlevels($roleid, get_default_contextlevels($roles[$roleid]->archetype));
        }
        //reset or delete the capabilities
        reset_role_capabilities($roleid);
        // Mark context dirty, log and redirect.
        mark_context_dirty($systemcontext->path);
        add_to_log(SITEID, 'role', 'reset', 'admin/roles/manage.php?action=reset&roleid=' . $roleid, $roles[$roleid]->localname, '', $USER->id);
        redirect($defineurl . '?action=view&roleid=' . $roleid);
        break;
}
/// Print the page header and tabs.
echo $OUTPUT->header();
$currenttab = 'manage';
include_once 'managetabs.php';
/// Initialise table.
$table = new html_table();
Example #24
0
 public function save_changes()
 {
     global $DB;
     if (!$this->roleid) {
         // Creating role
         if (isset($this->legacyroles[$this->role->legacytype])) {
             $legacycap = $this->legacyroles[$this->role->legacytype];
         } else {
             $legacycap = '';
         }
         $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $legacycap);
         $this->roleid = $this->role->id;
         // Needed to make the parent::save_changes(); call work.
     } else {
         // Updating role
         $DB->update_record('role', $this->role);
         // Legacy type
         foreach ($this->legacyroles as $type => $cap) {
             if ($type == $this->role->legacytype) {
                 assign_capability($cap, CAP_ALLOW, $this->role->id, $this->context->id);
             } else {
                 unassign_capability($cap, $this->role->id);
             }
         }
     }
     // Assignable contexts.
     set_role_contextlevels($this->role->id, $this->contextlevels);
     // Permissions.
     parent::save_changes();
 }
 /**
  * Test default enrol roles.
  */
 public function test_get_default_enrol_roles()
 {
     $this->resetAfterTest();
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     $id2 = create_role('New student role', 'student2', 'New student description', 'student');
     set_role_contextlevels($id2, array(CONTEXT_COURSE));
     $allroles = get_all_roles();
     $expected = array($id2 => $allroles[$id2]);
     foreach (get_role_archetypes() as $archetype) {
         $defaults = get_default_contextlevels($archetype);
         if (in_array(CONTEXT_COURSE, $defaults)) {
             $roles = get_archetype_roles($archetype);
             foreach ($roles as $role) {
                 $expected[$role->id] = $role;
             }
         }
     }
     $roles = get_default_enrol_roles($coursecontext);
     foreach ($allroles as $role) {
         $this->assertEquals(isset($expected[$role->id]), isset($roles[$role->id]));
         if (isset($roles[$role->id])) {
             $this->assertSame(role_get_name($role, $coursecontext), $roles[$role->id]);
         }
     }
 }
 public function save_changes()
 {
     global $DB, $CFG;
     if (!$this->roleid) {
         // Creating role.
         $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $this->role->archetype);
         $this->roleid = $this->role->id;
         // Needed to make the parent::save_changes(); call work.
     } else {
         // Updating role.
         $DB->update_record('role', $this->role);
         // This will ensure the course contacts cache is purged so name changes get updated in
         // the UI. It would be better to do this only when we know that fields affected are
         // updated. But thats getting into the weeds of the coursecat cache and role edits
         // should not be that frequent, so here is the ugly brutal approach.
         require_once $CFG->libdir . '/coursecatlib.php';
         coursecat::role_assignment_changed($this->role->id, context_system::instance());
     }
     // Assignable contexts.
     set_role_contextlevels($this->role->id, $this->contextlevels);
     // Set allowed roles.
     $this->save_allow('assign');
     $this->save_allow('override');
     $this->save_allow('switch');
     // Permissions.
     parent::save_changes();
 }
Example #27
0
/**
 * 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;
    if (!defined('RESTORE_SILENTLY')) {
        echo "<li>" . get_string("creatingrolesdefinitions") . '</li>';
    }
    $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
            } else {
                // 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);
                }
            }
            /// 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;
}
Example #28
0
/**
 * @package mod
 * @subpackage adobeconnect
 * @author Akinsaya Delamarre (adelamarre@remote-learner.net)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function xmldb_adobeconnect_install()
{
    global $DB;
    $result = true;
    $sysctx = context_system::instance();
    $levels = array(CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE);
    $param = array('shortname' => 'coursecreator');
    $coursecreator = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    if (empty($coursecreator)) {
        $param = array('archetype' => 'coursecreator');
        $coursecreator = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    }
    $coursecreatorrid = array_shift($coursecreator);
    $param = array('shortname' => 'editingteacher');
    $editingteacher = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    if (empty($editingteacher)) {
        $param = array('archetype' => 'editingteacher');
        $editingteacher = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    }
    $editingteacherrid = array_shift($editingteacher);
    $param = array('shortname' => 'teacher');
    $teacher = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    if (empty($teacher)) {
        $param = array('archetype' => 'teacher');
        $teacher = $DB->get_records('role', $param, 'id ASC', 'id', 0, 1);
    }
    $teacherrid = array_shift($teacher);
    // Fully setup the Adobe Connect Presenter role.
    $param = array('shortname' => 'adobeconnectpresenter');
    if (!($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnectpresenter', 'adobeconnect'), 'adobeconnectpresenter', get_string('adobeconnectpresenterdescription', 'adobeconnect'), 'adobeconnectpresenter')) {
            $mrole = new stdClass();
            $mrole->id = $rid;
            $result = $result && assign_capability('mod/adobeconnect:meetingpresenter', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    if (isset($coursecreatorrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($coursecreatorrid->id, $mrole->id);
        }
    }
    if (isset($editingteacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($editingteacherrid->id, $mrole->id);
        }
    }
    if (isset($teacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($teacherrid->id, $mrole->id);
        }
    }
    // Fully setup the Adobe Connect Participant role.
    $param = array('shortname' => 'adobeconnectparticipant');
    if ($result && !($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnectparticipant', 'adobeconnect'), 'adobeconnectparticipant', get_string('adobeconnectparticipantdescription', 'adobeconnect'), 'adobeconnectparticipant')) {
            $mrole = new stdClass();
            $mrole->id = $rid;
            $result = $result && assign_capability('mod/adobeconnect:meetingparticipant', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    if (isset($coursecreatorrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($coursecreatorrid->id, $mrole->id);
        }
    }
    if (isset($editingteacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($editingteacherrid->id, $mrole->id);
        }
    }
    if (isset($teacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($teacherrid->id, $mrole->id);
        }
    }
    // Fully setup the Adobe Connect Host role.
    $param = array('shortname' => 'adobeconnecthost');
    if ($result && !($mrole = $DB->get_record('role', $param))) {
        if ($rid = create_role(get_string('adobeconnecthost', 'adobeconnect'), 'adobeconnecthost', get_string('adobeconnecthostdescription', 'adobeconnect'), 'adobeconnecthost')) {
            $mrole = new stdClass();
            $mrole->id = $rid;
            $result = $result && assign_capability('mod/adobeconnect:meetinghost', CAP_ALLOW, $mrole->id, $sysctx->id);
            set_role_contextlevels($mrole->id, $levels);
        } else {
            $result = false;
        }
    }
    if (isset($coursecreatorrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $coursecreatorrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($coursecreatorrid->id, $mrole->id);
        }
    }
    if (isset($editingteacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $editingteacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($editingteacherrid->id, $mrole->id);
        }
    }
    if (isset($teacherrid->id)) {
        $param = array('allowassign' => $mrole->id, 'roleid' => $teacherrid->id);
        if (!$DB->get_record('role_allow_assign', $param)) {
            allow_assign($teacherrid->id, $mrole->id);
        }
    }
    return $result;
}
Example #29
0
function xmldb_main_install()
{
    global $CFG, $DB, $SITE, $OUTPUT;
    /// make sure system context exists
    $syscontext = get_system_context(false);
    if ($syscontext->id != 1) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new system context id!');
    }
    /// create site course
    $newsite = new stdClass();
    $newsite->fullname = '';
    $newsite->shortname = '';
    $newsite->summary = NULL;
    $newsite->newsitems = 3;
    $newsite->numsections = 0;
    $newsite->category = 0;
    $newsite->format = 'site';
    // Only for this course
    $newsite->timecreated = time();
    $newsite->timemodified = $newsite->timecreated;
    $newsite->id = $DB->insert_record('course', $newsite);
    $SITE = get_site();
    if ($newsite->id != 1 or $SITE->id != 1) {
        throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new site course id!');
    }
    /// make sure site course context exists
    get_context_instance(CONTEXT_COURSE, $SITE->id);
    /// create default course category
    $cat = get_course_category();
    $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol_plugins_enabled' => 'manual,guest,self,cohort', 'theme' => theme_config::DEFAULT_THEME, 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'tinymce,textarea');
    foreach ($defaults as $key => $value) {
        set_config($key, $value);
    }
    /// bootstrap mnet
    $mnethost = new stdClass();
    $mnethost->wwwroot = $CFG->wwwroot;
    $mnethost->name = '';
    $mnethost->name = '';
    $mnethost->public_key = '';
    if (empty($_SERVER['SERVER_ADDR'])) {
        // SERVER_ADDR is only returned by Apache-like webservers
        preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches);
        $my_hostname = $matches[1];
        $my_ip = gethostbyname($my_hostname);
        // Returns unmodified hostname on failure. DOH!
        if ($my_ip == $my_hostname) {
            $mnethost->ip_address = 'UNKNOWN';
        } else {
            $mnethost->ip_address = $my_ip;
        }
    } else {
        $mnethost->ip_address = $_SERVER['SERVER_ADDR'];
    }
    $mnetid = $DB->insert_record('mnet_host', $mnethost);
    set_config('mnet_localhost_id', $mnetid);
    // Initial insert of mnet applications info
    $mnet_app = new stdClass();
    $mnet_app->name = 'moodle';
    $mnet_app->display_name = 'Moodle';
    $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/mnet/land.php';
    $mnet_app->sso_jump_url = '/auth/mnet/jump.php';
    $moodleapplicationid = $DB->insert_record('mnet_application', $mnet_app);
    $mnet_app = new stdClass();
    $mnet_app->name = 'mahara';
    $mnet_app->display_name = 'Mahara';
    $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php';
    $mnet_app->sso_land_url = '/auth/xmlrpc/land.php';
    $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php';
    $DB->insert_record('mnet_application', $mnet_app);
    // Set up the probably-to-be-removed-soon 'All hosts' record
    $mnetallhosts = new stdClass();
    $mnetallhosts->wwwroot = '';
    $mnetallhosts->ip_address = '';
    $mnetallhosts->public_key = '';
    $mnetallhosts->public_key_expires = 0;
    $mnetallhosts->last_connect_time = 0;
    $mnetallhosts->last_log_id = 0;
    $mnetallhosts->deleted = 0;
    $mnetallhosts->name = 'All Hosts';
    $mnetallhosts->applicationid = $moodleapplicationid;
    $mnetallhosts->id = $DB->insert_record('mnet_host', $mnetallhosts, true);
    set_config('mnet_all_hosts_id', $mnetallhosts->id);
    /// Create guest record - do not assign any role, guest user get's the default guest role automatically on the fly
    $guest = new stdClass();
    $guest->auth = 'manual';
    $guest->username = '******';
    $guest->password = hash_internal_user_password('guest');
    $guest->firstname = get_string('guestuser');
    $guest->lastname = ' ';
    $guest->email = 'root@localhost';
    $guest->description = get_string('guestuserinfo');
    $guest->mnethostid = $CFG->mnet_localhost_id;
    $guest->confirmed = 1;
    $guest->lang = $CFG->lang;
    $guest->timemodified = time();
    $guest->id = $DB->insert_record('user', $guest);
    if ($guest->id != 1) {
        echo $OUTPUT->notification('Unexpected id generated for the Guest account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    // Store guest id
    set_config('siteguest', $guest->id);
    /// Now create admin user
    $admin = new stdClass();
    $admin->auth = 'manual';
    $admin->firstname = get_string('admin');
    $admin->lastname = get_string('user');
    $admin->username = '******';
    $admin->password = '******';
    $admin->email = '';
    $admin->confirmed = 1;
    $admin->mnethostid = $CFG->mnet_localhost_id;
    $admin->lang = $CFG->lang;
    $admin->maildisplay = 1;
    $admin->timemodified = time();
    $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr();
    // installation hijacking prevention
    $admin->id = $DB->insert_record('user', $admin);
    if ($admin->id != 2) {
        echo $OUTPUT->notification('Unexpected id generated for the Admin account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem');
    }
    if ($admin->id != $guest->id + 1) {
        echo $OUTPUT->notification('Nonconsecutive id generated for the Admin account. Your database configuration or clustering setup may not be fully supported.', 'notifyproblem');
    }
    /// Store list of admins
    set_config('siteadmins', $admin->id);
    /// Install the roles system.
    $managerrole = create_role(get_string('manager', 'role'), 'manager', get_string('managerdescription', 'role'), 'manager');
    $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'coursecreator');
    $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'editingteacher');
    $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'teacher');
    $studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'student');
    $guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'guest');
    $userrole = create_role(get_string('authenticateduser'), 'user', get_string('authenticateduserdescription'), 'user');
    $frontpagerole = create_role(get_string('frontpageuser', 'role'), 'frontpage', get_string('frontpageuserdescription', 'role'), 'frontpage');
    /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    update_capabilities('moodle');
    /// Default allow assign
    $defaultallowassigns = array(array($managerrole, $managerrole), array($managerrole, $coursecreatorrole), array($managerrole, $editteacherrole), array($managerrole, $noneditteacherrole), array($managerrole, $studentrole), array($editteacherrole, $noneditteacherrole), array($editteacherrole, $studentrole));
    foreach ($defaultallowassigns as $allow) {
        list($fromroleid, $toroleid) = $allow;
        allow_assign($fromroleid, $toroleid);
    }
    /// Default allow override
    $defaultallowoverrides = array(array($managerrole, $managerrole), array($managerrole, $coursecreatorrole), array($managerrole, $editteacherrole), array($managerrole, $noneditteacherrole), array($managerrole, $studentrole), array($managerrole, $guestrole), array($managerrole, $userrole), array($managerrole, $frontpagerole), array($editteacherrole, $noneditteacherrole), array($editteacherrole, $studentrole), array($editteacherrole, $guestrole));
    foreach ($defaultallowoverrides as $allow) {
        list($fromroleid, $toroleid) = $allow;
        allow_override($fromroleid, $toroleid);
        // There is a rant about this in MDL-15841.
    }
    /// Default allow switch.
    $defaultallowswitch = array(array($managerrole, $editteacherrole), array($managerrole, $noneditteacherrole), array($managerrole, $studentrole), array($managerrole, $guestrole), array($editteacherrole, $noneditteacherrole), array($editteacherrole, $studentrole), array($editteacherrole, $guestrole), array($noneditteacherrole, $studentrole), array($noneditteacherrole, $guestrole));
    foreach ($defaultallowswitch as $allow) {
        list($fromroleid, $toroleid) = $allow;
        allow_switch($fromroleid, $toroleid);
    }
    /// Set up the context levels where you can assign each role.
    set_role_contextlevels($managerrole, get_default_contextlevels('manager'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
    // Init themes
    set_config('themerev', 1);
    // Install licenses
    require_once $CFG->libdir . '/licenselib.php';
    license_manager::install_licenses();
    /// Add two lines of data into this new table
    $mypage = new stdClass();
    $mypage->userid = NULL;
    $mypage->name = '__default';
    $mypage->private = 0;
    $mypage->sortorder = 0;
    if (!$DB->record_exists('my_pages', array('userid' => NULL, 'private' => 0))) {
        $DB->insert_record('my_pages', $mypage);
    }
    $mypage->private = 1;
    if (!$DB->record_exists('my_pages', array('userid' => NULL, 'private' => 1))) {
        $DB->insert_record('my_pages', $mypage);
    }
}
Example #30
0
/**
 * Installs the roles system.
 * This function runs on a fresh install as well as on an upgrade from the old
 * hard-coded student/teacher/admin etc. roles to the new roles system.
 */
function moodle_install_roles()
{
    global $CFG, $db;
    /// Create a system wide context for assignemnt.
    $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
    /// Create default/legacy roles and capabilities.
    /// (1 legacy capability per legacy role at system level).
    $adminrole = create_role(addslashes(get_string('administrator')), 'admin', addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
    $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator', addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
    $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher', addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
    $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher', addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
    $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student', addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
    $guestrole = create_role(addslashes(get_string('guest')), 'guest', addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
    $userrole = create_role(addslashes(get_string('authenticateduser')), 'user', addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
    /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
    if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
        error('Could not assign moodle/site:doanything to the admin role');
    }
    if (!update_capabilities()) {
        error('Had trouble upgrading the core capabilities for the Roles System');
    }
    /// Look inside user_admin, user_creator, user_teachers, user_students and
    /// assign above new roles. If a user has both teacher and student role,
    /// only teacher role is assigned. The assignment should be system level.
    $dbtables = $db->MetaTables('TABLES');
    /// Set up the progress bar
    $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
    $totalcount = $progresscount = 0;
    foreach ($usertables as $usertable) {
        if (in_array($CFG->prefix . $usertable, $dbtables)) {
            $totalcount += count_records($usertable);
        }
    }
    print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
    /// Upgrade the admins.
    /// Sort using id ASC, first one is primary admin.
    if (in_array($CFG->prefix . 'user_admins', $dbtables)) {
        if ($rs = get_recordset_sql('SELECT * from ' . $CFG->prefix . 'user_admins ORDER BY ID ASC')) {
            while ($admin = rs_fetch_next_record($rs)) {
                role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
                $progresscount++;
                print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
            }
            rs_close($rs);
        }
    } else {
        // This is a fresh install.
    }
    /// Upgrade course creators.
    if (in_array($CFG->prefix . 'user_coursecreators', $dbtables)) {
        if ($rs = get_recordset('user_coursecreators')) {
            while ($coursecreator = rs_fetch_next_record($rs)) {
                role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
                $progresscount++;
                print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
            }
            rs_close($rs);
        }
    }
    /// Upgrade editting teachers and non-editting teachers.
    if (in_array($CFG->prefix . 'user_teachers', $dbtables)) {
        if ($rs = get_recordset('user_teachers')) {
            while ($teacher = rs_fetch_next_record($rs)) {
                // removed code here to ignore site level assignments
                // since the contexts are separated now
                // populate the user_lastaccess table
                $access = new object();
                $access->timeaccess = $teacher->timeaccess;
                $access->userid = $teacher->userid;
                $access->courseid = $teacher->course;
                insert_record('user_lastaccess', $access);
                // assign the default student role
                $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course);
                // needs cache
                // hidden teacher
                if ($teacher->authority == 0) {
                    $hiddenteacher = 1;
                } else {
                    $hiddenteacher = 0;
                }
                if ($teacher->editall) {
                    // editting teacher
                    role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
                } else {
                    role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
                }
                $progresscount++;
                print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
            }
            rs_close($rs);
        }
    }
    /// Upgrade students.
    if (in_array($CFG->prefix . 'user_students', $dbtables)) {
        if ($rs = get_recordset('user_students')) {
            while ($student = rs_fetch_next_record($rs)) {
                // populate the user_lastaccess table
                $access = new object();
                $access->timeaccess = $student->timeaccess;
                $access->userid = $student->userid;
                $access->courseid = $student->course;
                insert_record('user_lastaccess', $access);
                // assign the default student role
                $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
                role_assign($studentrole, $student->userid, 0, $coursecontext->id, $student->timestart, $student->timeend, 0, $student->enrol, $student->time);
                $progresscount++;
                print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
            }
            rs_close($rs);
        }
    }
    /// Upgrade guest (only 1 entry).
    if ($guestuser = get_record('user', 'username', 'guest')) {
        role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
    }
    print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
    /// Insert the correct records for legacy roles
    allow_assign($adminrole, $adminrole);
    allow_assign($adminrole, $coursecreatorrole);
    allow_assign($adminrole, $noneditteacherrole);
    allow_assign($adminrole, $editteacherrole);
    allow_assign($adminrole, $studentrole);
    allow_assign($adminrole, $guestrole);
    allow_assign($coursecreatorrole, $noneditteacherrole);
    allow_assign($coursecreatorrole, $editteacherrole);
    allow_assign($coursecreatorrole, $studentrole);
    allow_assign($coursecreatorrole, $guestrole);
    allow_assign($editteacherrole, $noneditteacherrole);
    allow_assign($editteacherrole, $studentrole);
    allow_assign($editteacherrole, $guestrole);
    /// Set up default allow override matrix
    allow_override($adminrole, $adminrole);
    allow_override($adminrole, $coursecreatorrole);
    allow_override($adminrole, $noneditteacherrole);
    allow_override($adminrole, $editteacherrole);
    allow_override($adminrole, $studentrole);
    allow_override($adminrole, $guestrole);
    allow_override($adminrole, $userrole);
    //See MDL-15841
    //allow_override($editteacherrole, $noneditteacherrole);
    //allow_override($editteacherrole, $studentrole);
    //allow_override($editteacherrole, $guestrole);
    /// Set up the context levels where you can assign each role.
    set_role_contextlevels($adminrole, get_default_contextlevels('admin'));
    set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
    set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
    set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
    set_role_contextlevels($studentrole, get_default_contextlevels('student'));
    set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
    set_role_contextlevels($userrole, get_default_contextlevels('user'));
}