/**
  * Constructor.
  * @throws Command_Exception.
  */
 public function __construct()
 {
     global $DB;
     // Getting command description.
     $cmd_name = vmoodle_get_string('cmdsynccapabilityname', 'vmoodleadminset_roles');
     $cmd_desc = vmoodle_get_string('cmdsynccapabilitydesc', 'vmoodleadminset_roles');
     // Creating platform parameter.
     $platform_param = new Command_Parameter('platform', 'enum', vmoodle_get_string('platformparamsyncdesc', 'vmoodleadminset_roles'), null, get_available_platforms());
     // Getting role parameter.
     $roles = role_fix_names(get_all_roles(), \context_system::instance(), ROLENAME_ORIGINAL);
     $rolemenu = array();
     foreach ($roles as $r) {
         $rolemenu[$r->shortname] = $r->name;
     }
     $role_param = new Command_Parameter('role', 'enum', vmoodle_get_string('roleparamsyncdesc', 'vmoodleadminset_roles'), null, $rolemenu);
     // Creating capability parameter.
     $records = $DB->get_records('capabilities', null, 'name', 'name');
     $capabilities = array();
     foreach ($records as $record) {
         $capabilities[$record->name] = get_capability_string($record->name);
     }
     asort($capabilities);
     $capability_param = new Command_Parameter('capability', 'enum', vmoodle_get_string('capabilityparamsyncdesc', 'vmoodleadminset_roles'), null, $capabilities);
     // Creating command.
     parent::__construct($cmd_name, $cmd_desc, array($platform_param, $role_param, $capability_param));
 }
コード例 #2
0
    function definition() {
        $mform =& $this->_form;
        $contextid = $this->_customdata['contextid'];

        $export = $mform->addElement('hidden', 'export', ''); // Will be overwritten below

        $table = new html_table();
        /* Styling done using HTML table and CSS */
        $table->attributes['class'] = 'export_form_table';
        $table->align = array('left', 'left', 'left', 'center');
        $table->wrap = array('nowrap', '', 'nowrap', 'nowrap');
        $table->data = array();

        $table->head = array(get_string('name'),
                            get_string('description'),
                            get_string('shortname'),
                            get_string('export', 'report_rolesmigration'));

        $roles = get_all_roles();
        foreach ($roles as $role) {
            $row = array();
            $roleurl = new moodle_url('/admin/roles/define.php', array('roleid' => $role->id, 'action' => 'view'));
            $row[0] = '<a href="'.$roleurl.'">'.format_string($role->name).'</a>';
            $row[1] = format_text($role->description, FORMAT_HTML);
            $row[2] = ($role->shortname);
            /* Export values are added from role checkboxes */
            $row[3] = '<input type="checkbox" name="export[]" value="'.$role->shortname.'" />';

            $table->data[] = $row;
        }

        $mform->addElement('html', html_writer::table($table));
        $mform->addElement('hidden', 'contextid', $contextid);
        $this->add_action_buttons(false, get_string('submitexport', 'report_rolesmigration'));
    }
コード例 #3
0
 function definition()
 {
     $mform =& $this->_form;
     $mform->addElement('header', 'general', get_string('message', 'message'));
     //$mform->addElement('htmleditor', 'messagebody', get_string('messagebody'), array('rows'=>15, 'cols'=>60));
     //$mform->addRule('messagebody', '', 'required', null, 'client');
     //$mform->setHelpButton('messagebody', array('writing', 'reading', 'questions', 'richtext'), false, 'editorhelpbutton');
     //$mform->addElement('format', 'format', get_string('format'));
     $courses = get_courses();
     foreach ($courses as $course) {
         //$mform->addElement('checkbox','courseid',get_string('course')." ".$course->shortname);
         $courselist[$course->id] = $course->shortname;
     }
     //$select = &$mform->addElement('select', 'colors', get_string('colors'), array('red', 'blue', 'green'), $attributes);
     //$select->setMultiple(true);
     $select =& $mform->addElement('select', 'courses', get_string('courses'), $courselist, 'size="15"');
     $select->setMultiple(true);
     //$mform->addElement('group', 'coursesgrp', get_string('courses'), $select , ' ', false);
     $allroles = array();
     if ($roles = get_all_roles()) {
         foreach ($roles as $role) {
             $rolename = strip_tags(format_string($role->name, true));
             $allroles[$role->id] = $rolename;
         }
     }
     $mform->addElement('select', 'role', get_string('roles'), $allroles);
     $mform->setDefault('role', 'Student');
     $this->add_action_buttons();
 }
コード例 #4
0
ファイル: roles.php プロジェクト: blionut/elearning
function get_moodle_roles()
{
    $moodle_roles = array();
    foreach (get_all_roles() as $role) {
        $moodle_roles[] = $role->shortname;
    }
    return $moodle_roles;
}
コード例 #5
0
ファイル: install.php プロジェクト: evltuma/moodle
function xmldb_enrol_flatfile_install()
{
    global $CFG, $DB;
    // Flatfile role mappings are empty by default now.
    $roles = get_all_roles();
    foreach ($roles as $role) {
        set_config('map_' . $role->id, $role->shortname, 'enrol_flatfile');
    }
}
コード例 #6
0
 /**
  * Constructor.
  * @param context $context the context this table relates to.
  * @param string $contextname $context->get_context_name() - to save recomputing.
  * @param array $allowoverrides
  * @param array $allowsafeoverrides
  * @param array $overridableroles
  */
 public function __construct($context, $contextname, $allowoverrides, $allowsafeoverrides, $overridableroles)
 {
     parent::__construct($context, 'permissions');
     $this->contextname = $contextname;
     $this->allowoverrides = $allowoverrides;
     $this->allowsafeoverrides = $allowsafeoverrides;
     $this->overridableroles = $overridableroles;
     $roles = get_all_roles($context);
     $this->roles = role_fix_names(array_reverse($roles, true), $context, ROLENAME_ALIAS, true);
 }
コード例 #7
0
 /**
  * Constructor.
  * @throws Command_Exception.
  */
 public function __construct()
 {
     global $DB;
     // Getting command description
     $cmd_name = vmoodle_get_string('cmdcomparename', 'vmoodleadminset_roles');
     $cmd_desc = vmoodle_get_string('cmdcomparedesc', 'vmoodleadminset_roles');
     // Getting role parameter
     $roles = role_fix_names(get_all_roles(), \context_system::instance(), ROLENAME_ORIGINAL);
     $rolemenu = array();
     foreach ($roles as $r) {
         $rolemenu[$r->shortname] = $r->localname;
     }
     $role_param = new Command_Parameter('role', 'enum', vmoodle_get_string('roleparamcomparedesc', 'vmoodleadminset_roles'), null, $rolemenu);
     // Creating command.
     parent::__construct($cmd_name, $cmd_desc, $role_param);
 }
コード例 #8
0
 public function definition()
 {
     $mform =& $this->_form;
     $category = $this->_customdata['category'];
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->addHelpButton('rolerenaming', 'rolerenaming');
     if ($roles = get_all_roles()) {
         $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL);
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSECAT);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->localname));
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     $mform->addElement('hidden', 'id', $category->id);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('html', get_string('roleedit_notice', 'local_contextadmin'));
     $this->add_action_buttons(true, get_string('savechanges'));
 }
コード例 #9
0
 /**
  * Sets the parameters property of the extended class
  *
  * @param    USER  global object
  * @param    CFG   global object
  */
 function set_parameters()
 {
     global $USER, $CFG;
     $site = get_site();
     $littlecfg = new object();
     // to avoid some notices later
     $littlecfg->wwwroot = $CFG->wwwroot;
     $courseparameters = array('label3' => array('langstr' => get_string('course'), 'value' => 'optgroup'), 'courseid' => array('langstr' => 'id', 'value' => $this->course->id), 'coursefullname' => array('langstr' => get_string('fullnamecourse'), 'value' => $this->course->fullname), 'courseshortname' => array('langstr' => get_string('shortnamecourse'), 'value' => $this->course->shortname), 'courseidnumber' => array('langstr' => get_string('idnumbercourse'), 'value' => $this->course->idnumber), 'coursesummary' => array('langstr' => get_string('summary'), 'value' => $this->course->summary), 'courseformat' => array('langstr' => get_string('format'), 'value' => $this->course->format));
     $roles = get_all_roles();
     $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
     $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS);
     foreach ($roles as $role) {
         $courseparameters['course' . $role->shortname] = array('langstr' => get_string('yourwordforx', '', $role->name), 'value' => $role->localname);
     }
     $courseparameters['label4'] = array('langstr' => '', 'value' => '/optgroup');
     $miscparameters = array('label5' => array('langstr' => get_string('miscellaneous'), 'value' => 'optgroup'), 'lang' => array('langstr' => get_string('preferredlanguage'), 'value' => current_language()), 'sitename' => array('langstr' => get_string('fullsitename'), 'value' => format_string($site->fullname)), 'serverurl' => array('langstr' => get_string('serverurl', 'resource', $littlecfg), 'value' => $littlecfg->wwwroot), 'currenttime' => array('langstr' => get_string('time'), 'value' => time()), 'encryptedcode' => array('langstr' => get_string('encryptedcode'), 'value' => $this->set_encrypted_parameter()), 'label6' => array('langstr' => "", 'value' => '/optgroup'));
     $userparameters = array();
     if (!empty($USER->id)) {
         $userparameters = array('label1' => array('langstr' => get_string('user'), 'value' => 'optgroup'), 'userid' => array('langstr' => 'id', 'value' => $USER->id), 'userusername' => array('langstr' => get_string('username'), 'value' => $USER->username), 'useridnumber' => array('langstr' => get_string('idnumber'), 'value' => $USER->idnumber), 'userfirstname' => array('langstr' => get_string('firstname'), 'value' => $USER->firstname), 'userlastname' => array('langstr' => get_string('lastname'), 'value' => $USER->lastname), 'userfullname' => array('langstr' => get_string('fullnameuser'), 'value' => fullname($USER)), 'useremail' => array('langstr' => get_string('email'), 'value' => $USER->email), 'usericq' => array('langstr' => get_string('icqnumber'), 'value' => $USER->icq), 'userphone1' => array('langstr' => get_string('phone') . ' 1', 'value' => $USER->phone1), 'userphone2' => array('langstr' => get_string('phone2') . ' 2', 'value' => $USER->phone2), 'userinstitution' => array('langstr' => get_string('institution'), 'value' => $USER->institution), 'userdepartment' => array('langstr' => get_string('department'), 'value' => $USER->department), 'useraddress' => array('langstr' => get_string('address'), 'value' => $USER->address), 'usercity' => array('langstr' => get_string('city'), 'value' => $USER->city), 'usertimezone' => array('langstr' => get_string('timezone'), 'value' => get_user_timezone_offset()), 'userurl' => array('langstr' => get_string('webpage'), 'value' => $USER->url), 'label2' => array('langstr' => "", 'value' => '/optgroup'));
     }
     $this->parameters = array_merge($userparameters, $courseparameters, $miscparameters);
 }
コード例 #10
0
 /**
  * Constructor.
  * @throws Command_Exception.
  */
 function __construct()
 {
     global $DB;
     // Getting command description.
     $cmd_name = vmoodle_get_string('cmdallowsyncname', 'vmoodleadminset_roles');
     $cmd_desc = vmoodle_get_string('cmdallowsyncdesc', 'vmoodleadminset_roles');
     // Creating platform parameter
     $platform_param = new Command_Parameter('platform', 'enum', vmoodle_get_string('platformparamsyncdesc', 'vmoodleadminset_roles'), null, get_available_platforms());
     // Creating table parameter
     $tables['assign'] = vmoodle_get_string('assigntable', 'vmoodleadminset_roles');
     $tables['override'] = vmoodle_get_string('overridetable', 'vmoodleadminset_roles');
     $tables['switch'] = vmoodle_get_string('switchtable', 'vmoodleadminset_roles');
     $table_param = new Command_Parameter('table', 'enum', vmoodle_get_string('tableparamdesc', 'vmoodleadminset_roles'), null, $tables);
     // Creating role parameter
     $roles = role_fix_names(get_all_roles(), \context_system::instance(), ROLENAME_ORIGINAL);
     $rolemenu = array();
     foreach ($roles as $r) {
         $rolemenu[$r->shortname] = $r->localname;
     }
     $role_param = new Command_Parameter('role', 'enum', vmoodle_get_string('roleparamsyncdesc', 'vmoodleadminset_roles'), null, $rolemenu);
     // Creating command
     parent::__construct($cmd_name, $cmd_desc, array($platform_param, $table_param, $role_param));
 }
コード例 #11
0
 $ADMIN->add('accounts', new admin_externalpage('profilefields', get_string('profilefields', 'admin'), "{$CFG->wwwroot}/user/profile/index.php", 'moodle/site:config'));
 $ADMIN->add('accounts', new admin_externalpage('cohorts', get_string('cohorts', 'cohort'), $CFG->wwwroot . '/cohort/index.php', array('moodle/cohort:manage', 'moodle/cohort:view')));
 // stuff under the "roles" subcategory
 // "userpolicies" settingpage
 $temp = new admin_settingpage('userpolicies', get_string('userpolicies', 'admin'));
 if ($ADMIN->fulltree) {
     if (!during_initial_install()) {
         $context = get_context_instance(CONTEXT_SYSTEM);
         $otherroles = array();
         $guestroles = array();
         $userroles = array();
         $creatornewroles = array();
         $defaultteacherid = null;
         $defaultuserid = null;
         $defaultguestid = null;
         foreach (get_all_roles() as $role) {
             $rolename = strip_tags(format_string($role->name)) . ' (' . $role->shortname . ')';
             switch ($role->archetype) {
                 case 'manager':
                     $creatornewroles[$role->id] = $rolename;
                     break;
                 case 'coursecreator':
                     break;
                 case 'editingteacher':
                     $defaultteacherid = isset($defaultteacherid) ? $defaultteacherid : $role->id;
                     $creatornewroles[$role->id] = $rolename;
                     break;
                 case 'teacher':
                     $creatornewroles[$role->id] = $rolename;
                     break;
                 case 'student':
コード例 #12
0
ファイル: course_test.php プロジェクト: evltuma/moodle
 public function test_data_saved()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create.
     $mode = tool_uploadcourse_processor::MODE_CREATE_NEW;
     $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING;
     $data = array('shortname' => 'c1', 'fullname' => 'Fullname', 'category' => '1', 'visible' => '0', 'startdate' => '8 June 1990', 'idnumber' => '123abc', 'summary' => 'Summary', 'format' => 'weeks', 'theme' => 'afterburner', 'lang' => 'en', 'newsitems' => '7', 'showgrades' => '0', 'showreports' => '1', 'legacyfiles' => '1', 'maxbytes' => '1234', 'groupmode' => '2', 'groupmodeforce' => '1', 'enablecompletion' => '1', 'tags' => 'Cat, Dog', 'role_teacher' => 'Knight', 'role_manager' => 'Jedi', 'enrolment_1' => 'guest', 'enrolment_2' => 'self', 'enrolment_2_roleid' => '1', 'enrolment_3' => 'manual', 'enrolment_3_disable' => '1');
     $this->assertFalse($DB->record_exists('course', array('shortname' => 'c1')));
     $co = new tool_uploadcourse_course($mode, $updatemode, $data);
     $this->assertTrue($co->prepare());
     $co->proceed();
     $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
     $course = $DB->get_record('course', array('shortname' => 'c1'));
     $ctx = context_course::instance($course->id);
     $this->assertEquals($data['fullname'], $course->fullname);
     $this->assertEquals($data['category'], $course->category);
     $this->assertEquals($data['visible'], $course->visible);
     $this->assertEquals(mktime(0, 0, 0, 6, 8, 1990), $course->startdate);
     $this->assertEquals($data['idnumber'], $course->idnumber);
     $this->assertEquals($data['summary'], $course->summary);
     $this->assertEquals($data['format'], $course->format);
     $this->assertEquals($data['theme'], $course->theme);
     $this->assertEquals($data['lang'], $course->lang);
     $this->assertEquals($data['newsitems'], $course->newsitems);
     $this->assertEquals($data['showgrades'], $course->showgrades);
     $this->assertEquals($data['showreports'], $course->showreports);
     $this->assertEquals($data['legacyfiles'], $course->legacyfiles);
     $this->assertEquals($data['maxbytes'], $course->maxbytes);
     $this->assertEquals($data['groupmode'], $course->groupmode);
     $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce);
     $this->assertEquals($data['enablecompletion'], $course->enablecompletion);
     $this->assertEquals($data['tags'], join(', ', core_tag_tag::get_item_tags_array('core', 'course', $course->id)));
     // Roles.
     $roleids = array();
     $roles = get_all_roles();
     foreach ($roles as $role) {
         $roleids[$role->shortname] = $role->id;
     }
     $this->assertEquals('Knight', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher'])));
     $this->assertEquals('Jedi', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager'])));
     // Enrolment methods.
     $enroldata = array();
     $instances = enrol_get_instances($course->id, false);
     $this->assertCount(3, $instances);
     foreach ($instances as $instance) {
         $enroldata[$instance->enrol] = $instance;
     }
     $this->assertNotEmpty($enroldata['guest']);
     $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['guest']->status);
     $this->assertNotEmpty($enroldata['self']);
     $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid);
     $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status);
     $this->assertNotEmpty($enroldata['manual']);
     $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['manual']->status);
     // Update existing course.
     $cat = $this->getDataGenerator()->create_category();
     $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY;
     $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY;
     $data = array('shortname' => 'c1', 'fullname' => 'Fullname 2', 'category' => $cat->id, 'visible' => '1', 'startdate' => '11 June 1984', 'idnumber' => 'changeidn', 'summary' => 'Summary 2', 'format' => 'topics', 'theme' => 'clean', 'lang' => '', 'newsitems' => '2', 'showgrades' => '1', 'showreports' => '0', 'legacyfiles' => '0', 'maxbytes' => '4321', 'groupmode' => '1', 'groupmodeforce' => '0', 'enablecompletion' => '0', 'role_teacher' => 'Teacher', 'role_manager' => 'Manager', 'enrolment_1' => 'guest', 'enrolment_1_disable' => '1', 'enrolment_2' => 'self', 'enrolment_2_roleid' => '2', 'enrolment_3' => 'manual', 'enrolment_3_delete' => '1');
     $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1')));
     $co = new tool_uploadcourse_course($mode, $updatemode, $data);
     $this->assertTrue($co->prepare());
     $co->proceed();
     $course = $DB->get_record('course', array('shortname' => 'c1'));
     $ctx = context_course::instance($course->id);
     $this->assertEquals($data['fullname'], $course->fullname);
     $this->assertEquals($data['category'], $course->category);
     $this->assertEquals($data['visible'], $course->visible);
     $this->assertEquals(mktime(0, 0, 0, 6, 11, 1984), $course->startdate);
     $this->assertEquals($data['idnumber'], $course->idnumber);
     $this->assertEquals($data['summary'], $course->summary);
     $this->assertEquals($data['format'], $course->format);
     $this->assertEquals($data['theme'], $course->theme);
     $this->assertEquals($data['lang'], $course->lang);
     $this->assertEquals($data['newsitems'], $course->newsitems);
     $this->assertEquals($data['showgrades'], $course->showgrades);
     $this->assertEquals($data['showreports'], $course->showreports);
     $this->assertEquals($data['legacyfiles'], $course->legacyfiles);
     $this->assertEquals($data['maxbytes'], $course->maxbytes);
     $this->assertEquals($data['groupmode'], $course->groupmode);
     $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce);
     $this->assertEquals($data['enablecompletion'], $course->enablecompletion);
     // Roles.
     $roleids = array();
     $roles = get_all_roles();
     foreach ($roles as $role) {
         $roleids[$role->shortname] = $role->id;
     }
     $this->assertEquals('Teacher', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher'])));
     $this->assertEquals('Manager', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager'])));
     // Enrolment methods.
     $enroldata = array();
     $instances = enrol_get_instances($course->id, false);
     $this->assertCount(2, $instances);
     foreach ($instances as $instance) {
         $enroldata[$instance->enrol] = $instance;
     }
     $this->assertNotEmpty($enroldata['guest']);
     $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['guest']->status);
     $this->assertNotEmpty($enroldata['self']);
     $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid);
     $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status);
 }
コード例 #13
0
ファイル: settingslib.php プロジェクト: evltuma/moodle
 /**
  * Returns the current setting if it is set
  *
  * @return mixed null if null, else an array
  */
 public function get_setting()
 {
     $roles = role_fix_names(get_all_roles());
     $result = array();
     foreach ($roles as $role) {
         $contexts = $this->config_read('contexts_role' . $role->id);
         $memberattribute = $this->config_read('memberattribute_role' . $role->id);
         $result[] = array('id' => $role->id, 'name' => $role->localname, 'contexts' => $contexts, 'memberattribute' => $memberattribute);
     }
     return $result;
 }
コード例 #14
0
ファイル: users.php プロジェクト: vinoth4891/clinique
     $ADMIN->add('accounts', new admin_externalpage('cohorts', new lang_string('cohorts', 'cohort'), $CFG->wwwroot . '/cohort/index.php', array('moodle/cohort:manage', 'moodle/cohort:view')));
 }
 // stuff under the "roles" subcategory
 // "userpolicies" settingpage
 $temp = new admin_settingpage('userpolicies', new lang_string('userpolicies', 'admin'));
 if ($ADMIN->fulltree) {
     if (!during_initial_install()) {
         $context = context_system::instance();
         $otherroles = array();
         $guestroles = array();
         $userroles = array();
         $creatornewroles = array();
         $defaultteacherid = null;
         $defaultuserid = null;
         $defaultguestid = null;
         $roles = role_fix_names(get_all_roles(), null, ROLENAME_ORIGINALANDSHORT);
         foreach ($roles as $role) {
             $rolename = $role->localname;
             switch ($role->archetype) {
                 case 'manager':
                     $creatornewroles[$role->id] = $rolename;
                     break;
                 case 'coursecreator':
                     break;
                 case 'editingteacher':
                     $defaultteacherid = isset($defaultteacherid) ? $defaultteacherid : $role->id;
                     $creatornewroles[$role->id] = $rolename;
                     break;
                 case 'teacher':
                     $creatornewroles[$role->id] = $rolename;
                     break;
コード例 #15
0
ファイル: users.php プロジェクト: nadavkav/MoodleTAO
             set_config('creatornewroleid', 0);
         }
     }
     if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
         $guestroles = array();
         $defaultguestid = null;
     } else {
         $defaultguestid = reset($guestroles);
         $defaultguestid = $defaultguestid->id;
     }
     // we must not use assignable roles here:
     //   1/ unsetting roles as assignable for admin might bork the settings!
     //   2/ default user role should not be assignable anyway
     $allroles = array();
     $nonguestroles = array();
     if ($roles = get_all_roles()) {
         foreach ($roles as $role) {
             $rolename = strip_tags(format_string($role->name, true));
             $allroles[$role->id] = $rolename;
             if (!isset($guestroles[$role->id])) {
                 $nonguestroles[$role->id] = $rolename;
             }
         }
     }
     $temp->add(new admin_setting_configselect('notloggedinroleid', get_string('notloggedinroleid', 'admin'), get_string('confignotloggedinroleid', 'admin'), $defaultguestid, $allroles));
     $temp->add(new admin_setting_configselect('guestroleid', get_string('guestroleid', 'admin'), get_string('configguestroleid', 'admin'), $defaultguestid, $allroles));
     $temp->add(new admin_setting_configselect('defaultuserroleid', get_string('defaultuserroleid', 'admin'), get_string('configdefaultuserroleid', 'admin'), $userrole->id, $nonguestroles));
     // guest role here breaks a lot of stuff
 }
 // enable auto assign role LPC #2 in "Yesumy lemida" category #7 (nadavkav)
 $temp->add(new admin_setting_configcheckbox('autoassignlpctocategory', get_string('autoassignlpctocategory', 'admin'), get_string('configautoassignlpctocategory', 'admin'), 1));
コード例 #16
0
ファイル: adminlib.php プロジェクト: Alexbado/moodle2
 /**
  * Load roles as choices
  *
  * @return bool true=>success, false=>error
  */
 public function load_choices()
 {
     global $CFG, $DB;
     if (during_initial_install()) {
         return false;
     }
     if (is_array($this->choices)) {
         return true;
     }
     if ($roles = get_all_roles()) {
         $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
         return true;
     } else {
         return false;
     }
 }
コード例 #17
0
ファイル: locallib.php プロジェクト: lucaboesch/moodle
/**
 * Get the parameter values that may be appended to URL
 * @param object $url module instance
 * @param object $cm
 * @param object $course
 * @param object $config module config options
 * @return array of parameter values
 */
function url_get_variable_values($url, $cm, $course, $config)
{
    global $USER, $CFG;
    $site = get_site();
    $coursecontext = context_course::instance($course->id);
    $values = array('courseid' => $course->id, 'coursefullname' => format_string($course->fullname), 'courseshortname' => format_string($course->shortname, true, array('context' => $coursecontext)), 'courseidnumber' => $course->idnumber, 'coursesummary' => $course->summary, 'courseformat' => $course->format, 'lang' => current_language(), 'sitename' => format_string($site->fullname), 'serverurl' => $CFG->wwwroot, 'currenttime' => time(), 'urlinstance' => $url->id, 'urlcmid' => $cm->id, 'urlname' => format_string($url->name), 'urlidnumber' => $cm->idnumber);
    if (isloggedin()) {
        $values['userid'] = $USER->id;
        $values['userusername'] = $USER->username;
        $values['useridnumber'] = $USER->idnumber;
        $values['userfirstname'] = $USER->firstname;
        $values['userlastname'] = $USER->lastname;
        $values['userfullname'] = fullname($USER);
        $values['useremail'] = $USER->email;
        $values['usericq'] = $USER->icq;
        $values['userphone1'] = $USER->phone1;
        $values['userphone2'] = $USER->phone2;
        $values['userinstitution'] = $USER->institution;
        $values['userdepartment'] = $USER->department;
        $values['useraddress'] = $USER->address;
        $values['usercity'] = $USER->city;
        $now = new DateTime('now', core_date::get_user_timezone_object());
        $values['usertimezone'] = $now->getOffset() / 3600.0;
        // Value in hours for BC.
        $values['userurl'] = $USER->url;
    }
    // weak imitation of Single-Sign-On, for backwards compatibility only
    // NOTE: login hack is not included in 2.0 any more, new contrib auth plugin
    //       needs to be createed if somebody needs the old functionality!
    if (!empty($config->secretphrase)) {
        $values['encryptedcode'] = url_get_encrypted_parameter($url, $config);
    }
    //hmm, this is pretty fragile and slow, why do we need it here??
    if ($config->rolesinparams) {
        $coursecontext = context_course::instance($course->id);
        $roles = role_fix_names(get_all_roles($coursecontext), $coursecontext, ROLENAME_ALIAS);
        foreach ($roles as $role) {
            $values['course' . $role->shortname] = $role->localname;
        }
    }
    return $values;
}
コード例 #18
0
ファイル: ldap_test.php プロジェクト: pzhu2004/moodle
 public function test_enrol_ldap()
 {
     global $CFG, $DB;
     if (!extension_loaded('ldap')) {
         $this->markTestSkipped('LDAP extension is not loaded.');
     }
     $this->resetAfterTest();
     require_once $CFG->dirroot . '/enrol/ldap/lib.php';
     require_once $CFG->libdir . '/ldaplib.php';
     if (!defined('TEST_ENROL_LDAP_HOST_URL') or !defined('TEST_ENROL_LDAP_BIND_DN') or !defined('TEST_ENROL_LDAP_BIND_PW') or !defined('TEST_ENROL_LDAP_DOMAIN')) {
         $this->markTestSkipped('External LDAP test server not configured.');
     }
     // Make sure we can connect the server.
     $debuginfo = '';
     if (!($connection = ldap_connect_moodle(TEST_ENROL_LDAP_HOST_URL, 3, 'rfc2307', TEST_ENROL_LDAP_BIND_DN, TEST_ENROL_LDAP_BIND_PW, LDAP_DEREF_NEVER, $debuginfo, false))) {
         $this->markTestSkipped('Can not connect to LDAP test server: ' . $debuginfo);
     }
     $this->enable_plugin();
     // Create new empty test container.
     $topdn = 'dc=moodletest,' . TEST_ENROL_LDAP_DOMAIN;
     $this->recursive_delete($connection, TEST_ENROL_LDAP_DOMAIN, 'dc=moodletest');
     $o = array();
     $o['objectClass'] = array('dcObject', 'organizationalUnit');
     $o['dc'] = 'moodletest';
     $o['ou'] = 'MOODLETEST';
     if (!ldap_add($connection, 'dc=moodletest,' . TEST_ENROL_LDAP_DOMAIN, $o)) {
         $this->markTestSkipped('Can not create test LDAP container.');
     }
     // Configure enrol plugin.
     /** @var enrol_ldap_plugin $enrol */
     $enrol = enrol_get_plugin('ldap');
     $enrol->set_config('host_url', TEST_ENROL_LDAP_HOST_URL);
     $enrol->set_config('start_tls', 0);
     $enrol->set_config('ldap_version', 3);
     $enrol->set_config('ldapencoding', 'utf-8');
     $enrol->set_config('page_size', '2');
     $enrol->set_config('bind_dn', TEST_ENROL_LDAP_BIND_DN);
     $enrol->set_config('bind_pw', TEST_ENROL_LDAP_BIND_PW);
     $enrol->set_config('course_search_sub', 0);
     $enrol->set_config('memberattribute_isdn', 0);
     $enrol->set_config('user_contexts', '');
     $enrol->set_config('user_search_sub', 0);
     $enrol->set_config('user_type', 'rfc2307');
     $enrol->set_config('opt_deref', LDAP_DEREF_NEVER);
     $enrol->set_config('objectclass', '(objectClass=posixGroup)');
     $enrol->set_config('course_idnumber', 'cn');
     $enrol->set_config('course_shortname', 'cn');
     $enrol->set_config('course_fullname', 'cn');
     $enrol->set_config('course_summary', '');
     $enrol->set_config('ignorehiddencourses', 0);
     $enrol->set_config('nested_groups', 0);
     $enrol->set_config('autocreate', 0);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_KEEP);
     $roles = get_all_roles();
     foreach ($roles as $role) {
         $enrol->set_config('contexts_role' . $role->id, '');
         $enrol->set_config('memberattribute_role' . $role->id, '');
     }
     // Create group for teacher enrolments.
     $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
     $this->assertNotEmpty($teacherrole);
     $o = array();
     $o['objectClass'] = array('organizationalUnit');
     $o['ou'] = 'teachers';
     ldap_add($connection, 'ou=teachers,' . $topdn, $o);
     $enrol->set_config('contexts_role' . $teacherrole->id, 'ou=teachers,' . $topdn);
     $enrol->set_config('memberattribute_role' . $teacherrole->id, 'memberuid');
     // Create group for student enrolments.
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $this->assertNotEmpty($studentrole);
     $o = array();
     $o['objectClass'] = array('organizationalUnit');
     $o['ou'] = 'students';
     ldap_add($connection, 'ou=students,' . $topdn, $o);
     $enrol->set_config('contexts_role' . $studentrole->id, 'ou=students,' . $topdn);
     $enrol->set_config('memberattribute_role' . $studentrole->id, 'memberuid');
     // Create some users and courses.
     $user1 = $this->getDataGenerator()->create_user(array('idnumber' => 'user1', 'username' => 'user1'));
     $user2 = $this->getDataGenerator()->create_user(array('idnumber' => 'user2', 'username' => 'user2'));
     $user3 = $this->getDataGenerator()->create_user(array('idnumber' => 'user3', 'username' => 'user3'));
     $user4 = $this->getDataGenerator()->create_user(array('idnumber' => 'user4', 'username' => 'user4'));
     $user5 = $this->getDataGenerator()->create_user(array('idnumber' => 'user5', 'username' => 'user5'));
     $user6 = $this->getDataGenerator()->create_user(array('idnumber' => 'user6', 'username' => 'user6'));
     $course1 = $this->getDataGenerator()->create_course(array('idnumber' => 'course1', 'shortname' => 'course1'));
     $course2 = $this->getDataGenerator()->create_course(array('idnumber' => 'course2', 'shortname' => 'course2'));
     $course3 = $this->getDataGenerator()->create_course(array('idnumber' => 'course3', 'shortname' => 'course3'));
     // Set up some ldap data.
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3', 'userx');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '2';
     $o['memberUid'] = array('user5');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=teachers,' . $topdn, $o);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course2';
     $o['gidNumber'] = '3';
     $o['memberUid'] = array('user1', 'user2', 'user3', 'user4');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course4';
     $o['gidNumber'] = '4';
     $o['memberUid'] = array('user1', 'user2');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course4';
     $o['gidNumber'] = '5';
     $o['memberUid'] = array('user5', 'user6');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=teachers,' . $topdn, $o);
     // Test simple test without creation.
     $this->assertEquals(0, $DB->count_records('user_enrolments'));
     $this->assertEquals(0, $DB->count_records('role_assignments'));
     $this->assertEquals(4, $DB->count_records('course'));
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(8, $DB->count_records('user_enrolments'));
     $this->assertEquals(8, $DB->count_records('role_assignments'));
     $this->assertEquals(4, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id);
     $this->assertIsEnrolled($course1->id, $user2->id, $studentrole->id);
     $this->assertIsEnrolled($course1->id, $user3->id, $studentrole->id);
     $this->assertIsEnrolled($course1->id, $user5->id, $teacherrole->id);
     $this->assertIsEnrolled($course2->id, $user1->id, $studentrole->id);
     $this->assertIsEnrolled($course2->id, $user2->id, $studentrole->id);
     $this->assertIsEnrolled($course2->id, $user3->id, $studentrole->id);
     $this->assertIsEnrolled($course2->id, $user4->id, $studentrole->id);
     // Test course creation.
     $enrol->set_config('autocreate', 1);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(12, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $course4 = $DB->get_record('course', array('idnumber' => 'course4'), '*', MUST_EXIST);
     $this->assertIsEnrolled($course4->id, $user1->id, $studentrole->id);
     $this->assertIsEnrolled($course4->id, $user2->id, $studentrole->id);
     $this->assertIsEnrolled($course4->id, $user5->id, $teacherrole->id);
     $this->assertIsEnrolled($course4->id, $user6->id, $teacherrole->id);
     // Test unenrolment.
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_KEEP);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(12, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(12, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_SUSPENDED);
     $this->assertIsEnrolled($course1->id, $user2->id, $studentrole->id, ENROL_USER_SUSPENDED);
     $this->assertIsEnrolled($course1->id, $user3->id, $studentrole->id, ENROL_USER_SUSPENDED);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(12, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     $this->assertIsEnrolled($course1->id, $user2->id, $studentrole->id, ENROL_USER_ACTIVE);
     $this->assertIsEnrolled($course1->id, $user3->id, $studentrole->id, ENROL_USER_ACTIVE);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(9, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, 0, ENROL_USER_SUSPENDED);
     $this->assertIsEnrolled($course1->id, $user2->id, 0, ENROL_USER_SUSPENDED);
     $this->assertIsEnrolled($course1->id, $user3->id, 0, ENROL_USER_SUSPENDED);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(12, $DB->count_records('user_enrolments'));
     $this->assertEquals(12, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     $this->assertIsEnrolled($course1->id, $user2->id, $studentrole->id, ENROL_USER_ACTIVE);
     $this->assertIsEnrolled($course1->id, $user3->id, $studentrole->id, ENROL_USER_ACTIVE);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     $enrol->sync_enrolments(new null_progress_trace());
     $this->assertEquals(9, $DB->count_records('user_enrolments'));
     $this->assertEquals(9, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsNotEnrolled($course1->id, $user1->id);
     $this->assertIsNotEnrolled($course1->id, $user2->id);
     $this->assertIsNotEnrolled($course1->id, $user3->id);
     // Individual user enrolments-
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(10, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_KEEP);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(10, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(10, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_SUSPENDED);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(10, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(9, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, 0, ENROL_USER_SUSPENDED);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user1', 'user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(10, $DB->count_records('user_enrolments'));
     $this->assertEquals(10, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsEnrolled($course1->id, $user1->id, $studentrole->id, ENROL_USER_ACTIVE);
     ldap_delete($connection, 'cn=course1,ou=students,' . $topdn);
     $o = array();
     $o['objectClass'] = array('posixGroup');
     $o['cn'] = 'course1';
     $o['gidNumber'] = '1';
     $o['memberUid'] = array('user2', 'user3');
     ldap_add($connection, 'cn=' . $o['cn'] . ',ou=students,' . $topdn, $o);
     $enrol->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     $enrol->sync_user_enrolments($user1);
     $this->assertEquals(9, $DB->count_records('user_enrolments'));
     $this->assertEquals(9, $DB->count_records('role_assignments'));
     $this->assertEquals(5, $DB->count_records('course'));
     $this->assertIsNotEnrolled($course1->id, $user1->id);
     $this->recursive_delete($connection, TEST_ENROL_LDAP_DOMAIN, 'dc=moodletest');
     ldap_close($connection);
     // NOTE: multiple roles in one course is not supported, sorry
 }
コード例 #19
0
ファイル: lib.php プロジェクト: vinoth4891/clinique
 /**
  * Forces synchronisation of all enrolments with external database.
  *
  * @param bool $verbose
  * @param null|int $onecourse limit sync to one course only (used primarily in restore)
  * @return int 0 means success, 1 db connect failure, 2 db read failure
  */
 public function sync_enrolments($verbose = false, $onecourse = null)
 {
     global $CFG, $DB;
     // We do not create courses here intentionally because it requires full sync and is slow.
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
         if ($verbose) {
             mtrace('User enrolment synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting user enrolment synchronisation...');
     }
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     // We may need a lot of memory here.
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     $table = $this->get_config('remoteenroltable');
     $coursefield = trim($this->get_config('remotecoursefield'));
     $userfield = trim($this->get_config('remoteuserfield'));
     $rolefield = trim($this->get_config('remoterolefield'));
     // Lowercased versions - necessary because we normalise the resultset with array_change_key_case().
     $coursefield_l = strtolower($coursefield);
     $userfield_l = strtolower($userfield);
     $rolefield_l = strtolower($rolefield);
     $localrolefield = $this->get_config('localrolefield');
     $localuserfield = $this->get_config('localuserfield');
     $localcoursefield = $this->get_config('localcoursefield');
     $unenrolaction = $this->get_config('unenrolaction');
     $defaultrole = $this->get_config('defaultrole');
     // Create roles mapping.
     $allroles = get_all_roles();
     if (!isset($allroles[$defaultrole])) {
         $defaultrole = 0;
     }
     $roles = array();
     foreach ($allroles as $role) {
         $roles[$role->{$localrolefield}] = $role->id;
     }
     if ($onecourse) {
         $sql = "SELECT c.id, c.visible, c.{$localcoursefield} AS mapping, c.shortname, e.id AS enrolid\n                      FROM {course} c\n                 LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')\n                     WHERE c.id = :id";
         if (!($course = $DB->get_record_sql($sql, array('id' => $onecourse)))) {
             // Course does not exist, nothing to sync.
             return 0;
         }
         if (empty($course->mapping)) {
             // We can not map to this course, sorry.
             return 0;
         }
         if (empty($course->enrolid)) {
             $course->enrolid = $this->add_instance($course);
         }
         $existing = array($course->mapping => $course);
         // Feel free to unenrol everybody, no safety tricks here.
         $preventfullunenrol = false;
         // Course being restored are always hidden, we have to ignore the setting here.
         $ignorehidden = false;
     } else {
         // Get a list of courses to be synced that are in external table.
         $externalcourses = array();
         $sql = $this->db_get_sql($table, array(), array($coursefield), true);
         if ($rs = $extdb->Execute($sql)) {
             if (!$rs->EOF) {
                 while ($mapping = $rs->FetchRow()) {
                     $mapping = reset($mapping);
                     $mapping = $this->db_decode($mapping);
                     if (empty($mapping)) {
                         // invalid mapping
                         continue;
                     }
                     $externalcourses[$mapping] = true;
                 }
             }
             $rs->Close();
         } else {
             mtrace('Error reading data from the external enrolment table');
             $extdb->Close();
             return 2;
         }
         $preventfullunenrol = empty($externalcourses);
         if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
             mtrace('  Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
         }
         // First find all existing courses with enrol instance.
         $existing = array();
         $sql = "SELECT c.id, c.visible, c.{$localcoursefield} AS mapping, e.id AS enrolid, c.shortname\n                      FROM {course} c\n                      JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')";
         $rs = $DB->get_recordset_sql($sql);
         // Watch out for idnumber duplicates.
         foreach ($rs as $course) {
             if (empty($course->mapping)) {
                 continue;
             }
             $existing[$course->mapping] = $course;
             unset($externalcourses[$course->mapping]);
         }
         $rs->close();
         // Add necessary enrol instances that are not present yet.
         $params = array();
         $localnotempty = "";
         if ($localcoursefield !== 'id') {
             $localnotempty = "AND c.{$localcoursefield} <> :lcfe";
             $params['lcfe'] = $DB->sql_empty();
         }
         $sql = "SELECT c.id, c.visible, c.{$localcoursefield} AS mapping, c.shortname\n                      FROM {course} c\n                 LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')\n                     WHERE e.id IS NULL {$localnotempty}";
         $rs = $DB->get_recordset_sql($sql, $params);
         foreach ($rs as $course) {
             if (empty($course->mapping)) {
                 continue;
             }
             if (!isset($externalcourses[$course->mapping])) {
                 // Course not synced or duplicate.
                 continue;
             }
             $course->enrolid = $this->add_instance($course);
             $existing[$course->mapping] = $course;
             unset($externalcourses[$course->mapping]);
         }
         $rs->close();
         // Print list of missing courses.
         if ($verbose and $externalcourses) {
             $list = implode(', ', array_keys($externalcourses));
             mtrace("  error: following courses do not exist - {$list}");
             unset($list);
         }
         // Free memory.
         unset($externalcourses);
         $ignorehidden = $this->get_config('ignorehiddencourses');
     }
     // Sync user enrolments.
     $sqlfields = array($userfield);
     if ($rolefield) {
         $sqlfields[] = $rolefield;
     }
     foreach ($existing as $course) {
         if ($ignorehidden and !$course->visible) {
             continue;
         }
         if (!($instance = $DB->get_record('enrol', array('id' => $course->enrolid)))) {
             continue;
             // Weird!
         }
         $context = context_course::instance($course->id);
         // Get current list of enrolled users with their roles.
         $current_roles = array();
         $current_status = array();
         $user_mapping = array();
         $sql = "SELECT u.{$localuserfield} AS mapping, u.id, ue.status, ue.userid, ra.roleid\n                      FROM {user} u\n                      JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)\n                      JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.itemid = ue.enrolid AND ra.component = 'enrol_database')\n                     WHERE u.deleted = 0";
         $params = array('enrolid' => $instance->id);
         if ($localuserfield === 'username') {
             $sql .= " AND u.mnethostid = :mnethostid";
             $params['mnethostid'] = $CFG->mnet_localhost_id;
         }
         $rs = $DB->get_recordset_sql($sql, $params);
         foreach ($rs as $ue) {
             $current_roles[$ue->userid][$ue->roleid] = $ue->roleid;
             $current_status[$ue->userid] = $ue->status;
             $user_mapping[$ue->mapping] = $ue->userid;
         }
         $rs->close();
         // Get list of users that need to be enrolled and their roles.
         $requested_roles = array();
         $sql = $this->db_get_sql($table, array($coursefield => $course->mapping), $sqlfields);
         if ($rs = $extdb->Execute($sql)) {
             if (!$rs->EOF) {
                 $usersearch = array('deleted' => 0);
                 if ($localuserfield === 'username') {
                     $usersearch['mnethostid'] = $CFG->mnet_localhost_id;
                 }
                 while ($fields = $rs->FetchRow()) {
                     $fields = array_change_key_case($fields, CASE_LOWER);
                     if (empty($fields[$userfield_l])) {
                         if ($verbose) {
                             mtrace("  error: skipping user without mandatory {$localuserfield} in course '{$course->mapping}'");
                         }
                         continue;
                     }
                     $mapping = $fields[$userfield_l];
                     if (!isset($user_mapping[$mapping])) {
                         $usersearch[$localuserfield] = $mapping;
                         if (!($user = $DB->get_record('user', $usersearch, 'id', IGNORE_MULTIPLE))) {
                             if ($verbose) {
                                 mtrace("  error: skipping unknown user {$localuserfield} '{$mapping}' in course '{$course->mapping}'");
                             }
                             continue;
                         }
                         $user_mapping[$mapping] = $user->id;
                         $userid = $user->id;
                     } else {
                         $userid = $user_mapping[$mapping];
                     }
                     if (empty($fields[$rolefield_l]) or !isset($roles[$fields[$rolefield_l]])) {
                         if (!$defaultrole) {
                             if ($verbose) {
                                 mtrace("  error: skipping user '{$userid}' in course '{$course->mapping}' - missing course and default role");
                             }
                             continue;
                         }
                         $roleid = $defaultrole;
                     } else {
                         $roleid = $roles[$fields[$rolefield_l]];
                     }
                     $requested_roles[$userid][$roleid] = $roleid;
                 }
             }
             $rs->Close();
         } else {
             mtrace("  error: skipping course '{$course->mapping}' - could not match with external database");
             continue;
         }
         unset($user_mapping);
         // Enrol all users and sync roles.
         foreach ($requested_roles as $userid => $userroles) {
             foreach ($userroles as $roleid) {
                 if (empty($current_roles[$userid])) {
                     $this->enrol_user($instance, $userid, $roleid, 0, 0, ENROL_USER_ACTIVE);
                     $current_roles[$userid][$roleid] = $roleid;
                     $current_status[$userid] = ENROL_USER_ACTIVE;
                     if ($verbose) {
                         mtrace("  enrolling: {$userid} ==> {$course->shortname} as " . $allroles[$roleid]->shortname);
                     }
                 }
             }
             // Assign extra roles.
             foreach ($userroles as $roleid) {
                 if (empty($current_roles[$userid][$roleid])) {
                     role_assign($roleid, $userid, $context->id, 'enrol_database', $instance->id);
                     $current_roles[$userid][$roleid] = $roleid;
                     if ($verbose) {
                         mtrace("  assigning roles: {$userid} ==> {$course->shortname} as " . $allroles[$roleid]->shortname);
                     }
                 }
             }
             // Unassign removed roles.
             foreach ($current_roles[$userid] as $cr) {
                 if (empty($userroles[$cr])) {
                     role_unassign($cr, $userid, $context->id, 'enrol_database', $instance->id);
                     unset($current_roles[$userid][$cr]);
                     if ($verbose) {
                         mtrace("  unsassigning roles: {$userid} ==> {$course->shortname}");
                     }
                 }
             }
             // Reenable enrolment when previously disable enrolment refreshed.
             if ($current_status[$userid] == ENROL_USER_SUSPENDED) {
                 $this->update_user_enrol($instance, $userid, ENROL_USER_ACTIVE);
                 if ($verbose) {
                     mtrace("  unsuspending: {$userid} ==> {$course->shortname}");
                 }
             }
         }
         // Deal with enrolments removed from external table.
         if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
             if (!$preventfullunenrol) {
                 // Unenrol.
                 foreach ($current_status as $userid => $status) {
                     if (isset($requested_roles[$userid])) {
                         continue;
                     }
                     $this->unenrol_user($instance, $userid);
                     if ($verbose) {
                         mtrace("  unenrolling: {$userid} ==> {$course->shortname}");
                     }
                 }
             }
         } else {
             if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) {
                 // Keep - only adding enrolments.
             } else {
                 if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
                     // Suspend enrolments.
                     foreach ($current_status as $userid => $status) {
                         if (isset($requested_roles[$userid])) {
                             continue;
                         }
                         if ($status != ENROL_USER_SUSPENDED) {
                             $this->update_user_enrol($instance, $userid, ENROL_USER_SUSPENDED);
                             if ($verbose) {
                                 mtrace("  suspending: {$userid} ==> {$course->shortname}");
                             }
                         }
                         if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
                             role_unassign_all(array('contextid' => $context->id, 'userid' => $userid, 'component' => 'enrol_database', 'itemid' => $instance->id));
                             if ($verbose) {
                                 mtrace("  unsassigning all roles: {$userid} ==> {$course->shortname}");
                             }
                         }
                     }
                 }
             }
         }
     }
     // Close db connection.
     $extdb->Close();
     if ($verbose) {
         mtrace('...user enrolment synchronisation finished.');
     }
     return 0;
 }
コード例 #20
0
ファイル: edit_form.php プロジェクト: Jtgadbois/Pedadida
 function definition()
 {
     global $USER, $CFG, $DB, $PAGE;
     $mform = $this->_form;
     $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser', array(array('formid' => $mform->getAttribute('id'))));
     $course = $this->_customdata['course'];
     // this contains the data of this form
     $category = $this->_customdata['category'];
     $editoroptions = $this->_customdata['editoroptions'];
     $returnto = $this->_customdata['returnto'];
     $systemcontext = context_system::instance();
     $categorycontext = context_coursecat::instance($category->id);
     if (!empty($course->id)) {
         $coursecontext = context_course::instance($course->id);
         $context = $coursecontext;
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     $courseconfig = get_config('moodlecourse');
     $this->course = $course;
     $this->context = $context;
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('hidden', 'returnto', null);
     $mform->setType('returnto', PARAM_ALPHANUM);
     $mform->setConstant('returnto', $returnto);
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->addHelpButton('fullname', 'fullnamecourse');
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_TEXT);
     if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->addHelpButton('shortname', 'shortnamecourse');
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_TEXT);
     if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     // Verify permissions to change course category or keep current.
     if (empty($course->id)) {
         if (has_capability('moodle/course:create', $categorycontext)) {
             $displaylist = coursecat::make_categories_list('moodle/course:create');
             $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
             $mform->addHelpButton('category', 'coursecategory');
             $mform->setDefault('category', $category->id);
         } else {
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $category->id);
         }
     } else {
         if (has_capability('moodle/course:changecategory', $coursecontext)) {
             $displaylist = coursecat::make_categories_list('moodle/course:create');
             if (!isset($displaylist[$course->category])) {
                 //always keep current
                 $displaylist[$course->category] = coursecat::get($course->category)->get_formatted_name();
             }
             $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
             $mform->addHelpButton('category', 'coursecategory');
         } else {
             //keep current
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $course->category);
         }
     }
     $choices = array();
     $choices['0'] = get_string('hide');
     $choices['1'] = get_string('show');
     $mform->addElement('select', 'visible', get_string('visible'), $choices);
     $mform->addHelpButton('visible', 'visible');
     $mform->setDefault('visible', $courseconfig->visible);
     if (!has_capability('moodle/course:visibility', $context)) {
         $mform->hardFreeze('visible');
         if (!empty($course->id)) {
             $mform->setConstant('visible', $course->visible);
         } else {
             $mform->setConstant('visible', $courseconfig->visible);
         }
     }
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->addHelpButton('startdate', 'startdate');
     $mform->setDefault('startdate', time() + 3600 * 24);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->addHelpButton('idnumber', 'idnumbercourse');
     $mform->setType('idnumber', PARAM_RAW);
     if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     // Description.
     $mform->addElement('header', 'descriptionhdr', get_string('description'));
     $mform->setExpanded('descriptionhdr');
     $mform->addElement('editor', 'summary_editor', get_string('coursesummary'), null, $editoroptions);
     $mform->addHelpButton('summary_editor', 'coursesummary');
     $mform->setType('summary_editor', PARAM_RAW);
     $summaryfields = 'summary_editor';
     if ($overviewfilesoptions = course_overviewfiles_options($course)) {
         $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions);
         $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles');
         $summaryfields .= ',overviewfiles_filemanager';
     }
     if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
         // Remove the description header it does not contain anything any more.
         $mform->removeElement('descriptionhdr');
         $mform->hardFreeze($summaryfields);
     }
     // Course format.
     $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin'));
     $courseformats = get_sorted_course_formats(true);
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats[$courseformat] = get_string('pluginname', "format_{$courseformat}");
     }
     if (isset($course->format)) {
         $course->format = course_get_format($course)->get_format();
         // replace with default if not found
         if (!in_array($course->format, $courseformats)) {
             // this format is disabled. Still display it in the dropdown
             $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle', get_string('pluginname', 'format_' . $course->format));
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->addHelpButton('format', 'format');
     $mform->setDefault('format', $courseconfig->format);
     // Button to update format-specific options on format change (will be hidden by JavaScript).
     $mform->registerNoSubmitButton('updatecourseformat');
     $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate'));
     // Just a placeholder for the course format options.
     $mform->addElement('hidden', 'addcourseformatoptionshere');
     $mform->setType('addcourseformatoptionshere', PARAM_BOOL);
     // Appearance.
     $mform->addElement('header', 'appearancehdr', get_string('appearance'));
     if (!empty($CFG->allowcoursethemes)) {
         $themeobjects = get_list_of_themes();
         $themes = array();
         $themes[''] = get_string('forceno');
         foreach ($themeobjects as $key => $theme) {
             if (empty($theme->hidefromselector)) {
                 $themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
             }
         }
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_string_manager()->get_list_of_translations();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->addHelpButton('newsitems', 'newsitemsnumber');
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->addHelpButton('showgrades', 'showgrades');
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->addHelpButton('showreports', 'showreports');
     $mform->setDefault('showreports', $courseconfig->showreports);
     // Files and uploads.
     $mform->addElement('header', 'filehdr', get_string('filesanduploads'));
     if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
         if (empty($course->legacyfiles)) {
             //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
             $choices = array('0' => get_string('no'), '2' => get_string('yes'));
         } else {
             $choices = array('1' => get_string('no'), '2' => get_string('yes'));
         }
         $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
         $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
         if (!isset($courseconfig->legacyfiles)) {
             // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
             $courseconfig->legacyfiles = 0;
         }
         $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
     }
     // Handle non-existing $course->maxbytes on course creation.
     $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes;
     // Let's prepare the maxbytes popup.
     $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->addHelpButton('maxbytes', 'maximumupload');
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     // Completion tracking.
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', 'completionhdr', get_string('completion', 'completion'));
         $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion'));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
         $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion');
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setType('enablecompletion', PARAM_INT);
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     enrol_course_edit_form($mform, $course, $context);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'groups', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
     $mform->addHelpButton('groupmode', 'groupmode', 'group');
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group'));
     $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     //default groupings selector
     $options = array();
     $options[0] = get_string('none');
     $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     //--------------------------------------------------------------------------------
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->addHelpButton('rolerenaming', 'rolerenaming');
     if ($roles = get_all_roles()) {
         $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL);
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->localname));
             $mform->setType('role_' . $role->id, PARAM_TEXT);
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     /// finally set the current form data
     //--------------------------------------------------------------------------------
     $this->set_data($course);
 }
コード例 #21
0
ファイル: accesslib.php プロジェクト: rwijaya/moodle
/**
 * Prepare list of roles for display, apply aliases and localise default role names.
 *
 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
 * @param context $context the context, null means system context
 * @param int $rolenamedisplay
 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
 * @return array Array of context-specific role names, or role objects with a ->localname field added.
 */
function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
    global $DB;

    if (empty($roleoptions)) {
        return array();
    }

    if (!$context or !$coursecontext = $context->get_course_context(false)) {
        $coursecontext = null;
    }

    // We usually need all role columns...
    $first = reset($roleoptions);
    if ($returnmenu === null) {
        $returnmenu = !is_object($first);
    }

    if (!is_object($first) or !property_exists($first, 'shortname')) {
        $allroles = get_all_roles($context);
        foreach ($roleoptions as $rid => $unused) {
            $roleoptions[$rid] = $allroles[$rid];
        }
    }

    // Inject coursealias if necessary.
    if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
        $first = reset($roleoptions);
        if (!property_exists($first, 'coursealias')) {
            $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
            foreach ($aliasnames as $alias) {
                if (isset($roleoptions[$alias->roleid])) {
                    $roleoptions[$alias->roleid]->coursealias = $alias->name;
                }
            }
        }
    }

    // Add localname property.
    foreach ($roleoptions as $rid => $role) {
        $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
    }

    if (!$returnmenu) {
        return $roleoptions;
    }

    $menu = array();
    foreach ($roleoptions as $rid => $role) {
        $menu[$rid] = $role->localname;
    }

    return $menu;
}
コード例 #22
0
ファイル: lib.php プロジェクト: abhilash1994/moodle
 /**
  * Forces synchronisation of all enrolments with LDAP server.
  * It creates courses if the plugin is configured to do so.
  *
  * @param progress_trace $trace
  * @param int|null $onecourse limit sync to one course->id, null if all courses
  * @return void
  */
 public function sync_enrolments(progress_trace $trace, $onecourse = null)
 {
     global $CFG, $DB;
     if (!$this->ldap_connect($trace)) {
         $trace->finished();
         return;
     }
     $ldap_pagedresults = ldap_paged_results_supported($this->get_config('ldap_version'));
     // we may need a lot of memory here
     core_php_time_limit::raise();
     raise_memory_limit(MEMORY_HUGE);
     $oneidnumber = null;
     if ($onecourse) {
         if (!($course = $DB->get_record('course', array('id' => $onecourse), 'id,' . $this->enrol_localcoursefield))) {
             // Course does not exist, nothing to do.
             $trace->output("Requested course {$onecourse} does not exist, no sync performed.");
             $trace->finished();
             return;
         }
         if (empty($course->{$this->enrol_localcoursefield})) {
             $trace->output("Requested course {$onecourse} does not have {$this->enrol_localcoursefield}, no sync performed.");
             $trace->finished();
             return;
         }
         $oneidnumber = ldap_filter_addslashes(core_text::convert($course->idnumber, 'utf-8', $this->get_config('ldapencoding')));
     }
     // Get enrolments for each type of role.
     $roles = get_all_roles();
     $enrolments = array();
     foreach ($roles as $role) {
         // Get all contexts
         $ldap_contexts = explode(';', $this->config->{'contexts_role' . $role->id});
         // Get all the fields we will want for the potential course creation
         // as they are light. Don't get membership -- potentially a lot of data.
         $ldap_fields_wanted = array('dn', $this->config->course_idnumber);
         if (!empty($this->config->course_fullname)) {
             array_push($ldap_fields_wanted, $this->config->course_fullname);
         }
         if (!empty($this->config->course_shortname)) {
             array_push($ldap_fields_wanted, $this->config->course_shortname);
         }
         if (!empty($this->config->course_summary)) {
             array_push($ldap_fields_wanted, $this->config->course_summary);
         }
         array_push($ldap_fields_wanted, $this->config->{'memberattribute_role' . $role->id});
         // Define the search pattern
         $ldap_search_pattern = $this->config->objectclass;
         if ($oneidnumber !== null) {
             $ldap_search_pattern = "(&{$ldap_search_pattern}({$this->config->course_idnumber}={$oneidnumber}))";
         }
         $ldap_cookie = '';
         foreach ($ldap_contexts as $ldap_context) {
             $ldap_context = trim($ldap_context);
             if (empty($ldap_context)) {
                 continue;
                 // Next;
             }
             $flat_records = array();
             do {
                 if ($ldap_pagedresults) {
                     ldap_control_paged_result($this->ldapconnection, $this->config->pagesize, true, $ldap_cookie);
                 }
                 if ($this->config->course_search_sub) {
                     // Use ldap_search to find first user from subtree
                     $ldap_result = @ldap_search($this->ldapconnection, $ldap_context, $ldap_search_pattern, $ldap_fields_wanted);
                 } else {
                     // Search only in this context
                     $ldap_result = @ldap_list($this->ldapconnection, $ldap_context, $ldap_search_pattern, $ldap_fields_wanted);
                 }
                 if (!$ldap_result) {
                     continue;
                     // Next
                 }
                 if ($ldap_pagedresults) {
                     ldap_control_paged_result_response($this->ldapconnection, $ldap_result, $ldap_cookie);
                 }
                 // Check and push results
                 $records = ldap_get_entries($this->ldapconnection, $ldap_result);
                 // LDAP libraries return an odd array, really. fix it:
                 for ($c = 0; $c < $records['count']; $c++) {
                     array_push($flat_records, $records[$c]);
                 }
                 // Free some mem
                 unset($records);
             } while ($ldap_pagedresults && !empty($ldap_cookie));
             // If LDAP paged results were used, the current connection must be completely
             // closed and a new one created, to work without paged results from here on.
             if ($ldap_pagedresults) {
                 $this->ldap_close();
                 $this->ldap_connect($trace);
             }
             if (count($flat_records)) {
                 $ignorehidden = $this->get_config('ignorehiddencourses');
                 foreach ($flat_records as $course) {
                     $course = array_change_key_case($course, CASE_LOWER);
                     $idnumber = $course[$this->config->course_idnumber][0];
                     $trace->output(get_string('synccourserole', 'enrol_ldap', array('idnumber' => $idnumber, 'role_shortname' => $role->shortname)));
                     // Does the course exist in moodle already?
                     $course_obj = $DB->get_record('course', array($this->enrol_localcoursefield => $idnumber));
                     if (empty($course_obj)) {
                         // Course doesn't exist
                         if ($this->get_config('autocreate')) {
                             // Autocreate
                             $trace->output(get_string('createcourseextid', 'enrol_ldap', array('courseextid' => $idnumber)));
                             if (!($newcourseid = $this->create_course($course, $trace))) {
                                 continue;
                             }
                             $course_obj = $DB->get_record('course', array('id' => $newcourseid));
                         } else {
                             $trace->output(get_string('createnotcourseextid', 'enrol_ldap', array('courseextid' => $idnumber)));
                             continue;
                             // Next; skip this one!
                         }
                     } else {
                         // Check if course needs update & update as needed.
                         $this->update_course($course_obj, $course, $trace);
                     }
                     // Enrol & unenrol
                     // Pull the ldap membership into a nice array
                     // this is an odd array -- mix of hash and array --
                     $ldapmembers = array();
                     if (array_key_exists('memberattribute_role' . $role->id, $this->config) && !empty($this->config->{'memberattribute_role' . $role->id}) && !empty($course[$this->config->{'memberattribute_role' . $role->id}])) {
                         // May have no membership!
                         $ldapmembers = $course[$this->config->{'memberattribute_role' . $role->id}];
                         unset($ldapmembers['count']);
                         // Remove oddity ;)
                         // If we have enabled nested groups, we need to expand
                         // the groups to get the real user list. We need to do
                         // this before dealing with 'memberattribute_isdn'.
                         if ($this->config->nested_groups) {
                             $users = array();
                             foreach ($ldapmembers as $ldapmember) {
                                 $grpusers = $this->ldap_explode_group($ldapmember, $this->config->{'memberattribute_role' . $role->id});
                                 $users = array_merge($users, $grpusers);
                             }
                             $ldapmembers = array_unique($users);
                             // There might be duplicates.
                         }
                         // Deal with the case where the member attribute holds distinguished names,
                         // but only if the user attribute is not a distinguished name itself.
                         if ($this->config->memberattribute_isdn && $this->config->idnumber_attribute !== 'dn' && $this->config->idnumber_attribute !== 'distinguishedname') {
                             // We need to retrieve the idnumber for all the users in $ldapmembers,
                             // as the idnumber does not match their dn and we get dn's from membership.
                             $memberidnumbers = array();
                             foreach ($ldapmembers as $ldapmember) {
                                 $result = ldap_read($this->ldapconnection, $ldapmember, '(objectClass=*)', array($this->config->idnumber_attribute));
                                 $entry = ldap_first_entry($this->ldapconnection, $result);
                                 $values = ldap_get_values($this->ldapconnection, $entry, $this->config->idnumber_attribute);
                                 array_push($memberidnumbers, $values[0]);
                             }
                             $ldapmembers = $memberidnumbers;
                         }
                     }
                     // Prune old ldap enrolments
                     // hopefully they'll fit in the max buffer size for the RDBMS
                     $sql = "SELECT u.id as userid, u.username, ue.status,\n                                      ra.contextid, ra.itemid as instanceid\n                                 FROM {user} u\n                                 JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.component = 'enrol_ldap' AND ra.roleid = :roleid)\n                                 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = ra.itemid)\n                                 JOIN {enrol} e ON (e.id = ue.enrolid)\n                                WHERE u.deleted = 0 AND e.courseid = :courseid ";
                     $params = array('roleid' => $role->id, 'courseid' => $course_obj->id);
                     $context = context_course::instance($course_obj->id);
                     if (!empty($ldapmembers)) {
                         list($ldapml, $params2) = $DB->get_in_or_equal($ldapmembers, SQL_PARAMS_NAMED, 'm', false);
                         $sql .= "AND u.idnumber {$ldapml}";
                         $params = array_merge($params, $params2);
                         unset($params2);
                     } else {
                         $shortname = format_string($course_obj->shortname, true, array('context' => $context));
                         $trace->output(get_string('emptyenrolment', 'enrol_ldap', array('role_shortname' => $role->shortname, 'course_shortname' => $shortname)));
                     }
                     $todelete = $DB->get_records_sql($sql, $params);
                     if (!empty($todelete)) {
                         $transaction = $DB->start_delegated_transaction();
                         foreach ($todelete as $row) {
                             $instance = $DB->get_record('enrol', array('id' => $row->instanceid));
                             switch ($this->get_config('unenrolaction')) {
                                 case ENROL_EXT_REMOVED_UNENROL:
                                     $this->unenrol_user($instance, $row->userid);
                                     $trace->output(get_string('extremovedunenrol', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     break;
                                 case ENROL_EXT_REMOVED_KEEP:
                                     // Keep - only adding enrolments
                                     break;
                                 case ENROL_EXT_REMOVED_SUSPEND:
                                     if ($row->status != ENROL_USER_SUSPENDED) {
                                         $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid' => $instance->id, 'userid' => $row->userid));
                                         $trace->output(get_string('extremovedsuspend', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     }
                                     break;
                                 case ENROL_EXT_REMOVED_SUSPENDNOROLES:
                                     if ($row->status != ENROL_USER_SUSPENDED) {
                                         $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid' => $instance->id, 'userid' => $row->userid));
                                     }
                                     role_unassign_all(array('contextid' => $row->contextid, 'userid' => $row->userid, 'component' => 'enrol_ldap', 'itemid' => $instance->id));
                                     $trace->output(get_string('extremovedsuspendnoroles', 'enrol_ldap', array('user_username' => $row->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                                     break;
                             }
                         }
                         $transaction->allow_commit();
                     }
                     // Insert current enrolments
                     // bad we can't do INSERT IGNORE with postgres...
                     // Add necessary enrol instance if not present yet;
                     $sql = "SELECT c.id, c.visible, e.id as enrolid\n                                  FROM {course} c\n                                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'ldap')\n                                 WHERE c.id = :courseid";
                     $params = array('courseid' => $course_obj->id);
                     if (!($course_instance = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE))) {
                         $course_instance = new stdClass();
                         $course_instance->id = $course_obj->id;
                         $course_instance->visible = $course_obj->visible;
                         $course_instance->enrolid = $this->add_instance($course_instance);
                     }
                     if (!($instance = $DB->get_record('enrol', array('id' => $course_instance->enrolid)))) {
                         continue;
                         // Weird; skip this one.
                     }
                     if ($ignorehidden && !$course_instance->visible) {
                         continue;
                     }
                     $transaction = $DB->start_delegated_transaction();
                     foreach ($ldapmembers as $ldapmember) {
                         $sql = 'SELECT id,username,1 FROM {user} WHERE idnumber = ? AND deleted = 0';
                         $member = $DB->get_record_sql($sql, array($ldapmember));
                         if (empty($member) || empty($member->id)) {
                             $trace->output(get_string('couldnotfinduser', 'enrol_ldap', $ldapmember));
                             continue;
                         }
                         $sql = "SELECT ue.status\n                                     FROM {user_enrolments} ue\n                                     JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'ldap')\n                                    WHERE e.courseid = :courseid AND ue.userid = :userid";
                         $params = array('courseid' => $course_obj->id, 'userid' => $member->id);
                         $userenrolment = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
                         if (empty($userenrolment)) {
                             $this->enrol_user($instance, $member->id, $role->id);
                             // Make sure we set the enrolment status to active. If the user wasn't
                             // previously enrolled to the course, enrol_user() sets it. But if we
                             // configured the plugin to suspend the user enrolments _AND_ remove
                             // the role assignments on external unenrol, then enrol_user() doesn't
                             // set it back to active on external re-enrolment. So set it
                             // unconditionally to cover both cases.
                             $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid' => $instance->id, 'userid' => $member->id));
                             $trace->output(get_string('enroluser', 'enrol_ldap', array('user_username' => $member->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                         } else {
                             if (!$DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $member->id, 'contextid' => $context->id, 'component' => 'enrol_ldap', 'itemid' => $instance->id))) {
                                 // This happens when reviving users or when user has multiple roles in one course.
                                 $context = context_course::instance($course_obj->id);
                                 role_assign($role->id, $member->id, $context->id, 'enrol_ldap', $instance->id);
                                 $trace->output("Assign role to user '{$member->username}' in course '{$course_obj->shortname} ({$course_obj->id})'");
                             }
                             if ($userenrolment->status == ENROL_USER_SUSPENDED) {
                                 // Reenable enrolment that was previously disabled. Enrolment refreshed
                                 $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid' => $instance->id, 'userid' => $member->id));
                                 $trace->output(get_string('enroluserenable', 'enrol_ldap', array('user_username' => $member->username, 'course_shortname' => $course_obj->shortname, 'course_id' => $course_obj->id)));
                             }
                         }
                     }
                     $transaction->allow_commit();
                 }
             }
         }
     }
     @$this->ldap_close();
     $trace->finished();
 }
コード例 #23
0
ファイル: adminlib.php プロジェクト: raymondAntonio/moodle
 /**
  * Load roles as choices
  *
  * @return bool true=>success, false=>error
  */
 public function load_choices()
 {
     global $CFG, $DB;
     if (during_initial_install()) {
         return false;
     }
     if (is_array($this->choices)) {
         return true;
     }
     if ($roles = get_all_roles()) {
         $this->choices = array();
         foreach ($roles as $role) {
             $this->choices[$role->id] = format_string($role->name);
         }
         return true;
     } else {
         return false;
     }
 }
コード例 #24
0
ファイル: lib.php プロジェクト: numbas/moodle
 /**
  * Forces synchronisation of all enrolments with external database.
  *
  * @param bool $verbose
  * @return int 0 means success, 1 db connect failure, 2 db read failure
  */
 public function sync_enrolments($verbose = false)
 {
     global $CFG, $DB;
     // we do not create courses here intentionally because it requires full sync and is slow
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
         if ($verbose) {
             mtrace('User enrolment synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting user enrolment synchronisation...');
     }
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     // we may need a lot of memory here
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     // second step is to sync instances and users
     $table = $this->get_config('remoteenroltable');
     $coursefield = strtolower($this->get_config('remotecoursefield'));
     $userfield = strtolower($this->get_config('remoteuserfield'));
     $rolefield = strtolower($this->get_config('remoterolefield'));
     $localrolefield = $this->get_config('localrolefield');
     $localuserfield = $this->get_config('localuserfield');
     $localcoursefield = $this->get_config('localcoursefield');
     $unenrolaction = $this->get_config('unenrolaction');
     $defaultrole = $this->get_config('defaultrole');
     // create roles mapping
     $allroles = get_all_roles();
     if (!isset($allroles[$defaultrole])) {
         $defaultrole = 0;
     }
     $roles = array();
     foreach ($allroles as $role) {
         $roles[$role->{$localrolefield}] = $role->id;
     }
     // get a list of courses to be synced that are in external table
     $externalcourses = array();
     $sql = $this->db_get_sql($table, array(), array($coursefield), true);
     if ($rs = $extdb->Execute($sql)) {
         if (!$rs->EOF) {
             while ($mapping = $rs->FetchRow()) {
                 $mapping = reset($mapping);
                 $mapping = $this->db_decode($mapping);
                 if (empty($mapping)) {
                     // invalid mapping
                     continue;
                 }
                 $externalcourses[$mapping] = true;
             }
         }
         $rs->Close();
     } else {
         mtrace('Error reading data from the external enrolment table');
         $extdb->Close();
         return 2;
     }
     $preventfullunenrol = empty($externalcourses);
     if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
         mtrace('  Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
     }
     // first find all existing courses with enrol instance
     $existing = array();
     $sql = "SELECT c.id, c.visible, c.{$localcoursefield} AS mapping, e.id AS enrolid, c.shortname\n                  FROM {course} c\n                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')";
     $rs = $DB->get_recordset_sql($sql);
     // watch out for idnumber duplicates
     foreach ($rs as $course) {
         if (empty($course->mapping)) {
             continue;
         }
         $existing[$course->mapping] = $course;
     }
     $rs->close();
     // add necessary enrol instances that are not present yet
     $params = array();
     $localnotempty = "";
     if ($localcoursefield !== 'id') {
         $localnotempty = "AND c.{$localcoursefield} <> :lcfe";
         $params['lcfe'] = $DB->sql_empty();
     }
     $sql = "SELECT c.id, c.visible, c.{$localcoursefield} AS mapping, c.shortname\n                  FROM {course} c\n             LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')\n                 WHERE e.id IS NULL {$localnotempty}";
     $rs = $DB->get_recordset_sql($sql, $params);
     foreach ($rs as $course) {
         if (empty($course->mapping)) {
             continue;
         }
         if (!isset($externalcourses[$course->mapping])) {
             // course not synced
             continue;
         }
         if (isset($existing[$course->mapping])) {
             // some duplicate, sorry
             continue;
         }
         $course->enrolid = $this->add_instance($course);
         $existing[$course->mapping] = $course;
     }
     $rs->close();
     // free memory
     unset($externalcourses);
     // sync enrolments
     $ignorehidden = $this->get_config('ignorehiddencourses');
     $sqlfields = array($userfield);
     if ($rolefield) {
         $sqlfields[] = $rolefield;
     }
     foreach ($existing as $course) {
         if ($ignorehidden and !$course->visible) {
             continue;
         }
         if (!($instance = $DB->get_record('enrol', array('id' => $course->enrolid)))) {
             continue;
             //weird
         }
         $context = get_context_instance(CONTEXT_COURSE, $course->id);
         // get current list of enrolled users with their roles
         $current_roles = array();
         $current_status = array();
         $user_mapping = array();
         $sql = "SELECT u.{$localuserfield} AS mapping, u.id, ue.status, ue.userid, ra.roleid\n                      FROM {user} u\n                      JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)\n                      JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.itemid = ue.enrolid AND ra.component = 'enrol_database')\n                     WHERE u.deleted = 0";
         $params = array('enrolid' => $instance->id);
         if ($localuserfield === 'username') {
             $sql .= " AND u.mnethostid = :mnethostid";
             $params['mnethostid'] = $CFG->mnet_localhost_id;
         }
         $rs = $DB->get_recordset_sql($sql, $params);
         foreach ($rs as $ue) {
             $current_roles[$ue->userid][$ue->roleid] = $ue->roleid;
             $current_status[$ue->userid] = $ue->status;
             $user_mapping[$ue->mapping] = $ue->userid;
         }
         $rs->close();
         // get list of users that need to be enrolled and their roles
         $requested_roles = array();
         $sql = $this->db_get_sql($table, array($coursefield => $course->mapping), $sqlfields);
         if ($rs = $extdb->Execute($sql)) {
             if (!$rs->EOF) {
                 if ($localuserfield === 'username') {
                     $usersearch = array('mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0);
                 }
                 while ($fields = $rs->FetchRow()) {
                     $fields = array_change_key_case($fields, CASE_LOWER);
                     if (empty($fields[$userfield])) {
                         //user identification is mandatory!
                     }
                     $mapping = $fields[$userfield];
                     if (!isset($user_mapping[$mapping])) {
                         $usersearch[$localuserfield] = $mapping;
                         if (!($user = $DB->get_record('user', $usersearch, 'id', IGNORE_MULTIPLE))) {
                             // user does not exist or was deleted
                             continue;
                         }
                         $user_mapping[$mapping] = $user->id;
                         $userid = $user->id;
                     } else {
                         $userid = $user_mapping[$mapping];
                     }
                     if (empty($fields[$rolefield]) or !isset($roles[$fields[$rolefield]])) {
                         if (!$defaultrole) {
                             // role is mandatory
                             continue;
                         }
                         $roleid = $defaultrole;
                     } else {
                         $roleid = $roles[$fields[$rolefield]];
                     }
                     $requested_roles[$userid][$roleid] = $roleid;
                 }
             }
             $rs->Close();
         } else {
             mtrace('Error while communicating with external enrolment database');
             $extdb->Close();
             return;
         }
         unset($user_mapping);
         // enrol all users and sync roles
         foreach ($requested_roles as $userid => $userroles) {
             foreach ($userroles as $roleid) {
                 if (empty($current_roles[$userid])) {
                     $this->enrol_user($instance, $userid, $roleid, 0, 0, ENROL_USER_ACTIVE);
                     $current_roles[$userid][$roleid] = $roleid;
                     $current_status[$userid] = ENROL_USER_ACTIVE;
                     if ($verbose) {
                         mtrace("  enrolling: {$userid} ==> {$course->shortname} as " . $allroles[$roleid]->shortname);
                     }
                 }
             }
             // assign extra roles
             foreach ($userroles as $roleid) {
                 if (empty($current_roles[$userid][$roleid])) {
                     role_assign($roleid, $userid, $context->id, 'enrol_database', $instance->id);
                     $current_roles[$userid][$roleid] = $roleid;
                     if ($verbose) {
                         mtrace("  assigning roles: {$userid} ==> {$course->shortname} as " . $allroles[$roleid]->shortname);
                     }
                 }
             }
             // unassign removed roles
             foreach ($current_roles[$userid] as $cr) {
                 if (empty($userroles[$cr])) {
                     role_unassign($cr, $userid, $context->id, 'enrol_database', $instance->id);
                     unset($current_roles[$userid][$cr]);
                     if ($verbose) {
                         mtrace("  unsassigning roles: {$userid} ==> {$course->shortname}");
                     }
                 }
             }
             // reenable enrolment when previously disable enrolment refreshed
             if ($current_status[$userid] == ENROL_USER_SUSPENDED) {
                 $this->update_user_enrol($instance, $userid, ENROL_USER_ACTIVE);
                 if ($verbose) {
                     mtrace("  unsuspending: {$userid} ==> {$course->shortname}");
                 }
             }
         }
         // deal with enrolments removed from external table
         if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
             if (!$preventfullunenrol) {
                 // unenrol
                 foreach ($current_status as $userid => $status) {
                     if (isset($requested_roles[$userid])) {
                         continue;
                     }
                     $this->unenrol_user($instance, $userid);
                     if ($verbose) {
                         mtrace("  unenrolling: {$userid} ==> {$course->shortname}");
                     }
                 }
             }
         } else {
             if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) {
                 // keep - only adding enrolments
             } else {
                 if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
                     // disable
                     foreach ($current_status as $userid => $status) {
                         if (isset($requested_roles[$userid])) {
                             continue;
                         }
                         if ($status != ENROL_USER_SUSPENDED) {
                             $this->update_user_enrol($instance, $userid, ENROL_USER_SUSPENDED);
                             if ($verbose) {
                                 mtrace("  suspending: {$userid} ==> {$course->shortname}");
                             }
                         }
                         if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
                             role_unassign_all(array('contextid' => $context->id, 'userid' => $userid, 'component' => 'enrol_database', 'itemid' => $instance->id));
                             if ($verbose) {
                                 mtrace("  unsassigning all roles: {$userid} ==> {$course->shortname}");
                             }
                         }
                     }
                 }
             }
         }
     }
     // close db connection
     $extdb->Close();
     if ($verbose) {
         mtrace('...user enrolment synchronisation finished.');
     }
     return 0;
 }
コード例 #25
0
 /**
  * Returns array of parameters to be passed to legacy add_to_log() function.
  *
  * @return array
  */
 protected function get_legacy_logdata()
 {
     $roles = get_all_roles();
     $rolenames = role_fix_names($roles, $this->get_context(), ROLENAME_ORIGINAL, true);
     return array($this->courseid, 'role', 'unassign', 'admin/roles/assign.php?contextid=' . $this->contextid . '&roleid=' . $this->objectid, $rolenames[$this->objectid], '', $this->userid);
 }
コード例 #26
0
ファイル: locallib.php プロジェクト: EmmanuelYupit/educursos
 /**
  * Gets all of the roles this course can contain.
  *
  * @return array
  */
 public function get_all_roles()
 {
     if ($this->_roles === null) {
         $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
     }
     return $this->_roles;
 }
コード例 #27
0
 function definition()
 {
     global $USER, $CFG, $DB;
     $courseconfig = get_config('moodlecourse');
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 // if users already enrolled directly into coures, do not allow switching to meta,
                 // users with metacourse manage permission are exception
                 // please note that we do not need exact results - anything unexpected here prevents metacourse
                 $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
                 $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext);
                 if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
                     foreach ($users as $user) {
                         if (!isset($managers[$user->id])) {
                             $disable_meta = get_string('metaalreadyhasenrolments');
                             break;
                         }
                     }
                 }
                 unset($managers);
                 unset($users);
                 unset($enrolroles);
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist, 'moodle/course:create');
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $fullname = get_string('defaultcoursefullname');
     $shortname = get_string('defaultcourseshortname');
     while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) {
         $fullname++;
         $shortname++;
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true);
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->setDefault('fullname', $fullname);
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true);
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->setDefault('shortname', $shortname);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text2', get_string('helptext')), true);
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', $courseconfig->format);
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', $courseconfig->metacourse);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $mform->setDefault('enrol', $courseconfig->enrol);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', $courseconfig->enrollable);
     $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
     $mform->setDefault('enrolstartdate', 0);
     $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
     $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
     $mform->setDefault('enrolenddate', 0);
     $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
     $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
     $mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', $courseconfig->expirynotify);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', $courseconfig->notifystudents);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', $courseconfig->visible);
     if ($course and !has_capability('moodle/course:visibility', $coursecontext)) {
         $mform->hardFreeze('visible');
         $mform->setConstant('visible', $course->visible);
     }
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
     $mform->setType('enrolpassword', PARAM_RAW);
     if (empty($course) or $course->password !== '' and $course->id != SITEID) {
         // do not require password in existing courses that do not have password yet - backwards compatibility ;-)
         if (!empty($CFG->enrol_manual_requirekey)) {
             $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
         }
     }
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', $courseconfig->guest);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     require_once $CFG->libdir . '/completionlib.php';
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true);
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
 }
コード例 #28
0
/**
 * Sync all meta course links.
 *
 * @param int $courseid one course, empty mean all
 * @param bool $verbose verbose CLI output
 * @return int 0 means ok, 1 means error, 2 means plugin disabled
 */
function enrol_meta_sync($courseid = NULL, $verbose = false)
{
    global $CFG, $DB;
    // purge all roles if meta sync disabled, those can be recreated later here in cron
    if (!enrol_is_enabled('meta')) {
        if ($verbose) {
            mtrace('Meta sync plugin is disabled, unassigning all plugin roles and stopping.');
        }
        role_unassign_all(array('component' => 'enrol_meta'));
        return 2;
    }
    // unfortunately this may take a long time, execution can be interrupted safely
    @set_time_limit(0);
    raise_memory_limit(MEMORY_HUGE);
    if ($verbose) {
        mtrace('Starting user enrolment synchronisation...');
    }
    $instances = array();
    // cache instances
    $meta = enrol_get_plugin('meta');
    $unenrolaction = $meta->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
    $skiproles = $meta->get_config('nosyncroleids', '');
    $skiproles = empty($skiproles) ? array() : explode(',', $skiproles);
    $syncall = $meta->get_config('syncall', 1);
    $allroles = get_all_roles();
    // iterate through all not enrolled yet users
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT pue.userid, e.id AS enrolid, pue.status\n              FROM {user_enrolments} pue\n              JOIN {enrol} pe ON (pe.id = pue.enrolid AND pe.enrol <> 'meta' AND pe.enrol {$enabled})\n              JOIN {enrol} e ON (e.customint1 = pe.courseid AND e.enrol = 'meta' {$onecourse})\n              JOIN {user} u ON (u.id = pue.userid AND u.deleted = 0)\n         LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = pue.userid)\n             WHERE ue.id IS NULL";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        if (!$syncall) {
            // this may be slow if very many users are ignored in sync
            $parentcontext = context_course::instance($instance->customint1);
            list($ignoreroles, $params) = $DB->get_in_or_equal($skiproles, SQL_PARAMS_NAMED, 'ri', false, -1);
            $params['contextid'] = $parentcontext->id;
            $params['userid'] = $ue->userid;
            $select = "contextid = :contextid AND userid = :userid AND component <> 'enrol_meta' AND roleid {$ignoreroles}";
            if (!$DB->record_exists_select('role_assignments', $select, $params)) {
                // bad luck, this user does not have any role we want in parent course
                if ($verbose) {
                    mtrace("  skipping enrolling: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
                continue;
            }
        }
        $meta->enrol_user($instance, $ue->userid, $ue->status);
        if ($verbose) {
            mtrace("  enrolling: {$ue->userid} ==> {$instance->courseid}");
        }
    }
    $rs->close();
    // unenrol as necessary - ignore enabled flag, we want to get rid of existing enrols in any case
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT ue.*\n              FROM {user_enrolments} ue\n              JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n         LEFT JOIN ({user_enrolments} xpue\n                      JOIN {enrol} xpe ON (xpe.id = xpue.enrolid AND xpe.enrol <> 'meta' AND xpe.enrol {$enabled})\n                   ) ON (xpe.courseid = e.customint1 AND xpue.userid = ue.userid)\n             WHERE xpue.userid IS NULL";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
            $meta->unenrol_user($instance, $ue->userid);
            if ($verbose) {
                mtrace("  unenrolling: {$ue->userid} ==> {$instance->courseid}");
            }
            continue;
        } else {
            // ENROL_EXT_REMOVED_SUSPENDNOROLES
            // just disable and ignore any changes
            if ($ue->status != ENROL_USER_SUSPENDED) {
                $meta->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
                $context = context_course::instance($instance->courseid);
                role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id, 'component' => 'enrol_meta'));
                if ($verbose) {
                    mtrace("  suspending and removing all roles: {$ue->userid} ==> {$instance->courseid}");
                }
            }
            continue;
        }
    }
    $rs->close();
    // update status - meta enrols + start and end dates are ignored, sorry
    // note the trick here is that the active enrolment and instance constants have value 0
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e');
    $params['courseid'] = $courseid;
    $sql = "SELECT ue.userid, ue.enrolid, pue.pstatus\n              FROM {user_enrolments} ue\n              JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n              JOIN (SELECT xpue.userid, xpe.courseid, MIN(xpue.status + xpe.status) AS pstatus\n                      FROM {user_enrolments} xpue\n                      JOIN {enrol} xpe ON (xpe.id = xpue.enrolid AND xpe.enrol <> 'meta' AND xpe.enrol {$enabled})\n                  GROUP BY xpue.userid, xpe.courseid\n                   ) pue ON (pue.courseid = e.customint1 AND pue.userid = ue.userid)\n             WHERE (pue.pstatus = 0 AND ue.status > 0) OR (pue.pstatus > 0 and ue.status = 0)";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ue) {
        if (!isset($instances[$ue->enrolid])) {
            $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
        }
        $instance = $instances[$ue->enrolid];
        $ue->pstatus = $ue->pstatus == ENROL_USER_ACTIVE ? ENROL_USER_ACTIVE : ENROL_USER_SUSPENDED;
        if ($ue->pstatus == ENROL_USER_ACTIVE and !$syncall and $unenrolaction != ENROL_EXT_REMOVED_UNENROL) {
            // this may be slow if very many users are ignored in sync
            $parentcontext = context_course::instance($instance->customint1);
            list($ignoreroles, $params) = $DB->get_in_or_equal($skiproles, SQL_PARAMS_NAMED, 'ri', false, -1);
            $params['contextid'] = $parentcontext->id;
            $params['userid'] = $ue->userid;
            $select = "contextid = :contextid AND userid = :userid AND component <> 'enrol_meta' AND roleid {$ignoreroles}";
            if (!$DB->record_exists_select('role_assignments', $select, $params)) {
                // bad luck, this user does not have any role we want in parent course
                if ($verbose) {
                    mtrace("  skipping unsuspending: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
                continue;
            }
        }
        $meta->update_user_enrol($instance, $ue->userid, $ue->pstatus);
        if ($verbose) {
            if ($ue->pstatus == ENROL_USER_ACTIVE) {
                mtrace("  unsuspending: {$ue->userid} ==> {$instance->courseid}");
            } else {
                mtrace("  suspending: {$ue->userid} ==> {$instance->courseid}");
            }
        }
    }
    $rs->close();
    // now assign all necessary roles
    $enabled = explode(',', $CFG->enrol_plugins_enabled);
    foreach ($enabled as $k => $v) {
        if ($v === 'meta') {
            continue;
            // no meta sync of meta roles
        }
        $enabled[$k] = 'enrol_' . $v;
    }
    $enabled[] = '';
    // manual assignments are replicated too
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    list($enabled, $params) = $DB->get_in_or_equal($enabled, SQL_PARAMS_NAMED, 'e');
    $params['coursecontext'] = CONTEXT_COURSE;
    $params['courseid'] = $courseid;
    $params['activeuser'] = ENROL_USER_ACTIVE;
    $params['enabledinstance'] = ENROL_INSTANCE_ENABLED;
    $sql = "SELECT DISTINCT pra.roleid, pra.userid, c.id AS contextid, e.id AS enrolid, e.courseid\n              FROM {role_assignments} pra\n              JOIN {user} u ON (u.id = pra.userid AND u.deleted = 0)\n              JOIN {context} pc ON (pc.id = pra.contextid AND pc.contextlevel = :coursecontext AND pra.component {$enabled})\n              JOIN {enrol} e ON (e.customint1 = pc.instanceid AND e.enrol = 'meta' {$onecourse} AND e.status = :enabledinstance)\n              JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = u.id AND ue.status = :activeuser)\n              JOIN {context} c ON (c.contextlevel = pc.contextlevel AND c.instanceid = e.courseid)\n         LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = pra.userid AND ra.roleid = pra.roleid AND ra.itemid = e.id AND ra.component = 'enrol_meta')\n             WHERE ra.id IS NULL";
    if ($ignored = $meta->get_config('nosyncroleids')) {
        list($notignored, $xparams) = $DB->get_in_or_equal(explode(',', $ignored), SQL_PARAMS_NAMED, 'ig', false);
        $params = array_merge($params, $xparams);
        $sql = "{$sql} AND pra.roleid {$notignored}";
    }
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ra) {
        role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_meta', $ra->enrolid);
        if ($verbose) {
            mtrace("  assigning role: {$ra->userid} ==> {$ra->courseid} as " . $allroles[$ra->roleid]->shortname);
        }
    }
    $rs->close();
    // remove unwanted roles - include ignored roles and disabled plugins too
    $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
    $params = array();
    $params['coursecontext'] = CONTEXT_COURSE;
    $params['courseid'] = $courseid;
    $params['activeuser'] = ENROL_USER_ACTIVE;
    $params['enabledinstance'] = ENROL_INSTANCE_ENABLED;
    if ($ignored = $meta->get_config('nosyncroleids')) {
        list($notignored, $xparams) = $DB->get_in_or_equal(explode(',', $ignored), SQL_PARAMS_NAMED, 'ig', false);
        $params = array_merge($params, $xparams);
        $notignored = "AND pra.roleid {$notignored}";
    } else {
        $notignored = "";
    }
    $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid\n              FROM {role_assignments} ra\n              JOIN {enrol} e ON (e.id = ra.itemid AND ra.component = 'enrol_meta' AND e.enrol = 'meta' {$onecourse})\n              JOIN {context} pc ON (pc.instanceid = e.customint1 AND pc.contextlevel = :coursecontext)\n         LEFT JOIN {role_assignments} pra ON (pra.contextid = pc.id AND pra.userid = ra.userid AND pra.roleid = ra.roleid AND pra.component <> 'enrol_meta' {$notignored})\n         LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :activeuser)\n             WHERE pra.id IS NULL OR ue.id IS NULL OR e.status <> :enabledinstance";
    $rs = $DB->get_recordset_sql($sql, $params);
    foreach ($rs as $ra) {
        role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_meta', $ra->itemid);
        if ($verbose) {
            mtrace("  unassigning role: {$ra->userid} ==> {$ra->courseid} as " . $allroles[$ra->roleid]->shortname);
        }
    }
    $rs->close();
    // kick out or suspend users without synced roles if syncall disabled
    if (!$syncall) {
        if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
            $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
            $params = array();
            $params['coursecontext'] = CONTEXT_COURSE;
            $params['courseid'] = $courseid;
            $sql = "SELECT ue.userid, ue.enrolid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n                      JOIN {context} c ON (e.courseid = c.instanceid AND c.contextlevel = :coursecontext)\n                 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.itemid = e.id AND ra.userid = ue.userid)\n                     WHERE ra.id IS NULL";
            $ues = $DB->get_recordset_sql($sql, $params);
            foreach ($ues as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
                }
                $instance = $instances[$ue->enrolid];
                $meta->unenrol_user($instance, $ue->userid);
                if ($verbose) {
                    mtrace("  unenrolling: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
            }
            $ues->close();
        } else {
            // just suspend the users
            $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
            $params = array();
            $params['coursecontext'] = CONTEXT_COURSE;
            $params['courseid'] = $courseid;
            $params['active'] = ENROL_USER_ACTIVE;
            $sql = "SELECT ue.userid, ue.enrolid\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'meta' {$onecourse})\n                      JOIN {context} c ON (e.courseid = c.instanceid AND c.contextlevel = :coursecontext)\n                 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.itemid = e.id AND ra.userid = ue.userid)\n                     WHERE ra.id IS NULL AND ue.status = :active";
            $ues = $DB->get_recordset_sql($sql, $params);
            foreach ($ues as $ue) {
                if (!isset($instances[$ue->enrolid])) {
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id' => $ue->enrolid));
                }
                $instance = $instances[$ue->enrolid];
                $meta->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
                if ($verbose) {
                    mtrace("  suspending: {$ue->userid} ==> {$instance->courseid} (user without role)");
                }
            }
            $ues->close();
        }
    }
    if ($verbose) {
        mtrace('...user enrolment synchronisation finished.');
    }
    return 0;
}
コード例 #29
0
function main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion < 2003010101) {
        delete_records("log_display", "module", "user");
        $new->module = "user";
        $new->action = "view";
        $new->mtable = "user";
        $new->field = "CONCAT(firstname,\" \",lastname)";
        insert_record("log_display", $new);
        delete_records("log_display", "module", "course");
        $new->module = "course";
        $new->action = "view";
        $new->mtable = "course";
        $new->field = "fullname";
        insert_record("log_display", $new);
        $new->action = "update";
        insert_record("log_display", $new);
        $new->action = "enrol";
        insert_record("log_display", $new);
    }
    //support user based course creating
    if ($oldversion < 2003032400) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_coursecreators (\n                                  id int8 SERIAL PRIMARY KEY,\n                                  userid int8  NOT NULL default '0'\n                                  )");
    }
    if ($oldversion < 2003041400) {
        table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
    }
    if ($oldversion < 2003042104) {
        // Try to update permissions of all files
        if ($files = get_directory_list($CFG->dataroot)) {
            echo "Attempting to update permissions for all files... ignore any errors.";
            foreach ($files as $file) {
                echo "{$CFG->dataroot}/{$file}<br />";
                @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions);
            }
        }
    }
    if ($oldversion < 2003042400) {
        // Rebuild all course caches, because of changes to do with visible variable
        if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2003042500) {
        //  Convert all usernames to lowercase.
        $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
        $cerrors = "";
        $rarray = array();
        foreach ($users as $user) {
            // Check for possible conflicts
            $lcname = trim(moodle_strtolower($user->username));
            if (in_array($lcname, $rarray)) {
                $cerrors .= $user->id . "->" . $lcname . '<br/>';
            } else {
                array_push($rarray, $lcname);
            }
        }
        if ($cerrors != '') {
            notify("Error: Cannot convert usernames to lowercase. \n                    Following usernames would overlap (id->username):<br/> {$cerrors} . \n                    Please resolve overlapping errors.");
            $result = false;
        }
        $cerrors = "";
        echo "Checking userdatabase:<br />";
        foreach ($users as $user) {
            $lcname = trim(moodle_strtolower($user->username));
            if ($lcname != $user->username) {
                $convert = set_field("user", "username", $lcname, "id", $user->id);
                if (!$convert) {
                    if ($cerrors) {
                        $cerrors .= ", ";
                    }
                    $cerrors .= $item;
                } else {
                    echo ".";
                }
            }
        }
        if ($cerrors != '') {
            notify("There were errors when converting following usernames to lowercase. \n                   '{$cerrors}' . Sorry, but you will need to fix your database by hand.");
            $result = false;
        }
    }
    if ($oldversion < 2003042700) {
        /// Changing to multiple indexes
        execute_sql(" CREATE INDEX {$CFG->prefix}log_coursemoduleaction_idx ON {$CFG->prefix}log (course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}log_courseuserid_idx ON {$CFG->prefix}log (course,userid) ");
    }
    if ($oldversion < 2003042801) {
        execute_sql("CREATE TABLE {$CFG->prefix}course_display (\n                         id SERIAL PRIMARY KEY,\n                         course integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         display integer NOT NULL default '0'\n                      )");
        execute_sql("CREATE INDEX {$CFG->prefix}course_display_courseuserid_idx ON {$CFG->prefix}course_display (course,userid)");
    }
    if ($oldversion < 2003050400) {
        table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050401) {
        table_column("user", "", "lang", "VARCHAR", "5", "", "{$CFG->lang}", "NOT NULL", "");
    }
    if ($oldversion < 2003050900) {
        table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050902) {
        if (get_records("modules", "name", "pgassignment")) {
            print_simple_box("Note: the pgassignment module will soon be deleted from CVS!  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        }
    }
    if ($oldversion < 2003051600) {
        print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
    }
    if ($oldversion < 2003052300) {
        table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
    }
    if ($oldversion < 2003072100) {
        table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
    }
    if ($oldversion < 2003072101) {
        table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
    }
    if ($oldversion < 2003072800) {
        print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        flush();
        execute_sql(" CREATE INDEX {$CFG->prefix}log_timecoursemoduleaction_idx ON {$CFG->prefix}log (time,course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_students_courseuserid_idx ON {$CFG->prefix}user_students (course,userid) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_teachers_courseuserid_idx ON {$CFG->prefix}user_teachers (course,userid) ");
    }
    if ($oldversion < 2003072802) {
        table_column("course_categories", "", "description", "text", "", "", "");
        table_column("course_categories", "", "parent", "integer", "10", "unsigned");
        table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
        table_column("course_categories", "", "courseorder", "text", "", "", "");
        table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
        table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
    }
    if ($oldversion < 2003080400) {
        notify("If the following command fails you may want to change the type manually, from TEXT to INTEGER.  Moodle should keep working even if you don't.");
        table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
        table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
    }
    if ($oldversion < 2003081502) {
        execute_sql(" CREATE TABLE {$CFG->prefix}scale (\n                         id SERIAL PRIMARY KEY,\n                         courseid integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         name varchar(255) NOT NULL default '',\n                         scale text,\n                         description text,\n                         timemodified integer NOT NULL default '0'\n                      )");
    }
    if ($oldversion < 2003081503) {
        table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
        get_scales_menu(0);
        // Just to force the default scale to be created
    }
    if ($oldversion < 2003081600) {
        table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
        table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
    }
    if ($oldversion < 2003081900) {
        table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003080700) {
        notify("Cleaning up categories and course ordering...");
        fix_course_sortorder();
    }
    if ($oldversion < 2003082001) {
        table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
    }
    if ($oldversion < 2003082101) {
        execute_sql(" CREATE INDEX {$CFG->prefix}course_category_idx ON {$CFG->prefix}course (category) ");
    }
    if ($oldversion < 2003082702) {
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
    }
    if ($oldversion < 2003091000) {
        # Old field that was never added!
        table_column("course", "", "showrecent", "integer", "10", "unsigned", "1", "", "numsections");
    }
    if ($oldversion < 2003091400) {
        table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
    }
    if ($oldversion < 2003092900) {
        table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
    }
    if ($oldversion < 2003102700) {
        table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
        table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
        $db->debug = false;
        $CFG->debug = 0;
        notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
        flush();
        if ($courses = get_records_select("course", "category > 0")) {
            foreach ($courses as $course) {
                notify("Processing " . format_string($course->fullname) . " ...", "green");
                flush();
                if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '{$course->id}' and userid = '{$user->userid}'                                                               ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
                if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log \n                                                   WHERE course = '{$course->id}' and userid = '{$user->userid}' \n                                                   ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_students \n                                     SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
            }
        }
        notify("All courses complete.", "green");
        $db->debug = true;
    }
    if ($oldversion < 2003103100) {
        table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
    }
    if ($oldversion < 2003121600) {
        execute_sql("CREATE TABLE {$CFG->prefix}groups (\n                        id SERIAL PRIMARY KEY,\n                        courseid integer NOT NULL default '0',\n                        name varchar(255) NOT NULL default '',\n                        description text,\n                        lang varchar(10) NOT NULL default '',\n                        picture integer NOT NULL default '0',\n                        timecreated integer NOT NULL default '0',\n                        timemodified integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_idx ON {$CFG->prefix}groups (courseid) ");
        execute_sql("CREATE TABLE {$CFG->prefix}groups_members (\n                        id SERIAL PRIMARY KEY,\n                        groupid integer NOT NULL default '0',\n                        userid integer NOT NULL default '0',\n                        timeadded integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_members_idx ON {$CFG->prefix}groups_members (groupid) ");
    }
    if ($oldversion < 2003122600) {
        table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
        table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
    }
    if ($oldversion < 2004010900) {
        table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
    }
    if ($oldversion < 2004011700) {
        modify_database("", "CREATE TABLE prefix_event (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(255) NOT NULL default '',\n                                description text,\n                                courseid integer NOT NULL default '0',\n                                groupid integer NOT NULL default '0',\n                                userid integer NOT NULL default '0',\n                                modulename varchar(20) NOT NULL default '',\n                                instance integer NOT NULL default '0',\n                                eventtype varchar(20) NOT NULL default '',\n                                timestart integer NOT NULL default '0',\n                                timeduration integer NOT NULL default '0',\n                                timemodified integer NOT NULL default '0'\n                             ); ");
        modify_database("", "CREATE INDEX prefix_event_courseid_idx ON prefix_event (courseid);");
        modify_database("", "CREATE INDEX prefix_event_userid_idx ON prefix_event (userid);");
    }
    if ($oldversion < 2004012800) {
        modify_database("", "CREATE TABLE prefix_user_preferences (\n                                id SERIAL PRIMARY KEY,\n                                userid integer NOT NULL default '0',\n                                name varchar(50) NOT NULL default '',\n                                value varchar(255) NOT NULL default ''\n                             ); ");
        modify_database("", "CREATE INDEX prefix_user_preferences_useridname_idx ON prefix_user_preferences (userid,name);");
    }
    if ($oldversion < 2004012900) {
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004013101) {
        table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
        set_config("upgrade", "logs");
    }
    if ($oldversion < 2004020900) {
        table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
    }
    if ($oldversion < 2004020903) {
        modify_database("", "CREATE TABLE prefix_cache_text (\n                                id SERIAL PRIMARY KEY,\n                                md5key varchar(32) NOT NULL default '',\n                                formattedtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004021000) {
        $textfilters = array();
        for ($i = 1; $i <= 10; $i++) {
            $variable = "textfilter{$i}";
            if (!empty($CFG->{$variable})) {
                /// No more filters
                if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) {
                    $textfilters[] = $CFG->{$variable};
                }
            }
        }
        $textfilters = implode(',', $textfilters);
        if (empty($textfilters)) {
            $textfilters = 'mod/glossary/dynalink.php';
        }
        set_config('textfilters', $textfilters);
    }
    if ($oldversion < 2004021201) {
        modify_database("", "CREATE TABLE prefix_cache_filters (\n                                id SERIAL PRIMARY KEY,\n                                filter varchar(32) NOT NULL default '',\n                                version integer NOT NULL default '0',\n                                md5key varchar(32) NOT NULL default '',\n                                rawtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
        modify_database("", "CREATE INDEX prefix_cache_filters_filtermd5key_idx ON prefix_cache_filters (filter,md5key);");
        modify_database("", "CREATE INDEX prefix_cache_text_md5key_idx ON prefix_cache_text (md5key);");
    }
    if ($oldversion < 2004021500) {
        table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
    }
    if ($oldversion < 2004021700) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004022000) {
        table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
    }
    if ($oldversion < 2004022200) {
        /// Final renaming I hope.  :-)
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
            $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
            $textfilters = explode(',', $CFG->textfilters);
            foreach ($textfilters as $key => $textfilter) {
                $textfilters[$key] = trim($textfilter);
            }
            set_config("textfilters", implode(',', $textfilters));
        }
    }
    if ($oldversion < 2004030702) {
        /// Because of the renaming of Czech language pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
    }
    if ($oldversion < 2004041800) {
        /// Integrate Block System from contrib
        table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
    }
    if ($oldversion < 2004042600) {
        /// Rebuild course caches for resource icons
        //include_once("$CFG->dirroot/course/lib.php");
        //rebuild_course_cache();
    }
    if ($oldversion < 2004042700) {
        /// Increase size of lang fields
        table_column("user", "lang", "lang", "varchar", "10", "", "en");
        table_column("groups", "lang", "lang", "varchar", "10", "", "");
        table_column("course", "lang", "lang", "varchar", "10", "", "");
    }
    if ($oldversion < 2004042701) {
        /// Add hiddentopics field to control hidden topics behaviour
        #table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
        #See 'hiddensections' further down
    }
    if ($oldversion < 2004042702) {
        /// Add a format field for the description
        table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
    }
    if ($oldversion < 2004043001) {
        /// Add hiddentopics field to control hidden topics behaviour
        table_column("course", "", "hiddensections", "integer", "2", "unsigned", "0", "not null", "visible");
    }
    if ($oldversion < 2004050400) {
        /// add a visible field for events
        table_column("event", "", "visible", "smallint", "1", "", "1", "not null", "timeduration");
        if ($events = get_records('event')) {
            foreach ($events as $event) {
                if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
                    if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
                        set_field('event', 'visible', 0, 'id', $event->id);
                    }
                }
            }
        }
    }
    if ($oldversion < 2004052800) {
        /// First version tagged "1.4 development", version.php 1.227
        set_config('siteblocksadded', true);
        /// This will be used later by the block upgrade
    }
    if ($oldversion < 2004053000) {
        /// set defaults for site course
        $site = get_site();
        set_field('course', 'numsections', 0, 'id', $site->id);
        set_field('course', 'groupmodeforce', 1, 'id', $site->id);
        set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
        set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
        set_field('course', 'student', get_string('user'), 'id', $site->id);
        set_field('course', 'students', get_string('users'), 'id', $site->id);
    }
    if ($oldversion < 2004060100) {
        set_config('digestmailtime', 0);
        table_column('user', "", 'maildigest', 'smallint', '1', '', '0', 'not null', 'mailformat');
    }
    if ($oldversion < 2004062400) {
        table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
        table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
    }
    if ($oldversion < 2004062401) {
        table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
        execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname');
        // By default
    }
    if ($oldversion < 2004062600) {
        table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
    }
    if ($oldversion < 2004072900) {
        table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
    }
    if ($oldversion < 2004072901) {
        // Fixing error in schema
        if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
            delete_records('log_display', 'module', 'course', 'action', 'update');
            insert_record('log_display', $record, false);
        }
    }
    if ($oldversion < 2004081200) {
        // Fixing version errors in some blocks
        set_field('blocks', 'version', 2004081200, 'name', 'admin');
        set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
        set_field('blocks', 'version', 2004081200, 'name', 'course_list');
    }
    if ($oldversion < 2004081500) {
        // Adding new "auth" field to user table to allow more flexibility
        table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
        execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");
        // Set everyone to 'manual' to be sure
        if ($admins = get_admins()) {
            // Set all the NON-admins to whatever the current auth module is
            $adminlist = array();
            foreach ($admins as $user) {
                $adminlist[] = $user->id;
            }
            $adminlist = implode(',', $adminlist);
            execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})");
        }
    }
    if ($oldversion < 2004082600) {
        //update auth-fields for external users
        // following code would not work in 1.8
        /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
                if (function_exists('auth_get_userlist')) {
                    $externalusers = auth_get_userlist();
                    if (!empty($externalusers)){
                        $externalusers = '\''. implode('\',\'',$externalusers).'\'';
                        execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
                    }
                }*/
    }
    if ($oldversion < 2004082900) {
        // Make sure guest is "manual" too.
        set_field('user', 'auth', 'manual', 'username', 'guest');
    }
    /* Just commenteed unused fields out
       if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
               table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
               execute_sql("CREATE INDEX {$CFG->prefix}user_auth_guid_idx ON {$CFG->prefix}user (auth, guid)"); 
       }
       */
    if ($oldversion < 2004091900) {
        //Modify idnumber to hold longer keys
        set_field('user', 'auth', 'manual', 'username', 'guest');
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
        execute_sql("DROP INDEX {$CFG->prefix}user_idnumber_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("DROP INDEX {$CFG->prefix}user_auth_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("CREATE INDEX {$CFG->prefix}user_idnumber_idx ON {$CFG->prefix}user (idnumber)");
        execute_sql("CREATE INDEX {$CFG->prefix}user_auth_idx ON {$CFG->prefix}user (auth)");
    }
    if ($oldversion < 2004092000) {
        //redoing this just to be sure that column type is text (postgres type changes didnt work when this was done first time)
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004093001) {
        // add new table for sessions storage
        execute_sql(" CREATE TABLE {$CFG->prefix}sessions (\n                          sesskey char(32) PRIMARY KEY,\n                          expiry integer NOT null,\n                          expireref varchar(64),\n                          data text NOT null\n                      );");
        execute_sql(" CREATE INDEX {$CFG->prefix}sessions_expiry_idx ON {$CFG->prefix}sessions (expiry)");
    }
    if ($oldversion < 2004111500) {
        // Update any users/courses using wrongly-named lang pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
    }
    if ($oldversion < 2004111700) {
        // add indexes- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_idnumber_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_shortname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_userid_idx;", false);
        modify_database("", "CREATE INDEX {$CFG->prefix}course_idnumber_idx ON {$CFG->prefix}course (idnumber);");
        modify_database("", "CREATE INDEX {$CFG->prefix}course_shortname_idx ON {$CFG->prefix}course (shortname);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_userid_idx ON {$CFG->prefix}user_students (userid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_userid_idx ON {$CFG->prefix}user_teachers (userid);");
    }
    if ($oldversion < 2004111700) {
        // add an index to event for timestart and timeduration- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}event_timestart_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}event_timeduration_idx;", false);
        modify_database('', 'CREATE INDEX prefix_event_timestart_idx ON prefix_event (timestart);');
        modify_database('', 'CREATE INDEX prefix_event_timeduration_idx ON prefix_event (timeduration);');
    }
    if ($oldversion < 2004117000) {
        // add an index on the groups_members table- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}groups_members_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_groups_members_userid_idx ON prefix_groups_members (userid);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on modules and course_modules- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_visible_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_module_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_instance_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}modules_name_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_modules_visible_idx ON prefix_course_modules (visible);');
        modify_database('', 'CREATE INDEX prefix_course_modules_course_idx ON prefix_course_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_modules_module_idx ON prefix_course_modules (module);');
        modify_database('', 'CREATE INDEX prefix_course_modules_instance_idx ON prefix_course_modules (instance);');
        modify_database('', 'CREATE INDEX prefix_course_modules_deleted_idx ON prefix_course_modules (deleted);');
        modify_database('', 'CREATE INDEX prefix_modules_name_idx ON prefix_modules (name);');
    }
    if ($oldversion < 2004111700) {
        // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
        execute_sql("DROP INDEX {$CFG->prefix}user_students_timeaccess_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_students_timeaccess_idx ON prefix_user_students (timeaccess);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on faux foreign keys  - drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_sections_coursesection_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}scale_courseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_admins_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_coursecreators_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_sections_coursesection_idx ON prefix_course_sections (course,section);');
        modify_database('', 'CREATE INDEX prefix_scale_courseid_idx ON prefix_scale (courseid);');
        modify_database('', 'CREATE INDEX prefix_user_admins_userid_idx ON prefix_user_admins (userid);');
        modify_database('', 'CREATE INDEX prefix_user_coursecreators_userid_idx ON prefix_user_coursecreators (userid);');
    }
    if ($oldversion < 2004111700) {
        // make new indexes on user table.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk;", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder)");
        execute_sql("DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        modify_database("", "CREATE INDEX prefix_user_deleted_idx ON prefix_user (deleted)");
        modify_database("", "CREATE INDEX prefix_user_confirmed_idx ON prefix_user (confirmed)");
        modify_database("", "CREATE INDEX prefix_user_firstname_idx ON prefix_user (firstname)");
        modify_database("", "CREATE INDEX prefix_user_lastname_idx ON prefix_user (lastname)");
        modify_database("", "CREATE INDEX prefix_user_city_idx ON prefix_user (city)");
        modify_database("", "CREATE INDEX prefix_user_country_idx ON prefix_user (country)");
        modify_database("", "CREATE INDEX prefix_user_lastaccess_idx ON prefix_user (lastaccess)");
    }
    if ($oldversion < 2004111700) {
        // one more index for email (for sorting)
        execute_sql("DROP INDEX {$CFG->prefix}user_email_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_email_idx ON prefix_user (email);');
    }
    if ($oldversion < 2004112200) {
        // new 'enrol' field for enrolment tables
        table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
        table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_enrol_idx ON {$CFG->prefix}user_students (enrol);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_enrol_idx ON {$CFG->prefix}user_teachers (enrol);");
    }
    if ($oldversion < 2004112300) {
        // update log display to use correct postgres friendly sql
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='user' AND action='view' AND mtable='user'");
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='course' AND action='user report' AND mtable='user'");
    }
    if ($oldversion < 2004112400) {
        /// Delete duplicate enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_students_courseuserid_uk ON prefix_user_students (course,userid);');
        /// Delete duplicate teacher enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_teachers_courseuserid_uk ON prefix_user_teachers (course,userid);');
    }
    if ($oldversion < 2004112401) {
        // some postgres databases may have a non-unique index mislabeled unique.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk  ", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx  ", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder);");
        // odd! username was missing its unique index!
        // first silently drop it just in case...
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP CONSTRAINT {$CFG->prefix}user_username_uk;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_username_uk", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_user_username_uk ON prefix_user (username);");
    }
    if ($oldversion < 2004112900) {
        table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
    }
    if ($oldversion < 2004121400) {
        table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
    }
    if ($oldversion < 2004121600) {
        modify_database('', "CREATE TABLE prefix_dst_preset (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(48) NOT NULL default '',\n                                apply_offset integer NOT NULL default '0',\n                                activate_index integer NOT NULL default '1',\n                                activate_day integer NOT NULL default '1',\n                                activate_month integer NOT NULL default '1',\n                                activate_time char(5) NOT NULL default '03:00',\n                                deactivate_index integer NOT NULL default '1',\n                                deactivate_day integer NOT NULL default '1',\n                                deactivate_month integer NOT NULL default '2',\n                                deactivate_time char(5) NOT NULL default '03:00',\n                                last_change integer NOT NULL default '0',\n                                next_change integer NOT NULL default '0',\n                                current_offset integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004122800) {
        execute_sql("DROP TABLE {$CFG->prefix}message", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_contacts_useridcontactid_idx", false);
        modify_database('', "CREATE TABLE prefix_message (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default ''\n                            );\n\n                            CREATE INDEX prefix_message_useridfrom_idx ON prefix_message (useridfrom);\n                            CREATE INDEX prefix_message_useridto_idx ON prefix_message (useridto);\n\n                            CREATE TABLE prefix_message_read (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               timeread integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default '',\n                               mailed integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_read_useridfrom_idx ON prefix_message_read (useridfrom);\n                            CREATE INDEX prefix_message_read_useridto_idx ON prefix_message_read (useridto);\n                            ");
        modify_database('', "CREATE TABLE prefix_message_contacts (\n                               id SERIAL PRIMARY KEY,\n                               userid integer NOT NULL default '0',\n                               contactid integer NOT NULL default '0',\n                               blocked integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_contacts_useridcontactid_idx ON prefix_message_contacts (userid,contactid);\n                            ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2004122801) {
        table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
        table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
    }
    if ($oldversion < 2005010100) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2005011000) {
        // Create a .htaccess file in dataroot, just in case
        if (!file_exists($CFG->dataroot . '/.htaccess')) {
            if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) {
                // For safety
                @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
                @fclose($handle);
                notify("Created a default .htaccess file in {$CFG->dataroot}");
            }
        }
    }
    if ($oldversion < 2005012500) {
        // add new table for meta courses.
        /*
        modify_database("","CREATE TABLE prefix_meta_course (
             id SERIAL primary key,
             parent_course integer NOT NULL,
             child_course integer NOT NULL
             );");
        
        modify_database("","CREATE INDEX prefix_meta_course_parent_idx ON prefix_meta_course (parent_course);");
        modify_database("","CREATE INDEX prefix_meta_course_child_idx ON prefix_meta_course (child_course);");
        table_column('course','','meta_course','integer','1','','0','not null');
        */
        // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
    }
    if ($oldversion < 2005012501) {
        //fix table names for consistency
        execute_sql("DROP TABLE {$CFG->prefix}meta_course", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false);
        // drop silently
        modify_database("", "CREATE TABLE prefix_course_meta (\n             id SERIAL primary key,\n             parent_course integer NOT NULL,\n             child_course integer NOT NULL\n             );");
        modify_database("", "CREATE INDEX prefix_course_meta_parent_idx ON prefix_course_meta (parent_course);");
        modify_database("", "CREATE INDEX prefix_course_meta_child_idx ON prefix_course_meta (child_course);");
        table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005020100) {
        fix_course_sortorder(0, 1, 1);
    }
    if ($oldversion < 2005021000) {
        // New fields for theme choices
        table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        set_config('theme', 'standardwhite');
        // Reset to a known good theme
    }
    if ($oldversion < 2005021700) {
        table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
    }
    if ($oldversion < 2005021800) {
        modify_database("", "CREATE TABLE adodb_logsql (\n                              created timestamp NOT NULL,\n                              sql0 varchar(250) NOT NULL,\n                              sql1 text NOT NULL,\n                              params text NOT NULL,\n                              tracer text NOT NULL,\n                              timer decimal(16,6) NOT NULL\n                           );");
    }
    if ($oldversion < 2005022400) {
        table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
        table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
    }
    if ($oldversion < 2005030501) {
        table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
    }
    if ($oldversion < 2005032300) {
        table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
        execute_sql('UPDATE ' . $CFG->prefix . 'user SET timezonename = \'\'');
    }
    if ($oldversion < 2005032600) {
        execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false);
        modify_database('', "CREATE TABLE prefix_timezone (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(100) NOT NULL default '',\n                              year integer NOT NULL default '0',\n                              rule varchar(20) NOT NULL default '',\n                              gmtoff integer NOT NULL default '0',\n                              dstoff integer NOT NULL default '0',\n                              dst_month integer NOT NULL default '0',\n                              dst_startday integer NOT NULL default '0',\n                              dst_weekday integer NOT NULL default '0',\n                              dst_skipweeks integer NOT NULL default '0',\n                              dst_time varchar(5) NOT NULL default '00:00',\n                              std_month integer NOT NULL default '0',\n                              std_startday integer NOT NULL default '0',\n                              std_weekday integer NOT NULL default '0',\n                              std_skipweeks integer NOT NULL default '0',\n                              std_time varchar(5) NOT NULL default '00:00'\n                            );");
    }
    if ($oldversion < 2005032800) {
        modify_database('', "CREATE TABLE prefix_grade_category (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(64) default NULL,\n                              courseid integer NOT NULL default '0',\n                              drop_x_lowest integer NOT NULL default '0',\n                              bonus_points integer NOT NULL default '0',\n                              hidden integer NOT NULL default '0',\n                              weight decimal(4,2) default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_category_courseid_idx ON prefix_grade_category (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_exceptions (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer  NOT NULL default '0',\n                              grade_itemid integer  NOT NULL default '0',\n                              userid integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_exceptions_courseid_idx ON prefix_grade_exceptions (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_item (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              category integer default NULL,\n                              modid integer default NULL,\n                              cminstance integer default NULL,\n                              scale_grade float(11) default '1.0000000000',\n                              extra_credit integer NOT NULL default '0',\n                              sort_order integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_item_courseid_idx ON prefix_grade_item (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_letter (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer NOT NULL default '0',\n                              letter varchar(8) NOT NULL default 'NA',\n                              grade_high decimal(6,2) NOT NULL default '100.00',\n                              grade_low decimal(6,2) NOT NULL default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_letter_courseid_idx ON prefix_grade_letter (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_preferences (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              preference integer NOT NULL default '0',\n                              value integer NOT NULL default '0'\n                            );");
        modify_database('', "CREATE UNIQUE INDEX prefix_grade_prefs_courseidpref_uk ON prefix_grade_preferences (courseid,preference);");
    }
    if ($oldversion < 2005033100) {
        // Get rid of defunct field from course modules table
        delete_records('course_modules', 'deleted', 1);
        // Delete old records we don't need any more
        execute_sql('DROP INDEX ' . $CFG->prefix . 'course_modules_deleted_idx;');
        // Old index
        execute_sql('ALTER TABLE ' . $CFG->prefix . 'course_modules DROP deleted;');
        // Old field
    }
    if ($oldversion < 2005040800) {
        table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
        execute_sql(" ALTER TABLE {$CFG->prefix}user DROP timezonename ");
    }
    if ($oldversion < 2005041101) {
        require_once $CFG->libdir . '/filelib.php';
        if (is_readable($CFG->dirroot . '/lib/timezones.txt')) {
            // Distribution file
            if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) {
                $db->debug = false;
                update_timezone_records($timezones);
                notify(count($timezones) . ' timezones installed');
                $db->debug = true;
            }
        }
    }
    if ($oldversion < 2005041900) {
        // Copy all Dialogue entries into Messages, and hide Dialogue module
        if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
                                          FROM ' . $CFG->prefix . 'dialogue_conversations c,
                                               ' . $CFG->prefix . 'dialogue_entries e
                                         WHERE e.conversationid = c.id')) {
            foreach ($entries as $entry) {
                $message = NULL;
                $message->useridfrom = $entry->userid;
                $message->useridto = $entry->recipientid;
                $message->message = addslashes($entry->text);
                $message->format = FORMAT_HTML;
                $message->timecreated = $entry->timecreated;
                $message->messagetype = 'direct';
                insert_record('message_read', $message);
            }
        }
        set_field('modules', 'visible', 0, 'name', 'dialogue');
        notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
    }
    if ($oldversion < 2005042100) {
        $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
    }
    if ($oldversion < 2005042400) {
        // Add user tracking prefs field.
        table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
    }
    if ($oldversion < 2005051500) {
        // Add user tracking prefs field.
        table_column('grade_category', 'weight', 'weight', 'numeric(5,2)', '', '', '0.00', '', '');
    }
    if ($oldversion < 2005053000) {
        // Add config_plugins table
        // this table was created on the MOODLE_15_STABLE branch
        // so it may already exist. Therefore we hide potential errors
        // (Postgres doesn't support CREATE TABLE IF NOT EXISTS)
        execute_sql("CREATE TABLE {$CFG->prefix}config_plugins (\n                        id     SERIAL PRIMARY KEY,\n                        plugin varchar(100) NOT NULL default 'core',\n                        name   varchar(100) NOT NULL default '',\n                        value  text NOT NULL default '',\n                        CONSTRAINT {$CFG->prefix}config_plugins_plugin_name_uk UNIQUE (plugin, name)\n                     );", false);
    }
    if ($oldversion < 2005060200) {
        // migrate some config items to config_plugins table
        // NOTE: this block is in both postgres AND mysql upgrade
        // files. If you edit either, update the otherone.
        $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang");
        if (!empty($CFG->auth)) {
            // if we have no auth, just pass
            foreach ($user_fields as $field) {
                $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
                foreach ($suffixes as $suffix) {
                    $key = 'auth_user_' . $field . $suffix;
                    if (isset($CFG->{$key})) {
                        // translate keys & values
                        // to the new convention
                        // this should support upgrading
                        // even 1.5dev installs
                        $newkey = $key;
                        $newval = $CFG->{$key};
                        if ($suffix === '') {
                            $newkey = 'field_map_' . $field;
                        } elseif ($suffix === '_editlock') {
                            $newkey = 'field_lock_' . $field;
                            $newval = $newval == 1 ? 'locked' : 'unlocked';
                            // translate 0/1 to locked/unlocked
                        } elseif ($suffix === '_updateremote') {
                            $newkey = 'field_updateremote_' . $field;
                        } elseif ($suffix === '_updatelocal') {
                            $newkey = 'field_updatelocal_' . $field;
                            $newval = $newval == 1 ? 'onlogin' : 'oncreate';
                            // translate 0/1 to locked/unlocked
                        }
                        if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) {
                            notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} .");
                            $result = false;
                        }
                    }
                    // end if isset key
                }
                // end foreach suffix
            }
            // end foreach field
        }
    }
    if ($oldversion < 2005060201) {
        // Close down the Attendance module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) {
            if (count_records('attendance')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'attendance');
                notify('The Attendance module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Attendance activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false);
                delete_records('modules', 'name', 'attendance');
                notify("The Attendance module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005060223) {
        // Mass cleanup of bad postgres upgrade scripts
        execute_sql("DROP TABLE {$CFG->prefix}attendance_roll", false);
        // There are no attendance module anymore
        modify_database('', 'ALTER TABLE prefix_config ALTER value SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER metacourse SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_event ALTER repeatid SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER password SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message_read ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER aim DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER idnumber DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER msn DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER policyagreed SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER skype DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER timezone SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER trackforums SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER yahoo DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user_students ALTER enrol SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user_teachers ALTER enrol SET NOT NULL');
    }
    if ($oldversion < 2005071700) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (count_records('dialogue')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'dialogue');
                notify('The Dialogue module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Dialogue activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false);
                delete_records('modules', 'name', 'dialogue');
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005072000) {
        // Add a couple fields to mdl_event to work towards iCal import/export
        table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
        table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
    }
    if ($oldversion < 2005072100) {
        // run the online assignment cleanup code
        include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php';
        if (function_exists('online_assignment_cleanup')) {
            online_assignment_cleanup();
        }
    }
    if ($oldversion < 2005072200) {
        // fix the mistakenly-added currency stuff from enrol/authorize
        execute_sql("DROP TABLE {$CFG->prefix}currencies", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
        $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
        table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
    }
    if ($oldversion < 2005081600) {
        //set up the course requests table
        modify_database('', "CREATE TABLE prefix_course_request (\n           id SERIAL PRIMARY KEY,\n           fullname varchar(254) NOT NULL default '',\n           shortname varchar(15) NOT NULL default '',\n           summary text NOT NULL default '',\n           reason text NOT NULL default '',\n           requester INTEGER NOT NULL default 0\n         );");
        modify_database('', 'CREATE INDEX prefix_course_request_shortname_idx ON prefix_course_request (shortname);');
        table_column('course', '', 'requested');
    }
    if ($oldversion < 2005081601) {
        modify_database('', 'CREATE TABLE prefix_course_allowed_modules (
            id SERIAL PRIMARY KEY,
            course INTEGER NOT NULL default 0,
            module INTEGER NOT NULL default 0
         );');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_course_idx ON prefix_course_allowed_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_module_idx ON prefix_course_allowed_modules (module);');
        table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005081700) {
        table_column('course_categories', '', 'depth', 'integer');
        table_column('course_categories', '', 'path', 'varchar', '255');
    }
    if ($oldversion < 2005090100) {
        // stats!
        modify_database('', 'CREATE TABLE prefix_stats_daily (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_daily_courseid_idx ON prefix_stats_daily (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_daily_timeend_idx ON prefix_stats_daily (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_weekly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_courseid_idx ON prefix_stats_weekly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_timeend_idx ON prefix_stats_weekly (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_monthly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_courseid_idx ON prefix_stats_monthly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_timeend_idx ON prefix_stats_monthly (timeend);');
        modify_database("", "CREATE TABLE prefix_stats_user_daily (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_courseid_idx ON prefix_stats_user_daily (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_userid_idx ON prefix_stats_user_daily (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_roleid_idx ON prefix_stats_user_daily (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_timeend_idx ON prefix_stats_user_daily (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_courseid_idx ON prefix_stats_user_weekly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_userid_idx ON prefix_stats_user_weekly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_roleid_idx ON prefix_stats_user_weekly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_timeend_idx ON prefix_stats_user_weekly (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_courseid_idx ON prefix_stats_user_monthly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_userid_idx ON prefix_stats_user_monthly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_roleid_idx ON prefix_stats_user_monthly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_timeend_idx ON prefix_stats_user_monthly (timeend);");
    }
    if ($oldversion < 2005100300) {
        table_column('course', '', 'expirynotify', 'integer', '1');
        table_column('course', '', 'expirythreshold', 'integer');
        table_column('course', '', 'notifystudents', 'integer', '1');
        $new = new stdClass();
        $new->name = 'lastexpirynotify';
        $new->value = 0;
        insert_record('config', $new);
    }
    if ($oldversion < 2005100400) {
        table_column('course', '', 'enrollable', 'integer', '1', 'unsigned', '1');
        table_column('course', '', 'enrolstartdate', 'integer');
        table_column('course', '', 'enrolenddate', 'integer');
    }
    if ($oldversion < 2005101200) {
        // add enrolment key to course_request.
        table_column('course_request', '', 'password', 'text');
    }
    if ($oldversion < 2006030800) {
        # add extra indexes to log (see bug #4112)
        modify_database('', "CREATE INDEX prefix_log_userid_idx ON prefix_log (userid);");
        modify_database('', "CREATE INDEX prefix_log_info_idx ON prefix_log (info);");
    }
    if ($oldversion < 2006030900) {
        table_column('course', '', 'enrol', 'varchar', '20', '', '');
        if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
            set_config('enrol_plugins_enabled', 'manual');
            set_config('enrol', 'manual');
        } else {
            set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol);
        }
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            // switch enrollable to off for all courses in this case
            modify_database('', 'UPDATE prefix_course SET enrollable = 0');
        }
        execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
        execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
    }
    if ($oldversion < 2006031000) {
        modify_database("", "CREATE TABLE prefix_post (\n          id SERIAL PRIMARY KEY,\n          userid INTEGER NOT NULL default 0,\n          courseid INTEGER NOT NULL default 0,\n          groupid INTEGER NOT NULL default 0,\n          moduleid INTEGER NOT NULL default 0,\n          coursemoduleid INTEGER NOT NULL default 0,\n          subject varchar(128) NOT NULL default '',\n          summary text,\n          content text,\n          uniquehash varchar(128) NOT NULL default '',\n          rating INTEGER NOT NULL default 0,\n          format INTEGER NOT NULL default 0,\n          publishstate varchar(10) CHECK (publishstate IN ('draft','site','public')) NOT NULL default 'draft',\n          lastmodified INTEGER NOT NULL default '0',\n          created INTEGER NOT NULL default '0'\n        );");
        modify_database("", "CREATE INDEX id_user_idx ON prefix_post  (id, courseid);");
        modify_database("", "CREATE INDEX post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX post_subject_idx ON prefix_post (subject);");
        modify_database("", "CREATE TABLE prefix_tags (\n          id SERIAL PRIMARY KEY,\n          type varchar(255) NOT NULL default 'official',\n          userid INTEGER NOT NULL default 0,\n          text varchar(255) NOT NULL default ''\n        );");
        modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n          id SERIAL PRIMARY KEY,\n          entryid integer NOT NULL default 0,\n          tagid integer NOT NULL default 0,\n          groupid integer NOT NULL default 0,\n          courseid integer NOT NULL default 0,\n          userid integer NOT NULL default 0\n        );");
    }
    if ($oldversion < 2006031400) {
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            set_config('enrol', 'manual');
        }
    }
    if ($oldversion < 2006032000) {
        table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id');
        modify_database('', "CREATE INDEX post_module_idx ON prefix_post (module);");
        modify_database('', "UPDATE prefix_post SET module = 'blog';");
    }
    if ($oldversion < 2006032001) {
        table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid');
        modify_database('', "CREATE INDEX bti_entryid_idx ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX bti_tagid_idx ON prefix_blog_tag_instance (tagid);");
        modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';");
    }
    if ($oldversion < 2006040500) {
        // Add an index to course_sections that was never upgraded (bug 5100)
        execute_sql(" CREATE INDEX {$CFG->prefix}course_sections_coursesection_idx ON {$CFG->prefix}course_sections (course,section) ", false);
    }
    if ($oldversion < 2006041100) {
        table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible');
    }
    if ($oldversion < 2006042400) {
        // Look through table log_display and get rid of duplicates.
        $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display');
        // Drop the log_display table and create it back with an id field.
        execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
        modify_database('', "CREATE TABLE prefix_log_display (\n                               id SERIAL PRIMARY KEY,\n                               module varchar(30) NOT NULL default '',\n                               action varchar(40) NOT NULL default '',\n                               mtable varchar(30) NOT NULL default '',\n                               field varchar(50) NOT NULL default '')");
        // Add index to ensure that module and action combination is unique.
        modify_database('', 'CREATE INDEX prefix_log_display_moduleaction ON prefix_log_display (module,action)');
        // Insert the records back in, sans duplicates.
        if ($rs) {
            while (!$rs->EOF) {
                $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')";
                execute_sql($sql, false);
                $rs->MoveNext();
            }
            rs_close($rs);
        }
    }
    // add 2 indexes to tags table
    if ($oldversion < 2006042401) {
        modify_database('', "CREATE INDEX tags_typeuserid_idx ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX tags_text_idx ON prefix_tags (text);");
    }
    if ($oldversion < 2006050500) {
        table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
    }
    if ($oldversion < 2006050502) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (!count_records('dialogue_conversations')) {
                // no data, drop the extra tables
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_conversations', false);
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_entries', false);
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
        table_column('course_request', 'password', 'password', 'varchar', '50', '', '');
        table_column('course', 'currency', 'currency', 'varchar', '3');
        modify_database('', 'ALTER TABLE prefix_course_categories
            ALTER COLUMN path SET DEFAULT \'\'');
        table_column('log_display', 'module', 'module', 'varchar', '20');
        modify_database("", "DROP INDEX id_user_idx");
        modify_database("", "DROP INDEX post_lastmodified_idx");
        modify_database("", "DROP INDEX post_subject_idx");
        modify_database('', "DROP INDEX bti_entryid_idx");
        modify_database('', "DROP INDEX bti_tagid_idx");
        modify_database('', "DROP INDEX post_module_idx");
        modify_database('', "DROP INDEX tags_typeuserid_idx");
        modify_database('', "DROP INDEX tags_text_idx");
        modify_database("", "CREATE INDEX {$CFG->prefix}id_user_idx           ON prefix_post (id, courseid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_subject_idx      ON prefix_post (subject);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_entryid_idx       ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_tagid_idx         ON prefix_blog_tag_instance (tagid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}post_module_idx       ON prefix_post (moduleid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_typeuserid_idx   ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_text_idx         ON prefix_tags (text);");
    }
    // renaming of reads and writes for stats_user_xyz
    if ($oldversion < 2006052400) {
        // change this later
        // we are using this because we want silent updates
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN writes TO statswrites", false);
    }
    // Adding some missing log actions
    if ($oldversion < 2006060400) {
        // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
        if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
        }
    }
    //Renaming lastIP to lastip (all fields lowercase)
    if ($oldversion < 2006060900) {
        //Not needed unded PG because it stores fieldnames lowecase by default
        //Only if it exists (because MOODLE_16_STABLE could have done this work before. Bug 5763)
        //$fields = $db->MetaColumnNames($CFG->prefix.'user');
        //if (in_array('lastIP',$fields)) {
        //    table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "", "currentlogin");
        //}
    }
    if ($oldversion < 2006080400) {
        modify_database('', "CREATE TABLE prefix_role (\n                                  id SERIAL PRIMARY KEY,\n                                  name varchar(255) NOT NULL default '',\n                                  shortname varchar(100) NOT NULL default '',     \n                                  description text NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_context (\n                                  id SERIAL PRIMARY KEY,\n                                  level integer NOT NULL default 0,\n                                  instanceid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_assignments (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default 0,\n                                  contextid integer NOT NULL default 0,\n                                  userid integer NOT NULL default 0,\n                                  hidden integer NOT NULL default 0,\n                                  timestart integer NOT NULL default 0,\n                                  timeend integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0,\n                                  enrol varchar(20) NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_role_capabilities (\n                                  id SERIAL PRIMARY KEY,\n                                  contextid integer NOT NULL default 0,\n                                  roleid integer NOT NULL default 0,\n                                  capability varchar(255) NOT NULL default '',\n                                  permission integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_deny_grant (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default '0',\n                                  unviewableroleid integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_capabilities ( \n                              id SERIAL PRIMARY KEY,\n                              name varchar(255) NOT NULL default '', \n                              captype varchar(50) NOT NULL default '', \n                              contextlevel integer NOT NULL default 0, \n                              component varchar(100) NOT NULL default ''\n                                );");
        modify_database('', "CREATE TABLE prefix_role_names ( \n                              id SERIAL PRIMARY KEY,\n                              roleid integer NOT NULL default 0,\n                              contextid integer NOT NULL default 0, \n                              text text NOT NULL default ''\n                                );");
    }
    if ($oldversion < 2006081000) {
        modify_database('', "CREATE INDEX prefix_role_sortorder_idx ON prefix_role (sortorder);");
        modify_database('', "CREATE INDEX prefix_context_instanceid_idx ON prefix_context (instanceid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_context_levelinstanceid_idx ON prefix_context (level, instanceid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_roleid_idx ON prefix_role_assignments (roleid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_contextidid_idx ON prefix_role_assignments (contextid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_userid_idx ON prefix_role_assignments (userid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_assignments_contextidroleiduserid_idx ON prefix_role_assignments (contextid, roleid, userid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_sortorder_idx ON prefix_role_assignments (sortorder);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_roleid_idx ON prefix_role_capabilities (roleid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_contextid_idx ON prefix_role_capabilities (contextid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_modifierid_idx ON prefix_role_capabilities (modifierid);");
        // MDL-10640  adding missing index from upgrade
        modify_database('', "CREATE INDEX prefix_role_capabilities_capability_idx ON prefix_role_capabilities (capability);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_capabilities_roleidcontextidcapability_idx ON prefix_role_capabilities (roleid, contextid, capability);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_roleid_idx ON prefix_role_deny_grant (roleid);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_unviewableroleid_idx ON prefix_role_deny_grant (unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_deny_grant_roleidunviewableroleid_idx ON prefix_role_deny_grant (roleid, unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_capabilities_name_idx ON prefix_capabilities (name);");
        modify_database('', "CREATE INDEX prefix_role_names_roleid_idx ON prefix_role_names (roleid);");
        modify_database('', "CREATE INDEX prefix_role_names_contextid_idx ON prefix_role_names (contextid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_names_roleidcontextid_idx ON prefix_role_names (roleid, contextid);");
    }
    if ($oldversion < 2006081700) {
        modify_database('', "DROP TABLE prefix_role_deny_grant");
        modify_database('', "CREATE TABLE prefix_role_allow_assign (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowassign integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_roleid_idx ON prefix_role_allow_assign (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_allowassign_idx ON prefix_role_allow_assign (allowassign);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_assign_roleidallowassign_idx ON prefix_role_allow_assign (roleid, allowassign);");
        modify_database('', "CREATE TABLE prefix_role_allow_override (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowoverride integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_override_roleid_idx ON prefix_role_allow_override (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_override_allowoverride_idx ON prefix_role_allow_override (allowoverride);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_override_roleidallowoverride_idx ON prefix_role_allow_override (roleid, allowoverride);");
    }
    if ($oldversion < 2006082100) {
        execute_sql("DROP INDEX {$CFG->prefix}context_levelinstanceid_idx;", false);
        table_column('context', 'level', 'aggregatelevel', 'integer', '10', 'unsigned', '0', 'not null', '');
        modify_database('', "CREATE UNIQUE INDEX prefix_context_aggregatelevelinstanceid_idx ON prefix_context (aggregatelevel, instanceid);");
    }
    if ($oldversion < 2006082200) {
        table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
    }
    if ($oldversion < 2006082800) {
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(255) NOT NULL default '',\n                expiry TIMESTAMP NOT NULL,\n                expireref VARCHAR(255),\n                created TIMESTAMP NOT NULL,\n                modified TIMESTAMP NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT {$CFG->prefix}sess_ses_pk PRIMARY KEY (sesskey)\n            );", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP DEFAULT");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP DEFAULT");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP DEFAULT");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    id SERIAL PRIMARY KEY,     \n                    userid integer NOT NULL default 0,\n                    courseid integer NOT NULL default 0, \n                    timeaccess integer NOT NULL default 0\n                    );", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_userid_idx ON {$CFG->prefix}user_lastaccess (userid);", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_courseid_idx ON {$CFG->prefix}user_lastaccess (courseid);", true);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}user_lastaccess_useridcourseid_idx ON {$CFG->prefix}user_lastaccess (userid, courseid);", true);
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
                                $updated->id = $role->id;
                                $updated->shortname = $name . $i;
                                update_record('role', $updated);
                                $i++;
                            }
                        }
                    }
                }
            }
        }
    }
    /// Tables for customisable user profile fields
    if ($oldversion < 2006092000) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        datatype VARCHAR(255) NOT NULL default '',\n                        categoryid BIGINT NOT NULL default 0,\n                        sortorder BIGINT NOT NULL default 0,\n                        required SMALLINT NOT NULL default 0,\n                        locked SMALLINT NOT NULL default 0,\n                        visible SMALLINT NOT NULL default 0,\n                        defaultdata TEXT,\n                        CONSTRAINT {$CFG->prefix}userinfofiel_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_field IS 'Customisable user profile fields';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        sortorder BIGINT NOT NULL default 0,\n                        CONSTRAINT {$CFG->prefix}userinfocate_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_category IS 'Customisable fields categories';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n                        id BIGSERIAL,\n                        userid BIGINT NOT NULL default 0,\n                        fieldid BIGINT NOT NULL default 0,\n                        data TEXT NOT NULL,\n                        CONSTRAINT {$CFG->prefix}userinfodata_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_data IS 'Data for the customisable user fields';", true);
    }
    if ($oldversion < 2006092200) {
        table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
        /*      execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
                execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);  // see 2006092409 below */
    }
    if ($oldversion < 2006092302) {
        // fix sortorder first if needed
        if ($roles = get_all_roles()) {
            $i = 0;
            foreach ($roles as $rolex) {
                if ($rolex->sortorder != $i) {
                    $r = new object();
                    $r->id = $rolex->id;
                    $r->sortorder = $i;
                    update_record('role', $r);
                }
                $i++;
            }
        }
        /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;");
                execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)");*/
    }
    if ($oldversion < 2006092400) {
        table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092409) {
        // ok, once more and now correctly!
        execute_sql("DROP INDEX \"aggregatelevel-instanceid\";", false);
        execute_sql("DROP INDEX \"contextlevel-instanceid\";", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix;", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
    }
    if ($oldversion < 2006092410) {
        /// Convert all the PG unique keys into their corresponding unique indexes
        /// we don't want such keys inside Moodle 1.7 and above
        /// Look for all the UNIQUE CONSTRAINSTS existing in DB
        $uniquecons = get_records_sql("SELECT conname, relname, conkey, clas.oid AS tableoid\n                                          FROM pg_constraint cons,\n                                               pg_class clas\n                                         WHERE cons.contype='u'\n                                           AND cons.conrelid = clas.oid");
        /// Iterate over every unique constraint, calculating its fields
        if ($uniquecons) {
            foreach ($uniquecons as $uniquecon) {
                $conscols = trim(trim($uniquecon->conkey, '}'), '{');
                $conscols = explode(',', $conscols);
                /// Iterate over each column to fetch its name
                $indexcols = array();
                foreach ($conscols as $conscol) {
                    $column = get_record_sql("SELECT attname, attname\n                                                 FROM pg_attribute\n                                                WHERE attrelid = {$uniquecon->tableoid}\n                                                  AND attnum   = {$conscol}");
                    $indexcols[] = $column->attname;
                }
                /// Drop the old UNIQUE CONSTRAINT
                execute_sql("ALTER TABLE {$uniquecon->relname} DROP CONSTRAINT {$uniquecon->conname}", false);
                /// Create the new UNIQUE INDEX
                execute_sql("CREATE UNIQUE INDEX {$uniquecon->relname}_" . implode('_', $indexcols) . "_uix ON {$uniquecon->relname} (" . implode(', ', $indexcols) . ')', false);
            }
        }
    }
    if ($oldversion < 2006092601) {
        table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
コード例 #30
0
ファイル: mysql.php プロジェクト: veritech/pare-project
function main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion == 0) {
        execute_sql("\n          CREATE TABLE `config` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `name` varchar(255) NOT NULL default '',\n            `value` varchar(255) NOT NULL default '',\n            PRIMARY KEY  (`id`),\n            UNIQUE KEY `name` (`name`)\n          ) COMMENT='Moodle configuration variables';");
        notify("Created a new table 'config' to hold configuration data");
    }
    if ($oldversion < 2002073100) {
        execute_sql(" DELETE FROM `modules` WHERE `name` = 'chat' ");
    }
    if ($oldversion < 2002080200) {
        execute_sql(" ALTER TABLE `modules` DROP `fullname`  ");
        execute_sql(" ALTER TABLE `modules` DROP `search`  ");
    }
    if ($oldversion < 2002080300) {
        execute_sql(" ALTER TABLE `log_display` CHANGE `table` `mtable` VARCHAR( 20 ) NOT NULL ");
        execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 3 ) DEFAULT '3' NOT NULL ");
    }
    if ($oldversion < 2002082100) {
        execute_sql(" ALTER TABLE `course` CHANGE `guest` `guest` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2002082101) {
        execute_sql(" ALTER TABLE `user` ADD `maildisplay` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL AFTER `mailformat` ");
    }
    if ($oldversion < 2002090100) {
        execute_sql(" ALTER TABLE `course_sections` CHANGE `summary` `summary` TEXT NOT NULL ");
    }
    if ($oldversion < 2002090701) {
        execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 10 ) DEFAULT '3' NOT NULL ");
        execute_sql(" ALTER TABLE `user_teachers` ADD `role` VARCHAR(40) NOT NULL AFTER `authority` ");
    }
    if ($oldversion < 2002090800) {
        execute_sql(" ALTER TABLE `course` ADD `teachers` VARCHAR( 100 ) DEFAULT 'Teachers' NOT NULL AFTER `teacher` ");
        execute_sql(" ALTER TABLE `course` ADD `students` VARCHAR( 100 ) DEFAULT 'Students' NOT NULL AFTER `student` ");
    }
    if ($oldversion < 2002091000) {
        execute_sql(" ALTER TABLE `user` CHANGE `personality` `secret` VARCHAR( 15 ) NOT NULL DEFAULT ''  ");
    }
    if ($oldversion < 2002091400) {
        execute_sql(" ALTER TABLE `user` ADD `lang` VARCHAR( 3 ) DEFAULT 'en' NOT NULL AFTER `country`  ");
    }
    if ($oldversion < 2002091900) {
        notify("Most Moodle configuration variables have been moved to the database and can now be edited via the admin page.");
        notify("Although it is not vital that you do so, you might want to edit <U>config.php</U> and remove all the unused settings (except the database, URL and directory definitions).  See <U>config-dist.php</U> for an example of how your new slim config.php should look.");
    }
    if ($oldversion < 2002092000) {
        execute_sql(" ALTER TABLE `user` CHANGE `lang` `lang` VARCHAR(5) DEFAULT 'en' NOT NULL  ");
    }
    if ($oldversion < 2002092100) {
        execute_sql(" ALTER TABLE `user` ADD `deleted` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `confirmed` ");
    }
    if ($oldversion < 2002101001) {
        execute_sql(" ALTER TABLE `user` ADD `htmleditor` TINYINT(1) UNSIGNED DEFAULT '1' NOT NULL AFTER `maildisplay` ");
    }
    if ($oldversion < 2002101701) {
        execute_sql(" ALTER TABLE `reading` RENAME `resource` ");
        // Small line with big consequences!
        execute_sql(" DELETE FROM `log_display` WHERE module = 'reading'");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('resource', 'view', 'resource', 'name') ");
        execute_sql(" UPDATE log SET module = 'resource' WHERE module = 'reading' ");
        execute_sql(" UPDATE modules SET name = 'resource' WHERE name = 'reading' ");
    }
    if ($oldversion < 2002102503) {
        execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
        require_once "{$CFG->dirroot}/mod/forum/lib.php";
        require_once "{$CFG->dirroot}/course/lib.php";
        if (!($module = get_record("modules", "name", "forum"))) {
            notify("Could not find forum module!!");
            return false;
        }
        // First upgrade the site forums
        if ($site = get_site()) {
            print_heading("Making News forums editable for main site (moving to section 1)...");
            if ($news = forum_get_course_forum($site->id, "news")) {
                $mod->course = $site->id;
                $mod->module = $module->id;
                $mod->instance = $news->id;
                $mod->section = 1;
                if (!($mod->coursemodule = add_course_module($mod))) {
                    notify("Could not add a new course module to the site");
                    return false;
                }
                if (!($sectionid = add_mod_to_section($mod))) {
                    notify("Could not add the new course module to that section");
                    return false;
                }
                if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                    notify("Could not update the course module with the correct section");
                    return false;
                }
            }
        }
        // Now upgrade the courses.
        if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0")) {
            print_heading("Making News and Social forums editable for each course (moving to section 0)...");
            foreach ($courses as $course) {
                if ($course->format == "social") {
                    // we won't touch them
                    continue;
                }
                if ($news = forum_get_course_forum($course->id, "news")) {
                    $mod->course = $course->id;
                    $mod->module = $module->id;
                    $mod->instance = $news->id;
                    $mod->section = 0;
                    if (!($mod->coursemodule = add_course_module($mod))) {
                        notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
                        return false;
                    }
                    if (!($sectionid = add_mod_to_section($mod))) {
                        notify("Could not add the new course module to that section");
                        return false;
                    }
                    if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                        notify("Could not update the course module with the correct section");
                        return false;
                    }
                }
                if ($social = forum_get_course_forum($course->id, "social")) {
                    $mod->course = $course->id;
                    $mod->module = $module->id;
                    $mod->instance = $social->id;
                    $mod->section = 0;
                    if (!($mod->coursemodule = add_course_module($mod))) {
                        notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
                        return false;
                    }
                    if (!($sectionid = add_mod_to_section($mod))) {
                        notify("Could not add the new course module to that section");
                        return false;
                    }
                    if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                        notify("Could not update the course module with the correct section");
                        return false;
                    }
                }
            }
        }
    }
    if ($oldversion < 2002111003) {
        execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
        if ($courses = get_records_sql("SELECT * FROM course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2002111100) {
        print_simple_box_start("CENTER", "", "#FFCCCC");
        echo "<FONT SIZE=+1>";
        echo "<P>Changes have been made to all built-in themes, to add the new popup navigation menu.";
        echo "<P>If you have customised themes, you will need to edit theme/xxxx/header.html as follows:";
        echo "<UL><LI>Change anywhere it says <B>\$" . "button</B> to say <B>\$" . "menu</B>";
        echo "<LI>Add <B>\$" . "button</B> elsewhere (eg at the end of the navigation bar)</UL>";
        echo "<P>See the standard themes for examples, eg: theme/standard/header.html";
        print_simple_box_end();
    }
    if ($oldversion < 2002111200) {
        execute_sql(" ALTER TABLE `course` ADD `showrecent` TINYINT(5) UNSIGNED DEFAULT '1' NOT NULL AFTER `numsections` ");
    }
    if ($oldversion < 2002111400) {
        // Rebuild all course caches, because some may not be done in new installs (eg site page)
        if ($courses = get_records_sql("SELECT * FROM course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2002112000) {
        set_config("guestloginbutton", 1);
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `log` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_admins` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_teachers` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `start` `timestart` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `end` `timeend` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2002122700) {
        if (!record_exists("log_display", "module", "user", "action", "view")) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname,' ',lastname)') ");
        }
    }
    if ($oldversion < 2003010101) {
        delete_records("log_display", "module", "user");
        $new->module = "user";
        $new->action = "view";
        $new->mtable = "user";
        $new->field = "CONCAT(firstname,\" \",lastname)";
        insert_record("log_display", $new);
        delete_records("log_display", "module", "course");
        $new->module = "course";
        $new->action = "view";
        $new->mtable = "course";
        $new->field = "fullname";
        insert_record("log_display", $new);
        $new->action = "update";
        insert_record("log_display", $new);
        $new->action = "enrol";
        insert_record("log_display", $new);
    }
    if ($oldversion < 2003012200) {
        // execute_sql(" ALTER TABLE `log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
        // Commented out - see below where it's done properly
    }
    if ($oldversion < 2003032500) {
        modify_database("", "CREATE TABLE `prefix_user_coursecreators` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `userid` int(10) unsigned NOT NULL default '0',\n                             PRIMARY KEY  (`id`),\n                             UNIQUE KEY `id` (`id`)\n                             ) TYPE=MyISAM COMMENT='One record per course creator';");
    }
    if ($oldversion < 2003032602) {
        // Redoing it because of no prefix last time
        execute_sql(" ALTER TABLE `{$CFG->prefix}log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
        // Add some indexes for speed
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(course) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(userid) ");
    }
    if ($oldversion < 2003041400) {
        table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
    }
    if ($oldversion < 2003042104) {
        // Try to update permissions of all files
        if ($files = get_directory_list($CFG->dataroot)) {
            echo "Attempting to update permissions for all files... ignore any errors.";
            foreach ($files as $file) {
                echo "{$CFG->dataroot}/{$file}<br />";
                @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions);
            }
        }
    }
    if ($oldversion < 2003042400) {
        // Rebuild all course caches, because of changes to do with visible variable
        if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2003042500) {
        //  Convert all usernames to lowercase.
        $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
        $cerrors = "";
        $rarray = array();
        foreach ($users as $user) {
            // Check for possible conflicts
            $lcname = trim(moodle_strtolower($user->username));
            if (in_array($lcname, $rarray)) {
                $cerrors .= $user->id . "->" . $lcname . '<br/>';
            } else {
                array_push($rarray, $lcname);
            }
        }
        if ($cerrors != '') {
            notify("Error: Cannot convert usernames to lowercase.\n                    Following usernames would overlap (id->username):<br/> {$cerrors} .\n                    Please resolve overlapping errors.");
            $result = false;
        }
        $cerrors = "";
        echo "Checking userdatabase:<br />";
        foreach ($users as $user) {
            $lcname = trim(moodle_strtolower($user->username));
            if ($lcname != $user->username) {
                $convert = set_field("user", "username", $lcname, "id", $user->id);
                if (!$convert) {
                    if ($cerrors) {
                        $cerrors .= ", ";
                    }
                    $cerrors .= $item;
                } else {
                    echo ".";
                }
            }
        }
        if ($cerrors != '') {
            notify("There were errors when converting following usernames to lowercase.\n                   '{$cerrors}' . Sorry, but you will need to fix your database by hand.");
            $result = false;
        }
    }
    if ($oldversion < 2003042600) {
        /// Some more indexes - we need all the help we can get on the logs
        //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(module) ");
        //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(action) ");
    }
    if ($oldversion < 2003042700) {
        /// Changing to multiple indexes
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX module ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX action ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX course ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX userid ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX coursemoduleaction (course,module,action) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX courseuserid (course,userid) ");
    }
    if ($oldversion < 2003042801) {
        execute_sql("CREATE TABLE `{$CFG->prefix}course_display` (\n                        `id` int(10) unsigned NOT NULL auto_increment,\n                        `course` int(10) unsigned NOT NULL default '0',\n                        `userid` int(10) unsigned NOT NULL default '0',\n                        `display` int(10) NOT NULL default '0',\n                        PRIMARY KEY  (`id`),\n                        UNIQUE KEY `id` (`id`),\n                        KEY `courseuserid` (course,userid)\n                     ) TYPE=MyISAM COMMENT='Stores info about how to display the course'");
    }
    if ($oldversion < 2003050400) {
        table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050900) {
        table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050902) {
        if (get_records("modules", "name", "pgassignment")) {
            print_simple_box("Note: the pgassignment module has been removed (it will be replaced later by the workshop module).  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        }
    }
    if ($oldversion < 2003051600) {
        print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
    }
    if ($oldversion < 2003052300) {
        table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
    }
    if ($oldversion < 2003072100) {
        table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
    }
    if ($oldversion < 2003072101) {
        table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
    }
    if ($oldversion < 2003072800) {
        print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        flush();
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX timecoursemoduleaction (time,course,module,action) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX courseuserid (course,userid) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX courseuserid (course,userid) ");
    }
    if ($oldversion < 2003072803) {
        table_column("course_categories", "", "description", "text", "", "", "");
        table_column("course_categories", "", "parent", "integer", "10", "unsigned");
        table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
        table_column("course_categories", "", "courseorder", "text", "", "", "");
        table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
        table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
    }
    if ($oldversion < 2003080400) {
        table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
        table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
    }
    if ($oldversion < 2003080700) {
        notify("Cleaning up categories and course ordering...");
        fix_course_sortorder();
    }
    if ($oldversion < 2003081001) {
        table_column("course", "format", "format", "varchar", "10", "", "topics");
    }
    if ($oldversion < 2003081500) {
        //        print_simple_box("Some important changes have been made to how course creators work.  Formerly, they could create new courses and assign teachers, and teachers could edit courses.  Now, ordinary teachers can no longer edit courses - they <b>need to be a teacher of a course AND a course creator</b>.  A new site-wide configuration variable allows you to choose whether to allow course creators to create new courses as well (by default this is off).  <p>The following update will automatically convert all your existing teachers into course creators, to maintain backward compatibility.  Make sure you look at your upgraded site carefully and understand these new changes.", "center", "50%", "$THEME->cellheading", "20", "noticebox");
        //        $count = 0;
        //        $errorcount = 0;
        //        if ($teachers = get_records("user_teachers")) {
        //            foreach ($teachers as $teacher) {
        //                if (! record_exists("user_coursecreators", "userid", $teacher->userid)) {
        //                    $creator = NULL;
        //                    $creator->userid = $teacher->userid;
        //                    if (!insert_record("user_coursecreators", $creator)) {
        //                        $errorcount++;
        //                    } else {
        //                        $count++;
        //                    }
        //                }
        //            }
        //        }
        //        print_simple_box("$count teachers were upgraded to course creators (with $errorcount errors)", "center", "50%", "$THEME->cellheading", "20", "noticebox");
    }
    if ($oldversion < 2003081501) {
        execute_sql(" CREATE TABLE `{$CFG->prefix}scale` (\n                         `id` int(10) unsigned NOT NULL auto_increment,\n                         `courseid` int(10) unsigned NOT NULL default '0',\n                         `userid` int(10) unsigned NOT NULL default '0',\n                         `name` varchar(255) NOT NULL default '',\n                         `scale` text NOT NULL,\n                         `description` text NOT NULL,\n                         `timemodified` int(10) unsigned NOT NULL default '0',\n                         PRIMARY KEY  (id)\n                       ) TYPE=MyISAM COMMENT='Defines grading scales'");
    }
    if ($oldversion < 2003081503) {
        table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
        get_scales_menu(0);
        // Just to force the default scale to be created
    }
    if ($oldversion < 2003081600) {
        table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
        table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
    }
    if ($oldversion < 2003081900) {
        table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003082001) {
        table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
    }
    if ($oldversion < 2003082101) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX category (category) ");
    }
    if ($oldversion < 2003082702) {
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
    }
    if ($oldversion < 2003091400) {
        table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
    }
    if ($oldversion < 2003092900) {
        table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
    }
    if ($oldversion < 2003102700) {
        table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
        table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
        $db->debug = false;
        $CFG->debug = 0;
        notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
        flush();
        if ($courses = get_records_select("course", "category > 0")) {
            foreach ($courses as $course) {
                notify("Processing " . format_string($course->fullname) . " ...", "green");
                flush();
                if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '{$course->id}' and userid = '{$user->userid}'                                                               ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '{$loginfo->time}'\n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
                if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log\n                                                   WHERE course = '{$course->id}' and userid = '{$user->userid}'\n                                                   ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_students\n                                     SET timeaccess = '{$loginfo->time}'\n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
            }
        }
        notify("All courses complete.", "green");
        $db->debug = true;
    }
    if ($oldversion < 2003103100) {
        table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
    }
    if ($oldversion < 2003121600) {
        modify_database("", "CREATE TABLE `prefix_groups` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `courseid` int(10) unsigned NOT NULL default '0',\n                                `name` varchar(254) NOT NULL default '',\n                                `description` text NOT NULL,\n                                `lang` varchar(10) NOT NULL default 'en',\n                                `picture` int(10) unsigned NOT NULL default '0',\n                                `timecreated` int(10) unsigned NOT NULL default '0',\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `courseid` (`courseid`)\n                              ) TYPE=MyISAM COMMENT='Each record is a group in a course.'; ");
        modify_database("", "CREATE TABLE `prefix_groups_members` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `groupid` int(10) unsigned NOT NULL default '0',\n                                `userid` int(10) unsigned NOT NULL default '0',\n                                `timeadded` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `groupid` (`groupid`)\n                              ) TYPE=MyISAM COMMENT='Lists memberships of users in groups'; ");
    }
    if ($oldversion < 2003121800) {
        table_column("course", "modinfo", "modinfo", "longtext", "", "", "");
    }
    if ($oldversion < 2003122600) {
        table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "showreports");
        table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
    }
    if ($oldversion < 2004010900) {
        table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
    }
    if ($oldversion < 2004011700) {
        modify_database("", "CREATE TABLE `prefix_event` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `name` varchar(255) NOT NULL default '',\n                              `description` text NOT NULL,\n                              `courseid` int(10) unsigned NOT NULL default '0',\n                              `groupid` int(10) unsigned NOT NULL default '0',\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `modulename` varchar(20) NOT NULL default '',\n                              `instance` int(10) unsigned NOT NULL default '0',\n                              `eventtype` varchar(20) NOT NULL default '',\n                              `timestart` int(10) unsigned NOT NULL default '0',\n                              `timeduration` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`),\n                              UNIQUE KEY `id` (`id`),\n                              KEY `courseid` (`courseid`),\n                              KEY `userid` (`userid`)\n                            ) TYPE=MyISAM COMMENT='For everything with a time associated to it'; ");
    }
    if ($oldversion < 2004012800) {
        modify_database("", "CREATE TABLE `prefix_user_preferences` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `name` varchar(50) NOT NULL default '',\n                              `value` varchar(255) NOT NULL default '',\n                              PRIMARY KEY  (`id`),\n                              UNIQUE KEY `id` (`id`),\n                              KEY `useridname` (userid,name)\n                            ) TYPE=MyISAM COMMENT='Allows modules to store arbitrary user preferences'; ");
    }
    if ($oldversion < 2004012900) {
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004013101) {
        table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
        set_config("upgrade", "logs");
    }
    if ($oldversion < 2004020900) {
        table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
    }
    if ($oldversion < 2004020903) {
        modify_database("", "CREATE TABLE `prefix_cache_text` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `md5key` varchar(32) NOT NULL default '',\n                                `formattedtext` longtext NOT NULL,\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `md5key` (`md5key`)\n                             ) TYPE=MyISAM COMMENT='For storing temporary copies of processed texts';");
    }
    if ($oldversion < 2004021000) {
        $textfilters = array();
        for ($i = 1; $i <= 10; $i++) {
            $variable = "textfilter{$i}";
            if (!empty($CFG->{$variable})) {
                /// No more filters
                if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) {
                    $textfilters[] = $CFG->{$variable};
                }
            }
        }
        $textfilters = implode(',', $textfilters);
        if (empty($textfilters)) {
            $textfilters = 'mod/glossary/dynalink.php';
        }
        set_config('textfilters', $textfilters);
    }
    if ($oldversion < 2004021201) {
        modify_database("", "CREATE TABLE `prefix_cache_filters` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `filter` varchar(32) NOT NULL default '',\n                                `version` int(10) unsigned NOT NULL default '0',\n                                `md5key` varchar(32) NOT NULL default '',\n                                `rawtext` text NOT NULL,\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `filtermd5key` (filter,md5key)\n                              ) TYPE=MyISAM COMMENT='For keeping information about cached data';");
    }
    if ($oldversion < 2004021500) {
        table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
    }
    if ($oldversion < 2004021700) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004022000) {
        table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
    }
    if ($oldversion < 2004022200) {
        /// Final renaming I hope.  :-)
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
            $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
            $textfilters = explode(',', $CFG->textfilters);
            foreach ($textfilters as $key => $textfilter) {
                $textfilters[$key] = trim($textfilter);
            }
            set_config("textfilters", implode(',', $textfilters));
        }
    }
    if ($oldversion < 2004030702) {
        /// Because of the renaming of Czech language pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
    }
    if ($oldversion < 2004041800) {
        /// Integrate Block System from contrib
        table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
    }
    if ($oldversion < 2004042600) {
        /// Rebuild course caches for resource icons
        include_once "{$CFG->dirroot}/course/lib.php";
        rebuild_course_cache();
    }
    if ($oldversion < 2004042700) {
        /// Increase size of lang fields
        table_column("user", "lang", "lang", "varchar", "10", "", "en");
        table_column("groups", "lang", "lang", "varchar", "10", "", "");
        table_column("course", "lang", "lang", "varchar", "10", "", "");
    }
    if ($oldversion < 2004042701) {
        /// Add hiddentopics field to control hidden topics behaviour
        table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
    }
    if ($oldversion < 2004042702) {
        /// add a format field for the description
        table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
    }
    if ($oldversion < 2004042900) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP `showrecent` ");
    }
    if ($oldversion < 2004043001) {
        /// Change hiddentopics to hiddensections
        table_column("course", "hiddentopics", "hiddensections", "integer", "2", "unsigned", "0", "not null");
    }
    if ($oldversion < 2004050400) {
        /// add a visible field for events
        table_column("event", "", "visible", "tinyint", "1", "", "1", "not null", "timeduration");
        if ($events = get_records('event')) {
            foreach ($events as $event) {
                if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
                    if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
                        set_field('event', 'visible', 0, 'id', $event->id);
                    }
                }
            }
        }
    }
    if ($oldversion < 2004052800) {
        /// First version tagged "1.4 development", version.php 1.227
        set_config('siteblocksadded', true);
        /// This will be used later by the block upgrade
    }
    if ($oldversion < 2004053000) {
        /// set defaults for site course
        $site = get_site();
        set_field('course', 'numsections', 0, 'id', $site->id);
        set_field('course', 'groupmodeforce', 1, 'id', $site->id);
        set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
        set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
        set_field('course', 'student', get_string('user'), 'id', $site->id);
        set_field('course', 'students', get_string('users'), 'id', $site->id);
    }
    if ($oldversion < 2004060100) {
        set_config('digestmailtime', 0);
        table_column('user', "", 'maildigest', 'tinyint', '1', '', '0', 'not null', 'mailformat');
    }
    if ($oldversion < 2004062400) {
        table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
        table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
    }
    if ($oldversion < 2004062401) {
        table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
        execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname');
        // By default
    }
    if ($oldversion < 2004062600) {
        table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
    }
    if ($oldversion < 2004072900) {
        table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
    }
    if ($oldversion < 2004072901) {
        // Fixing error in schema
        if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
            delete_records('log_display', 'module', 'course', 'action', 'update');
            insert_record('log_display', $record, false);
        }
    }
    if ($oldversion < 2004081200) {
        // Fixing version errors in some blocks
        set_field('blocks', 'version', 2004081200, 'name', 'admin');
        set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
        set_field('blocks', 'version', 2004081200, 'name', 'course_list');
    }
    if ($oldversion < 2004081500) {
        // Adding new "auth" field to user table to allow more flexibility
        table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
        execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");
        // Set everyone to 'manual' to be sure
        if ($admins = get_admins()) {
            // Set all the NON-admins to whatever the current auth module is
            $adminlist = array();
            foreach ($admins as $user) {
                $adminlist[] = $user->id;
            }
            $adminlist = implode(',', $adminlist);
            execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})");
        }
    }
    if ($oldversion < 2004082200) {
        // Making admins teachers on site course
        $site = get_site();
        $admins = get_admins();
        foreach ($admins as $admin) {
            add_teacher($admin->id, $site->id);
        }
    }
    if ($oldversion < 2004082600) {
        //update auth-fields for external users
        // following code would not work in 1.8
        /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
                if (function_exists('auth_get_userlist')) {
                    $externalusers = auth_get_userlist();
                    if (!empty($externalusers)){
                        $externalusers = '\''. implode('\',\'',$externalusers).'\'';
                        execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
                    }
                }*/
    }
    if ($oldversion < 2004082900) {
        // Make sure guest is "manual" too.
        set_field('user', 'auth', 'manual', 'username', 'guest');
    }
    /* Commented out unused guid-field code
       if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
           table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
           execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX authguid (auth, guid)");
       }
       */
    if ($oldversion < 2004091900) {
        // modify idnumber to hold longer values
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_idnumber", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_auth", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX idnumber (idnumber)");
        execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX auth (auth)");
    }
    if ($oldversion < 2004093001) {
        // add new table for sessions storage
        execute_sql(" CREATE TABLE `{$CFG->prefix}sessions` (\n                          `sesskey` char(32) NOT null,\n                          `expiry` int(11) unsigned NOT null,\n                          `expireref` varchar(64),\n                          `data` text NOT null,\n                          PRIMARY KEY (`sesskey`), \n                          KEY (`expiry`) \n                      ) TYPE=MyISAM COMMENT='Optional database session storage, not used by default';");
    }
    if ($oldversion < 2004111500) {
        // Update any users/courses using wrongly-named lang pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
    }
    if ($oldversion < 2004111700) {
        // add indexes. - drop them first silently to avoid conflicts when upgrading.
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX idnumber;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX shortname;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` DROP INDEX userid;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` DROP INDEX userid;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX idnumber (idnumber);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX shortname (shortname);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX userid (userid);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX userid (userid);");
    }
    if ($oldversion < 2004111700) {
        // add an index to event for timestart and timeduration. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timestart;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timeduration;", false);
        modify_database('', 'ALTER TABLE prefix_event ADD INDEX timestart (timestart);');
        modify_database('', 'ALTER TABLE prefix_event ADD INDEX timeduration (timeduration);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on modules and course_modules. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key visible;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key module;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key instance;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key deleted;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}modules drop key name;", false);
        modify_database('', 'ALTER TABLE prefix_course_modules add key visible(visible);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key course(course);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key module(module);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key instance (instance);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key deleted (deleted);');
        modify_database('', 'ALTER TABLE prefix_modules add key name(name);');
    }
    if ($oldversion < 2004111700) {
        // add an index on the groups_members table. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}groups_members DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_groups_members ADD INDEX userid (userid);');
    }
    if ($oldversion < 2004111700) {
        // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
        execute_sql("ALTER TABLE {$CFG->prefix}user_students DROP INDEX timeaccess;", false);
        modify_database('', 'ALTER TABLE prefix_user_students ADD INDEX timeaccess (timeaccess);');
    }
    if ($oldversion < 2004111700) {
        // add indexes on faux-foreign keys. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}scale DROP INDEX courseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}user_admins DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}user_coursecreators DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_scale ADD INDEX courseid (courseid);');
        modify_database('', 'ALTER TABLE prefix_user_admins ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_user_coursecreators ADD INDEX userid (userid);');
    }
    if ($oldversion < 2004111700) {
        // replace index on course
        fix_course_sortorder(0, 0, 1);
        execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category_sortorder;", false);
        modify_database('', "ALTER TABLE `prefix_course` ADD UNIQUE KEY category_sortorder(category,sortorder)");
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_deleted_idx  (deleted)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_confirmed_idx (confirmed)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_firstname_idx (firstname)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastname_idx (lastname)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_city_idx (city)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_country_idx (country)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastaccess_idx (lastaccess)");
    }
    if ($oldversion < 2004111700) {
        // one more index for email (for sorting)
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false);
        modify_database('', 'ALTER TABLE `prefix_user` ADD INDEX prefix_user_email_idx (email);');
    }
    if ($oldversion < 2004112200) {
        // new 'enrol' field for enrolment tables
        table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
        table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
        execute_sql("ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX enrol (enrol);");
        execute_sql("ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX enrol (enrol);");
    }
    if ($oldversion < 2004112400) {
        /// Delete duplicate enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        modify_database('', 'ALTER TABLE prefix_user_students DROP INDEX courseuserid;');
        modify_database('', 'ALTER TABLE prefix_user_students ADD UNIQUE INDEX courseuserid(course,userid);');
        /// Delete duplicate teacher enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        modify_database('', 'ALTER TABLE prefix_user_teachers DROP INDEX courseuserid;');
        modify_database('', 'ALTER TABLE prefix_user_teachers ADD UNIQUE INDEX courseuserid(course,userid);');
    }
    if ($oldversion < 2004112900) {
        table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
    }
    if ($oldversion < 2004121400) {
        table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
    }
    if ($oldversion < 2004121500) {
        modify_database('', "CREATE TABLE prefix_dst_preset (\n            id int(10) NOT NULL auto_increment,\n            name char(48) default '' NOT NULL,\n            \n            apply_offset tinyint(3) default '0' NOT NULL,\n            \n            activate_index tinyint(1) default '1' NOT NULL,\n            activate_day tinyint(1) default '1' NOT NULL,\n            activate_month tinyint(2) default '1' NOT NULL,\n            activate_time char(5) default '03:00' NOT NULL,\n            \n            deactivate_index tinyint(1) default '1' NOT NULL,\n            deactivate_day tinyint(1) default '1' NOT NULL,\n            deactivate_month tinyint(2) default '2' NOT NULL,\n            deactivate_time char(5) default '03:00' NOT NULL,\n            \n            last_change int(10) default '0' NOT NULL,\n            next_change int(10) default '0' NOT NULL,\n            current_offset tinyint(3) default '0' NOT NULL,\n            \n            PRIMARY KEY (id))");
    }
    if ($oldversion < 2004122800) {
        execute_sql("DROP TABLE {$CFG->prefix}message", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
        modify_database('', "CREATE TABLE `prefix_message` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `useridfrom` int(10) NOT NULL default '0',\n                               `useridto` int(10) NOT NULL default '0',\n                               `message` text NOT NULL,\n                               `timecreated` int(10) NOT NULL default '0',\n                               `messagetype` varchar(50) NOT NULL default '',\n                               PRIMARY KEY  (`id`),\n                               KEY `useridfrom` (`useridfrom`),\n                               KEY `useridto` (`useridto`)\n                             ) TYPE=MyISAM COMMENT='Stores all unread messages';");
        modify_database('', "CREATE TABLE `prefix_message_read` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `useridfrom` int(10) NOT NULL default '0',\n                               `useridto` int(10) NOT NULL default '0',\n                               `message` text NOT NULL,\n                               `timecreated` int(10) NOT NULL default '0',\n                               `timeread` int(10) NOT NULL default '0',\n                               `messagetype` varchar(50) NOT NULL default '',\n                               `mailed` tinyint(1) NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               KEY `useridfrom` (`useridfrom`),\n                               KEY `useridto` (`useridto`)\n                             ) TYPE=MyISAM COMMENT='Stores all messages that have been read';");
        modify_database('', "CREATE TABLE `prefix_message_contacts` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `userid` int(10) unsigned NOT NULL default '0',\n                               `contactid` int(10) unsigned NOT NULL default '0',\n                               `blocked` tinyint(1) unsigned NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               UNIQUE KEY `usercontact` (`userid`,`contactid`)\n                             ) TYPE=MyISAM COMMENT='Maintains lists of relationships between users';");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
    }
    if ($oldversion < 2004122801) {
        table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
        table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
    }
    if ($oldversion < 2005010100) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
    }
    if ($oldversion < 2005011000) {
        // Create a .htaccess file in dataroot, just in case
        if (!file_exists($CFG->dataroot . '/.htaccess')) {
            if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) {
                // For safety
                @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
                @fclose($handle);
                notify("Created a default .htaccess file in {$CFG->dataroot}");
            }
        }
    }
    if ($oldversion < 2005012500) {
        /*
        // add new table for meta courses.
        modify_database("","CREATE TABLE `prefix_meta_course` (
            `id` int(1) unsigned NOT NULL auto_increment,
            `parent_course` int(10) NOT NULL default 0,
            `child_course` int(10) NOT NULL default 0,
            PRIMARY KEY (`id`),
            KEY `parent_course` (parent_course),
            KEY `child_course` (child_course)
        );");
        // add flag to course field
        table_column('course','','meta_course','integer','1','','0','not null');
        */
        // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
    }
    if ($oldversion < 2005012501) {
        execute_sql("DROP TABLE {$CFG->prefix}meta_course", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false);
        // drop silently
        // add new table for meta courses.
        modify_database("", "CREATE TABLE `prefix_course_meta` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `parent_course` int(10) NOT NULL default 0,\n            `child_course` int(10) NOT NULL default 0,\n            PRIMARY KEY (`id`),\n            KEY `parent_course` (parent_course),\n            KEY `child_course` (child_course)\n        );");
        // add flag to course field
        table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005012800) {
        // fix a typo (int 1 becomes int 10)
        table_column('course_meta', 'id', 'id', 'integer', '10', '', '0', 'not null');
    }
    if ($oldversion < 2005020100) {
        fix_course_sortorder(0, 1, 1);
    }
    if ($oldversion < 2005020101) {
        // hopefully this is the LAST TIME we need to do this ;)
        if ($rows = count_records("course_meta")) {
            // we need to upgrade
            modify_database("", "CREATE TABLE `prefix_course_meta_tmp` (\n            `parent_course` int(10) NOT NULL default 0,\n            `child_course` int(10) NOT NULL default 0);");
            execute_sql("INSERT INTO {$CFG->prefix}course_meta_tmp (parent_course,child_course) \n               SELECT {$CFG->prefix}course_meta.parent_course, {$CFG->prefix}course_meta.child_course\n               FROM {$CFG->prefix}course_meta");
            $insertafter = true;
        }
        execute_sql("DROP TABLE {$CFG->prefix}course_meta");
        modify_database("", "CREATE TABLE `prefix_course_meta` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `parent_course` int(10) unsigned NOT NULL default 0,\n            `child_course` int(10) unsigned NOT NULL default 0,\n            PRIMARY KEY (`id`),\n            KEY `parent_course` (parent_course),\n            KEY `child_course` (child_course));");
        if (!empty($insertafter)) {
            execute_sql("INSERT INTO {$CFG->prefix}course_meta (parent_course,child_course) \n               SELECT {$CFG->prefix}course_meta_tmp.parent_course, {$CFG->prefix}course_meta_tmp.child_course\n               FROM {$CFG->prefix}course_meta_tmp");
            execute_sql("DROP TABLE {$CFG->prefix}course_meta_tmp");
        }
    }
    if ($oldversion < 2005020800) {
        // Expand module column to max 20 chars
        table_column('log', 'module', 'module', 'varchar', '20', '', '', 'not null');
    }
    if ($oldversion < 2005021000) {
        // New fields for theme choices
        table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        set_config('theme', 'standardwhite');
        // Reset to a known good theme
    }
    if ($oldversion < 2005021600) {
        // course.idnumber should be varchar(100)
        table_column('course', 'idnumber', 'idnumber', 'varchar', '100', '', '', '', '');
    }
    if ($oldversion < 2005021700) {
        table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
    }
    if ($oldversion < 2005021800) {
        // For database debugging, not for normal use
        modify_database("", " CREATE TABLE `adodb_logsql` (\n                               `created` datetime NOT NULL,\n                               `sql0` varchar(250) NOT NULL,\n                               `sql1` text NOT NULL,\n                               `params` text NOT NULL,\n                               `tracer` text NOT NULL,\n                               `timer` decimal(16,6) NOT NULL\n                              );");
    }
    if ($oldversion < 2005022400) {
        // Add more visible digits to the fields
        table_column('dst_preset', 'activate_index', 'activate_index', 'tinyint', '2', '', '0', 'not null');
        table_column('dst_preset', 'activate_day', 'activate_day', 'tinyint', '2', '', '0', 'not null');
        // Add family and year fields
        table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
        table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
    }
    if ($oldversion < 2005030501) {
        table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
    }
    if ($oldversion < 2005032300) {
        table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
        execute_sql('UPDATE `' . $CFG->prefix . 'user` SET timezonename = \'\'');
    }
    if ($oldversion < 2005032600) {
        execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false);
        modify_database('', "CREATE TABLE `prefix_timezone` (\n                              `id` int(10) NOT NULL auto_increment,\n                              `name` varchar(100) NOT NULL default '',\n                              `year` int(11) NOT NULL default '0',\n                              `rule` varchar(20) NOT NULL default '',\n                              `gmtoff` int(11) NOT NULL default '0',\n                              `dstoff` int(11) NOT NULL default '0',\n                              `dst_month` tinyint(2) NOT NULL default '0',\n                              `dst_startday` tinyint(3) NOT NULL default '0',\n                              `dst_weekday` tinyint(3) NOT NULL default '0',\n                              `dst_skipweeks` tinyint(3) NOT NULL default '0',\n                              `dst_time` varchar(5) NOT NULL default '00:00',\n                              `std_month` tinyint(2) NOT NULL default '0',\n                              `std_startday` tinyint(3) NOT NULL default '0',\n                              `std_weekday` tinyint(3) NOT NULL default '0',\n                              `std_skipweeks` tinyint(3) NOT NULL default '0',\n                              `std_time` varchar(5) NOT NULL default '00:00',\n                              PRIMARY KEY (`id`)\n                            ) TYPE=MyISAM COMMENT='Rules for calculating local wall clock time for users';");
    }
    if ($oldversion < 2005032800) {
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_category` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `name` varchar(64) NOT NULL default '',\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `drop_x_lowest` int(10) unsigned NOT NULL default '0',\n            `bonus_points` int(10) unsigned NOT NULL default '0',\n            `hidden` int(10) unsigned NOT NULL default '0',\n            `weight` decimal(4,2) NOT NULL default '0.00',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_exceptions` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `grade_itemid` int(10) unsigned NOT NULL default '0',\n            `userid` int(10) unsigned NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_item` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `category` int(10) unsigned NOT NULL default '0',\n            `modid` int(10) unsigned NOT NULL default '0',\n            `cminstance` int(10) unsigned NOT NULL default '0',\n            `scale_grade` float(11,10) default '1.0000000000',\n            `extra_credit` int(10) unsigned NOT NULL default '0',\n            `sort_order` int(10) unsigned NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_letter` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `letter` varchar(8) NOT NULL default 'NA',\n            `grade_high` decimal(4,2) NOT NULL default '100.00',\n            `grade_low` decimal(4,2) NOT NULL default '0.00',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_preferences` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `preference` int(10) NOT NULL default '0',\n            `value` int(10) NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            UNIQUE KEY `courseidpreference` (`courseid`,`preference`)\n          ) TYPE=MyISAM ;");
    }
    if ($oldversion < 2005033100) {
        // Get rid of defunct field from course modules table
        delete_records('course_modules', 'deleted', 1);
        // Delete old records we don't need any more
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP INDEX `deleted`');
        // Old index
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP `deleted`');
        // Old field
    }
    if ($oldversion < 2005040800) {
        table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
        execute_sql(" ALTER TABLE `{$CFG->prefix}user` DROP `timezonename` ");
    }
    if ($oldversion < 2005041101) {
        require_once $CFG->libdir . '/filelib.php';
        if (is_readable($CFG->dirroot . '/lib/timezones.txt')) {
            // Distribution file
            if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) {
                $db->debug = false;
                update_timezone_records($timezones);
                notify(count($timezones) . ' timezones installed');
                $db->debug = true;
            }
        }
    }
    if ($oldversion < 2005041900) {
        // Copy all Dialogue entries into Messages, and hide Dialogue module
        if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
                                          FROM ' . $CFG->prefix . 'dialogue_conversations c,
                                               ' . $CFG->prefix . 'dialogue_entries e
                                         WHERE e.conversationid = c.id')) {
            foreach ($entries as $entry) {
                $message = new object();
                $message->useridfrom = $entry->userid;
                $message->useridto = $entry->recipientid;
                $message->message = addslashes($entry->text);
                $message->format = FORMAT_HTML;
                $message->timecreated = $entry->timecreated;
                $message->messagetype = 'direct';
                insert_record('message_read', $message);
            }
        }
        set_field('modules', 'visible', 0, 'name', 'dialogue');
        notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
    }
    if ($oldversion < 2005042100) {
        $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
    }
    if ($oldversion < 2005042400) {
        // Add user tracking prefs field.
        table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
    }
    if ($oldversion < 2005053000) {
        // Add config_plugins table
        // this table was created on the MOODLE_15_STABLE branch
        // so it may already exist.
        $result = execute_sql("CREATE TABLE IF NOT EXISTS `{$CFG->prefix}config_plugins` (\n                                  `id`         int(10) unsigned NOT NULL auto_increment,\n                                  `plugin`     varchar(100) NOT NULL default 'core',\n                                  `name`       varchar(100) NOT NULL default '',\n                                  `value`      text NOT NULL default '',\n                                  PRIMARY KEY  (`id`),\n                                           UNIQUE KEY `plugin_name` (`plugin`, `name`)\n                                  ) TYPE=MyISAM \n                                  COMMENT='Moodle modules and plugins configuration variables';");
    }
    if ($oldversion < 2005060200) {
        // migrate some config items to config_plugins table
        // NOTE: this block is in both postgres AND mysql upgrade
        // files. If you edit either, update the otherone.
        $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang");
        if (!empty($CFG->auth)) {
            // if we have no auth, just pass
            foreach ($user_fields as $field) {
                $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
                foreach ($suffixes as $suffix) {
                    $key = 'auth_user_' . $field . $suffix;
                    if (isset($CFG->{$key})) {
                        // translate keys & values
                        // to the new convention
                        // this should support upgrading
                        // even 1.5dev installs
                        $newkey = $key;
                        $newval = $CFG->{$key};
                        if ($suffix === '') {
                            $newkey = 'field_map_' . $field;
                        } elseif ($suffix === '_editlock') {
                            $newkey = 'field_lock_' . $field;
                            $newval = $newval == 1 ? 'locked' : 'unlocked';
                            // translate 0/1 to locked/unlocked
                        } elseif ($suffix === '_updateremote') {
                            $newkey = 'field_updateremote_' . $field;
                        } elseif ($suffix === '_updatelocal') {
                            $newkey = 'field_updatelocal_' . $field;
                            $newval = $newval == 1 ? 'onlogin' : 'oncreate';
                            // translate 0/1 to locked/unlocked
                        }
                        if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) {
                            notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} .");
                            $result = false;
                        }
                    }
                    // end if isset key
                }
                // end foreach suffix
            }
            // end foreach field
        }
    }
    if ($oldversion < 2005060201) {
        // Close down the Attendance module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) {
            if (count_records('attendance')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'attendance');
                notify('The Attendance module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Attendance activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false);
                delete_records('modules', 'name', 'attendance');
                notify("The Attendance module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005071700) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (count_records('dialogue')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'dialogue');
                notify('The Dialogue module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Dialogue activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false);
                delete_records('modules', 'name', 'dialogue');
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005072000) {
        // Add a couple fields to mdl_event to work towards iCal import/export
        table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
        table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
    }
    if ($oldversion < 2005072100) {
        // run the online assignment cleanup code
        include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php';
        if (function_exists('online_assignment_cleanup')) {
            online_assignment_cleanup();
        }
    }
    if ($oldversion < 2005072200) {
        // fix the mistakenly-added currency stuff from enrol/authorize
        execute_sql("DROP TABLE {$CFG->prefix}currencies", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
        $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
        table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
    }
    if ($oldversion < 2005081600) {
        //set up the course requests table
        modify_database('', "CREATE TABLE `prefix_course_request`  (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `fullname` varchar(254) NOT NULL default '',\n          `shortname` varchar(15) NOT NULL default '',\n          `summary` text NOT NULL,\n          `reason` text NOT NULL,\n          `requester` int(10) NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `shortname` (`shortname`)\n        ) TYPE=MyISAM;");
        table_column('course', '', 'requested');
    }
    if ($oldversion < 2005081601) {
        modify_database('', "CREATE TABLE `prefix_course_allowed_modules` (\n         `id` int(10) unsigned NOT NULL auto_increment,\n         `course` int(10) unsigned NOT NULL default 0,\n         `module` int(10) unsigned NOT NULL default 0,\n         PRIMARY KEY (`id`),\n         KEY `course` (`course`),\n         KEY `module` (`module`)\n      ) TYPE=MyISAM;");
        table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005081700) {
        table_column('course_categories', '', 'depth', 'integer');
        table_column('course_categories', '', 'path', 'varchar', '255');
    }
    if ($oldversion < 2005090100) {
        modify_database("", "CREATE TABLE `prefix_stats_daily` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_weekly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_monthly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_daily (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
    }
    if ($oldversion < 2005100300) {
        table_column('course', '', 'expirynotify', 'tinyint', '1');
        table_column('course', '', 'expirythreshold', 'int', '10');
        table_column('course', '', 'notifystudents', 'tinyint', '1');
        $new = new stdClass();
        $new->name = 'lastexpirynotify';
        $new->value = 0;
        insert_record('config', $new);
    }
    if ($oldversion < 2005100400) {
        table_column('course', '', 'enrollable', 'tinyint', '1', 'unsigned', '1');
        table_column('course', '', 'enrolstartdate', 'int');
        table_column('course', '', 'enrolenddate', 'int');
    }
    if ($oldversion < 2005101200) {
        // add enrolment key to course_request.
        table_column('course_request', '', 'password', 'varchar', 50);
    }
    if ($oldversion < 2006030800) {
        # add extra indexes to log (see bug #4112)
        modify_database('', "ALTER TABLE prefix_log ADD INDEX userid (userid);");
        modify_database('', "ALTER TABLE prefix_log ADD INDEX info (info);");
    }
    if ($oldversion < 2006030900) {
        table_column('course', '', 'enrol', 'varchar', '20', '', '');
        if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
            set_config('enrol_plugins_enabled', 'manual');
            set_config('enrol', 'manual');
        } else {
            set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol);
        }
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            // switch enrollable to off for all courses in this case
            modify_database('', 'UPDATE prefix_course SET enrollable = 0');
        }
        execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
        execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
    }
    if ($oldversion < 2006031000) {
        modify_database("", "CREATE TABLE prefix_post (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `userid` int(10) unsigned NOT NULL default '0',\n          `courseid` int(10) unsigned NOT NULL default'0',\n          `groupid` int(10) unsigned NOT NULL default'0',\n          `moduleid` int(10) unsigned NOT NULL default'0',\n          `coursemoduleid` int(10) unsigned NOT NULL default'0',\n          `subject` varchar(128) NOT NULL default '',\n          `summary` longtext,\n          `content` longtext,\n          `uniquehash` varchar(128) NOT NULL default '',\n          `rating` int(10) unsigned NOT NULL default'0',\n          `format` int(10) unsigned NOT NULL default'0',\n          `publishstate` enum('draft','site','public') NOT NULL default 'draft',\n          `lastmodified` int(10) unsigned NOT NULL default '0',\n          `created` int(10) unsigned NOT NULL default '0',\n          PRIMARY KEY  (`id`),\n          UNIQUE KEY `id_user_idx` (`id`, `userid`),\n          KEY `post_lastmodified_idx` (`lastmodified`),\n          KEY `post_subject_idx` (`subject`)\n        ) TYPE=MyISAM  COMMENT='New moodle post table. Holds data posts such as forum entries or blog entries.';");
        modify_database("", "CREATE TABLE prefix_tags (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `type` varchar(255) NOT NULL default 'official',\n          `userid` int(10) unsigned NOT NULL default'0',\n          `text` varchar(255) NOT NULL default '',\n          PRIMARY KEY  (`id`)\n        ) TYPE=MyISAM COMMENT ='tags structure for moodle.';");
        modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `entryid` int(10) unsigned NOT NULL default'0',\n          `tagid` int(10) unsigned NOT NULL default'0',\n          `groupid` int(10) unsigned NOT NULL default'0',\n          `courseid` int(10) unsigned NOT NULL default'0',\n          `userid` int(10) unsigned NOT NULL default'0',\n          PRIMARY KEY  (`id`)\n          ) TYPE=MyISAM COMMENT ='tag instance for blogs.';");
    }
    if ($oldversion < 2006031400) {
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            set_config('enrol', 'manual');
        }
    }
    if ($oldversion < 2006031600) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}grade_category` CHANGE `weight` `weight` decimal(5,2) default '0.00';");
    }
    if ($oldversion < 2006032000) {
        table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id');
        modify_database('', "ALTER TABLE prefix_post ADD INDEX post_module_idx (module);");
        modify_database('', "UPDATE prefix_post SET module = 'blog';");
    }
    if ($oldversion < 2006032001) {
        table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid');
        modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_entryid_idx (entryid);");
        modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_tagid_idx (tagid);");
        modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';");
    }
    if ($oldversion < 2006040500) {
        // Add an index to course_sections that was never upgraded (bug 5100)
        execute_sql(" CREATE INDEX coursesection ON {$CFG->prefix}course_sections (course,section) ", false);
    }
    /// change all the int(11) to int(10) for blogs and tags
    if ($oldversion < 2006041000) {
        table_column('post', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'moduleid', 'moduleid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'coursemoduleid', 'coursemoduleid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'rating', 'rating', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'format', 'format', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('tags', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('tags', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'entryid', 'entryid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'tagid', 'tagid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006041001) {
        table_column('cache_text', 'formattedtext', 'formattedtext', 'longblob', '', '', '', 'not null');
    }
    if ($oldversion < 2006041100) {
        table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible');
    }
    if ($oldversion < 2006041801) {
        // forgot auto_increments for ids
        modify_database('', "ALTER TABLE prefix_post CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
        modify_database('', "ALTER TABLE prefix_tags CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
        modify_database('', "ALTER TABLE prefix_blog_tag_instance CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
    }
    // changed user->firstname, user->lastname, course->shortname to varchar(100)
    if ($oldversion < 2006041900) {
        table_column('course', 'shortname', 'shortname', 'varchar', '100', '', '', 'not null');
        table_column('user', 'firstname', 'firstname', 'varchar', '100', '', '', 'not null');
        table_column('user', 'lastname', 'lastname', 'varchar', '100', '', '', 'not null');
    }
    if ($oldversion < 2006042400) {
        // Look through table log_display and get rid of duplicates.
        $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display');
        // Drop the log_display table and create it back with an id field.
        execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
        modify_database('', "CREATE TABLE prefix_log_display (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `module` varchar(30),\n                               `action` varchar(40),\n                               `mtable` varchar(30),\n                               `field` varchar(50),\n                               PRIMARY KEY (`id`)\n                               ) TYPE=MyISAM");
        // Add index to ensure that module and action combination is unique.
        modify_database('', "ALTER TABLE prefix_log_display ADD UNIQUE `moduleaction`(`module` , `action`)");
        // Insert the records back in, sans duplicates.
        if ($rs && $rs->RecordCount() > 0) {
            while (!$rs->EOF) {
                $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')";
                execute_sql($sql, false);
                $rs->MoveNext();
            }
        }
    }
    // change tags->type to varchar(20), adding 2 indexes for tags table.
    if ($oldversion < 2006042401) {
        table_column('tags', 'type', 'type', 'varchar', '20', '', '', 'not null');
        modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_typeuserid_idx (type(20), userid)");
        modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_text_idx(text(255))");
    }
    /***************************************************
     * The following is an effort to change all the    *
     * default NULLs to NOT NULL defaut '' in all      *
     * mysql tables, to prevent 5303 and be consistent *
     ***************************************************/
    if ($oldversion < 2006042800) {
        execute_sql("UPDATE {$CFG->prefix}grade_category SET name='' WHERE name IS NULL");
        table_column('grade_category', 'name', 'name', 'varchar', '64', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_category SET weight='0' WHERE weight IS NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}grade_category change weight weight decimal(5,2) NOT NULL default 0.00");
        execute_sql("UPDATE {$CFG->prefix}grade_item SET courseid='0' WHERE courseid IS NULL");
        table_column('grade_item', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET category='0' WHERE category IS NULL");
        table_column('grade_item', 'category', 'category', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET modid='0' WHERE modid IS NULL");
        table_column('grade_item', 'modid', 'modid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET cminstance='0' WHERE cminstance IS NULL");
        table_column('grade_item', 'cminstance', 'cminstance', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET scale_grade='0' WHERE scale_grade IS NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}grade_item change scale_grade scale_grade float(11,10) NOT NULL default 1.0000000000");
        execute_sql("UPDATE {$CFG->prefix}grade_preferences SET courseid='0' WHERE courseid IS NULL");
        table_column('grade_preferences', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET idnumber='' WHERE idnumber IS NULL");
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET icq='' WHERE icq IS NULL");
        table_column('user', 'icq', 'icq', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET skype='' WHERE skype IS NULL");
        table_column('user', 'skype', 'skype', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET yahoo='' WHERE yahoo IS NULL");
        table_column('user', 'yahoo', 'yahoo', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET aim='' WHERE aim IS NULL");
        table_column('user', 'aim', 'aim', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET msn='' WHERE msn IS NULL");
        table_column('user', 'msn', 'msn', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET phone1='' WHERE phone1 IS NULL");
        table_column('user', 'phone1', 'phone1', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET phone2='' WHERE phone2 IS NULL");
        table_column('user', 'phone2', 'phone2', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET institution='' WHERE institution IS NULL");
        table_column('user', 'institution', 'institution', 'varchar', '40', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET department='' WHERE department IS NULL");
        table_column('user', 'department', 'department', 'varchar', '30', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET address='' WHERE address IS NULL");
        table_column('user', 'address', 'address', 'varchar', '70', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET city='' WHERE city IS NULL");
        table_column('user', 'city', 'city', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET country='' WHERE country IS NULL");
        table_column('user', 'country', 'country', 'char', '2', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET lang='' WHERE lang IS NULL");
        table_column('user', 'lang', 'lang', 'varchar', '10', '', 'en', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET lastIP='' WHERE lastIP IS NULL");
        table_column('user', 'lastIP', 'lastIP', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET secret='' WHERE secret IS NULL");
        table_column('user', 'secret', 'secret', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET picture='0' WHERE picture IS NULL");
        table_column('user', 'picture', 'picture', 'tinyint', '1', '', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET url='' WHERE url IS NULL");
        table_column('user', 'url', 'url', 'varchar', '255', '', '', 'not null');
    }
    if ($oldversion < 2006050400) {
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_deleted (deleted)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_confirmed (confirmed)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_firstname (firstname)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastname (lastname)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_city (city)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_country (country)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastaccess (lastaccess)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_email (email)", false);
    }
    if ($oldversion < 2006050500) {
        table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
    }
    if ($oldversion < 2006050501) {
        table_column('sessions', 'data', 'data', 'mediumtext', '', '', '', 'not null');
    }
    // renaming of reads and writes for stats_user_xyz
    if ($oldversion < 2006052400) {
        // change this later
        // we are using this because we want silent updates
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
    }
    // Adding some missing log actions
    if ($oldversion < 2006060400) {
        // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
        if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
        }
    }
    //Renaming lastIP to lastip (all fields lowercase)
    if ($oldversion < 2006060900) {
        //Only if it exists
        $fields = $db->MetaColumnNames($CFG->prefix . 'user');
        if (in_array('lastIP', $fields)) {
            table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "not null", "currentlogin");
        }
    }
    // Change in MySQL 5.0.3 concerning how decimals are stored. Mimic from 16_STABLE
    // this isn't dangerous because it's a simple type change, but be careful with
    // versions and duplicate work in order to provide smooth upgrade paths.
    if ($oldversion < 2006071800) {
        table_column('grade_letter', 'grade_high', 'grade_high', 'decimal(5,2)', '', '', '100.00', 'not null', '');
        table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', '');
    }
    if ($oldversion < 2006080400) {
        execute_sql("CREATE TABLE {$CFG->prefix}role (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `name` varchar(255) NOT NULL default '',\n                              `shortname` varchar(100) NOT NULL default '',\n                              `description` text NOT NULL default '',\n                              `sortorder` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}context (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `level` int(10) unsigned NOT NULL default '0',\n                              `instanceid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_assignments (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `contextid` int(10) unsigned NOT NULL default '0',\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `hidden` int(1) unsigned NOT NULL default '0',\n                              `timestart` int(10) unsigned NOT NULL default '0',\n                              `timeend` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              `modifierid` int(10) unsigned NOT NULL default '0',\n                              `enrol` varchar(20) NOT NULL default '',\n                              `sortorder` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_capabilities (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `contextid` int(10) unsigned NOT NULL default '0',\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `capability` varchar(255) NOT NULL default '',\n                              `permission` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              `modifierid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_deny_grant (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `unviewableroleid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}capabilities ( \n                              `id` int(10) unsigned NOT NULL auto_increment, \n                              `name` varchar(255) NOT NULL default '', \n                              `captype` varchar(50) NOT NULL default '', \n                              `contextlevel` int(10) unsigned NOT NULL default '0', \n                              `component` varchar(100) NOT NULL default '', \n                              PRIMARY KEY (`id`) \n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_names ( \n                              `id` int(10) unsigned NOT NULL auto_increment, \n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `contextid` int(10) unsigned NOT NULL default '0', \n                              `text` text NOT NULL default '',\n                              PRIMARY KEY (`id`) \n                            )", true);
    }
    if ($oldversion < 2006081000) {
        execute_sql("ALTER TABLE `{$CFG->prefix}role` ADD INDEX `sortorder` (`sortorder`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD INDEX `instanceid` (`instanceid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `level-instanceid` (`level`, `instanceid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `userid` (`userid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD UNIQUE INDEX `contextid-roleid-userid` (`contextid`, `roleid`, `userid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `sortorder` (`sortorder`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `modifierid` (`modifierid`)", true);
        // MDL-10640  adding missing index from upgrade
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `capability` (`capability`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD UNIQUE INDEX `roleid-contextid-capability` (`roleid`, `contextid`, `capability`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `unviewableroleid` (`unviewableroleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD UNIQUE INDEX `roleid-unviewableroleid` (`roleid`, `unviewableroleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}capabilities` ADD UNIQUE INDEX `name` (`name`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD UNIQUE INDEX `roleid-contextid` (`roleid`, `contextid`)", true);
    }
    if ($oldversion < 2006081600) {
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` CHANGE permission permission int(10) NOT NULL default '0'", true);
    }
    // drop role_deny_grant table, and create 2 new ones
    if ($oldversion < 2006081700) {
        execute_sql("DROP TABLE `{$CFG->prefix}role_deny_grant`", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_allow_assign (\n                    `id` int(10) unsigned NOT NULL auto_increment,\n                    `roleid` int(10) unsigned NOT NULL default '0',\n                    `allowassign` int(10) unsigned NOT NULL default '0',\n                    KEY `roleid` (`roleid`),\n                    KEY `allowassign` (`allowassign`),\n                    UNIQUE KEY `roleid-allowassign` (`roleid`, `allowassign`),\n                    PRIMARY KEY (`id`)\n                    )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_allow_override (\n                    `id` int(10) unsigned NOT NULL auto_increment,\n                    `roleid` int(10) unsigned NOT NULL default '0',\n                    `allowoverride` int(10) unsigned NOT NULL default '0',\n                    KEY `roleid` (`roleid`),\n                    KEY `allowoverride` (`allowoverride`),\n                    UNIQUE KEY `roleid-allowoverride` (`roleid`, `allowoverride`),\n                    PRIMARY KEY (`id`)\n                    )", true);
    }
    if ($oldversion < 2006082100) {
        execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `level-instanceid`;", false);
        table_column('context', 'level', 'aggregatelevel', 'int', '10', 'unsigned', '0', 'not null', '');
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `aggregatelevel-instanceid` (`aggregatelevel`, `instanceid`)", false);
    }
    if ($oldversion < 2006082200) {
        table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
    }
    if ($oldversion < 2006082800) {
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(64) NOT NULL default '',\n                expiry DATETIME NOT NULL,\n                expireref VARCHAR(250),\n                created DATETIME NOT NULL,\n                modified DATETIME NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT  PRIMARY KEY (sesskey)\n            ) COMMENT='Optional database session storage in new format, not used by default';", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083001) {
        table_column('sessions2', 'sessdata', 'sessdata', 'LONGTEXT', '', '', '', '', '');
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course CHANGE modinfo modinfo longtext NULL AFTER showgrades");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories CHANGE description description text NULL AFTER name");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user CHANGE description description text NULL AFTER url");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE summary summary text NULL AFTER section");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE sequence sequence text NULL AFTER section");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    `id` int(10) unsigned NOT NULL auto_increment, \n                    `userid` int(10) unsigned NOT NULL default '0',\n                    `courseid` int(10) unsigned NOT NULL default '0', \n                    `timeaccess` int(10) unsigned NOT NULL default '0', \n                    KEY `userid` (`userid`),\n                    KEY `courseid` (`courseid`),\n                    UNIQUE KEY `userid-courseid` (`userid`, `courseid`),\n                    PRIMARY KEY (`id`) \n                    )TYPE=MYISAM COMMENT ='time user last accessed any page in a course';", true);
    }
    if ($oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if ($oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
                                $updated->id = $role->id;
                                $updated->shortname = $name . $i;
                                update_record('role', $updated);
                                $i++;
                            }
                        }
                    }
                }
            }
        }
    }
    /// Tables for customisable user profile fields
    if ($oldversion < 2006092000) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        name VARCHAR(255) NOT NULL default '',\n                        datatype VARCHAR(255) NOT NULL default '',\n                        categoryid BIGINT(10) unsigned NOT NULL default 0,\n                        sortorder BIGINT(10) unsigned NOT NULL default 0,\n                        required TINYINT(2) unsigned NOT NULL default 0,\n                        locked TINYINT(2) unsigned NOT NULL default 0,\n                        visible SMALLINT(4) unsigned NOT NULL default 0,\n                        defaultdata LONGTEXT,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_field COMMENT='Customisable user profile fields';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        name VARCHAR(255) NOT NULL default '',\n                        sortorder BIGINT(10) unsigned NOT NULL default 0,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_category COMMENT='Customisable fields categories';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        userid BIGINT(10) unsigned NOT NULL default 0,\n                        fieldid BIGINT(10) unsigned NOT NULL default 0,\n                        data LONGTEXT NOT NULL,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_data COMMENT='Data for the customisable user fields';", true);
    }
    if ($oldversion < 2006092200) {
        table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
        /*        execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
                execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);   // see 2006092409 below  */
    }
    if ($oldversion < 2006092201) {
        execute_sql('TRUNCATE TABLE ' . $CFG->prefix . 'cache_text', true);
        table_column('cache_text', 'formattedtext', 'formattedtext', 'longtext', '', '', '', 'not null');
    }
    if ($oldversion < 2006092302) {
        // fix sortorder first if needed
        if ($roles = get_all_roles()) {
            $i = 0;
            foreach ($roles as $rolex) {
                if ($rolex->sortorder != $i) {
                    $r = new object();
                    $r->id = $rolex->id;
                    $r->sortorder = $i;
                    update_record('role', $r);
                }
                $i++;
            }
        }
        /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;", false);
                execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)", false);*/
    }
    if ($oldversion < 2006092400) {
        table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092409) {
        // ok, once more and now correctly!
        execute_sql("DROP INDEX `aggregatelevel-instanceid` ON {$CFG->prefix}context ;", false);
        execute_sql("DROP INDEX `contextlevel-instanceid` ON {$CFG->prefix}context ;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix ON {$CFG->prefix}role ;", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role ;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
    }
    if ($oldversion < 2006092601) {
        table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}