function validation($data, $files)
 {
     global $CFG, $USER, $DB;
     $errors = parent::validation($data, $files);
     $referentiel = $this->_customdata['referentiel'];
     $cm = $this->_customdata['cm'];
     // Valable pour Moodle 2.1 et Moodle 2.2
     //if ($CFG->version < 2011120100) {
     $context = context_module::instance($cm->id);
     //} else {
     // $context = context_module::instance($cm);
     //}
     $id = (int) $data['id'];
     $data['concept'] = trim($data['concept']);
     if ($id) {
         //We are updating an entry, so we compare current session user with
         //existing entry user to avoid some potential problems if secureforms=off
         //Perhaps too much security? Anyway thanks to skodak (Bug 1823)
         $old = $DB->get_record('referentiel_entries', array('id' => $id));
         $ineditperiod = time() - $old->timecreated < $CFG->maxeditingtime || $referentiel->editalways;
         if (!$ineditperiod || $USER->id != $old->userid and !has_capability('mod/referentiel:manageentries', $context)) {
             if ($USER->id != $old->userid) {
                 $errors['concept'] = get_string('errcannoteditothers', 'referentiel');
             } elseif (!$ineditperiod) {
                 $errors['concept'] = get_string('erredittimeexpired', 'referentiel');
             }
         }
         if (!$referentiel->allowduplicatedentries) {
             if ($DB->record_exists_select('referentiel_entries', 'referentielid = :referentielid AND LOWER(concept) = :concept AND id != :id', array('referentielid' => $referentiel->id, 'concept' => moodle_strtolower($data['concept']), 'id' => $id))) {
                 $errors['concept'] = get_string('errconceptalreadyexists', 'referentiel');
             }
         }
     } else {
         if (!$referentiel->allowduplicatedentries) {
             if ($DB->record_exists_select('referentiel_entries', 'referentielid = :referentielid AND LOWER(concept) = :concept', array('referentielid' => $referentiel->id, 'concept' => moodle_strtolower($data['concept'])))) {
                 $errors['concept'] = get_string('errconceptalreadyexists', 'referentiel');
             }
         }
     }
     return $errors;
 }
 function validation($usernew, $files)
 {
     global $CFG;
     $usernew = (object) $usernew;
     $usernew->username = trim($usernew->username);
     $user = get_record('user', 'id', $usernew->id);
     $err = array();
     if (!empty($usernew->newpassword)) {
         $errmsg = '';
         //prevent eclipse warning
         if (!check_password_policy($usernew->newpassword, $errmsg)) {
             $err['newpassword'] = $errmsg;
         }
     }
     if (empty($usernew->username)) {
         //might be only whitespace
         $err['username'] = get_string('required');
     } else {
         if (!$user or $user->username !== stripslashes($usernew->username)) {
             //check new username does not exist
             if (record_exists('user', 'username', $usernew->username, 'mnethostid', $CFG->mnet_localhost_id)) {
                 $err['username'] = get_string('usernameexists');
             }
             //check allowed characters
             if ($usernew->username !== moodle_strtolower($usernew->username)) {
                 echo 'grrrr';
                 $err['username'] = get_string('usernamelowercase');
             } else {
                 if (empty($CFG->extendedusernamechars)) {
                     $string = eregi_replace("[^(-\\.[:alnum:])]", '', $usernew->username);
                     if ($usernew->username !== $string) {
                         $err['username'] = get_string('alphanumerical');
                     }
                 }
             }
         }
     }
     if (!$user or $user->email !== stripslashes($usernew->email)) {
         if (!validate_email(stripslashes($usernew->email))) {
             $err['email'] = get_string('invalidemail');
         } else {
             if (record_exists('user', 'email', $usernew->email, 'mnethostid', $CFG->mnet_localhost_id)) {
                 $err['email'] = get_string('emailexists');
             }
         }
     }
     /// Next the customisable profile fields
     $err += profile_validation($usernew, $files);
     if (count($err) == 0) {
         return true;
     } else {
         return $err;
     }
 }
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;
}
Example #4
0
/**
 * This function will highlight instances of $needle in $haystack
 *
 * It's faster that the above function {@link highlight()} and doesn't care about
 * HTML or anything.
 *
 * @param string $needle The string to search for
 * @param string $haystack The string to search for $needle in
 * @return string The highlighted HTML
 */
function highlightfast($needle, $haystack)
{
    if (empty($needle) or empty($haystack)) {
        return $haystack;
    }
    $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
    if (count($parts) === 1) {
        return $haystack;
    }
    $pos = 0;
    foreach ($parts as $key => $part) {
        $parts[$key] = substr($haystack, $pos, strlen($part));
        $pos += strlen($part);
        $parts[$key] .= '<span class="highlight">' . substr($haystack, $pos, strlen($needle)) . '</span>';
        $pos += strlen($needle);
    }
    return str_replace('<span class="highlight"></span>', '', join('', $parts));
}
Example #5
0
/**
 * @todo Document this function
 * @param array $linkarray
 * @return array
 */
function filter_remove_duplicates($linkarray)
{
    $concepts = array();
    // keep a record of concepts as we cycle through
    $lconcepts = array();
    // a lower case version for case insensitive
    $cleanlinks = array();
    foreach ($linkarray as $key => $filterobject) {
        if ($filterobject->casesensitive) {
            $exists = in_array($filterobject->phrase, $concepts);
        } else {
            $exists = in_array(moodle_strtolower($filterobject->phrase), $lconcepts);
        }
        if (!$exists) {
            $cleanlinks[] = $filterobject;
            $concepts[] = $filterobject->phrase;
            $lconcepts[] = moodle_strtolower($filterobject->phrase);
        }
    }
    return $cleanlinks;
}
 /**
  * Set whether to show advanced elements in the form on first displaying form. Default is not to
  * display advanced elements in the form until 'Show Advanced' is pressed.
  *
  * You can get the last state of the form and possibly save it for this user by using
  * value 'mform_showadvanced_last' in submitted data.
  *
  * @param boolean $showadvancedNow
  */
 function setShowAdvanced($showadvancedNow = null)
 {
     if ($showadvancedNow === null) {
         if ($this->_showAdvanced !== null) {
             return;
         } else {
             //if setShowAdvanced is called without any preference
             //make the default to not show advanced elements.
             $showadvancedNow = get_user_preferences(moodle_strtolower($this->_formName . '_showadvanced', 0));
         }
     }
     //value of hidden element
     $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
     //value of button
     $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
     //toggle if button pressed or else stay the same
     if ($hiddenLast == -1) {
         $next = $showadvancedNow;
     } elseif ($buttonPressed) {
         //toggle on button press
         $next = !$hiddenLast;
     } else {
         $next = $hiddenLast;
     }
     $this->_showAdvanced = $next;
     if ($showadvancedNow != $next) {
         set_user_preference($this->_formName . '_showadvanced', $next);
     }
     $this->setConstants(array('mform_showadvanced_last' => $next));
 }
Example #7
0
 /**
  * will update a local user record from an external source.
  * is a lighter version of the one in moodlelib -- won't do
  * expensive ops such as enrolment
  *
  * If you don't pass $updatekeys, there is a performance hit and
  * values removed from DB won't be removed from moodle.
  *
  * @param string $username username (with system magic quotes)
  */
 function update_user_record($username, $updatekeys = false)
 {
     global $CFG;
     //just in case check text case
     $username = trim(moodle_strtolower($username));
     // get the current user record
     $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
     if (empty($user)) {
         // trouble
         error_log("Cannot update non-existent user: {$username}");
         print_error('auth_dbusernotexist', 'auth', $username);
         die;
     }
     // Ensure userid is not overwritten
     $userid = $user->id;
     if ($newinfo = $this->get_userinfo($username)) {
         $newinfo = truncate_userinfo($newinfo);
         if (empty($updatekeys)) {
             // all keys? this does not support removing values
             $updatekeys = array_keys($newinfo);
         }
         foreach ($updatekeys as $key) {
             if (isset($newinfo[$key])) {
                 $value = $newinfo[$key];
             } else {
                 $value = '';
             }
             if (!empty($this->config->{'field_updatelocal_' . $key})) {
                 if ($user->{$key} != $value) {
                     // only update if it's changed
                     set_field('user', $key, addslashes($value), 'id', $userid);
                 }
             }
         }
     }
     return get_record_select('user', "id = {$userid} AND deleted = 0");
 }
Example #8
0
 function validation($data, $files)
 {
     global $CFG, $DB;
     $errors = parent::validation($data, $files);
     $authplugin = get_auth_plugin($CFG->registerauth);
     if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
         $errors['username'] = get_string('usernameexists');
     } else {
         //check allowed characters
         if ($data['username'] !== moodle_strtolower($data['username'])) {
             $errors['username'] = get_string('usernamelowercase');
         } else {
             if ($data['username'] !== clean_param($data['username'], PARAM_USERNAME)) {
                 $errors['username'] = get_string('invalidusername');
             }
         }
     }
     //check if user exists in external db
     //TODO: maybe we should check all enabled plugins instead
     if ($authplugin->user_exists($data['username'])) {
         $errors['username'] = get_string('usernameexists');
     }
     if (!validate_email($data['email'])) {
         $errors['email'] = get_string('invalidemail');
     } else {
         if ($DB->record_exists('user', array('email' => $data['email']))) {
             $errors['email'] = get_string('emailexists') . ' <a href="forgot_password.php">' . get_string('newpassword') . '?</a>';
         }
     }
     if (empty($data['email2'])) {
         $errors['email2'] = get_string('missingemail');
     } else {
         if ($data['email2'] != $data['email']) {
             $errors['email2'] = get_string('invalidemail');
         }
     }
     if (!isset($errors['email'])) {
         if ($err = email_is_not_allowed($data['email'])) {
             $errors['email'] = $err;
         }
     }
     $errmsg = '';
     if (!check_password_policy($data['password'], $errmsg)) {
         $errors['password'] = $errmsg;
     }
     if ($this->signup_captcha_enabled()) {
         $recaptcha_element = $this->_form->getElement('recaptcha_element');
         if (!empty($this->_form->_submitValues['recaptcha_challenge_field'])) {
             $challenge_field = $this->_form->_submitValues['recaptcha_challenge_field'];
             $response_field = $this->_form->_submitValues['recaptcha_response_field'];
             if (true !== ($result = $recaptcha_element->verify($challenge_field, $response_field))) {
                 $errors['recaptcha'] = $result;
             }
         } else {
             $errors['recaptcha'] = get_string('missingrecaptchachallengefield');
         }
     }
     return $errors;
 }
Example #9
0
/**
 * Will update a local user record from an external source
 *
 * @uses $CFG
 * @param string $username New user's username to add to record
 * @return user A {@link $USER} object
 */
function update_user_record($username, $authplugin)
{
    $username = trim(moodle_strtolower($username));
    /// just in case check text case
    $oldinfo = get_record('user', 'username', $username, '', '', '', '', 'username, auth');
    $userauth = get_auth_plugin($oldinfo->auth);
    if ($newinfo = $userauth->get_userinfo($username)) {
        $newinfo = truncate_userinfo($newinfo);
        foreach ($newinfo as $key => $value) {
            if ($key === 'username') {
                // 'username' is not a mapped updateable/lockable field, so skip it.
                continue;
            }
            $confval = $userauth->config->{'field_updatelocal_' . $key};
            $lockval = $userauth->config->{'field_lock_' . $key};
            if (empty($confval) || empty($lockval)) {
                continue;
            }
            if ($confval === 'onlogin') {
                $value = addslashes($value);
                // MDL-4207 Don't overwrite modified user profile values with
                // empty LDAP values when 'unlocked if empty' is set. The purpose
                // of the setting 'unlocked if empty' is to allow the user to fill
                // in a value for the selected field _if LDAP is giving
                // nothing_ for this field. Thus it makes sense to let this value
                // stand in until LDAP is giving a value for this field.
                if (!(empty($value) && $lockval === 'unlockedifempty')) {
                    set_field('user', $key, $value, 'username', $username) || error_log("Error updating {$key} for {$username}");
                }
            }
        }
    }
    return get_complete_user_data('username', $username);
}
Example #10
0
/**
 * Will update a local user record from an external source.
 * (MNET users can not be updated using this method!)
 *
 * @param string $username user's username to update the record
 * @return stdClass A complete user object
 */
function update_user_record($username)
{
    global $DB, $CFG;
    $username = trim(moodle_strtolower($username));
    /// just in case check text case
    $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
    $newuser = array();
    $userauth = get_auth_plugin($oldinfo->auth);
    if ($newinfo = $userauth->get_userinfo($username)) {
        $newinfo = truncate_userinfo($newinfo);
        foreach ($newinfo as $key => $value) {
            $key = strtolower($key);
            if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id' or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
                // unknown or must not be changed
                continue;
            }
            $confval = $userauth->config->{'field_updatelocal_' . $key};
            $lockval = $userauth->config->{'field_lock_' . $key};
            if (empty($confval) || empty($lockval)) {
                continue;
            }
            if ($confval === 'onlogin') {
                // MDL-4207 Don't overwrite modified user profile values with
                // empty LDAP values when 'unlocked if empty' is set. The purpose
                // of the setting 'unlocked if empty' is to allow the user to fill
                // in a value for the selected field _if LDAP is giving
                // nothing_ for this field. Thus it makes sense to let this value
                // stand in until LDAP is giving a value for this field.
                if (!(empty($value) && $lockval === 'unlockedifempty')) {
                    if ((string) $oldinfo->{$key} !== (string) $value) {
                        $newuser[$key] = (string) $value;
                    }
                }
            }
        }
        if ($newuser) {
            $newuser['id'] = $oldinfo->id;
            $DB->update_record('user', $newuser);
            // fetch full user record for the event, the complete user data contains too much info
            // and we want to be consistent with other places that trigger this event
            events_trigger('user_updated', $DB->get_record('user', array('id' => $oldinfo->id)));
        }
    }
    return get_complete_user_data('id', $oldinfo->id);
}
Example #11
0
/**
 *
 * @param object $entry0
 * @param object $entry1
 * @return int [-1 | 0 | 1]
 */
function glossary_sort_entries ( $entry0, $entry1 ) {

    if ( moodle_strtolower(ltrim($entry0->concept)) < moodle_strtolower(ltrim($entry1->concept)) ) {
        return -1;
    } elseif ( moodle_strtolower(ltrim($entry0->concept)) > moodle_strtolower(ltrim($entry1->concept)) ) {
        return 1;
    } else {
        return 0;
    }
}
Example #12
0
             print_courses(0);
             echo html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => 'skipavailablecourses'));
         }
     }
     break;
 case FRONTPAGECATEGORYNAMES:
     echo html_writer::tag('a', get_string('skipa', 'access', moodle_strtolower(get_string('categories'))), array('href' => '#skipcategories', 'class' => 'skip-block'));
     echo $OUTPUT->heading(get_string('categories'), 2, 'headingblock header');
     echo $OUTPUT->box_start('generalbox categorybox');
     print_whole_category_list(NULL, NULL, NULL, -1, false);
     echo $OUTPUT->box_end();
     print_course_search('', false, 'short');
     echo html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => 'skipcategories'));
     break;
 case FRONTPAGECATEGORYCOMBO:
     echo html_writer::tag('a', get_string('skipa', 'access', moodle_strtolower(get_string('courses'))), array('href' => '#skipcourses', 'class' => 'skip-block'));
     echo $OUTPUT->heading(get_string('courses'), 2, 'headingblock header');
     $renderer = $PAGE->get_renderer('core', 'course');
     // if there are too many courses, budiling course category tree could be slow,
     // users should go to course index page to see the whole list.
     $coursecount = $DB->count_records('course');
     if (empty($CFG->numcoursesincombo)) {
         // if $CFG->numcoursesincombo hasn't been set, use default value 500
         $CFG->numcoursesincombo = 500;
     }
     if ($coursecount > $CFG->numcoursesincombo) {
         $link = new moodle_url('/course/');
         echo $OUTPUT->notification(get_string('maxnumcoursesincombo', 'moodle', array('link' => $link->out(), 'maxnumofcourses' => $CFG->numcoursesincombo, 'numberofcourses' => $coursecount)));
     } else {
         echo $renderer->course_category_tree(get_course_category_tree());
     }
Example #13
0
    /**
     * Processes and stores configuration data for this authentication plugin.
     */
    function process_config($config) {
        // Set to defaults if undefined
        if (!isset($config->host_url)) {
             $config->host_url = '';
        }
        if (empty($config->ldapencoding)) {
         $config->ldapencoding = 'utf-8';
        }
        if (!isset($config->contexts)) {
             $config->contexts = '';
        }
        if (!isset($config->user_type)) {
             $config->user_type = 'default';
        }
        if (!isset($config->user_attribute)) {
             $config->user_attribute = '';
        }
        if (!isset($config->search_sub)) {
             $config->search_sub = '';
        }
        if (!isset($config->opt_deref)) {
             $config->opt_deref = LDAP_DEREF_NEVER;
        }
        if (!isset($config->preventpassindb)) {
             $config->preventpassindb = 0;
        }
        if (!isset($config->bind_dn)) {
            $config->bind_dn = '';
        }
        if (!isset($config->bind_pw)) {
            $config->bind_pw = '';
        }
        if (!isset($config->ldap_version)) {
            $config->ldap_version = '3';
        }
        if (!isset($config->objectclass)) {
            $config->objectclass = '';
        }
        if (!isset($config->memberattribute)) {
            $config->memberattribute = '';
        }
        if (!isset($config->memberattribute_isdn)) {
            $config->memberattribute_isdn = '';
        }
        if (!isset($config->creators)) {
            $config->creators = '';
        }
        if (!isset($config->create_context)) {
            $config->create_context = '';
        }
        if (!isset($config->expiration)) {
            $config->expiration = '';
        }
        if (!isset($config->expiration_warning)) {
            $config->expiration_warning = '10';
        }
        if (!isset($config->expireattr)) {
            $config->expireattr = '';
        }
        if (!isset($config->gracelogins)) {
            $config->gracelogins = '';
        }
        if (!isset($config->graceattr)) {
            $config->graceattr = '';
        }
        if (!isset($config->auth_user_create)) {
            $config->auth_user_create = '';
        }
        if (!isset($config->forcechangepassword)) {
            $config->forcechangepassword = 0;
        }
        if (!isset($config->stdchangepassword)) {
            $config->stdchangepassword = 0;
        }
        if (!isset($config->passtype)) {
            $config->passtype = 'plaintext';
        }
        if (!isset($config->changepasswordurl)) {
            $config->changepasswordurl = '';
        }
        if (!isset($config->removeuser)) {
            $config->removeuser = AUTH_REMOVEUSER_KEEP;
        }
        if (!isset($config->ntlmsso_enabled)) {
            $config->ntlmsso_enabled = 0;
        }
        if (!isset($config->ntlmsso_subnet)) {
            $config->ntlmsso_subnet = '';
        }
        if (!isset($config->ntlmsso_ie_fastpath)) {
            $config->ntlmsso_ie_fastpath = 0;
        }
        if (!isset($config->ntlmsso_type)) {
            $config->ntlmsso_type = 'ntlm';
        }

        // Save settings
        set_config('host_url', trim($config->host_url), $this->pluginconfig);
        set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
        set_config('contexts', trim($config->contexts), $this->pluginconfig);
        set_config('user_type', moodle_strtolower(trim($config->user_type)), $this->pluginconfig);
        set_config('user_attribute', moodle_strtolower(trim($config->user_attribute)), $this->pluginconfig);
        set_config('search_sub', $config->search_sub, $this->pluginconfig);
        set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
        set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
        set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
        set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
        set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
        set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
        set_config('memberattribute', moodle_strtolower(trim($config->memberattribute)), $this->pluginconfig);
        set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
        set_config('creators', trim($config->creators), $this->pluginconfig);
        set_config('create_context', trim($config->create_context), $this->pluginconfig);
        set_config('expiration', $config->expiration, $this->pluginconfig);
        set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
        set_config('expireattr', moodle_strtolower(trim($config->expireattr)), $this->pluginconfig);
        set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
        set_config('graceattr', moodle_strtolower(trim($config->graceattr)), $this->pluginconfig);
        set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
        set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
        set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
        set_config('passtype', $config->passtype, $this->pluginconfig);
        set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
        set_config('removeuser', $config->removeuser, $this->pluginconfig);
        set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
        set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
        set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
        set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');

        return true;
    }
    /**
     * Removes excess backups from the external system and the local file system.
     *
     * The number of backups keep comes from $config->backup_auto_keep
     *
     * @param stdClass $course
     * @return bool
     */
    public static function remove_excess_backups($course) {
        $config = get_config('backup');
        $keep =     (int)$config->backup_auto_keep;
        $storage =  $config->backup_auto_storage;
        $dir =      $config->backup_auto_destination;

        $backupword = str_replace(' ', '_', moodle_strtolower(get_string('backupfilename')));
        $backupword = trim(clean_filename($backupword), '_');

        if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
            $dir = null;
        }

        // Clean up excess backups in the course backup filearea
        if ($storage == 0 || $storage == 2) {
            $fs = get_file_storage();
            $context = get_context_instance(CONTEXT_COURSE, $course->id);
            $component = 'backup';
            $filearea = 'automated';
            $itemid = 0;
            $files = array();
            // Store all the matching files into timemodified => stored_file array
            foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
                if (strpos($file->get_filename(), $backupword) !== 0) {
                    continue;
                }
                $files[$file->get_timemodified()] = $file;
            }
            if (count($files) <= $keep) {
                // There are less matching files than the desired number to keep
                // do there is nothing to clean up.
                return 0;
            }
            // Sort by keys descending (newer to older filemodified)
            krsort($files);
            $remove = array_splice($files, $keep);
            foreach ($remove as $file) {
                $file->delete();
            }
            //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
        }

        // Clean up excess backups in the specified external directory
        if (!empty($dir) && ($storage == 1 || $storage == 2)) {
            // Calculate backup filename regex, ignoring the date/time/info parts that can be
            // variable, depending of languages, formats and automated backup settings
            $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' .$course->id . '-';
            $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';

            // Store all the matching files into fullpath => timemodified array
            $files = array();
            foreach (scandir($dir) as $file) {
                if (preg_match($regex, $file, $matches)) {
                    $files[$file] = filemtime($dir . '/' . $file);
                }
            }
            if (count($files) <= $keep) {
                // There are less matching files than the desired number to keep
                // do there is nothing to clean up.
                return 0;
            }
            // Sort by values descending (newer to older filemodified)
            arsort($files);
            $remove = array_splice($files, $keep);
            foreach (array_keys($remove) as $file) {
                unlink($dir . '/' . $file);
            }
            //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
        }

        return true;
    }
Example #15
0
            } else {
                $frm = data_submitted($loginurl);
            }
        } else {
            $frm = data_submitted($loginurl);
        }
    }
}
/// Check if the user has actually submitted login data to us
if (empty($CFG->usesid) and $testcookies and get_moodle_cookie() == '') {
    // Login without cookie when test requested
    $errormsg = get_string("cookiesnotenabled");
} else {
    if ($frm) {
        // Login WITH cookies
        $frm->username = trim(moodle_strtolower($frm->username));
        if (is_enabled_auth('none') && empty($CFG->extendedusernamechars)) {
            $string = eregi_replace("[^(-\\.[:alnum:])]", "", $frm->username);
            if (strcmp($frm->username, $string)) {
                $errormsg = get_string('username') . ': ' . get_string("alphanumerical");
                $user = null;
            }
        }
        if ($user) {
            //user already supplied by aut plugin prelogin hook
        } else {
            if ($frm->username == 'guest' and empty($CFG->guestloginbutton)) {
                $user = false;
                /// Can't log in as guest if guest button is disabled
                $frm = false;
            } else {
Example #16
0
function xmldb_main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $USER, $SITE, $db;
    $result = true;
    if ($result && $oldversion < 2006100401) {
        /// Only for those tracking Moodle 1.7 dev, others will have these dropped in moodle_install_roles()
        if (!empty($CFG->rolesactive)) {
            drop_table(new XMLDBTable('user_students'));
            drop_table(new XMLDBTable('user_teachers'));
            drop_table(new XMLDBTable('user_coursecreators'));
            drop_table(new XMLDBTable('user_admins'));
        }
        upgrade_main_savepoint($result, 2006100401);
    }
    if ($result && $oldversion < 2006100601) {
        /// Disable the exercise module because it's unmaintained
        if ($module = get_record('modules', 'name', 'exercise')) {
            if ($module->visible) {
                // Hide/disable the module entry
                set_field('modules', 'visible', '0', 'id', $module->id);
                // Save existing visible state for all activities
                set_field('course_modules', 'visibleold', '1', 'visible', '1', 'module', $module->id);
                set_field('course_modules', 'visibleold', '0', 'visible', '0', 'module', $module->id);
                // Hide all activities
                set_field('course_modules', 'visible', '0', 'module', $module->id);
                //require_once($CFG->dirroot.'/course/lib.php');
                //rebuild_course_cache();  // Rebuld cache for all modules because they might have changed
            }
        }
        upgrade_main_savepoint($result, 2006100601);
    }
    if ($result && $oldversion < 2006101001) {
        /// Disable the LAMS module by default (if it is installed)
        if (count_records('modules', 'name', 'lams') && !count_records('lams')) {
            set_field('modules', 'visible', 0, 'name', 'lams');
            // Disable it by default
        }
        upgrade_main_savepoint($result, 2006101001);
    }
    if ($result && $oldversion < 2006102600) {
        /// Define fields to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('description');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'categoryid');
        $field1 = new XMLDBField('param1');
        $field1->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'defaultdata');
        $field2 = new XMLDBField('param2');
        $field2->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param1');
        $field3 = new XMLDBField('param3');
        $field3->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param2');
        $field4 = new XMLDBField('param4');
        $field4->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param3');
        $field5 = new XMLDBField('param5');
        $field5->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param4');
        /// Launch add fields
        $result = $result && add_field($table, $field);
        $result = $result && add_field($table, $field1);
        $result = $result && add_field($table, $field2);
        $result = $result && add_field($table, $field3);
        $result = $result && add_field($table, $field4);
        $result = $result && add_field($table, $field5);
        upgrade_main_savepoint($result, 2006102600);
    }
    if ($result && $oldversion < 2006112000) {
        /// Define field attachment to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('attachment');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'format');
        /// Launch add field attachment
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112000);
    }
    if ($result && $oldversion < 2006112200) {
        /// Define field imagealt to be added to user
        $table = new XMLDBTable('user');
        $field = new XMLDBField('imagealt');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'trustbitmask');
        /// Launch add field imagealt
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('user');
        $field = new XMLDBField('screenreader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'imagealt');
        /// Launch add field screenreader
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112200);
    }
    if ($result && $oldversion < 2006120300) {
        /// Delete guest course section settings
        // following code can be executed repeatedly, such as when upgrading from 1.7.x - it is ok
        if ($guest = get_record('user', 'username', 'guest')) {
            execute_sql("DELETE FROM {$CFG->prefix}course_display where userid={$guest->id}", true);
        }
        upgrade_main_savepoint($result, 2006120300);
    }
    if ($result && $oldversion < 2006120400) {
        /// Remove secureforms config setting
        execute_sql("DELETE FROM {$CFG->prefix}config where name='secureforms'", true);
        upgrade_main_savepoint($result, 2006120400);
    }
    if (!empty($CFG->rolesactive) && $oldversion < 2006120700) {
        // add moodle/user:viewdetails to all roles!
        // note: use of assign_capability() is discouraged in upgrade script!
        if ($roles = get_records('role')) {
            $context = get_context_instance(CONTEXT_SYSTEM);
            foreach ($roles as $roleid => $role) {
                assign_capability('moodle/user:viewdetails', CAP_ALLOW, $roleid, $context->id);
            }
        }
        upgrade_main_savepoint($result, 2006120700);
    }
    // Move the auth plugin settings into the config_plugin table
    if ($result && $oldversion < 2007010300) {
        if ($CFG->auth == 'email') {
            set_config('registerauth', 'email');
        } else {
            set_config('registerauth', '');
        }
        $authplugins = get_list_of_plugins('auth');
        foreach ($CFG as $k => $v) {
            if (strpos($k, 'ldap_') === 0) {
                //upgrade nonstandard ldap settings
                $setting = substr($k, 5);
                if (set_config($setting, $v, "auth/ldap")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                continue;
            }
            if (strpos($k, 'auth_') !== 0) {
                continue;
            }
            $authsetting = substr($k, 5);
            foreach ($authplugins as $auth) {
                if (strpos($authsetting, $auth) !== 0) {
                    continue;
                }
                $setting = substr($authsetting, strlen($auth));
                if (set_config($setting, $v, "auth/{$auth}")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                break;
                // don't check the rest of the auth plugin names
            }
        }
        upgrade_main_savepoint($result, 2007010300);
    }
    if ($result && $oldversion < 2007010301) {
        //
        // Core MNET tables
        //
        $table = new XMLDBTable('mnet_host');
        $table->comment = 'Information about the local and remote hosts for RPC';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f->comment = 'Unique Host ID';
        $f = $table->addFieldInfo('deleted', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('wwwroot', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('ip_address', XMLDB_TYPE_CHAR, '39', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key_expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('transport', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('portno', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_connect_time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_log_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_host2service');
        $table->comment = 'Information about the services for a given host';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('publish', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('subscribe', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_serviceid', XMLDB_INDEX_UNIQUE, array('hostid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_log');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('ip', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('coursename', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('module', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('host_user_course', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'userid', 'course'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_rpc');
        $table->comment = 'Functions or methods that we may publish or subscribe to';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('function_name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_path', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent_type', XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enabled', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('help', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('profile', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('enabled_xpath', XMLDB_INDEX_NOTUNIQUE, array('enabled', 'xmlrpc_path'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service');
        $table->comment = 'A service is a group of functions';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('description', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('apiversion', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('offer', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service2rpc');
        $table->comment = 'Group functions or methods under a service';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rpcid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('unique', XMLDB_INDEX_UNIQUE, array('rpcid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        //
        // Prime MNET configuration entries -- will be needed later by auth/mnet
        //
        include_once $CFG->dirroot . '/mnet/lib.php';
        $env = new mnet_environment();
        $env->init();
        unset($env);
        // add mnethostid to user-
        $table = new XMLDBTable('user');
        $field = new XMLDBField('mnethostid');
        $field->setType(XMLDB_TYPE_INTEGER);
        $field->setLength(10);
        $field->setNotNull(true);
        $field->setSequence(null);
        $field->setEnum(null);
        $field->setDefault('0');
        $field->setPrevious("deleted");
        $field->setNext("username");
        $result = $result && add_field($table, $field);
        // The default mnethostid is zero... we need to update this for all
        // users of the local IdP service.
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'mnethostid', '0');
        $index = new XMLDBIndex('username');
        $index->setUnique(true);
        $index->setFields(array('username'));
        drop_index($table, $index);
        $index->setFields(array('mnethostid', 'username'));
        if (!add_index($table, $index)) {
            notify(get_string('duplicate_usernames', 'mnet', 'http://docs.moodle.org/en/DuplicateUsernames'));
        }
        unset($table, $field, $index);
        /**
         ** auth/mnet tables
         **/
        $table = new XMLDBTable('mnet_session');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('useragent', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('confirm_timeout', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('session_id', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('token', XMLDB_INDEX_UNIQUE, array('token'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_sso_access_control');
        $table->comment = 'Users by host permitted (or not) to login from a remote provider';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnet_host_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('access', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, 'allow');
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('mnethostid_username', XMLDB_INDEX_UNIQUE, array('mnet_host_id', 'username'));
        // Create the table
        $result = $result && create_table($table);
        if (empty($USER->mnet_host_id)) {
            $USER->mnet_host_id = $CFG->mnet_localhost_id;
            // Something for the current user to prevent warnings
        }
        /**
         ** enrol/mnet tables
         **/
        $table = new XMLDBTable('mnet_enrol_course');
        $table->comment = 'Information about courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cat_description', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '254', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('summary', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('startdate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cost', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('currency', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('defaultroleid', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('defaultrolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_remoteid', XMLDB_INDEX_UNIQUE, array('hostid', 'remoteid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_enrol_assignments');
        $table->comment = 'Information about enrolments on courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enroltime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('enroltype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_courseid', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'courseid'));
        $table->addIndexInfo('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Create the table
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007010301);
    }
    if ($result && $oldversion < 2007010404) {
        /// Define field shortname to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, 'shortname', 'id');
        /// Launch add field shortname
        $result = $result && add_field($table, $field);
        /// Changing type of field name on table user_info_field to text
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null, 'shortname');
        /// Launch change of type for field name
        $result = $result && change_field_type($table, $field);
        /// For existing fields use 'name' as the 'shortname' entry
        if ($fields = get_records_select('user_info_field', '', '', 'id, name')) {
            foreach ($fields as $field) {
                $field->shortname = clean_param($field->name, PARAM_ALPHANUM);
                $result && update_record('user_info_field', $field);
            }
        }
        upgrade_main_savepoint($result, 2007010404);
    }
    if ($result && $oldversion < 2007011501) {
        if (!empty($CFG->enablerecordcache) && empty($CFG->rcache) && empty($CFG->cachetype) && empty($CFG->intcachemax)) {
            set_config('cachetype', 'internal');
            set_config('rcache', true);
            set_config('intcachemax', $CFG->enablerecordcache);
            unset_config('enablerecordcache');
            unset($CFG->enablerecordcache);
        }
        upgrade_main_savepoint($result, 2007011501);
    }
    if ($result && $oldversion < 2007012100) {
        /// Some old PG servers have user->firstname & user->lastname with 30cc. They must be 100cc.
        /// Fixing that conditionally. MDL-7110
        if ($CFG->dbfamily == 'postgres') {
            /// Get Metadata from user table
            $cols = array_change_key_case($db->MetaColumns($CFG->prefix . 'user'), CASE_LOWER);
            /// Process user->firstname if needed
            if ($col = $cols['firstname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field firstname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('firstname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'idnumber');
                    /// Launch change of precision for field firstname
                    $result = $result && change_field_precision($table, $field);
                }
            }
            /// Process user->lastname if needed
            if ($col = $cols['lastname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field lastname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('lastname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'firstname');
                    /// Launch change of precision for field lastname
                    $result = $result && change_field_precision($table, $field);
                }
            }
        }
        upgrade_main_savepoint($result, 2007012100);
    }
    if ($result && $oldversion < 2007012101) {
        /// Changing precision of field lang on table course to (30)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null, 'groupmodeforce');
        /// Launch change of precision for field course->lang
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field lang on table user to (30)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en', 'country');
        /// Launch change of precision for field user->lang
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007012101);
    }
    if ($result && $oldversion < 2007012400) {
        /// Rename field access on table mnet_sso_access_control to accessctrl
        $table = new XMLDBTable('mnet_sso_access_control');
        $field = new XMLDBField('access');
        $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'allow', 'mnet_host_id');
        /// Launch rename field accessctrl
        $result = $result && rename_field($table, $field, 'accessctrl');
        upgrade_main_savepoint($result, 2007012400);
    }
    if ($result && $oldversion < 2007012500) {
        execute_sql("DELETE FROM {$CFG->prefix}user WHERE username='******'", true);
        upgrade_main_savepoint($result, 2007012500);
    }
    if ($result && $oldversion < 2007020400) {
        /// Only for MySQL and PG, declare the user->ajax field as not null. MDL-8421.
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            /// Changing nullability of field ajax on table user to not null
            $table = new XMLDBTable('user');
            $field = new XMLDBField('ajax');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'htmleditor');
            /// Launch change of nullability for field ajax
            $result = $result && change_field_notnull($table, $field);
        }
        upgrade_main_savepoint($result, 2007020400);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007021401) {
        /// create default logged in user role if not present - upgrade rom 1.7.x
        if (empty($CFG->defaultuserroleid) or empty($CFG->guestroleid) or $CFG->defaultuserroleid == $CFG->guestroleid) {
            if (!get_records('role', 'shortname', 'user')) {
                $userroleid = create_role(addslashes(get_string('authenticateduser')), 'user', addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
                if ($userroleid) {
                    reset_role_capabilities($userroleid);
                    set_config('defaultuserroleid', $userroleid);
                }
            }
        }
        upgrade_main_savepoint($result, 2007021401);
    }
    if ($result && $oldversion < 2007021501) {
        /// delete removed setting from config
        unset_config('tabselectedtofront');
        upgrade_main_savepoint($result, 2007021501);
    }
    if ($result && $oldversion < 2007032200) {
        /// Define table role_sortorder to be created
        $table = new XMLDBTable('role_sortorder');
        /// Adding fields to table role_sortorder
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortoder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table role_sortorder
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        $table->addKeyInfo('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table role_sortorder
        $table->addIndexInfo('userid-roleid-contextid', XMLDB_INDEX_UNIQUE, array('userid', 'roleid', 'contextid'));
        /// Launch create table for role_sortorder
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007032200);
    }
    /// code to change lenghen tag field to 255, MDL-9095
    if ($result && $oldversion < 2007040400) {
        /// Define index text (not unique) to be dropped form tags
        $table = new XMLDBTable('tags');
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch drop index text
        $result = $result && drop_index($table, $index);
        $field = new XMLDBField('text');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'userid');
        /// Launch change of type for field text
        $result = $result && change_field_type($table, $field);
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch add index text
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007040400);
    }
    if ($result && $oldversion < 2007041100) {
        /// Define field idnumber to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'section');
        /// Launch add field idnumber
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007041100);
    }
    /* Changes to the custom profile menu type - store values rather than indices.
       We could do all this with one tricky SQL statement but it's a one-off so no
       harm in using PHP loops */
    if ($result && $oldversion < 2007041600) {
        /// Get the menu fields
        if ($fields = get_records('user_info_field', 'datatype', 'menu')) {
            foreach ($fields as $field) {
                /// Get user data for the menu field
                if ($data = get_records('user_info_data', 'fieldid', $field->id)) {
                    /// Get the menu options
                    $options = explode("\n", $field->param1);
                    foreach ($data as $d) {
                        $key = array_search($d->data, $options);
                        /// If the data is an integer and is not one of the options,
                        /// set the respective option value
                        if (is_int($d->data) and ($key === NULL or $key === false) and isset($options[$d->data])) {
                            $d->data = $options[$d->data];
                            $result = $result && update_record('user_info_data', $d);
                        }
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007041600);
    }
    /// adding new gradebook tables
    if ($result && $oldversion < 2007041800) {
        /// Define table events_handlers to be created
        $table = new XMLDBTable('events_handlers');
        /// Adding fields to table events_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventname', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlermodule', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfunction', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        /// Adding keys to table events_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table events_handlers
        $table->addIndexInfo('eventname-handlermodule', XMLDB_INDEX_UNIQUE, array('eventname', 'handlermodule'));
        /// Launch create table for events_handlers
        $result = $result && create_table($table);
        /// Define table events_queue to be created
        $table = new XMLDBTable('events_queue');
        /// Adding fields to table events_queue
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventdata', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('schedule', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('stackdump', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch create table for events_queue
        $result = $result && create_table($table);
        /// Define table events_queue_handlers to be created
        $table = new XMLDBTable('events_queue_handlers');
        /// Adding fields to table events_queue_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('queuedeventid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('status', XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null);
        $table->addFieldInfo('errormessage', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('queuedeventid', XMLDB_KEY_FOREIGN, array('queuedeventid'), 'events_queue', array('id'));
        $table->addKeyInfo('handlerid', XMLDB_KEY_FOREIGN, array('handlerid'), 'events_handlers', array('id'));
        /// Launch create table for events_queue_handlers
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007041800);
    }
    if ($result && $oldversion < 2007043001) {
        /// Define field schedule to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('schedule');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'handlerfunction');
        /// Launch add field schedule
        $result = $result && add_field($table, $field);
        /// Define field status to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('status');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'schedule');
        /// Launch add field status
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007043001);
    }
    if ($result && $oldversion < 2007050201) {
        /// Define field theme to be added to course_categories
        $table = new XMLDBTable('course_categories');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'path');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007050201);
    }
    if ($result && $oldversion < 2007051100) {
        /// Define field forceunique to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('forceunique');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'visible');
        /// Launch add field forceunique
        $result = $result && add_field($table, $field);
        /// Define field signup to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('signup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'forceunique');
        /// Launch add field signup
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007051100);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007051801) {
        // Get the role id of the "Auth. User" role and check if the default role id is different
        // note: use of assign_capability() is discouraged in upgrade script!
        $userrole = get_record('role', 'shortname', 'user');
        $defaultroleid = $CFG->defaultuserroleid;
        if ($defaultroleid != $userrole->id) {
            //  Add in the new moodle/my:manageblocks capibility to the default user role
            $context = get_context_instance(CONTEXT_SYSTEM);
            assign_capability('moodle/my:manageblocks', CAP_ALLOW, $defaultroleid, $context->id);
        }
        upgrade_main_savepoint($result, 2007051801);
    }
    if ($result && $oldversion < 2007052200) {
        /// Define field schedule to be dropped from events_queue
        $table = new XMLDBTable('events_queue');
        $field = new XMLDBField('schedule');
        /// Launch drop field stackdump
        $result = $result && drop_field($table, $field);
        upgrade_main_savepoint($result, 2007052200);
    }
    if ($result && $oldversion < 2007052300) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype();
        upgrade_main_savepoint($result, 2007052300);
    }
    if ($result && $oldversion < 2007060500) {
        /// Define field usermodified to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('usermodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'created');
        /// Launch add field usermodified
        $result = $result && add_field($table, $field);
        /// Define key usermodified (foreign) to be added to post
        $table = new XMLDBTable('post');
        $key = new XMLDBKey('usermodified');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch add key usermodified
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007060500);
    }
    if ($result && $oldversion < 2007070603) {
        // Small update of guest user to be 100% sure it has the correct mnethostid (MDL-10375)
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'username', 'guest');
        upgrade_main_savepoint($result, 2007070603);
    }
    if ($result && $oldversion < 2007071400) {
        /**
         ** mnet application table
         **/
        $table = new XMLDBTable('mnet_application');
        $table->comment = 'Information about applications on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('display_name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_server_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sso_land_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        // Insert initial applications (moodle and mahara)
        $application = new stdClass();
        $application->name = 'moodle';
        $application->display_name = 'Moodle';
        $application->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
        $application->sso_land_url = '/auth/mnet/land.php';
        if ($result) {
            $newid = insert_record('mnet_application', $application, false);
        }
        $application = new stdClass();
        $application->name = 'mahara';
        $application->display_name = 'Mahara';
        $application->xmlrpc_server_url = '/api/xmlrpc/server.php';
        $application->sso_land_url = '/auth/xmlrpc/land.php';
        $result = $result && insert_record('mnet_application', $application, false);
        // New mnet_host->applicationid field
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, $newid, 'last_log_id');
        $result = $result && add_field($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007071400);
    }
    if ($result && $oldversion < 2007071607) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype_config_string();
        upgrade_main_savepoint($result, 2007071607);
    }
    if ($result && $oldversion < 2007072200) {
        /// Remove all grade tables used in development phases - we need new empty tables for final gradebook upgrade
        $tables = array('grade_categories', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses', 'grade_history', 'grade_import_newitem', 'grade_import_values');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        $tables = array('grade_categories_history', 'grade_items_history', 'grade_grades_history', 'grade_grades_text_history', 'grade_scale_history', 'grade_outcomes_history');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define table grade_outcomes to be created
        $table = new XMLDBTable('grade_outcomes');
        /// Adding fields to table grade_outcomes
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_outcomes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch create table for grade_outcomes
        $result = $result && create_table($table);
        /// Define table grade_categories to be created
        $table = new XMLDBTable('grade_categories');
        /// Adding fields to table grade_categories
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_categories
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        /// Launch create table for grade_categories
        $result = $result && create_table($table);
        /// Define table grade_items to be created
        $table = new XMLDBTable('grade_items');
        /// Adding fields to table grade_items
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_items
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        $table->addIndexInfo('itemtype-needsupdate', XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        $table->addIndexInfo('gradetype', XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        /// Launch create table for grade_items
        $result = $result && create_table($table);
        /// Define table grade_grades to be created
        $table = new XMLDBTable('grade_grades');
        /// Adding fields to table grade_grades
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_grades
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        /// Launch create table for grade_grades
        $result = $result && create_table($table);
        /// Define table grade_outcomes_history to be created
        $table = new XMLDBTable('grade_outcomes_history');
        /// Adding fields to table grade_outcomes_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_outcomes_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_outcomes_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_outcomes_history
        $result = $result && create_table($table);
        /// Define table grade_categories_history to be created
        $table = new XMLDBTable('grade_categories_history');
        /// Adding fields to table grade_categories_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_categories_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_categories', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_categories_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_categories_history
        $result = $result && create_table($table);
        /// Define table grade_items_history to be created
        $table = new XMLDBTable('grade_items_history');
        /// Adding fields to table grade_items_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_items_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_items', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_items_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_items_history
        $result = $result && create_table($table);
        /// Define table grade_grades_history to be created
        $table = new XMLDBTable('grade_grades_history');
        /// Adding fields to table grade_grades_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_grades_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_grades', array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_grades_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_grades_history
        $result = $result && create_table($table);
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for scale_history
        $result = $result && create_table($table);
        /// upgrade the old 1.8 gradebook - migrade data into new grade tables
        if ($result) {
            if ($rs = get_recordset('course')) {
                while ($course = rs_fetch_next_record($rs)) {
                    // this function uses SQL only, it must not be changed after 1.9 goes stable!!
                    if (!upgrade_18_gradebook($course->id)) {
                        $result = false;
                        break;
                    }
                }
                rs_close($rs);
            }
        }
        upgrade_main_savepoint($result, 2007072200);
    }
    if ($result && $oldversion < 2007072400) {
        /// Dropping one DEFAULT in a TEXT column. It's was only one remaining
        /// since Moodle 1.7, so new servers won't have those anymore.
        /// Changing the default of field sessdata on table sessions2 to drop it
        $table = new XMLDBTable('sessions2');
        $field = new XMLDBField('sessdata');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'modified');
        /// Launch change of default for field sessdata
        $result = $result && change_field_default($table, $field);
        upgrade_main_savepoint($result, 2007072400);
    }
    if ($result && $oldversion < 2007073100) {
        /// Define table grade_outcomes_courses to be created
        $table = new XMLDBTable('grade_outcomes_courses');
        /// Adding fields to table grade_outcomes_courses
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_outcomes_courses
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid-outcomeid', XMLDB_KEY_UNIQUE, array('courseid', 'outcomeid'));
        /// Launch create table for grade_outcomes_courses
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073100);
    }
    if ($result && $oldversion < 2007073101) {
        // Add new tag tables
        /// Define table tag to be created
        $table = new XMLDBTable('tag');
        /// Adding fields to table tag
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('tagtype', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('flag', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table tag
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag
        $table->addIndexInfo('name', XMLDB_INDEX_UNIQUE, array('name'));
        /// Launch create table for tag
        $result = $result && create_table($table);
        /// Define table tag_correlation to be created
        $table = new XMLDBTable('tag_correlation');
        /// Adding fields to table tag_correlation
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('correlatedtags', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_correlation
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_correlation
        $table->addIndexInfo('tagid', XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch create table for tag_correlation
        $result = $result && create_table($table);
        /// Define table tag_instance to be created
        $table = new XMLDBTable('tag_instance');
        /// Adding fields to table tag_instance
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_instance
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_instance
        $table->addIndexInfo('tagiditem', XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch create table for tag_instance
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073101);
    }
    if ($result && $oldversion < 2007073103) {
        /// Define field rawname to be added to tag
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('rawname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'name');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007073103);
    }
    if ($result && $oldversion < 2007073105) {
        /// Define field description to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_outcomes_history');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007073105);
    }
    // adding unique contraint on (courseid,shortname) of an outcome
    if ($result && $oldversion < 2007080100) {
        /// Define key courseid-shortname (unique) to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $key = new XMLDBKey('courseid-shortname');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('courseid', 'shortname'));
        /// Launch add key courseid-shortname
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007080100);
    }
    /// originally there was supportname and supportemail upgrade code - this is handled in upgradesettings.php instead
    if ($result && $oldversion < 2007080202) {
        /// Define index tagiditem (not unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        drop_index($table, $index);
        /// Define index tagiditem (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch add index tagiditem
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007080202);
    }
    if ($result && $oldversion < 2007080300) {
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007080300);
    }
    if ($result && $oldversion < 2007080800) {
        /// Normalize course->shortname MDL-10026
        /// Changing precision of field shortname on table course to (100)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'fullname');
        /// Launch change of precision for field shortname
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007080800);
    }
    if ($result && $oldversion < 2007080900) {
        /// Add context.path & index
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('context');
        $index = new XMLDBIndex('path');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('path'));
        $result = $result && add_index($table, $index);
        /// Add context.depth
        $table = new XMLDBTable('context');
        $field = new XMLDBField('depth');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'path');
        $result = $result && add_field($table, $field);
        /// make sure the system context has proper data
        get_system_context(false);
        upgrade_main_savepoint($result, 2007080900);
    }
    if ($result && $oldversion < 2007080903) {
        /// Define index
        $table = new XMLDBTable('grade_grades');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index itemtype-needsupdate (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('itemtype-needsupdate');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        if (!index_exists($table, $index)) {
            /// Launch add index itemtype-needsupdate
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('gradetype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007080903);
    }
    if ($result && $oldversion < 2007081000) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_upgrade_context_etc();
        upgrade_main_savepoint($result, 2007081000);
    }
    if ($result && $oldversion < 2007081302) {
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('password');
        if (field_exists($table, $field)) {
            /// 1.7.*/1.6.*/1.5.* - create 'groupings' and 'groupings_groups' + rename password to enrolmentkey
            /// or second run after fixing structure broken from 1.8.x
            $result = $result && upgrade_17_groups();
        } else {
            if (table_exists(new XMLDBTable('groups_groupings'))) {
                /// ELSE 'groups_groupings' table exists, this is 1.8.* properly upgraded
                $result = $result && upgrade_18_groups();
            } else {
                /// broken groups, failed 1.8.x upgrade
                upgrade_18_broken_groups();
                notify('Warning: failed groups upgrade detected! Unfortunately this problem ' . 'can not be fixed automatically. Mapping of groups to courses was lost, ' . 'you can either revert to backup from 1.7.x and run ugprade again or ' . 'continue and fill in the missing course ids into groups table manually.');
                $result = false;
            }
        }
        upgrade_main_savepoint($result, 2007081302);
    }
    if ($result && $oldversion < 2007081303) {
        /// Common groups upgrade for 1.8.* and 1.7.*/1.6.*..
        // delete not used fields
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('theme');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('lang');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        /// Add groupingid field/f.key to 'course' table.
        $table = new XMLDBTable('course');
        $field = new XMLDBField('defaultgroupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmodeforce');
        $result = $result && add_field($table, $field);
        /// Add grouping ID, grouponly field/f.key to 'course_modules' table.
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmode');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupmembersonly');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupingid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $key = new XMLDBKey('groupingid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007081303);
    }
    if ($result && $oldversion < 2007082300) {
        /// Define field ordering to be added to tag_instance table
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'itemid');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082300);
    }
    if ($result && $oldversion < 2007082700) {
        /// Define field timemodified to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'ordering');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082700);
    }
    /// migrate all tags table to tag - this code MUST use SQL only,
    /// because if the db structure changes the library functions will fail in future
    if ($result && $oldversion < 2007082701) {
        $tagrefs = array();
        // $tagrefs[$oldtagid] = $newtagid
        if ($rs = get_recordset('tags')) {
            $db->debug = false;
            while ($oldtag = rs_fetch_next_record($rs)) {
                $raw_normalized = clean_param($oldtag->text, PARAM_TAG);
                $normalized = moodle_strtolower($raw_normalized);
                // if this tag does not exist in tag table yet
                if (!($newtag = get_record('tag', 'name', addslashes($normalized), '', '', '', '', 'id'))) {
                    $itag = new object();
                    $itag->name = $normalized;
                    $itag->rawname = $raw_normalized;
                    $itag->userid = $oldtag->userid;
                    $itag->timemodified = time();
                    $itag->descriptionformat = 0;
                    // default format
                    if ($oldtag->type == 'official') {
                        $itag->tagtype = 'official';
                    } else {
                        $itag->tagtype = 'default';
                    }
                    if ($idx = insert_record('tag', addslashes_recursive($itag))) {
                        $tagrefs[$oldtag->id] = $idx;
                    }
                    // if this tag is already used by tag table
                } else {
                    $tagrefs[$oldtag->id] = $newtag->id;
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        // fetch all the tag instances and migrate them as well
        if ($rs = get_recordset('blog_tag_instance')) {
            $db->debug = false;
            while ($blogtag = rs_fetch_next_record($rs)) {
                if (array_key_exists($blogtag->tagid, $tagrefs)) {
                    $tag_instance = new object();
                    $tag_instance->tagid = $tagrefs[$blogtag->tagid];
                    $tag_instance->itemtype = 'blog';
                    $tag_instance->itemid = $blogtag->entryid;
                    $tag_instance->ordering = 1;
                    // does not matter much, because originally there was no ordering in blogs
                    $tag_instance->timemodified = time();
                    insert_record('tag_instance', $tag_instance);
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        unset($tagrefs);
        // release memory
        $table = new XMLDBTable('tags');
        drop_table($table);
        $table = new XMLDBTable('blog_tag_instance');
        drop_table($table);
        upgrade_main_savepoint($result, 2007082701);
    }
    /// MDL-11015, MDL-11016
    if ($result && $oldversion < 2007082800) {
        /// Changing type of field userid on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field userid
        $result = $result && change_field_type($table, $field);
        /// Changing type of field descriptionformat on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('descriptionformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'description');
        /// Launch change of type for field descriptionformat
        $result = $result && change_field_type($table, $field);
        /// Define key userid (foreign) to be added to tag
        $table = new XMLDBTable('tag');
        $key = new XMLDBKey('userid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch add key userid
        $result = $result && add_key($table, $key);
        /// Define index tagiditem (unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_instance to int
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        /// Changing sign of field itemid on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('itemid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'itemtype');
        /// Launch change of sign for field itemid
        $result = $result && change_field_unsigned($table, $field);
        /// Changing sign of field ordering on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'itemid');
        /// Launch change of sign for field ordering
        $result = $result && change_field_unsigned($table, $field);
        /// Define index itemtype-itemid-tagid (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('itemtype-itemid-tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid'));
        /// Launch add index itemtype-itemid-tagid
        $result = $result && add_index($table, $index);
        /// Define index tagid (unique) to be dropped form tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $index = new XMLDBIndex('tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch drop index tagid
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_correlation to int
        $table = new XMLDBTable('tag_correlation');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082800);
    }
    if ($result && $oldversion < 2007082801) {
        /// Define table user_private_key to be created
        $table = new XMLDBTable('user_private_key');
        /// Adding fields to table user_private_key
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('script', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iprestriction', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('validuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table user_private_key
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table user_private_key
        $table->addIndexInfo('script-value', XMLDB_INDEX_NOTUNIQUE, array('script', 'value'));
        /// Launch create table for user_private_key
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007082801);
    }
    /// Going to modify the applicationid from int(1) to int(10). Dropping and
    /// re-creating the associated keys/indexes is mandatory to be cross-db. MDL-11042
    if ($result && $oldversion < 2007082803) {
        /// Define key applicationid (foreign) to be dropped form mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch drop key applicationid
        $result = $result && drop_key($table, $key);
        /// Changing type of field applicationid on table mnet_host to int
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'last_log_id');
        /// Launch change of type for field applicationid
        $result = $result && change_field_type($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082803);
    }
    if ($result && $oldversion < 2007090503) {
        /// Define field aggregatesubcats to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregatesubcats to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// upgrade path in grade_categrories table - now using slash on both ends
        $concat = sql_concat('path', "'/'");
        $sql = "UPDATE {$CFG->prefix}grade_categories SET path = {$concat} WHERE path NOT LIKE '/%/'";
        execute_sql($sql, true);
        /// convert old aggregation constants if needed
        /*for ($i=0; $i<=12; $i=$i+2) {
              $j = $i+1;
              $sql = "UPDATE {$CFG->prefix}grade_categories SET aggregation = $i, aggregateonlygraded = 1 WHERE aggregation = $j";
              execute_sql($sql, true);
          }*/
        // not needed anymore - breaks upgrade now
        upgrade_main_savepoint($result, 2007090503);
    }
    /// To have UNIQUE indexes over NULLable columns isn't cross-db at all
    /// so we create a non unique index and programatically enforce uniqueness
    if ($result && $oldversion < 2007090600) {
        /// Define index idnumber (unique) to be dropped form course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        $result = $result && drop_index($table, $index);
        /// Define index idnumber-course (not unique) to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'course'));
        /// Launch add index idnumber-course
        $result = $result && add_index($table, $index);
        /// Define index idnumber-courseid (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('idnumber-courseid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'courseid'));
        /// Launch add index idnumber-courseid
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007090600);
    }
    /// Create the permanent context_temp table to be used by build_context_path()
    if ($result && $oldversion < 2007092001) {
        /// Define table context_temp to be created
        $table = new XMLDBTable('context_temp');
        /// Adding fields to table context_temp
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table context_temp
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for context_temp
        $result = $result && create_table($table);
        /// make sure category depths, parents and paths are ok, categories from 1.5 may not be properly initialized (MDL-12585)
        upgrade_fix_category_depths();
        /// Recalculate depths, paths and so on
        if (!empty($CFG->rolesactive)) {
            cleanup_contexts();
            // make sure all course, category and user contexts exist - we need it for grade letter upgrade, etc.
            create_contexts(CONTEXT_COURSE, false, true);
            create_contexts(CONTEXT_USER, false, true);
            // we need all contexts path/depths filled properly
            build_context_path(true, true);
            load_all_capabilities();
        } else {
            // upgrade from 1.6 - build all contexts
            create_contexts(null, true, true);
        }
        upgrade_main_savepoint($result, 2007092001);
    }
    /**
     * Merging of grade_grades_text back into grade_grades
     */
    if ($result && $oldversion < 2007092002) {
        /// Define field feedback to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        /// Define field feedback to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_grades_text');
        if ($result and table_exists($table)) {
            //migrade existing data into grade_grades table - this is slow but works for all dbs,
            //it will be executed on development sites only
            $fields = array('feedback', 'information');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = (\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id)";
                $result = execute_sql($sql) && $result;
            }
            $fields = array('feedbackformat', 'informationformat');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = COALESCE((\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id), 0)";
                $result = execute_sql($sql) && $result;
            }
            if ($result) {
                $tables = array('grade_grades_text', 'grade_grades_text_history');
                foreach ($tables as $table) {
                    $table = new XMLDBTable($table);
                    if (table_exists($table)) {
                        drop_table($table);
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007092002);
    }
    if ($result && $oldversion < 2007092803) {
        /// Remove obsoleted unit tests tables - they will be recreated automatically
        $tables = array('grade_categories', 'scale', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses');
        foreach ($tables as $tablename) {
            $table = new XMLDBTable('unittest_' . $tablename);
            if (table_exists($table)) {
                drop_table($table);
            }
            $table = new XMLDBTable('unittest_' . $tablename . '_history');
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define field display to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
        }
        /// Define field display to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// Define field decimals to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
            $result = $result && change_field_notnull($table, $field);
        }
        /// Define field decimals to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// fix incorrect -1 default for grade_item->display
        execute_sql("UPDATE {$CFG->prefix}grade_items SET display=0 WHERE display=-1");
        upgrade_main_savepoint($result, 2007092803);
    }
    /// migrade grade letters - we can not do this in normal grades upgrade becuase we need all course contexts
    if ($result && $oldversion < 2007092806) {
        $result = upgrade_18_letters();
        /// Define index contextidlowerboundary (not unique) to be added to grade_letters
        $table = new XMLDBTable('grade_letters');
        $index = new XMLDBIndex('contextid-lowerboundary');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
        /// Launch add index contextidlowerboundary
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007092806);
    }
    if ($result && $oldversion < 2007100100) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        /// Adding fields to table cache_flags
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flagtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table cache_flags
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /*
         * Note: mysql can not create indexes on text fields larger than 333 chars! 
         */
        /// Adding indexes to table cache_flags
        $table->addIndexInfo('flagtype', XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        $table->addIndexInfo('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        /// Launch create table for cache_flags
        if (!table_exists($table)) {
            $result = $result && create_table($table);
        }
        upgrade_main_savepoint($result, 2007100100);
    }
    if ($result && $oldversion < 2007100300) {
        /// MNET stuff for roaming theme
        /// Define field force_theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('force_theme');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'last_log_id');
        /// Launch add field force_theme
        $result = $result && add_field($table, $field);
        /// Define field theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'force_theme');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007100300);
    }
    if ($result && $oldversion < 2007100301) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('typename');
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('flagtype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('name');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007100301);
    }
    if ($result && $oldversion < 2007100303) {
        /// Changing nullability of field summary on table course to null
        $table = new XMLDBTable('course');
        $field = new XMLDBField('summary');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'idnumber');
        /// Launch change of nullability for field summary
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100303);
    }
    if ($result && $oldversion < 2007100500) {
        /// for dev sites - it is ok to do this repeatedly
        /// Changing nullability of field path on table context to null
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        /// Launch change of nullability for field path
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100500);
    }
    if ($result && $oldversion < 2007100700) {
        /// first drop existing tables - we do not need any data from there
        $table = new XMLDBTable('grade_import_values');
        if (table_exists($table)) {
            drop_table($table);
        }
        $table = new XMLDBTable('grade_import_newitem');
        if (table_exists($table)) {
            drop_table($table);
        }
        /// Define table grade_import_newitem to be created
        $table = new XMLDBTable('grade_import_newitem');
        /// Adding fields to table grade_import_newitem
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_import_newitem
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_newitem
        $result = $result && create_table($table);
        /// Define table grade_import_values to be created
        $table = new XMLDBTable('grade_import_values');
        /// Adding fields to table grade_import_values
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('newgradeitem', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_import_values
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('newgradeitem', XMLDB_KEY_FOREIGN, array('newgradeitem'), 'grade_import_newitem', array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_values
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100700);
    }
    /// dropping context_rel table - not used anymore
    if ($result && $oldversion < 2007100800) {
        /// Define table context_rel to be dropped
        $table = new XMLDBTable('context_rel');
        /// Launch drop table for context_rel
        if (table_exists($table)) {
            drop_table($table);
        }
        upgrade_main_savepoint($result, 2007100800);
    }
    /// Truncate the text_cahe table and add new index
    if ($result && $oldversion < 2007100802) {
        /// Truncate the cache_text table
        execute_sql("TRUNCATE TABLE {$CFG->prefix}cache_text", true);
        /// Define index timemodified (not unique) to be added to cache_text
        $table = new XMLDBTable('cache_text');
        $index = new XMLDBIndex('timemodified');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch add index timemodified
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007100802);
    }
    /// newtable for gradebook settings per course
    if ($result && $oldversion < 2007100803) {
        /// Define table grade_settings to be created
        $table = new XMLDBTable('grade_settings');
        /// Adding fields to table grade_settings
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_settings
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        /// Adding indexes to table grade_settings
        $table->addIndexInfo('courseid-name', XMLDB_INDEX_UNIQUE, array('courseid', 'name'));
        /// Launch create table for grade_settings
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100803);
    }
    /// cleanup in user_lastaccess
    if ($result && $oldversion < 2007100902) {
        $sql = "DELETE\n                  FROM {$CFG->prefix}user_lastaccess\n                 WHERE NOT EXISTS (SELECT 'x'\n                                    FROM {$CFG->prefix}course c\n                                   WHERE c.id = {$CFG->prefix}user_lastaccess.courseid)";
        execute_sql($sql);
        upgrade_main_savepoint($result, 2007100902);
    }
    /// drop old gradebook tables
    if ($result && $oldversion < 2007100903) {
        $tables = array('grade_category', 'grade_item', 'grade_letter', 'grade_preferences', 'grade_exceptions');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        upgrade_main_savepoint($result, 2007100903);
    }
    if ($result && $oldversion < 2007101500 && !file_exists($CFG->dataroot . '/user')) {
        // Get list of users by browsing moodledata/user
        $oldusersdir = $CFG->dataroot . '/users';
        $folders = get_directory_list($oldusersdir, '', false, true, false);
        foreach ($folders as $userid) {
            $olddir = $oldusersdir . '/' . $userid;
            $files = get_directory_list($olddir);
            if (empty($files)) {
                continue;
            }
            // Create new user directory
            if (!($newdir = make_user_directory($userid))) {
                // some weird directory - do not stop the upgrade, just ignore it
                continue;
            }
            // Move contents of old directory to new one
            if (file_exists($olddir) && file_exists($newdir)) {
                foreach ($files as $file) {
                    copy($olddir . '/' . $file, $newdir . '/' . $file);
                }
            } else {
                notify("Could not move the contents of {$olddir} into {$newdir}!");
                $result = false;
                break;
            }
        }
        // Leave a README in old users directory
        $readmefilename = $oldusersdir . '/README.txt';
        if ($handle = fopen($readmefilename, 'w+b')) {
            if (!fwrite($handle, get_string('olduserdirectory'))) {
                // Could not write to the readme file. No cause for huge concern
                notify("Could not write to the README.txt file in {$readmefilename}.");
            }
            fclose($handle);
        } else {
            // Could not create the readme file. No cause for huge concern
            notify("Could not create the README.txt file in {$readmefilename}.");
        }
    }
    if ($result && $oldversion < 2007101502) {
        /// try to remove duplicate entries
        $SQL = "SELECT userid, itemid, COUNT(*)\n               FROM {$CFG->prefix}grade_grades\n               GROUP BY userid, itemid\n               HAVING COUNT( * ) >1";
        // duplicates found
        if ($rs = get_recordset_sql($SQL)) {
            if ($rs && $rs->RecordCount() > 0) {
                while ($dup = rs_fetch_next_record($rs)) {
                    if ($thisdups = get_records_sql("SELECT id FROM {$CFG->prefix}grade_grades \n                                                    WHERE itemid = {$dup->itemid} AND userid = {$dup->userid}\n                                                    ORDER BY timemodified DESC")) {
                        $processed = 0;
                        // keep the first one
                        foreach ($thisdups as $thisdup) {
                            if ($processed) {
                                // remove the duplicates
                                delete_records('grade_grades', 'id', $thisdup->id);
                            }
                            $processed++;
                        }
                    }
                }
                rs_close($rs);
            }
        }
        /// Define key userid-itemid (unique) to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $key = new XMLDBKey('userid-itemid');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('userid', 'itemid'));
        /// Launch add key userid-itemid
        $result = $result && add_key($table, $key);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101502);
    }
    if ($result && $oldversion < 2007101505) {
        /// Changing precision of field dst_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('dst_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'dst_skipweeks');
        /// Launch change of precision for field dst_time
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field std_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('std_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'std_skipweeks');
        /// Launch change of precision for field std_time
        $result = $result && change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101505);
    }
    if ($result && $oldversion < 2007101506) {
        /// CONTEXT_PERSONAL was never implemented - removing
        $sql = "DELETE\n                  FROM {$CFG->prefix}context\n                 WHERE contextlevel=20";
        execute_sql($sql);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101506);
    }
    if ($result && $oldversion < 2007101507) {
        $db->debug = false;
        require_once $CFG->dirroot . '/course/lib.php';
        notify('Started rebuilding of course cache...', 'notifysuccess');
        rebuild_course_cache();
        // Rebuild course cache - new group related fields there
        notify('...finished rebuilding of course cache.', 'notifysuccess');
        $db->debug = true;
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101507);
    }
    if ($result && $oldversion < 2007101508) {
        $db->debug = false;
        notify('Updating country list according to recent official ISO listing...', 'notifysuccess');
        // re-assign users to valid countries
        set_field('user', 'country', 'CD', 'country', 'ZR');
        // Zaire is now Congo Democratique
        set_field('user', 'country', 'TL', 'country', 'TP');
        // Timor has changed
        set_field('user', 'country', 'FR', 'country', 'FX');
        // France metropolitaine doesn't exist
        set_field('user', 'country', 'RS', 'country', 'KO');
        // Kosovo is part of Serbia, "under the auspices of the United Nations, pursuant to UN Security Council Resolution 1244 of 10 June 1999."
        set_field('user', 'country', 'GB', 'country', 'WA');
        // Wales is part of UK (ie Great Britain)
        set_field('user', 'country', 'RS', 'country', 'CS');
        // Re-assign Serbia-Montenegro to Serbia.  This is arbitrary, but there is no way to make an automatic decision on this.
        notify('...update complete. Remember to update the language pack to get the most recent country names defitions and codes.  This is specialy important for sites with users from Congo (now CD), Timor (now TL), Kosovo (now RS), Wales (now GB), Serbia (RS) and Montenegro (ME).  Users based in Montenegro (ME) will need to manually update their profile.', 'notifysuccess');
        $db->debug = true;
        upgrade_main_savepoint($result, 2007101508);
    }
    if ($result && $oldversion < 2007101508.01) {
        // add forgotten table
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        if ($result and !table_exists($table)) {
            /// Launch create table for scale_history
            $result = $result && create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.01);
    }
    if ($result && $oldversion < 2007101508.02) {
        // upgade totals, no big deal if it fails
        require_once $CFG->libdir . '/statslib.php';
        stats_upgrade_totals();
        if (isset($CFG->loglifetime) and $CFG->loglifetime == 30) {
            set_config('loglifetime', 35);
            // we need more than 31 days for monthly stats!
        }
        notify('Upgrading log table indexes, this may take a long time, please be patient.', 'notifysuccess');
        /// Define index time-course-module-action (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time-course-module-action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time', 'course', 'module', 'action'));
        /// Launch drop index time-course-module-action
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        /// Launch drop index userid
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index info (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('info');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('info'));
        /// Launch drop index info
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index time (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time'));
        /// Launch add index time
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Define index action (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch add index action
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.02);
    }
    if ($result && $oldversion < 2007101508.03) {
        /// Define index course-userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('course-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'userid'));
        /// Launch drop index course-userid
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Define index userid-course (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid', 'course'));
        /// Launch add index userid-course
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.03);
    }
    if ($result && $oldversion < 2007101508.04) {
        set_field('tag_instance', 'itemtype', 'post', 'itemtype', 'blog');
        upgrade_main_savepoint($result, 2007101508.04);
    }
    if ($result && $oldversion < 2007101508.05) {
        /// Define index cmid (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('cmid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('cmid'));
        /// Launch add index cmid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.05);
    }
    if ($result && $oldversion < 2007101508.06) {
        /// Define index groupid-courseid-visible-userid (not unique) to be added to event
        $table = new XMLDBTable('event');
        $index = new XMLDBIndex('groupid-courseid-visible-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('groupid', 'courseid', 'visible', 'userid'));
        /// Launch add index groupid-courseid-visible-userid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.06);
    }
    if ($result && $oldversion < 2007101508.07) {
        /// Define table webdav_locks to be created
        $table = new XMLDBTable('webdav_locks');
        /// Adding fields to table webdav_locks
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('recursive', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exclusivelock', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('created', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('modified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('owner', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        /// Adding keys to table webdav_locks
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('token', XMLDB_KEY_UNIQUE, array('token'));
        /// Adding indexes to table webdav_locks
        $table->addIndexInfo('path', XMLDB_INDEX_NOTUNIQUE, array('path'));
        $table->addIndexInfo('expiry', XMLDB_INDEX_NOTUNIQUE, array('expiry'));
        /// Launch create table for webdav_locks
        $result = $result && create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.07);
    }
    if ($result && $oldversion < 2007101508.08) {
        // MDL-13676
        /// Define field name to be added to role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'text');
        /// Launch add field name
        $result = $result && add_field($table, $field);
        /// Copy data from old field to new field
        $result = $result && execute_sql('UPDATE ' . $CFG->prefix . 'role_names SET name = text');
        /// Define field text to be dropped from role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('text');
        /// Launch drop field text
        $result = $result && drop_field($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.08);
    }
    if ($result && $oldversion < 2007101509) {
        // force full regrading
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101510) {
        /// Fix minor problem caused by MDL-5482.
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_fix_random_question_parents();
        upgrade_main_savepoint($result, 2007101510);
    }
    if ($result && $oldversion < 2007101511) {
        // if guest role used as default user role unset it and force admin to choose new setting
        if (!empty($CFG->defaultuserroleid)) {
            if ($role = get_record('role', 'id', $CFG->defaultuserroleid)) {
                if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
                    if (isset($guestroles[$role->id])) {
                        set_config('defaultuserroleid', null);
                        notify('Guest role removed from "Default role for all users" setting, please select another role.', 'notifysuccess');
                    }
                }
            } else {
                set_config('defaultuserroleid', null);
            }
        }
    }
    if ($result && $oldversion < 2007101512) {
        notify('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
        /// Under MySQL and Postgres... detect old NULL contents and change them by correct empty string. MDL-14859
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            execute_sql("UPDATE {$CFG->prefix}user SET idnumber = '' WHERE idnumber IS NULL", true);
        }
        /// Define index idnumber (not unique) to be dropped form user
        $table = new XMLDBTable('user');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Changing precision of field idnumber on table user to (255)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'password');
        /// Launch change of precision for field idnumber
        $result = $result && change_field_precision($table, $field);
        /// Launch add index idnumber again
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        $result = $result && add_index($table, $index);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101512);
    }
    if ($result && $oldversion < 2007101513) {
        $log_action = new stdClass();
        $log_action->module = 'course';
        $log_action->action = 'unenrol';
        $log_action->mtable = 'course';
        $log_action->field = 'fullname';
        if (!record_exists("log_display", "action", "unenrol", "module", "course")) {
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101513);
    }
    if ($result && $oldversion < 2007101514) {
        $table = new XMLDBTable('mnet_enrol_course');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', true, true, null, false, false, 0);
        $result = change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007101514);
    }
    if ($result && $oldversion < 2007101515) {
        $result = delete_records_select('role_names', sql_isempty('role_names', 'name', false, false));
        upgrade_main_savepoint($result, 2007101515);
    }
    if ($result && $oldversion < 2007101517) {
        if (isset($CFG->defaultuserroleid) and isset($CFG->guestroleid) and $CFG->defaultuserroleid == $CFG->guestroleid) {
            // guest can not be selected in defaultuserroleid!
            unset_config('defaultuserroleid');
        }
        upgrade_main_savepoint($result, 2007101517);
    }
    if ($result && $oldversion < 2007101526) {
        /// Changing the default of field lang on table user to en_utf8
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en_utf8', 'country');
        /// Launch change of default for field lang
        $result = $result && change_field_default($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101526);
    }
    if ($result && $oldversion < 2007101527) {
        if (!get_config(NULL, 'statsruntimedays')) {
            set_config('statsruntimedays', '31');
        }
    }
    /// For MDL-17501. Ensure that any role that has moodle/course:update also
    /// has moodle/course:visibility.
    if ($result && $oldversion < 2007101532.1) {
        if (!empty($CFG->rolesactive)) {
            // In case we are upgrading from Moodle 1.6.
            /// Get the roles with 'moodle/course:update'.
            $systemcontext = get_context_instance(CONTEXT_SYSTEM);
            $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
            /// Give those roles 'moodle/course:visibility'.
            foreach ($roles as $role) {
                assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
            }
            /// Force all sessions to refresh access data.
            mark_context_dirty($systemcontext->path);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101532.1);
    }
    if ($result && $oldversion < 2007101542) {
        if (empty($CFG->hiddenuserfields)) {
            set_config('hiddenuserfields', 'firstaccess');
        } else {
            if (strpos($CFG->hiddenuserfields, 'firstaccess') === false) {
                //firstaccess should not already be listed but just in case
                set_config('hiddenuserfields', $CFG->hiddenuserfields . ',firstaccess');
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101542);
    }
    if ($result && $oldversion < 2007101545.01) {
        require_once "{$CFG->dirroot}/filter/tex/lib.php";
        filter_tex_updatedcallback(null);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101545.01);
    }
    if ($result && $oldversion < 2007101546.02) {
        if (empty($CFG->gradebook_latest195_upgrade)) {
            require_once $CFG->libdir . '/gradelib.php';
            // we need constants only
            // reset current coef for simple mean items - it may contain some rubbish ;-)
            $sql = "UPDATE {$CFG->prefix}grade_items\n                       SET aggregationcoef = 0\n                     WHERE categoryid IN (SELECT gc.id\n                                            FROM {$CFG->prefix}grade_categories gc\n                                           WHERE gc.aggregation = " . GRADE_AGGREGATE_WEIGHTED_MEAN2 . ")";
            $result = execute_sql($sql);
        } else {
            // direct upgrade from 1.8.x - no need to reset coef, because it is already ok
            unset_config('gradebook_latest195_upgrade');
        }
        upgrade_main_savepoint($result, 2007101546.02);
    }
    if ($result && $oldversion < 2007101546.03) {
        /// Deleting orphaned messages from deleted users.
        require_once $CFG->dirroot . '/message/lib.php';
        /// Detect deleted users with messages sent(useridfrom) and not read
        if ($deletedusers = get_records_sql("SELECT DISTINCT u.id\n                                           FROM {$CFG->prefix}user u\n                                           JOIN {$CFG->prefix}message m ON m.useridfrom = u.id\n                                          WHERE u.deleted = 1")) {
            foreach ($deletedusers as $deleteduser) {
                message_move_userfrom_unread2read($deleteduser->id);
                // move messages
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101546.03);
    }
    if ($result && $oldversion < 2007101546.05) {
        // force full regrading - the max grade for sum aggregation was not correct when scales involved,
        //                        extra credit grade is not dropped anymore in aggregations if drop low or keep high specified
        //                        sum aggragetion respects drop low and keep high when calculation max value
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101546.06) {
        unset_config('grade_report_showgroups');
        upgrade_main_savepoint($result, 2007101546.06);
    }
    if ($result && $oldversion < 2007101547) {
        // Let's check the status of mandatory mnet_host records, fixing them
        // and moving "orphan" users to default localhost record. MDL-16879
        notify('Fixing mnet records, this may take a while...', 'notifysuccess');
        $db->debug = false;
        // Can output too much. Disabling
        upgrade_fix_incorrect_mnethostids();
        $db->debug = true;
        // Restoring debug level
        upgrade_main_savepoint($result, 2007101547);
    }
    if ($result && $oldversion < 2007101551) {
        //insert new record for log_display table
        //used to record tag update.
        if (!record_exists("log_display", "action", "update", "module", "tag")) {
            $log_action = new stdClass();
            $log_action->module = 'tag';
            $log_action->action = 'update';
            $log_action->mtable = 'tag';
            $log_action->field = 'name';
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101551);
    }
    if ($result && $oldversion < 2007101561.01) {
        // As part of security changes password policy will now be enabled by default.
        // If it has not already been enabled then we will enable it... Admins will still
        // be able to switch it off after this upgrade
        if (record_exists('config', 'name', 'passwordpolicy', 'value', 0)) {
            unset_config('passwordpolicy');
        }
        $message = get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        notify($message, 'notifysuccess');
        unset($message);
        upgrade_main_savepoint($result, 2007101561.01);
    }
    if ($result && $oldversion < 2007101561.02) {
        $messagesubject = s($SITE->shortname) . ': ' . get_string('upgrade197noticesubject', 'admin');
        $message = '<p>' . s($SITE->fullname) . ' (' . s($CFG->wwwroot) . '):</p>' . get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        // Force administrators to change password on next login
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password, u.mailformat\n              FROM {$CFG->prefix}role_capabilities rc\n              JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n              JOIN {$CFG->prefix}user u ON u.id = ra.userid\n             WHERE rc.capability = 'moodle/site:doanything'\n                   AND rc.permission = " . CAP_ALLOW . "\n                   AND u.deleted = 0\n                   AND rc.contextid = " . $systemcontext->id . " AND (u.auth='manual' OR u.auth='email')";
        $adminusers = get_records_sql($sql);
        foreach ($adminusers as $adminuser) {
            if ($preference = get_record('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange')) {
                if ($preference->value == '1') {
                    continue;
                }
                set_field('user_preferences', 'value', '1', 'id', $preference->id);
            } else {
                $preference = new stdClass();
                $preference->userid = $adminuser->id;
                $preference->name = 'auth_forcepasswordchange';
                $preference->value = '1';
                insert_record('user_preferences', $preference);
            }
            $adminuser->maildisplay = 0;
            // do not use return email to self, it might actually help emails to get through and prevents notices
            // Message them with the notice about upgrading
            email_to_user($adminuser, $adminuser, $messagesubject, html_to_text($message), $message);
        }
        unset($adminusers);
        unset($preference);
        unset($message);
        unset($messagesubject);
        upgrade_main_savepoint($result, 2007101561.02);
    }
    if ($result && $oldversion < 2007101563.02) {
        // this block tries to undo incorrect forcing of new passwords for admins that have no
        // way to change passwords MDL-20933
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password\n                  FROM {$CFG->prefix}role_capabilities rc\n                  JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n                  JOIN {$CFG->prefix}user u ON u.id = ra.userid\n                 WHERE rc.capability = 'moodle/site:doanything'\n                       AND rc.permission = " . CAP_ALLOW . "\n                       AND u.deleted = 0\n                       AND rc.contextid = " . $systemcontext->id . " AND u.auth<>'manual' AND u.auth<>'email'";
        if ($adminusers = get_records_sql($sql)) {
            foreach ($adminusers as $adminuser) {
                delete_records('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange');
            }
        }
        unset($adminusers);
        upgrade_main_savepoint($result, 2007101563.02);
    }
    if ($result && $oldversion < 2007101563.03) {
        // NOTE: this is quite hacky, but anyway it should work fine in 1.9,
        //       in 2.0 we should always use plugin upgrade code for things like this
        $authsavailable = get_list_of_plugins('auth');
        foreach ($authsavailable as $authname) {
            if (!($auth = get_auth_plugin($authname))) {
                continue;
            }
            if ($auth->prevent_local_passwords()) {
                execute_sql("UPDATE {$CFG->prefix}user SET password='******' WHERE auth='{$authname}'");
            }
        }
        upgrade_main_savepoint($result, 2007101563.03);
    }
    return $result;
}
Example #17
0
        if ($category->glossaryid != $glossary->id) {
            print_error('invalidid', 'glossary');
        }
    } else {
        print_error('invalidcategoryid');
    }
}
require_login($course->id, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/glossary:managecategories', $context);
$strglossaries = get_string("modulenameplural", "glossary");
$strglossary = get_string("modulename", "glossary");
$PAGE->navbar->add($strglossaries, new moodle_url('/mod/glossary/index.php', array('id' => $course->id)));
$PAGE->navbar->add(get_string("categories", "glossary"));
if (!empty($action)) {
    $navaction = get_string($action) . " " . moodle_strtolower(get_string("category", "glossary"));
    $PAGE->navbar->add($navaction);
}
$PAGE->set_title(format_string($glossary->name));
$PAGE->set_heading($course->fullname);
echo $OUTPUT->header();
if ($hook > 0) {
    if ($action == "edit") {
        if ($confirm) {
            $action = "";
            $cat = new stdClass();
            $cat->id = $hook;
            $cat->name = $name;
            $cat->usedynalink = $usedynalink;
            $DB->update_record("glossary_categories", $cat);
            add_to_log($course->id, "glossary", "edit category", "editcategories.php?id={$cm->id}", $hook, $cm->id);
Example #18
0
 unset($newentry);
 $newentry->concept = trim(addslashes($xmlentry['#']['CONCEPT'][0]['#']));
 $newentry->definition = trusttext_strip(addslashes($xmlentry['#']['DEFINITION'][0]['#']));
 if (isset($xmlentry['#']['CASESENSITIVE'][0]['#'])) {
     $newentry->casesensitive = addslashes($xmlentry['#']['CASESENSITIVE'][0]['#']);
 } else {
     $newentry->casesensitive = $CFG->glossary_casesensitive;
 }
 $permissiongranted = 1;
 if ($newentry->concept and $newentry->definition) {
     if (!$glossary->allowduplicatedentries) {
         // checking if the entry is valid (checking if it is duplicated when should not be)
         if ($newentry->casesensitive) {
             $dupentry = get_record("glossary_entries", "concept", $newentry->concept, "glossaryid", $glossary->id);
         } else {
             $dupentry = get_record("glossary_entries", "lower(concept)", moodle_strtolower($newentry->concept), "glossaryid", $glossary->id);
         }
         if ($dupentry) {
             $permissiongranted = 0;
         }
     }
 } else {
     $permissiongranted = 0;
 }
 if ($permissiongranted) {
     $newentry->glossaryid = $glossary->id;
     $newentry->sourceglossaryid = 0;
     $newentry->approved = 1;
     $newentry->userid = $USER->id;
     $newentry->teacherentry = 1;
     $newentry->format = addslashes($xmlentry['#']['FORMAT'][0]['#']);
Example #19
0
    if (isset($USER->display[$course->id])) {
        $displaysection = $USER->display[$course->id];
    } else {
        $displaysection = course_set_display($course->id, 0);
    }
}
$streditsummary = get_string('editsummary');
$stradd = get_string('add');
$stractivities = get_string('activities');
$strshowallweeks = get_string('showallweeks');
$strweek = get_string('week');
$strgroups = get_string('groups');
$strgroupmy = get_string('groupmy');
$editing = $PAGE->user_is_editing();
if ($editing) {
    $strstudents = moodle_strtolower($course->students);
    $strweekhide = get_string('weekhide', '', $strstudents);
    $strweekshow = get_string('weekshow', '', $strstudents);
    $strmoveup = get_string('moveup');
    $strmovedown = get_string('movedown');
}
$context = get_context_instance(CONTEXT_COURSE, $course->id);
/// Layout the whole page as three big columns.
echo '<table id="layout-table" cellspacing="0" summary="' . get_string('layouttable') . '"><tr>';
$lt = empty($THEME->layouttable) ? array('left', 'middle', 'right') : $THEME->layouttable;
foreach ($lt as $column) {
    switch ($column) {
        case 'left':
            /// The left column ...
            if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $editing) {
                echo '<td style="width:' . $preferred_width_left . 'px" id="left-column">';
    }
    if (empty($form->username)) {
        $formerror['username'] = get_string('enterausername', 'mnet');
    }
    if (empty($form->mnet_host_id)) {
        $formerror['mnet_host_id'] = get_string('selectahost', 'mnet');
    }
    if (empty($form->accessctrl)) {
        $formerror['accessctrl'] = get_string('selectaccesslevel', 'mnet');
    }
    // process if there are no errors
    if (count($formerror) == 0) {
        // username can be a comma separated list
        $usernames = explode(',', $form->username);
        foreach ($usernames as $username) {
            $username = trim(moodle_strtolower($username));
            if (!empty($username)) {
                if (mnet_update_sso_access_control($username, $form->mnet_host_id, $form->accessctrl)) {
                    if ($form->accessctrl == 'allow') {
                        redirect('access_control.php', get_string('ssl_acl_allow', 'mnet', array($username, $mnethosts[$form->mnet_host_id])));
                    } elseif ($form->accessctrl == 'deny') {
                        redirect('access_control.php', get_string('ssl_acl_deny', 'mnet', array($username, $mnethosts[$form->mnet_host_id])));
                    }
                }
            }
        }
    }
    exit;
}
// Explain
print_box(get_string('ssoacldescr', 'mnet'));
Example #21
0
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;
}
Example #22
0
/**
* Create default export filename
*
* @return string   default export filename
* @param object $course
* @param object $category
*/
function default_export_filename($course, $category)
{
    //Take off some characters in the filename !!
    $takeoff = array(" ", ":", "/", "\\", "|");
    $export_word = str_replace($takeoff, "_", moodle_strtolower(get_string("exportfilename", "quiz")));
    //If non-translated, use "export"
    if (substr($export_word, 0, 1) == "[") {
        $export_word = "export";
    }
    //Calculate the date format string
    $export_date_format = str_replace(" ", "_", get_string("exportnameformat", "quiz"));
    //If non-translated, use "%Y%m%d-%H%M"
    if (substr($export_date_format, 0, 1) == "[") {
        $export_date_format = "%%Y%%m%%d-%%H%%M";
    }
    //Calculate the shortname
    $export_shortname = clean_filename($course->shortname);
    if (empty($export_shortname) or $export_shortname == '_') {
        $export_shortname = $course->id;
    }
    //Calculate the category name
    $export_categoryname = clean_filename($category->name);
    //Calculate the final export filename
    //The export word
    $export_name = $export_word . "-";
    //The shortname
    $export_name .= moodle_strtolower($export_shortname) . "-";
    //The category name
    $export_name .= moodle_strtolower($export_categoryname) . "-";
    //The date format
    $export_name .= userdate(time(), $export_date_format, 99, false);
    //Extension is supplied by format later.
    return $export_name;
}
Example #23
0
File: lib.php Project: r007/PMoodle
/**
 * Function that normalizes a list of tag names.
 *
 * @param mixed $tags array of tags, or a single tag.
 * @param int $case case to use for returned value (default: lower case). 
 *     Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
 * @return array of lowercased normalized tags, indexed by the normalized tag, 
 *     in the same order as the original array. (Eg: 'Banana' => 'banana').
 */
function tag_normalize($rawtags, $case = TAG_CASE_LOWER)
{
    // cache normalized tags, to prevent costly repeated calls to clean_param
    static $cleaned_tags_lc = array();
    // lower case - use for comparison
    static $cleaned_tags_mc = array();
    // mixed case - use for saving to database
    if (!is_array($rawtags)) {
        $rawtags = array($rawtags);
    }
    $result = array();
    foreach ($rawtags as $rawtag) {
        $rawtag = trim($rawtag);
        if (!$rawtag) {
            continue;
        }
        if (!array_key_exists($rawtag, $cleaned_tags_lc)) {
            $cleaned_tags_lc[$rawtag] = moodle_strtolower(clean_param($rawtag, PARAM_TAG));
            $cleaned_tags_mc[$rawtag] = clean_param($rawtag, PARAM_TAG);
        }
        if ($case == TAG_CASE_LOWER) {
            $result[$rawtag] = $cleaned_tags_lc[$rawtag];
        } else {
            // TAG_CASE_ORIGINAL
            $result[$rawtag] = $cleaned_tags_mc[$rawtag];
        }
    }
    return $result;
}
Example #24
0
/// Get all existing subscribers for this forum.
if (!($subscribers = forum_subscribed_users($course, $forum, $currentgroup, $context))) {
    $subscribers = array();
}
/// Get all the potential subscribers excluding users already subscribed
$users = forum_get_potential_subscribers($context, $currentgroup, 'id,email,firstname,lastname', 'firstname ASC, lastname ASC');
if (!$users) {
    $users = array();
}
foreach ($subscribers as $subscriber) {
    unset($users[$subscriber->id]);
}
/// This is yucky, but do the search in PHP, becuase the list we are using comes from get_users_by_capability,
/// which does not allow searching in the database. Fortunately the list is only this list of users in this
/// course, which is normally OK, except on the site course of a big site. But before you can enter a search
/// term, you have already seen a page that lists everyone, since this code never does paging, so you have probably
/// already crashed your server if you are going to. This will be fixed properly for Moodle 2.0: MDL-17550.
if ($searchtext) {
    $searchusers = array();
    $lcsearchtext = moodle_strtolower($searchtext);
    foreach ($users as $userid => $user) {
        if (strpos(moodle_strtolower($user->email), $lcsearchtext) !== false || strpos(moodle_strtolower($user->firstname . ' ' . $user->lastname), $lcsearchtext) !== false) {
            $searchusers[$userid] = $user;
        }
        unset($users[$userid]);
    }
}
echo $OUTPUT->box_start('generalbox boxaligncenter');
include 'subscriber.html';
echo $OUTPUT->box_end();
echo $OUTPUT->footer();
}
$strglossaries = get_string('modulenameplural', 'glossary');
$entryalreadyexist = get_string('entryalreadyexist', 'glossary');
$entryexported = get_string('entryexported', 'glossary');
$navigation = build_navigation('', $cm);
print_header_simple(format_string($glossary->name), '', $navigation, '', '', true, '', navmenu($course, $cm));
if ($PermissionGranted) {
    $entry = get_record('glossary_entries', 'id', $entry);
    if (!$confirm) {
        echo '<div class="boxaligncenter">';
        $areyousure = get_string('areyousureexport', 'glossary');
        notice_yesno('<h2>' . format_string($entry->concept) . '</h2><p align="center">' . $areyousure . '<br /><b>' . format_string($mainglossary->name) . '</b>?', 'exportentry.php?id=' . $id . '&amp;mode=' . $mode . '&amp;hook=' . $hook . '&amp;entry=' . $entry->id . '&amp;confirm=1', 'view.php?id=' . $cm->id . '&amp;mode=' . $mode . '&amp;hook=' . $hook);
        echo '</div>';
    } else {
        if (!$mainglossary->allowduplicatedentries) {
            $dupentry = get_record('glossary_entries', 'glossaryid', $mainglossary->id, 'lower(concept)', moodle_strtolower(addslashes($entry->concept)));
            if ($dupentry) {
                $PermissionGranted = 0;
            }
        }
        if ($PermissionGranted) {
            $dbentry = new stdClass();
            $dbentry->id = $entry->id;
            $dbentry->glossaryid = $mainglossary->id;
            $dbentry->sourceglossaryid = $glossary->id;
            if (!update_record('glossary_entries', $dbentry)) {
                error('Could not export the entry to the main glossary');
            } else {
                print_simple_box_start('center', '60%');
                echo '<p align="center"><font size="3">' . $entryexported . '</font></p></font>';
                print_continue('view.php?id=' . $cm->id . '&amp;mode=entry&amp;hook=' . $entry->id);
Example #26
0
function restore_create_messages($restore, $xml_file)
{
    global $CFG;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        //info will contain the id and name of every table
        //(message, message_read and message_contacts)
        //in backup_ids->info will be the real info (serialized)
        $info = restore_read_xml_messages($restore, $xml_file);
        //If we have info, then process messages & contacts
        if ($info > 0) {
            //Count how many we have
            $unreadcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message');
            $readcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_read');
            $contactcount = count_records('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_contacts');
            if ($unreadcount || $readcount || $contactcount) {
                //Start ul
                if (!defined('RESTORE_SILENTLY')) {
                    echo '<ul>';
                }
                //Number of records to get in every chunk
                $recordset_size = 4;
                //Process unread
                if ($unreadcount) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo '<li>' . get_string('unreadmessages', 'message') . '</li>';
                    }
                    $counter = 0;
                    while ($counter < $unreadcount) {
                        //Fetch recordset_size records in each iteration
                        $recs = get_records_select("backup_ids", "table_name = 'message' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                        if ($recs) {
                            foreach ($recs as $rec) {
                                //Get the full record from backup_ids
                                $data = backup_getid($restore->backup_unique_code, "message", $rec->old_id);
                                if ($data) {
                                    //Now get completed xmlized object
                                    $info = $data->info;
                                    //traverse_xmlize($info);                            //Debug
                                    //print_object ($GLOBALS['traverse_array']);         //Debug
                                    //$GLOBALS['traverse_array']="";                     //Debug
                                    //Now build the MESSAGE record structure
                                    $dbrec = new object();
                                    $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
                                    $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
                                    $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
                                    $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
                                    $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
                                    $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
                                    //We have to recode the useridfrom field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->useridfrom);
                                    if ($user) {
                                        //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->useridfrom = $user->new_id;
                                    }
                                    //We have to recode the useridto field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->useridto);
                                    if ($user) {
                                        //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->useridto = $user->new_id;
                                    }
                                    //Check if the record doesn't exist in DB!
                                    $exist = get_record('message', 'useridfrom', $dbrec->useridfrom, 'useridto', $dbrec->useridto, 'timecreated', $dbrec->timecreated);
                                    if (!$exist) {
                                        //Not exist. Insert
                                        $status = insert_record('message', $dbrec);
                                    } else {
                                        //Duplicate. Do nothing
                                    }
                                }
                                //Do some output
                                $counter++;
                                if ($counter % 10 == 0) {
                                    if (!defined('RESTORE_SILENTLY')) {
                                        echo ".";
                                        if ($counter % 200 == 0) {
                                            echo "<br />";
                                        }
                                    }
                                    backup_flush(300);
                                }
                            }
                        }
                    }
                }
                //Process read
                if ($readcount) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo '<li>' . get_string('readmessages', 'message') . '</li>';
                    }
                    $counter = 0;
                    while ($counter < $readcount) {
                        //Fetch recordset_size records in each iteration
                        $recs = get_records_select("backup_ids", "table_name = 'message_read' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                        if ($recs) {
                            foreach ($recs as $rec) {
                                //Get the full record from backup_ids
                                $data = backup_getid($restore->backup_unique_code, "message_read", $rec->old_id);
                                if ($data) {
                                    //Now get completed xmlized object
                                    $info = $data->info;
                                    //traverse_xmlize($info);                            //Debug
                                    //print_object ($GLOBALS['traverse_array']);         //Debug
                                    //$GLOBALS['traverse_array']="";                     //Debug
                                    //Now build the MESSAGE_READ record structure
                                    $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
                                    $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
                                    $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
                                    $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
                                    $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
                                    $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
                                    $dbrec->timeread = backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
                                    $dbrec->mailed = backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
                                    //We have to recode the useridfrom field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->useridfrom);
                                    if ($user) {
                                        //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->useridfrom = $user->new_id;
                                    }
                                    //We have to recode the useridto field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->useridto);
                                    if ($user) {
                                        //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->useridto = $user->new_id;
                                    }
                                    //Check if the record doesn't exist in DB!
                                    $exist = get_record('message_read', 'useridfrom', $dbrec->useridfrom, 'useridto', $dbrec->useridto, 'timecreated', $dbrec->timecreated);
                                    if (!$exist) {
                                        //Not exist. Insert
                                        $status = insert_record('message_read', $dbrec);
                                    } else {
                                        //Duplicate. Do nothing
                                    }
                                }
                                //Do some output
                                $counter++;
                                if ($counter % 10 == 0) {
                                    if (!defined('RESTORE_SILENTLY')) {
                                        echo ".";
                                        if ($counter % 200 == 0) {
                                            echo "<br />";
                                        }
                                    }
                                    backup_flush(300);
                                }
                            }
                        }
                    }
                }
                //Process contacts
                if ($contactcount) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo '<li>' . moodle_strtolower(get_string('contacts', 'message')) . '</li>';
                    }
                    $counter = 0;
                    while ($counter < $contactcount) {
                        //Fetch recordset_size records in each iteration
                        $recs = get_records_select("backup_ids", "table_name = 'message_contacts' AND backup_code = '{$restore->backup_unique_code}'", "old_id", "old_id", $counter, $recordset_size);
                        if ($recs) {
                            foreach ($recs as $rec) {
                                //Get the full record from backup_ids
                                $data = backup_getid($restore->backup_unique_code, "message_contacts", $rec->old_id);
                                if ($data) {
                                    //Now get completed xmlized object
                                    $info = $data->info;
                                    //traverse_xmlize($info);                            //Debug
                                    //print_object ($GLOBALS['traverse_array']);         //Debug
                                    //$GLOBALS['traverse_array']="";                     //Debug
                                    //Now build the MESSAGE_CONTACTS record structure
                                    $dbrec->userid = backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
                                    $dbrec->contactid = backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
                                    $dbrec->blocked = backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
                                    //We have to recode the userid field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->userid);
                                    if ($user) {
                                        //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->userid = $user->new_id;
                                    }
                                    //We have to recode the contactid field
                                    $user = backup_getid($restore->backup_unique_code, "user", $dbrec->contactid);
                                    if ($user) {
                                        //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />";   //Debug
                                        $dbrec->contactid = $user->new_id;
                                    }
                                    //Check if the record doesn't exist in DB!
                                    $exist = get_record('message_contacts', 'userid', $dbrec->userid, 'contactid', $dbrec->contactid);
                                    if (!$exist) {
                                        //Not exist. Insert
                                        $status = insert_record('message_contacts', $dbrec);
                                    } else {
                                        //Duplicate. Do nothing
                                    }
                                }
                                //Do some output
                                $counter++;
                                if ($counter % 10 == 0) {
                                    if (!defined('RESTORE_SILENTLY')) {
                                        echo ".";
                                        if ($counter % 200 == 0) {
                                            echo "<br />";
                                        }
                                    }
                                    backup_flush(300);
                                }
                            }
                        }
                    }
                }
                if (!defined('RESTORE_SILENTLY')) {
                    //End ul
                    echo '</ul>';
                }
            }
        }
    }
    return $status;
}
Example #27
0
/**
 * Stores a tag for a course for a user
 *
 * @uses $CFG
 * @param array $tags simple array of keywords to be stored
 * @param integer $courseid
 * @param integer $userid
 * @param string $tagtype official or default only
 * @param string $myurl optional for logging creation of course tags
 */
function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {

    global $CFG;

    if (is_array($tags) and !empty($tags)) {
        foreach($tags as $tag) {
            $tag = trim($tag);
            if (strlen($tag) > 0) {
                //tag_set_add('course', $courseid, $tag, $userid); //deletes official tags

                //add tag if does not exist
                if (!$tagid = tag_get_id($tag)) {
                    $tag_id_array = tag_add(array($tag), $tagtype);
                    $tagid = $tag_id_array[moodle_strtolower($tag)];
                }
                //ordering
                $ordering = 0;
                if ($current_ids = tag_get_tags_ids('course', $courseid)) {
                    end($current_ids);
                    $ordering = key($current_ids) + 1;
                }
                //set type
                tag_type_set($tagid, $tagtype);

                //tag_instance entry
                tag_assign('course', $courseid, $tagid, $ordering, $userid);

                //logging - note only for user added tags
                if ($tagtype == 'default' and $myurl != '') {
                    $url = $myurl.'?query='.urlencode($tag);
                    add_to_log($courseid, 'coursetags', 'add', $url, 'Course tagged');
                }
            }
        }
    }

}
/**
 * This function generates the common file substring for a course
 * used to keep n copies by the scheduled backup
 *
 * @param object $course course object
 * @return string common part of filename in backups of this course
 */
function backup_get_keep_name($course)
{
    //Calculate the backup word
    $backup_word = backup_get_backup_string($course);
    //Calculate the shortname
    $backup_shortname = clean_filename($course->shortname);
    if (empty($backup_shortname) or $backup_shortname == '_') {
        $backup_shortname = $course->id;
    }
    $keep_name = $backup_word . "-" . moodle_strtolower($backup_shortname) . "-";
    $keep_name = clean_filename($keep_name);
    return $keep_name;
}
 function validation($data, $files)
 {
     global $CFG, $USER;
     $errors = parent::validation($data, $files);
     $e = $this->_customdata['e'];
     $glossary = $this->_customdata['glossary'];
     $context = $this->_customdata['context'];
     $data['concept'] = trim($data['concept']);
     if ($e) {
         //We are updating an entry, so we compare current session user with
         //existing entry user to avoid some potential problems if secureforms=off
         //Perhaps too much security? Anyway thanks to skodak (Bug 1823)
         $old = get_record('glossary_entries', 'id', $e);
         $ineditperiod = time() - $old->timecreated < $CFG->maxeditingtime || $glossary->editalways;
         if (!$ineditperiod || $USER->id != $old->userid and !has_capability('mod/glossary:manageentries', $context)) {
             if ($USER->id != $old->userid) {
                 $errors['concept'] = get_string('errcannoteditothers', 'glossary');
             } elseif (!$ineditperiod) {
                 $errors['concept'] = get_string('erredittimeexpired', 'glossary');
             }
         }
         if (!$glossary->allowduplicatedentries) {
             if ($dupentries = get_records('glossary_entries', 'lower(concept)', moodle_strtolower($data['concept']))) {
                 foreach ($dupentries as $curentry) {
                     if ($glossary->id == $curentry->glossaryid) {
                         if ($curentry->id != $e) {
                             $errors['concept'] = get_string('errconceptalreadyexists', 'glossary');
                             break;
                         }
                     }
                 }
             }
         }
     } else {
         if (!$glossary->allowduplicatedentries) {
             if ($dupentries = get_record('glossary_entries', 'lower(concept)', moodle_strtolower($data['concept']), 'glossaryid', $glossary->id)) {
                 $errors['concept'] = get_string('errconceptalreadyexists', 'glossary');
             }
         }
     }
     return $errors;
 }
function schedule_backup_course_configure($course, $starttime = 0)
{
    global $CFG;
    $status = true;
    schedule_backup_log($starttime, $course->id, "    checking parameters");
    //Check the required variable
    if (empty($course->id)) {
        $status = false;
    }
    //Get scheduled backup preferences
    $backup_config = backup_get_config();
    //Checks backup_config pairs exist
    if ($status) {
        if (!isset($backup_config->backup_sche_modules)) {
            $backup_config->backup_sche_modules = 1;
        }
        if (!isset($backup_config->backup_sche_withuserdata)) {
            $backup_config->backup_sche_withuserdata = 1;
        }
        if (!isset($backup_config->backup_sche_metacourse)) {
            $backup_config->backup_sche_metacourse = 1;
        }
        if (!isset($backup_config->backup_sche_users)) {
            $backup_config->backup_sche_users = 1;
        }
        if (!isset($backup_config->backup_sche_logs)) {
            $backup_config->backup_sche_logs = 0;
        }
        if (!isset($backup_config->backup_sche_userfiles)) {
            $backup_config->backup_sche_userfiles = 1;
        }
        if (!isset($backup_config->backup_sche_coursefiles)) {
            $backup_config->backup_sche_coursefiles = 1;
        }
        if (!isset($backup_config->backup_sche_messages)) {
            $backup_config->backup_sche_messages = 0;
        }
        if (!isset($backup_config->backup_sche_active)) {
            $backup_config->backup_sche_active = 0;
        }
        if (!isset($backup_config->backup_sche_weekdays)) {
            $backup_config->backup_sche_weekdays = "0000000";
        }
        if (!isset($backup_config->backup_sche_hour)) {
            $backup_config->backup_sche_hour = 00;
        }
        if (!isset($backup_config->backup_sche_minute)) {
            $backup_config->backup_sche_minute = 00;
        }
        if (!isset($backup_config->backup_sche_destination)) {
            $backup_config->backup_sche_destination = "";
        }
        if (!isset($backup_config->backup_sche_keep)) {
            $backup_config->backup_sche_keep = 1;
        }
    }
    if ($status) {
        //Checks for the required files/functions to backup every mod
        //And check if there is data about it
        $count = 0;
        if ($allmods = get_records("modules")) {
            foreach ($allmods as $mod) {
                $modname = $mod->name;
                $modfile = "{$CFG->dirroot}/mod/{$modname}/backuplib.php";
                $modbackup = $modname . "_backup_mods";
                $modcheckbackup = $modname . "_check_backup_mods";
                if (file_exists($modfile)) {
                    include_once $modfile;
                    if (function_exists($modbackup) and function_exists($modcheckbackup)) {
                        $var = "exists_" . $modname;
                        ${$var} = true;
                        $count++;
                        // PENNY NOTES: I have moved from here to the closing brace inside
                        // by two sets of ifs()
                        // to avoid the backup failing on a non existant backup.
                        // If the file/function/whatever doesn't exist, we don't want to set this
                        // this module in backup preferences at all.
                        //Check data
                        //Check module info
                        $var = "backup_" . $modname;
                        if (!isset(${$var})) {
                            ${$var} = $backup_config->backup_sche_modules;
                        }
                        //Now stores all the mods preferences into an array into preferences
                        $preferences->mods[$modname]->backup = ${$var};
                        //Check include user info
                        $var = "backup_user_info_" . $modname;
                        if (!isset(${$var})) {
                            ${$var} = $backup_config->backup_sche_withuserdata;
                        }
                        //Now stores all the mods preferences into an array into preferences
                        $preferences->mods[$modname]->userinfo = ${$var};
                        //And the name of the mod
                        $preferences->mods[$modname]->name = $modname;
                    }
                }
            }
        }
        // now set instances
        if ($coursemods = get_course_mods($course->id)) {
            foreach ($coursemods as $mod) {
                if (array_key_exists($mod->modname, $preferences->mods)) {
                    // we are to backup this module
                    if (empty($preferences->mods[$mod->modname]->instances)) {
                        $preferences->mods[$mod->modname]->instances = array();
                        // avoid warnings
                    }
                    $preferences->mods[$mod->modname]->instances[$mod->instance]->backup = $preferences->mods[$mod->modname]->backup;
                    $preferences->mods[$mod->modname]->instances[$mod->instance]->userinfo = $preferences->mods[$mod->modname]->userinfo;
                    // there isn't really a nice way to do this...
                    $preferences->mods[$mod->modname]->instances[$mod->instance]->name = get_field($mod->modname, 'name', 'id', $mod->instance);
                }
            }
        }
        // finally, clean all the $preferences->mods[] not having instances. Nothing to backup about them
        foreach ($preferences->mods as $modname => $mod) {
            if (!isset($mod->instances)) {
                unset($preferences->mods[$modname]);
            }
        }
    }
    //Convert other parameters
    if ($status) {
        $preferences->backup_metacourse = $backup_config->backup_sche_metacourse;
        $preferences->backup_users = $backup_config->backup_sche_users;
        $preferences->backup_logs = $backup_config->backup_sche_logs;
        $preferences->backup_user_files = $backup_config->backup_sche_userfiles;
        $preferences->backup_course_files = $backup_config->backup_sche_coursefiles;
        $preferences->backup_messages = $backup_config->backup_sche_messages;
        $preferences->backup_course = $course->id;
        $preferences->backup_destination = $backup_config->backup_sche_destination;
        $preferences->backup_keep = $backup_config->backup_sche_keep;
    }
    //Calculate the backup string
    if ($status) {
        schedule_backup_log($starttime, $course->id, "    calculating backup name");
        //Calculate the backup word
        //Take off some characters in the filename !!
        $takeoff = array(" ", ":", "/", "\\", "|");
        $backup_word = str_replace($takeoff, "_", moodle_strtolower(get_string("backupfilename")));
        //If non-translated, use "backup"
        if (substr($backup_word, 0, 1) == "[") {
            $backup_word = "backup";
        }
        //Calculate the date format string
        $backup_date_format = str_replace(" ", "_", get_string("backupnameformat"));
        //If non-translated, use "%Y%m%d-%H%M"
        if (substr($backup_date_format, 0, 1) == "[") {
            $backup_date_format = "%%Y%%m%%d-%%H%%M";
        }
        //Calculate the shortname
        $backup_shortname = clean_filename($course->shortname);
        if (empty($backup_shortname) or $backup_shortname == '_') {
            $backup_shortname = $course->id;
        }
        //Calculate the final backup filename
        //The backup word
        $backup_name = $backup_word . "-";
        //The shortname
        $backup_name .= moodle_strtolower($backup_shortname) . "-";
        //The date format
        $backup_name .= userdate(time(), $backup_date_format, 99, false);
        //The extension
        $backup_name .= ".zip";
        //And finally, clean everything
        $backup_name = clean_filename($backup_name);
        //Calculate the string to match the keep preference
        $keep_name = $backup_word . "-";
        //The shortname
        $keep_name .= moodle_strtolower($backup_shortname) . "-";
        //And finally, clean everything
        $keep_name = clean_filename($keep_name);
        $preferences->backup_name = $backup_name;
        $preferences->keep_name = $keep_name;
    }
    //Calculate the backup unique code to allow simultaneus backups (to define
    //the temp-directory name and records in backup temp tables
    if ($status) {
        $backup_unique_code = time();
        $preferences->backup_unique_code = $backup_unique_code;
    }
    //Calculate necesary info to backup modules
    if ($status) {
        schedule_backup_log($starttime, $course->id, "    calculating modules data");
        if ($allmods = get_records("modules")) {
            foreach ($allmods as $mod) {
                $modname = $mod->name;
                $modbackup = $modname . "_backup_mods";
                //If exists the lib & function
                $var = "exists_" . $modname;
                if (isset(${$var}) && ${$var}) {
                    //Add hidden fields
                    $var = "backup_" . $modname;
                    //Only if selected
                    if (${$var} == 1) {
                        $var = "backup_user_info_" . $modname;
                        //Call the check function to show more info
                        $modcheckbackup = $modname . "_check_backup_mods";
                        schedule_backup_log($starttime, $course->id, "      {$modname}");
                        $modcheckbackup($course->id, ${$var}, $backup_unique_code);
                    }
                }
            }
        }
    }
    //Now calculate the users
    if ($status) {
        schedule_backup_log($starttime, $course->id, "    calculating users");
        //Decide about include users with messages, based on SITEID
        if ($preferences->backup_messages && $preferences->backup_course == SITEID) {
            $include_message_users = true;
        } else {
            $include_message_users = false;
        }
        user_check_backup($course->id, $backup_unique_code, $preferences->backup_users, $include_message_users);
    }
    //Now calculate the logs
    if ($status) {
        if ($preferences->backup_logs) {
            schedule_backup_log($starttime, $course->id, "    calculating logs");
            log_check_backup($course->id);
        }
    }
    //Now calculate the userfiles
    if ($status) {
        if ($preferences->backup_user_files) {
            schedule_backup_log($starttime, $course->id, "    calculating user files");
            user_files_check_backup($course->id, $preferences->backup_unique_code);
        }
    }
    //Now calculate the coursefiles
    if ($status) {
        if ($preferences->backup_course_files) {
            schedule_backup_log($starttime, $course->id, "    calculating course files");
            course_files_check_backup($course->id, $preferences->backup_unique_code);
        }
    }
    //If everything is ok, return calculated preferences
    if ($status) {
        $status = $preferences;
    }
    return $status;
}