示例#1
0
function slideshow_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2006112100) {
        table_column('slideshow', '', 'layout', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092600) {
        table_column('slideshow', '', 'location', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006012600) {
        table_column('slideshow', '', 'filename', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006112700) {
        modify_database('', "CREATE TABLE " . $CFG->prefix . "slideshow_captions (\r\n              id SERIAL PRIMARY KEY,\r\n              slideshow integer NOT NULL default '0',\r\n              image text NOT NULL,\r\n              title text NOT NULL,\r\n              caption text NOT NULL\r\n            )\r\n        ");
    }
    if ($oldversion < 2007070702) {
        table_column('slideshow', '', 'delaytime', 'int', '2', 'unsigned', '7', 'not null', '');
    }
    if ($oldversion < 2007070703) {
        table_column('slideshow', '', 'centred', 'int', '2', 'unsigned', '0', 'not null', '');
        table_column('slideshow', '', 'autobgcolor', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    return true;
}
function backup_upgrade($oldversion = 0)
{
    global $CFG;
    $result = true;
    if ($oldversion < 2006011600 and $result) {
        $result = execute_sql("DROP TABLE {$CFG->prefix}backup_files");
        if ($result) {
            $result = execute_sql("CREATE TABLE {$CFG->prefix}backup_files (\n                          id SERIAL PRIMARY KEY,\n                          backup_code integer NOT NULL default '0',\n                          file_type varchar(10) NOT NULL default '',\n                          path varchar(255) NOT NULL default '',\n                          old_id integer default NULL,\n                          new_id integer default NULL,\n                          CONSTRAINT {$CFG->prefix}backup_files_uk UNIQUE (backup_code, file_type, path))");
        }
        if ($result) {
            $result = execute_sql("DROP TABLE {$CFG->prefix}backup_ids");
        }
        if ($result) {
            $result = execute_sql("CREATE TABLE {$CFG->prefix}backup_ids (\n                          id SERIAL PRIMARY KEY,\n                          backup_code integer NOT NULL default '0',\n                          table_name varchar(30) NOT NULL default '',\n                          old_id integer NOT NULL default '0',\n                          new_id integer default NULL,\n                          info text,\n                          CONSTRAINT {$CFG->prefix}backup_ids_uk UNIQUE (backup_code, table_name, old_id))");
        }
    }
    if ($oldversion < 2006042801) {
        table_column('backup_log', 'time', 'time', 'integer', '', '', '0');
        table_column('backup_log', 'laststarttime', 'laststarttime', 'integer', '', '', '0');
        table_column('backup_log', 'courseid', 'courseid', 'integer', '', '', '0');
        table_column('backup_courses', 'lastendtime', 'lastendtime', 'integer', '', '', '0');
        table_column('backup_courses', 'laststarttime', 'laststarttime', 'integer', '', '', '0');
        table_column('backup_courses', 'courseid', 'courseid', 'integer', '', '', '0');
        table_column('backup_courses', 'nextstarttime', 'nextstarttime', 'integer', '', '', '0');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    //Finally, return result
    return $result;
}
示例#3
0
function slideshow_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2006112100) {
        table_column('slideshow', '', 'layout', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092600) {
        table_column('slideshow', '', 'location', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006012600) {
        table_column('slideshow', '', 'filename', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006120500) {
        modify_database('', "CREATE TABLE `" . $CFG->prefix . "slideshow_captions` (\r\n                    `id` int(10) unsigned NOT NULL auto_increment,\r\n                    `slideshow` int(10) unsigned NOT NULL default '0',\r\n                    `image` text NOT NULL,\r\n                    `title` text NOT NULL,\r\n                    `caption` text NOT NULL,\r\n                    PRIMARY KEY  (`id`),\r\n                    KEY slideshow (slideshow)\r\n                    );\r\n        ");
    }
    if ($oldversion < 2007070702) {
        table_column('slideshow', '', 'delaytime', 'int', '2', 'unsigned', '7', 'not null', '');
    }
    if ($oldversion < 2007070703) {
        table_column('slideshow', '', 'centred', 'int', '2', 'unsigned', '0', 'not null', '');
        table_column('slideshow', '', 'autobgcolor', 'int', '2', 'unsigned', '0', 'not null', '');
    }
    return true;
}
function resource_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004013101) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('resource', 'update', 'resource', 'name');");
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('resource', 'add', 'resource', 'name');");
    }
    if ($oldversion < 2004071000) {
        table_column("resource", "", "popup", "text", "", "", "", "", "alltext");
        if ($resources = get_records_select("resource", "type='3' OR type='5'", "", "id, alltext")) {
            foreach ($resources as $resource) {
                $resource->popup = addslashes($resource->alltext);
                $resource->alltext = "";
                if (!update_record("resource", $resource)) {
                    notify("Error updating popup field for resource id = {$resource->id}");
                }
            }
        }
        require_once "{$CFG->dirroot}/course/lib.php";
        rebuild_course_cache();
    }
    if ($oldversion < 2004071300) {
        table_column("resource", "", "options", "varchar", "255", "", "", "", "popup");
    }
    if ($oldversion < 2004071303) {
        table_column("resource", "type", "type", "varchar", "30", "", "", "", "");
        modify_database("", "UPDATE prefix_resource SET type='reference' WHERE type='1';");
        modify_database("", "UPDATE prefix_resource SET type='file', options='frame' WHERE type='2';");
        modify_database("", "UPDATE prefix_resource SET type='file' WHERE type='3';");
        modify_database("", "UPDATE prefix_resource SET type='text', options='0' WHERE type='4';");
        modify_database("", "UPDATE prefix_resource SET type='file' WHERE type='5';");
        modify_database("", "UPDATE prefix_resource SET type='html' WHERE type='6';");
        modify_database("", "UPDATE prefix_resource SET type='file' WHERE type='7';");
        modify_database("", "UPDATE prefix_resource SET type='text', options='3' WHERE type='8';");
        modify_database("", "UPDATE prefix_resource SET type='directory' WHERE type='9';");
    }
    if ($oldversion < 2004080801) {
        modify_database("", "UPDATE prefix_resource SET alltext=reference,type='html' WHERE type='reference';");
        rebuild_course_cache();
    }
    if ($oldversion < 2004111200) {
        //drop first to avoid conflicts when upgrading
        execute_sql("DROP INDEX {$CFG->prefix}resource_course_idx;", false);
        modify_database('', 'CREATE INDEX prefix_resource_course_idx ON prefix_resource (course);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $wtm->update('resource', 'alltext', 'options');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#5
0
function qtype_multichoice_upgrade($oldversion = 0)
{
    global $CFG;
    $success = true;
    if ($success && $oldversion < 2006081900) {
        $success = $success && table_column('question_multichoice', '', 'correctfeedback', 'text', '', '', '');
        $success = $success && table_column('question_multichoice', '', 'partiallycorrectfeedback', 'text', '', '', '');
        $success = $success && table_column('question_multichoice', '', 'incorrectfeedback', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $success;
}
示例#6
0
function chat_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003072100) {
        modify_database("", " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('chat', 'report', 'chat', 'name'); ");
    }
    if ($oldversion < 2003072101) {
        table_column("chat", "messages", "keepdays", "integer", "10", "unsigned", "0", "not null");
    }
    if ($oldversion < 2003072102) {
        table_column("chat", "", "studentlogs", "integer", "4", "unsigned", "0", "not null", "keepdays");
    }
    if ($oldversion < 2003072500) {
        table_column("chat", "", "chattime", "integer", "10", "unsigned", "0", "not null", "studentlogs");
        table_column("chat", "", "schedule", "integer", "4", "", "0", "not null", "studentlogs");
    }
    if ($oldversion < 2004022300) {
        table_column("chat_messages", "", "groupid", "integer", "10", "unsigned", "0", "not null", "userid");
        table_column("chat_users", "", "groupid", "integer", "10", "unsigned", "0", "not null", "userid");
    }
    if ($oldversion < 2004042500) {
        include_once "{$CFG->dirroot}/mod/chat/lib.php";
        chat_refresh_events();
    }
    if ($oldversion < 2004043000) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('chat', 'talk', 'chat', 'name');");
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}chat DROP INDEX `course`;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}chat_messages DROP INDEX  `chatid`;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}chat_messages DROP INDEX `userid`;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}chat_messages DROP INDEX `groupid`;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}chat_users DROP INDEX  `chatid`;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}chat_users DROP INDEX  `groupid`;", false);
        modify_database('', 'ALTER TABLE prefix_chat ADD INDEX `course` (`course`);');
        modify_database('', 'ALTER TABLE prefix_chat_messages ADD INDEX  `chatid` (`chatid`);');
        modify_database('', 'ALTER TABLE prefix_chat_messages ADD INDEX `userid` (`userid`);');
        modify_database('', 'ALTER TABLE prefix_chat_messages ADD INDEX `groupid` (`groupid`);');
        modify_database('', 'ALTER TABLE prefix_chat_users ADD INDEX  `chatid` (`chatid`);');
        modify_database('', 'ALTER TABLE prefix_chat_users ADD INDEX  `groupid` (`groupid`);');
    }
    if ($oldversion < 2005020300) {
        table_column('chat_users', '', 'course', 'integer', '10', 'unsigned', '0', 'not null', '');
        table_column('chat_users', '', 'lang', 'varchar', '10', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#7
0
function exercise_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003111400) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_submissions` ADD INDEX (`userid`)");
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_submissions` DROP INDEX `title`");
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_assessments` ADD INDEX (`submissionid`)");
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_assessments` ADD INDEX (`userid`)");
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_grades` ADD INDEX (`assessmentid`)");
    }
    if ($oldversion < 2003121000) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}exercise_submissions` ADD `late` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0'");
    }
    if ($oldversion < 2004062300) {
        table_column("exercise", "", "gradinggrade", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "grade");
        table_column("exercise", "", "assessmentcomps", "INTEGER", "4", "UNSIGNED", "2", "NOT NULL", "usemaximum");
        execute_sql("ALTER TABLE `{$CFG->prefix}exercise` DROP COLUMN `teacherweight`");
        execute_sql("ALTER TABLE `{$CFG->prefix}exercise` DROP COLUMN `gradingweight`");
    }
    if ($oldversion < 2004090200) {
        table_column("exercise", "", "usepassword", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        table_column("exercise", "", "password", "VARCHAR", "32", "", "", "NOT NULL");
    }
    if ($oldversion < 2004091000) {
        table_column("exercise_assessments", "generalcomment", "generalcomment", "text", "", "", "", "NOT NULL");
        table_column("exercise_assessments", "teachercomment", "teachercomment", "text", "", "", "", "NOT NULL");
    }
    if ($oldversion < 2004100800) {
        include_once "{$CFG->dirroot}/mod/exercise/lib.php";
        exercise_refresh_events();
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}exercise DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}exercise_submissions DROP INDEX exerciseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}exercise_assessments DROP INDEX exerciseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}exercise_elements DROP INDEX exerciseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}exercise_rubrics DROP INDEX exerciseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}exercise_grades DROP INDEX exerciseid;", false);
        modify_database('', 'ALTER TABLE prefix_exercise ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_exercise_submissions ADD INDEX exerciseid (exerciseid);');
        modify_database('', 'ALTER TABLE prefix_exercise_assessments ADD INDEX exerciseid (exerciseid);');
        modify_database('', 'ALTER TABLE prefix_exercise_elements ADD INDEX exerciseid (exerciseid);');
        modify_database('', 'ALTER TABLE prefix_exercise_rubrics ADD INDEX exerciseid (exerciseid);');
        modify_database('', 'ALTER TABLE prefix_exercise_grades ADD INDEX exerciseid (exerciseid);');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function chat_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004022300) {
        table_column("chat_messages", "", "groupid", "integer", "10", "unsigned", "0", "not null", "userid");
        table_column("chat_users", "", "groupid", "integer", "10", "unsigned", "0", "not null", "userid");
    }
    if ($oldversion < 2004042500) {
        include_once "{$CFG->dirroot}/mod/chat/lib.php";
        chat_refresh_events();
    }
    if ($oldversion < 2004043000) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('chat', 'talk', 'chat', 'name');");
    }
    if ($oldversion < 2004111200) {
        //drop them first to avoid collisions with upgrades from 1.4.2+
        execute_sql("DROP INDEX {$CFG->prefix}chat_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_messages_chatid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_messages_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_messages_groupid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_messages_timemodifiedchatid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_users_chatid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_users_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_users_groupid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}chat_users_lastping_idx;", false);
        modify_database('', 'CREATE INDEX prefix_chat_course_idx ON prefix_chat(course);');
        modify_database('', 'CREATE INDEX prefix_chat_messages_chatid_idx ON prefix_chat_messages (chatid);');
        modify_database('', 'CREATE INDEX prefix_chat_messages_userid_idx ON prefix_chat_messages (userid);');
        modify_database('', 'CREATE INDEX prefix_chat_messages_groupid_idx ON prefix_chat_messages (groupid);');
        modify_database('', 'CREATE INDEX prefix_chat_messages_timemodifiedchatid_idx ON prefix_chat_messages(timestamp,chatid);');
        modify_database('', 'CREATE INDEX prefix_chat_users_chatid_idx ON prefix_chat_users (chatid);');
        modify_database('', 'CREATE INDEX prefix_chat_users_userid_idx ON prefix_chat_users (userid);');
        modify_database('', 'CREATE INDEX prefix_chat_users_groupid_idx ON prefix_chat_users (groupid);');
        modify_database('', 'CREATE INDEX prefix_chat_users_lastping_idx ON prefix_chat_users (lastping);');
    }
    if ($oldversion < 2005020300) {
        table_column('chat_users', '', 'course', 'integer', '10', 'unsigned', '0', 'not null', '');
        table_column('chat_users', '', 'lang', 'varchar', '10', '', '', 'not null', '');
    }
    if ($oldversion < 2005031001) {
        // Mass cleanup of bad upgrade scripts
        modify_database('', 'ALTER TABLE prefix_chat_users ALTER course SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_chat_users ALTER lang SET NOT NULL');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function journal_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    $result = true;
    if ($oldversion < 2003081705) {
        $defaultscale = NULL;
        $defaultscale->courseid = 0;
        $defaultscale->userid = 0;
        $defaultscale->timemodified = time();
        $defaultscale->name = get_string("journalrating2", "journal");
        $defaultscale->scale = get_string("journalrating1", "journal") . "," . get_string("journalrating2", "journal") . "," . get_string("journalrating3", "journal");
        if ($defaultscale->id = insert_record("scale", $defaultscale)) {
            execute_sql("UPDATE {$CFG->prefix}journal SET assessed = '-{$defaultscale->id}'", false);
        } else {
            notify("An error occurred while inserting the default journal scale");
            $result = false;
        }
    }
    if ($oldversion < 2004011400) {
        table_column("journal", "", "introformat", "integer", "2", "", "1", "not null", "intro");
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}journal_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}journal_entries_journal_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}journal_entries_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_journal_course_idx ON prefix_journal (course);');
        modify_database('', 'CREATE INDEX prefix_journal_entries_journal_idx ON prefix_journal_entries (journal);');
        modify_database('', 'CREATE INDEX prefix_journal_entries_userid_idx ON prefix_journal_entries (userid);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        // journal intro
        $wtm->update('journal', 'intro', 'introformat');
        // journal entries
        $sql = "select course from {$CFG->prefix}journal, {$CFG->prefix}journal_entries ";
        $sql .= "where {$CFG->prefix}journal.id = {$CFG->prefix}journal_entries.journal ";
        $sql .= "and {$CFG->prefix}journal_entries.id = ";
        $wtm->update('journal_entries', 'text', 'format', $sql);
    }
    if ($oldversion < 2006092100) {
        table_column('journal_entries', 'comment', 'entrycomment', 'text', '', '', '', 'null');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
示例#10
0
function main_upgrade($oldversion = 0)
{
    global $CFG, $db, $METATABLES;
    $result = true;
    if ($oldversion < 2007062601) {
        modify_database("", "\n            CREATE TABLE `{$CFG->prefix}extauth_hash` (\n              `id` int(11) NOT NULL auto_increment,\n              `login` varchar(15) NOT NULL default '',\n              `hash` varchar(32) NOT NULL default '',\n              `time` timestamp NOT NULL default CURRENT_TIMESTAMP,\n              PRIMARY KEY (`id`));");
        $METATABLES = $db->Metatables();
        // table added/removed without using modify_database()
        // set initial value for auth config
        set_config('auth', '');
    }
    if ($oldversion < 2007062602) {
        table_column('ponente', 'domicilio', 'domicilio', 'varchar', '255', '', '');
    }
    return $result;
}
示例#11
0
function survey_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004021601) {
        modify_database("", "INSERT INTO `prefix_survey` (`course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (0, 0, 0, 985017600, 985017600, 'ciqname', 'ciqintro', '69,70,71,72,73')");
        modify_database("", "INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (69, 'ciq1', 'ciq1short', '', '', 0, '')");
        modify_database("", "INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (70, 'ciq2', 'ciq2short', '', '', 0, '')");
        modify_database("", "INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (71, 'ciq3', 'ciq3short', '', '', 0, '')");
        modify_database("", "INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (72, 'ciq4', 'ciq4short', '', '', 0, '')");
        modify_database("", "INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (73, 'ciq5', 'ciq5short', '', '', 0, '')");
    }
    if ($oldversion < 2004021602) {
        table_column("survey_answers", "answer1", "answer1", "text", "", "", "");
        table_column("survey_answers", "answer2", "answer2", "text", "", "", "");
    }
    if ($oldversion < 2004021900) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('survey', 'add', 'survey', 'name');");
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('survey', 'update', 'survey', 'name');");
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}survey_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}survey_analysis_survey_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}survey_analysis_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}survey_answers_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}survey_answers_survey_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}survey_answers_question_idx;", false);
        modify_database('', 'CREATE INDEX prefix_survey_course_idx ON prefix_survey (course);');
        modify_database('', 'CREATE INDEX prefix_survey_analysis_survey_idx ON prefix_survey_analysis (survey);');
        modify_database('', 'CREATE INDEX prefix_survey_analysis_userid_idx ON prefix_survey_analysis (userid);');
        modify_database('', 'CREATE INDEX prefix_survey_answers_userid_idx ON prefix_survey_answers (userid);');
        modify_database('', 'CREATE INDEX prefix_survey_answers_survey_idx ON prefix_survey_answers (survey);');
        modify_database('', 'CREATE INDEX prefix_survey_answers_question_idx ON prefix_survey_answers (question);');
    }
    if ($oldversion < 2005031600) {
        execute_sql('SELECT setval(\'' . $CFG->prefix . 'survey_id_seq\', (select max(id) from ' . $CFG->prefix . 'survey))');
        execute_sql('SELECT setval(\'' . $CFG->prefix . 'survey_questions_id_seq\', (select max(id) from ' . $CFG->prefix . 'survey_questions))');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#12
0
function label_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003091400) {
        table_column("label", "", "course", "integer", "10", "unsigned", "0", "not null", "id");
    }
    if ($oldversion < 2004021900) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('label', 'add', 'label', 'name');");
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('label', 'update', 'label', 'name');");
    }
    if ($oldversion < 2004111200) {
        //DROP first
        execute_sql("DROP INDEX {$CFG->prefix}label_course_idx;", false);
        modify_database('', 'CREATE INDEX prefix_label_course_idx ON prefix_label (course);');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function tab_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2008071159) {
        table_column("tab", "", "course", "integer", "10", "unsigned", "0", "not null", "id");
    }
    if ($oldversion < 2008071159) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('tab', 'add', 'quiz', 'name');");
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('tab', 'update', 'quiz', 'name');");
    }
    if ($oldversion < 2008071159) {
        //DROP first
        execute_sql("ALTER TABLE {$CFG->prefix}tab DROP INDEX course;", false);
        modify_database('', 'ALTER TABLE prefix_tab ADD INDEX course (course);');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function elluminate_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    $result = true;
    if ($oldversion < 2006062100) {
        $result = modify_database('', "\n            CREATE TABLE `prefix_elluminate` (\n                `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n                `course` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                `creator` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                `name` VARCHAR(64) NOT NULL DEFAULT '',\n                `description` TEXT NOT NULL DEFAULT '',\n                `meetingid` VARCHAR(20) NOT NULL DEFAULT 0,\n                `private` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,\n                `grade` INT(10) NOT NULL DEFAULT '0',\n                `timemodified` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                PRIMARY KEY  (`id`),\n                KEY `meetingid` (`meetingid`)\n            )\n        ");
        if ($result) {
            $result = modify_database('', "\n                CREATE TABLE `prefix_elluminate_recordings` (\n                    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n                    `meetingid` VARCHAR(20) NOT NULL DEFAULT '',\n                    `recordingid` VARCHAR(30) NOT NULL DEFAULT '',\n                    `created` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    PRIMARY KEY `id` (`id`),\n                    KEY `meetingid` (`meetingid`),\n                    KEY `recordingid` (`recordingid`)\n                )\n            ");
        }
        if ($result) {
            $result = modify_database('', "\n                CREATE TABLE `prefix_elluminate_users` (\n                    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n                    `userid` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    `elm_id` VARCHAR(20) NOT NULL DEFAULT '',\n                    `elm_password` VARCHAR(10) NOT NULL DEFAULT '',\n                    `timecreated` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    PRIMARY KEY `id` (`id`),\n                    KEY `userid` (`userid`),\n                    KEY `elm_id` (`elm_id`)\n                )\n            ");
        }
        if ($result) {
            $result = modify_database('', "\n                CREATE TABLE `prefix_elluminate_attendance` (\n                    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n                    `userid` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    `elluminateid` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    `grade` INT(11) NOT NULL DEFAULT '0',\n                    `timemodified` INT(10) UNSIGNED NOT NULL DEFAULT '0',\n                    PRIMARY KEY `id` (`id`),\n                    KEY `userid_elluminateid` (`userid`, `elluminateid`)\n                )\n            ");
        }
        /*
                if ($result) {
                    $result = modify_database('', "
                        CREATE TABLE `prefix_event_reminder` (
                            `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
                            `event` INT(10) UNSIGNED NOT NULL DEFAULT '0',
                            `type` INT(1) UNSIGNED NOT NULL DEFAULT '0',
                            `timedelta` INT(10) UNSIGNED NOT NULL DEFAULT '0',
                            `timeinterval` INT(10) UNSIGNED NOT NULL DEFAULT '0',
                            `timeend` INT(10) UNSIGNED NOT NULL DEFAULT '0',
                            PRIMARY KEY(`id`)
                        );
                    ");
                }
        */
    }
    if ($oldversion < 2006062101) {
        $result = table_column('elluminate_users', '', 'elm_username', 'VARCHAR', '50', '', '', 'NOT NULL', 'elm_id');
    }
    if ($oldversion < 2006062102) {
        $result = table_column('elluminate', '', 'seats', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'meetingid');
    }
    return $result;
}
示例#15
0
function exercise_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004062300) {
        table_column("exercise", "", "gradinggrade", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "grade");
        table_column("exercise", "", "assessmentcomps", "INTEGER", "4", "UNSIGNED", "2", "NOT NULL", "usemaximum");
    }
    if ($oldversion < 2004090200) {
        table_column("exercise", "", "usepassword", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        table_column("exercise", "", "password", "VARCHAR", "32", "", "", "NOT NULL");
    }
    if ($oldversion < 2004091000) {
        table_column("exercise_assessments", "generalcomment", "generalcomment", "text", "", "", "", "NOT NULL");
        table_column("exercise_assessments", "teachercomment", "teachercomment", "text", "", "", "", "NOT NULL");
    }
    if ($oldversion < 2004100800) {
        include_once "{$CFG->dirroot}/mod/exercise/lib.php";
        exercise_refresh_events();
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}exercise_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}exercise_submissions_exerciseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}exercise_assessments_exerciseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}exercise_rubrics_exerciseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}exercise_grades_exerciseid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_exercise_course_idx ON prefix_exercise (course);');
        modify_database('', 'CREATE INDEX prefix_exercise_submissions_exerciseid_idx ON prefix_exercise_submissions (exerciseid);');
        modify_database('', 'CREATE INDEX prefix_exercise_assessments_exerciseid_idx ON prefix_exercise_assessments (exerciseid);');
        modify_database('', 'CREATE INDEX prefix_exercise_rubrics_exerciseid_idx ON prefix_exercise_rubrics (exerciseid);');
        modify_database('', 'CREATE INDEX prefix_exercise_grades_exerciseid_idx ON prefix_exercise_grades (exerciseid);');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#16
0
function xmldb_core_upgrade($oldversion = 0)
{
    global $SESSION;
    raise_time_limit(120);
    raise_memory_limit('256M');
    $status = true;
    if ($oldversion < 2009022700) {
        // Get rid of all blocks with position 0 caused by 'about me' block on profile views
        if (count_records('block_instance', 'order', 0) && !count_records_select('block_instance', '"order" < 0')) {
            if (is_mysql()) {
                $ids = get_column_sql('
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column)');
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (' . join(',', $ids) . ')');
            } else {
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column))');
            }
            execute_sql('UPDATE {block_instance} SET "order" = 1 WHERE "order" = 0');
            execute_sql('UPDATE {block_instance} SET "order" = -1 * ("order" - 1) WHERE "order" < 0');
        }
    }
    if ($oldversion < 2009031000) {
        reload_html_filters();
    }
    if ($oldversion < 2009031300) {
        $table = new XMLDBTable('institution');
        $expiry = new XMLDBField('expiry');
        $expiry->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $expiry);
        $expirymailsent = new XMLDBField('expirymailsent');
        $expirymailsent->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $expirymailsent);
        $suspended = new XMLDBField('suspended');
        $suspended->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $suspended);
        // Insert a cron job to check for soon expiring and expired institutions
        if (!record_exists('cron', 'callfunction', 'auth_handle_institution_expiries')) {
            $cron = new StdClass();
            $cron->callfunction = 'auth_handle_institution_expiries';
            $cron->minute = '5';
            $cron->hour = '9';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2009031800) {
        // Files can only attach blogpost artefacts, but we would like to be able to attach them
        // to other stuff.  Rename the existing attachment table artefact_blog_blogpost_file to
        // artefact_file_attachment so we don't end up with many tables doing the same thing.
        execute_sql("ALTER TABLE {artefact_blog_blogpost_file} RENAME TO {artefact_attachment}");
        if (is_postgres()) {
            // Ensure all of the indexes and constraints are renamed
            execute_sql("\n            ALTER TABLE {artefact_attachment} RENAME blogpost TO artefact;\n            ALTER TABLE {artefact_attachment} RENAME file TO attachment;\n\n            ALTER INDEX {arteblogblogfile_blofil_pk} RENAME TO {arteatta_artatt_pk};\n            ALTER INDEX {arteblogblogfile_blo_ix} RENAME TO {arteatta_art_ix};\n            ALTER INDEX {arteblogblogfile_fil_ix} RENAME TO {arteatta_att_ix};\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_blo_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY (artefact) REFERENCES {artefact}(id);\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_fil_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY (attachment) REFERENCES {artefact}(id);\n            ");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_blo_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_blo_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE blogpost artefact BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY {arteatta_art_ix} (artefact) REFERENCES {artefact}(id)");
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_fil_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_fil_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE file attachment BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY {arteatta_att_ix} (attachment) REFERENCES {artefact}(id)");
            }
        }
        // Drop the _pending table. From now on files uploaded as attachments will become artefacts
        // straight away.  Hopefully changes to the upload/file browser form will make it clear to
        // the user that these attachments sit in his/her files area as soon as they are uploaded.
        $table = new XMLDBTable('artefact_blog_blogpost_file_pending');
        drop_table($table);
    }
    if ($oldversion < 2009040900) {
        // The view access page has been putting the string 'null' in as a group role in IE.
        set_field('view_access_group', 'role', null, 'role', 'null');
    }
    if ($oldversion < 2009040901) {
        $table = new XMLDBTable('import_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('import_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
        $table = new XMLDBTable('export_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('export_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2009050700) {
        if ($data = check_upgrades('export.html')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('export.leap')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('import.leap')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009051200) {
        // Rename submittedto column to submittedgroup
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} RENAME submittedto TO submittedgroup");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} DROP FOREIGN KEY {view_sub_fk}");
                execute_sql("ALTER TABLE {view} DROP INDEX {view_sub_ix}");
                execute_sql("ALTER TABLE {view} CHANGE submittedto submittedgroup BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_sub_fk} FOREIGN KEY {view_sub_ix} (submittedgroup) REFERENCES {group}(id)");
            }
        }
        // Add submittedhost column for views submitted to remote moodle hosts
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        // Do this manually because xmldb tries to create a key with the same name (view_sub_vk) as an existing one, and fails.
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY (submittedhost) REFERENCES {host}(wwwroot)");
            execute_sql("CREATE INDEX {view_subh_ix} ON {view} (submittedhost)");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY {view_subh_ix} (submittedhost) REFERENCES {host}(wwwroot)");
            }
        }
    }
    if ($oldversion < 2009051201) {
        // Invisible view access keys for roaming moodle teachers
        $table = new XMLDBTable('view_access_token');
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2009052700) {
        // Install a cron job to clean out old exports
        $cron = new StdClass();
        $cron->callfunction = 'export_cleanup_old_exports';
        $cron->minute = '0';
        $cron->hour = '3,13';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009070600) {
        // This was forgotten as part of the 1.0 -> 1.1 upgrade
        if ($data = check_upgrades('blocktype.file/html')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009070700) {
        foreach (array('addfriend', 'removefriend', 'addfriendrequest', 'removefriendrequest') as $eventtype) {
            $event = (object) array('name' => $eventtype);
            ensure_record_exists('event_type', $event, $event);
        }
    }
    if ($oldversion < 2009070900) {
        if (is_mysql()) {
            execute_sql("ALTER TABLE {usr} DROP FOREIGN KEY {usr_las_fk}");
            execute_sql("ALTER TABLE {usr} DROP INDEX {usr_las_ix}");
        }
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastauthinstance');
        drop_field($table, $field);
    }
    if ($oldversion < 2009080600) {
        $table = new XMLDBTable('view');
        $index = new XMLDBIndex('view_own_type_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('owner'));
        if (!index_exists($table, $index)) {
            // Delete duplicate profile views if there are any, then add an index
            // that will prevent it happening again - but only on postgres, as it's
            // the only db that supports partial indexes
            if ($viewdata = get_records_sql_array("\n                SELECT owner, id\n                FROM {view}\n                WHERE owner IN (\n                    SELECT owner\n                    FROM {view}\n                    WHERE type = 'profile'\n                    GROUP BY owner\n                    HAVING COUNT(*) > 1\n                )\n                AND type = 'profile'\n                ORDER BY owner, id", array())) {
                require_once 'view.php';
                $seen = array();
                foreach ($viewdata as $record) {
                    $seen[$record->owner][] = $record->id;
                }
                foreach ($seen as $owner => $views) {
                    // Remove the first one, which is their real profile view
                    array_shift($views);
                    foreach ($views as $viewid) {
                        delete_records('artefact_feedback', 'view', $viewid);
                        delete_records('view_feedback', 'view', $viewid);
                        delete_records('view_access', 'view', $viewid);
                        delete_records('view_access_group', 'view', $viewid);
                        delete_records('view_access_usr', 'view', $viewid);
                        delete_records('view_access_token', 'view', $viewid);
                        delete_records('view_autocreate_grouptype', 'view', $viewid);
                        delete_records('view_tag', 'view', $viewid);
                        delete_records('usr_watchlist_view', 'view', $viewid);
                        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $viewid)) {
                            foreach ($blockinstanceids as $id) {
                                if (table_exists(new XMLDBTable('blocktype_wall_post'))) {
                                    delete_records('blocktype_wall_post', 'instance', $id);
                                }
                                delete_records('view_artefact', 'block', $id);
                                delete_records('block_instance', 'id', $id);
                            }
                        }
                        delete_records('view', 'id', $viewid);
                    }
                }
            }
            if (is_postgres()) {
                execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
            }
        }
    }
    if ($oldversion < 2009080601) {
        execute_sql("DELETE FROM {group_member_invite} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'invite')");
        execute_sql("DELETE FROM {group_member_request} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'request')");
    }
    if ($oldversion < 2009081800) {
        $event = (object) array('name' => 'creategroup');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009082400) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('username');
        drop_field($table, $field);
        $field = new XMLDBField('salt');
        drop_field($table, $field);
        $field = new XMLDBField('password');
        drop_field($table, $field);
    }
    if ($oldversion < 2009082600) {
        $captcha = get_config('captcha_on_contact_form');
        set_config('captchaoncontactform', (int) (is_null($captcha) || $captcha));
        $captcha = get_config('captcha_on_register_form');
        set_config('captchaonregisterform', (int) (is_null($captcha) || $captcha));
    }
    if ($oldversion < 2009090700) {
        set_config('showselfsearchsideblock', 1);
        set_config('showtagssideblock', 1);
        set_config('tagssideblockmaxtags', 20);
    }
    if ($oldversion < 2009092100) {
        if ($data = check_upgrades('import.file')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.creativecommons')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009092900) {
        $event = (object) array('name' => 'deleteartefacts');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009101600) {
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        // Remove bbcode formatting from existing feedback
        if ($records = get_records_sql_array("SELECT * FROM {view_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('view_feedback', $r);
            }
        }
        if ($records = get_records_sql_array("SELECT * FROM {artefact_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('artefact_feedback', $r);
            }
        }
    }
    if ($oldversion < 2009102100) {
        // Now the view_layout table has to have records for all column widths
        $record = (object) array('columns' => 1, 'widths' => '100');
        insert_record('view_layout', $record);
        $record = (object) array('columns' => 5, 'widths' => '20,20,20,20,20');
        insert_record('view_layout', $record);
    }
    if ($oldversion < 2009102200) {
        if (!count_records_select('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'))) {
            insert_record('activity_type', (object) array('name' => 'groupmessage', 'admin' => 0, 'delay' => 0));
        }
    }
    if ($oldversion < 2009102900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('sessionid');
        drop_field($table, $field);
    }
    if ($oldversion < 2009110500) {
        set_config('creategroups', 'all');
    }
    if ($oldversion < 2009110900) {
        // Fix export cronjob so it runs 12 hours apart
        execute_sql("UPDATE {cron} SET hour = '3,15' WHERE callfunction = 'export_cleanup_old_exports'");
        // Cron job to clean old imports
        $cron = new StdClass();
        $cron->callfunction = 'import_cleanup_old_imports';
        $cron->minute = '0';
        $cron->hour = '4,16';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009111200) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailssent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009111201) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailsbounced');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009120100) {
        // Fix for bug in 1.1 => 1.2 upgrade which may have inserted
        // a second groupmessage activity_type record
        $records = get_records_select_array('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'), 'id');
        if ($records && count($records) > 1) {
            for ($i = 1; $i < count($records); $i++) {
                delete_records('activity_queue', 'type', $records[$i]->id);
                delete_records('notification_internal_activity', 'type', $records[$i]->id);
                delete_records('notification_emaildigest_queue', 'type', $records[$i]->id);
                delete_records('usr_activity_preference', 'activity', $records[$i]->id);
                delete_records('activity_type', 'id', $records[$i]->id);
            }
        }
    }
    if ($oldversion < 2009120900) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010011300) {
        // Clean up the mess left behind by failing to delete blogposts in a transaction
        try {
            include_once get_config('docroot') . 'artefact/lib.php';
            if (function_exists('rebuild_artefact_parent_cache_dirty')) {
                rebuild_artefact_parent_cache_dirty();
            }
        } catch (Exception $e) {
            log_debug('Upgrade 2010011300: rebuild_artefact_parent_cache_dirty failed.');
        }
        execute_sql("\n            INSERT INTO {artefact_blog_blogpost} (blogpost)\n            SELECT id FROM {artefact} WHERE artefacttype = 'blogpost' AND id NOT IN (\n                SELECT blogpost FROM {artefact_blog_blogpost}\n            )");
    }
    if ($oldversion < 2010012701) {
        set_config('userscanchooseviewthemes', 1);
    }
    if ($oldversion < 2010021500) {
        if ($data = check_upgrades('blocktype.recentforumposts')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010031000) {
        // For existing sites, preserve current user search behaviour:
        // Users are only searchable by their display names.
        set_config('userscanhiderealnames', 1);
        execute_sql("\n            INSERT INTO {usr_account_preference} (usr, field, value)\n            SELECT u.id, 'hiderealname', 1\n            FROM {usr} u LEFT JOIN {usr_account_preference} p ON (u.id = p.usr AND p.field = 'hiderealname')\n            WHERE NOT u.preferredname IS NULL AND u.preferredname != '' AND p.field IS NULL\n        ");
    }
    if ($oldversion < 2010040700) {
        // Set antispam defaults
        set_config('formsecret', get_random_key());
        if (!function_exists('checkdnsrr')) {
            require_once get_config('docroot') . 'lib/antispam.php';
        }
        if (checkdnsrr('test.uribl.com.black.uribl.com', 'A')) {
            set_config('antispam', 'advanced');
        } else {
            set_config('antispam', 'simple');
        }
        set_config('spamhaus', 0);
        set_config('surbl', 0);
    }
    if ($oldversion < 2010040800) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010041200) {
        delete_records('config', 'field', 'captchaoncontactform');
        delete_records('config', 'field', 'captchaonregisterform');
    }
    if ($oldversion < 2010041201) {
        $sql = "\n            SELECT u.id\n            FROM {usr} u\n            LEFT JOIN {artefact} a\n                ON (a.owner = u.id AND a.artefacttype = 'blog')\n            WHERE u.id > 0\n            GROUP BY u.id\n            HAVING COUNT(a.id) != 1";
        $manyblogusers = get_records_sql_array($sql, array());
        if ($manyblogusers) {
            foreach ($manyblogusers as $u) {
                $where = (object) array('usr' => $u->id, 'field' => 'multipleblogs');
                $data = (object) array('usr' => $u->id, 'field' => 'multipleblogs', 'value' => 1);
                ensure_record_exists('usr_account_preference', $where, $data);
            }
        }
    }
    if ($oldversion < 2010041600 && table_exists(new XMLDBTable('view_feedback'))) {
        // Add author, authorname to artefact table
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('author');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        table_column('artefact', null, 'authorname', 'text', null, null, null, '');
        if (is_postgres()) {
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN authorname DROP DEFAULT");
            set_field('artefact', 'authorname', null);
            execute_sql('UPDATE {artefact} SET authorname = g.name FROM {group} g WHERE "group" = g.id');
            execute_sql("UPDATE {artefact} SET authorname = CASE WHEN institution = 'mahara' THEN ? ELSE i.displayname END FROM {institution} i WHERE institution = i.name", array(get_config('sitename')));
        } else {
            execute_sql("UPDATE {artefact} a, {group} g SET a.authorname = g.name WHERE a.group = g.id");
            execute_sql("UPDATE {artefact} a, {institution} i SET a.authorname = CASE WHEN a.institution = 'mahara' THEN ? ELSE i.displayname END WHERE a.institution = i.name", array(get_config('sitename')));
        }
        execute_sql('UPDATE {artefact} SET author = owner WHERE owner IS NOT NULL');
        execute_sql('ALTER TABLE {artefact} ADD CHECK (
            (author IS NOT NULL AND authorname IS NULL    ) OR
            (author IS NULL     AND authorname IS NOT NULL)
        )');
        // Move feedback activity type to artefact plugin
        execute_sql("\n            UPDATE {activity_type}\n            SET plugintype = 'artefact', pluginname = 'comment'\n            WHERE name = 'feedback'\n        ");
        // Install the comment artefact
        if ($data = check_upgrades('artefact.comment')) {
            upgrade_plugin($data);
        }
        // Flag all views & artefacts to enable/disable comments
        table_column('artefact', null, 'allowcomments', 'integer', 1);
        table_column('view', null, 'allowcomments', 'integer', 1, null, 1);
        // Initially allow comments on blogposts, images, files
        set_field_select('artefact', 'allowcomments', 1, 'artefacttype IN (?,?,?)', array('blogpost', 'image', 'file'));
        // Convert old feedback to comment artefacts
        if ($viewfeedback = get_records_sql_array('
            SELECT f.*, v.id AS viewid, v.owner, v.group, v.institution
            FROM {view_feedback} f JOIN {view} v ON f.view = v.id', array())) {
            foreach ($viewfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onview' => $f->viewid);
                insert_record('artefact_comment_comment', $comment);
                if (!empty($f->attachment)) {
                    insert_record('artefact_attachment', (object) array('artefact' => $aid, 'attachment' => $f->attachment));
                }
            }
        }
        // We are throwing away the view information from artefact_feedback.
        // From now on all artefact comments appear together and are not
        // tied to a particular view.
        if ($artefactfeedback = get_records_sql_array('
            SELECT f.*, a.id AS artefactid, a.owner, a.group, a.institution
            FROM {artefact_feedback} f JOIN {artefact} a ON f.artefact = a.id', array())) {
            foreach ($artefactfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onartefact' => $f->artefactid);
                insert_record('artefact_comment_comment', $comment);
            }
        }
        // Drop feedback tables
        $table = new XMLDBTable('view_feedback');
        drop_table($table);
        $table = new XMLDBTable('artefact_feedback');
        drop_table($table);
        // Add site setting for anonymous comments
        set_config('anonymouscomments', 1);
    }
    if ($oldversion < 2010041900 && !table_exists(new XMLDBTable('site_data'))) {
        // Upgrades for admin stats pages
        // Table for collection of historical stats
        $table = new XMLDBTable('site_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'type'));
        create_table($table);
        // Insert cron jobs to save site data
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
        // Put best guess at installation time into config table.
        set_config('installation_time', get_field_sql("SELECT MIN(ctime) FROM {site_content}"));
        // Save the current time so we know when we started collecting stats
        set_config('stats_installation_time', db_format_timestamp(time()));
        // Add ctime to usr table for daily count of users created
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // Add visits column to view table
        $table = new XMLDBTable('view');
        $field = new XMLDBField('visits');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Add table to store daily view visits
        $table = new XMLDBTable('view_visit');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addIndexInfo('ctimeix', XMLDB_INDEX_NOTUNIQUE, array('ctime'));
        create_table($table);
        // Insert a cron job to check for new versions of Mahara
        $cron = new StdClass();
        $cron->callfunction = 'cron_check_for_updates';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2010042600) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('parent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('parentfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('parent'), 'notification_internal_activity', array('id'));
        add_key($table, $key);
        $field = new XMLDBField('from');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('fromfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('from'), 'usr', array('id'));
        add_key($table, $key);
        // Set from column for old user messages
        $usermessages = get_records_array('notification_internal_activity', 'type', get_field('activity_type', 'id', 'name', 'usermessage'));
        if ($usermessages) {
            foreach ($usermessages as &$m) {
                if (preg_match('/sendmessage\\.php\\?id=(\\d+)/', $m->url, $match)) {
                    set_field('notification_internal_activity', 'from', $match[1], 'id', $m->id);
                }
            }
        }
    }
    if ($oldversion < 2010042602 && !get_record('view_type', 'type', 'dashboard')) {
        insert_record('view_type', (object) array('type' => 'dashboard'));
        if ($data = check_upgrades('blocktype.inbox')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.newviews')) {
            upgrade_plugin($data);
        }
        // Install system dashboard view
        require_once get_config('libroot') . 'view.php';
        $dbtime = db_format_timestamp(time());
        $viewdata = (object) array('type' => 'dashboard', 'owner' => 0, 'numcolumns' => 2, 'ownerformat' => FORMAT_NAME_PREFERREDNAME, 'title' => get_string('dashboardviewtitle', 'view'), 'template' => 1, 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'newviews', 'title' => get_string('title', 'blocktype.newviews'), 'column' => 1, 'config' => array('limit' => 5)), array('blocktype' => 'myviews', 'title' => get_string('title', 'blocktype.myviews'), 'column' => 1, 'config' => null), array('blocktype' => 'inbox', 'title' => get_string('inboxblocktitle'), 'column' => 2, 'config' => array('feedback' => true, 'groupmessage' => true, 'institutionmessage' => true, 'maharamessage' => true, 'usermessage' => true, 'viewaccess' => true, 'watchlist' => true, 'maxitems' => '5')), array('blocktype' => 'inbox', 'title' => get_string('topicsimfollowing'), 'column' => 2, 'config' => array('newpost' => true, 'maxitems' => '5')));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        $weights = array(1 => 0, 2 => 0);
        foreach ($blocktypes as $blocktype) {
            if (in_array($blocktype['blocktype'], $installed)) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010042603) {
        execute_sql('ALTER TABLE {usr} ADD COLUMN showhomeinfo SMALLINT NOT NULL DEFAULT 1');
        set_config('homepageinfo', 1);
    }
    if ($oldversion < 2010042604) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('urltext');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2010051000) {
        set_field('activity_type', 'delay', 1, 'name', 'groupmessage');
    }
    if ($oldversion < 2010052000) {
        $showusers = get_config('showonlineuserssideblock');
        set_config('showonlineuserssideblock', (int) (is_null($showusers) || $showusers));
    }
    if ($oldversion < 2010060300) {
        // Add table to associate users with php session ids
        $table = new XMLDBTable('usr_session');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('session', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('session'));
        $table->addIndexInfo('usrix', XMLDB_INDEX_NOTUNIQUE, array('usr'));
        create_table($table);
    }
    if ($oldversion < 2010061100) {
        set_config('registerterms', 1);
    }
    if ($oldversion < 2010061800) {
        insert_record('view_type', (object) array('type' => 'grouphomepage'));
        if ($data = check_upgrades('blocktype.groupmembers')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupinfo')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupviews')) {
            upgrade_plugin($data);
        }
        $dbtime = db_format_timestamp(time());
        // create a system template for group homepage views
        require_once get_config('libroot') . 'view.php';
        $viewdata = (object) array('type' => 'grouphomepage', 'owner' => 0, 'numcolumns' => 1, 'template' => 1, 'title' => get_string('grouphomepage', 'view'), 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'groupinfo', 'title' => '', 'column' => 1, 'config' => null), array('blocktype' => 'recentforumposts', 'title' => get_string('latestforumposts', 'interaction.forum'), 'column' => 1, 'config' => null), array('blocktype' => 'groupviews', 'title' => get_string('Views', 'view'), 'column' => 1, 'config' => null), array('blocktype' => 'groupmembers', 'title' => get_string('Members', 'group'), 'column' => 1, 'config' => null));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        foreach ($blocktypes as $k => $blocktype) {
            if (!in_array($blocktype['blocktype'], $installed)) {
                unset($blocktypes[$k]);
            }
        }
        $weights = array(1 => 0);
        foreach ($blocktypes as $blocktype) {
            $weights[$blocktype['column']]++;
            insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
        }
        // add a default group homepage view for all groups in the system
        unset($viewdata->owner);
        $viewdata->template = 0;
        if (!($groups = get_records_array('group', '', '', '', 'id,public'))) {
            $groups = array();
        }
        foreach ($groups as $group) {
            $viewdata->group = $group->id;
            $id = insert_record('view', $viewdata, 'id', true);
            insert_record('view_access', (object) array('view' => $id, 'accesstype' => $group->public ? 'public' : 'loggedin'));
            insert_record('view_access_group', (object) array('view' => $id, 'group' => $group->id));
            $weights = array(1 => 0);
            foreach ($blocktypes as $blocktype) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010062502) {
        //new feature feedback control on views
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('allowcomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Add comment approval to view/artefact (default 0)
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table = new XMLDBTable('view');
        add_field($table, $field);
        $table = new XMLDBTable('artefact');
        add_field($table, $field);
        // view_access_(group|usr|token) tables are getting wide with duplicated columns,
        // so just create all the necessary columns in view_access and move stuff there
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null);
        change_field_notnull($table, $field);
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('role');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $field = new XMLDBField('usr');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('token');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Copy data to view_access
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, "group", role, startdate, stopdate)
            SELECT view, NULL, "group", role, startdate, stopdate FROM {view_access_group}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, usr, startdate, stopdate)
            SELECT view, NULL, usr, startdate, stopdate FROM {view_access_usr}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, token, visible, startdate, stopdate)
            SELECT view, NULL, token, visible, startdate, stopdate FROM {view_access_token}');
        // Add foreign keys
        $key = new XMLDBKey('groupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('usrfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        add_key($table, $key);
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        add_index($table, $index);
        // Exactly one of accesstype, group, usr, token must be not null
        execute_sql('ALTER TABLE {view_access} ADD CHECK (
            (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL)
        )');
        // Drop old tables
        $table = new XMLDBTable('view_access_group');
        drop_table($table);
        $table = new XMLDBTable('view_access_usr');
        drop_table($table);
        $table = new XMLDBTable('view_access_token');
        drop_table($table);
        // Insert explicit tutor access records for submitted views
        if (!($submittedviews = get_records_sql_array('
            SELECT v.id, v.submittedgroup, g.grouptype
            FROM {view} v JOIN {group} g ON (v.submittedgroup = g.id AND g.deleted = 0)', array()))) {
            $submittedviews = array();
        }
        $roles = array();
        foreach ($submittedviews as $v) {
            if (!isset($roles[$v->grouptype])) {
                $rs = get_column('grouptype_roles', 'role', 'grouptype', $v->grouptype, 'see_submitted_views', 1);
                $roles[$v->grouptype] = empty($rs) ? array() : $rs;
            }
            foreach ($roles[$v->grouptype] as $role) {
                $accessrecord = (object) array('view' => $v->id, 'group' => $v->submittedgroup, 'role' => $role, 'visible' => 0, 'allowcomments' => 1, 'approvecomments' => 0);
                ensure_record_exists('view_access', $accessrecord, $accessrecord);
            }
        }
    }
    if ($oldversion < 2010070700) {
        $table = new XMLDBTable('group_category');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('category');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('categoryfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('category'), 'group_category', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2010071300) {
        set_config('searchusernames', 1);
    }
    if ($oldversion < 2010071500) {
        reload_html_filters();
    }
    if ($oldversion < 2010071600) {
        if (is_postgres()) {
            // change_field_enum should do this
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends', 'objectionable'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2010071900) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('viewnotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2010081000) {
        // new table collection
        $table = new XMLDBTable('collection');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('navigation', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // new table collection_view
        $table = new XMLDBTable('collection_view');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('view'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
        // Drop unique constraint on token column of view_access
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        drop_index($table, $index);
        $index = new XMLDBIndex('tokenix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('token'));
        add_index($table, $index);
    }
    if ($oldversion < 2010081001) {
        if ($data = check_upgrades('artefact.plans')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.plans/plans')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010081100) {
        if ($data = check_upgrades('blocktype.navigation')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010082000) {
        delete_records_select('config', "field IN ('usersrank', 'groupsrank', 'viewsrank')");
    }
    if ($oldversion < 2010091300) {
        // Cron job missing from installs post 2010041900
        if (!record_exists('cron', 'callfunction', 'cron_check_for_updates')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_check_for_updates';
            $cron->minute = rand(0, 59);
            $cron->hour = rand(0, 23);
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010091500) {
        // Previous version of 2010040800 upgrade created the submittedtime
        // column not null (see bug #638550)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        change_field_notnull($table, $field);
        // Our crappy db is full of redundant data (submittedtime depends on
        // submittedhost or submittedgroup) so it's easy to correct this.
        execute_sql("\n            UPDATE {view} SET submittedtime = NULL\n            WHERE submittedtime IS NOT NULL AND submittedgroup IS NULL AND submittedhost IS NULL");
    }
    if ($oldversion < 2010100702) {
        // Add general notification cleanup cron
        if (!record_exists('cron', 'callfunction', 'cron_clean_internal_activity_notifications')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_clean_internal_activity_notifications';
            $cron->minute = 45;
            $cron->hour = 22;
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010110800) {
        // Encrypt all passwords with no set salt values
        $sql = "SELECT * FROM {usr}\n                WHERE salt IS NULL OR salt = ''";
        if ($passwords = get_records_sql_array($sql, array())) {
            foreach ($passwords as $p) {
                $p->salt = substr(md5(rand(1000000, 9999999)), 2, 8);
                $p->password = sha1($p->salt . $p->password);
                update_record('usr', $p);
            }
        }
    }
    if ($oldversion < 2010122200) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('priority');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        set_field('institution', 'priority', 0, 'name', 'mahara');
    }
    if ($oldversion < 2010122201) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('accessconf');
        $field->setAttributes(XMLDB_TYPE_CHAR, 40, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010122700) {
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('accesstypeix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        add_index($table, $index);
    }
    if ($oldversion < 2011012800) {
        reload_html_filters();
    }
    if ($oldversion < 2011032500) {
        // Uninstall solr plugin; it's moving to contrib until it's fixed up.
        delete_records('search_cron', 'plugin', 'solr');
        delete_records('search_event_subscription', 'plugin', 'solr');
        delete_records('search_config', 'plugin', 'solr');
        delete_records('search_installed', 'name', 'solr');
        $searchplugin = get_config('searchplugin');
        if ($searchplugin == 'solr') {
            set_config('searchplugin', 'internal');
        }
    }
    if ($oldversion < 2011041800) {
        // Remove titles from system dashboard, group homepage blocks, so new users/groups
        // get blocks with automatically generated, translatable default titles.
        $systemdashboard = get_field('view', 'id', 'owner', 0, 'type', 'dashboard');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('newviews','myviews','inbox')", array($systemdashboard));
        $systemgrouphomepage = get_field('view', 'id', 'owner', 0, 'type', 'grouphomepage');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('recentforumposts','groupviews','groupmembers')", array($systemgrouphomepage));
    }
    if ($oldversion < 2011042000) {
        // Create empty variables in database for email configuration
        set_config('smtphosts', '');
        set_config('smtpport', '');
        set_config('smtpuser', '');
        set_config('smtppass', '');
        set_config('smtpsecure', '');
        $SESSION->add_info_msg('Email settings now can be configured via Site settings, however they may be overriden by those set in the config file. If you have no specific reason to use config file email configuration, please consider moving them to Site settings area.');
    }
    if ($oldversion < 2011050300) {
        if (get_config('httpswwwroot')) {
            // Notify users about httpswwwroot removal if it is still set
            $SESSION->add_info_msg('HTTPS logins have been deprecated, you need to remove the httpswwwroot variable from config file and switch your wwwroot to https so that the whole site is served over HTTPS.<br>See <a href="https://bugs.launchpad.net/mahara/+bug/646713">https://bugs.launchpad.net/mahara/+bug/646713</a> for more details.', 0);
        }
    }
    if ($oldversion < 2011050600) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('username');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        // This drops the unique index on the username column in postgres.
        // See upgrade 2011051800.
        change_field_precision($table, $field);
    }
    if ($oldversion < 2011051700) {
        // Create new "external" category
        insert_record('blocktype_category', (object) array('name' => 'external'));
        // Migrate existing blocktypes to the new category
        set_field('blocktype_installed_category', 'category', 'external', 'category', 'feeds');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'externalvideo');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'googleapps');
        // Delete old "feeds" category
        delete_records('blocktype_category', 'name', 'feeds');
    }
    if ($oldversion < 2011051800) {
        // Restore index that may be missing due to upgrade 2011050600.
        $table = new XMLDBTable('usr');
        $index = new XMLDBIndex('usr_use_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
        if (!index_exists($table, $index)) {
            if (is_postgres()) {
                // For postgres, create the index on the lowercase username, the way it's
                // done in core_postinst().
                execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
            } else {
                $index = new XMLDBIndex('usernameuk');
                $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
                add_index($table, $index);
            }
        }
    }
    if ($oldversion < 2011052300) {
        if ($data = check_upgrades("blocktype.googleapps")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011061100) {
        // This block fixes an issue of upgrading from 1.4_STABLE to master
        // version number is date after 1.4_STABLE
        // 2011052400
        // add_field checks if field exists
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // 2011053100
        // add_field checks if field exists
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('defaultquota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        // 2011053101
        // add_field checks if field exists
        $table = new XMLDBTable('group');
        $field = new XMLDBField('quota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('quotaused');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060700
        // add_field checks if field exists
        $table = new XMLDBTable('view');
        $field = new XMLDBField('retainview');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060701
        // site setting to limit online users count
        if (!get_config('onlineuserssideblockmaxusers')) {
            set_config('onlineuserssideblockmaxusers', 10);
        }
        // 2011060701
        // add_field checks if field exists
        // instiutional setting to limit online users type
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('showonlineusers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 2);
        add_field($table, $field);
    }
    if ($oldversion < 2011061300) {
        // Add more indexes to the usr table for user searches
        if (is_postgres()) {
            $table = new XMLDBTable('usr');
            $index = new XMLDBIndex('usr_fir_ix');
            $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('firstname', 'lastname', 'preferredname', 'studentid', 'email'));
            if (!index_exists($table, $index)) {
                execute_sql('CREATE INDEX {usr_fir_ix} ON {usr}(LOWER(firstname))');
                execute_sql('CREATE INDEX {usr_las_ix} ON {usr}(LOWER(lastname))');
                execute_sql('CREATE INDEX {usr_pre_ix} ON {usr}(LOWER(preferredname))');
                execute_sql('CREATE INDEX {usr_stu_ix} ON {usr}(LOWER(studentid))');
                execute_sql('CREATE INDEX {usr_ema_ix} ON {usr}(LOWER(email))');
            }
        }
    }
    if ($oldversion < 2011061400) {
        // Add institution to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add shortname to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('shortnameuk');
        $index->setAttributes(XMLDB_KEY_UNIQUE, array('institution', 'shortname'));
        add_index($table, $index);
    }
    if ($oldversion < 2011061500) {
        // Add favourites
        $table = new XMLDBTable('favorite');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('ownershortuk', XMLDB_INDEX_UNIQUE, array('owner', 'shortname'));
        create_table($table);
        $table = new XMLDBTable('favorite_usr');
        $table->addFieldInfo('favorite', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('favorite,usr'));
        $table->addKeyInfo('favoritefk', XMLDB_KEY_FOREIGN, array('favorite'), 'favorite', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062100) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('allowinstitutionpublicviews');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2011062200) {
        $table = new XMLDBTable('usr_tag');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('usr', 'tag'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062300) {
        // Install a cron job to generate the sitemap
        if (!record_exists('cron', 'callfunction', 'cron_sitemap_daily')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_sitemap_daily';
            $cron->minute = '0';
            $cron->hour = '1';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2011062400) {
        // self-registration per institution confrimation setting
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerconfirm');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('pending');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('reason');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2011062700) {
        set_config('dropdownmenu', 0);
    }
    if ($oldversion < 2011070500) {
        // Add profileicon foreign key to artefact table, first clearing any bad profileicon
        // values out of usr.
        execute_sql("\n            UPDATE {usr} SET profileicon = NULL\n            WHERE NOT profileicon IN (SELECT id FROM {artefact} WHERE artefacttype = 'profileicon')");
        $table = new XMLDBTable('usr');
        $key = new XMLDBKey('profileiconfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('profileicon'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011070501) {
        // Add logo to institution table
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('logo');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('logofk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('logo'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011072200) {
        if (is_postgres()) {
            execute_sql("\n                UPDATE {group}\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    quotaused = f.quotaused\n                FROM (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                WHERE {group}.id = f.id");
        } else {
            execute_sql("\n                UPDATE {group}, (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    {group}.quotaused = f.quotaused\n                WHERE {group}.id = f.id");
        }
    }
    if ($oldversion < 2011072600) {
        // Add tables to store custom institution styles
        // Currently only institutions can use them, but merge this with skin tables later...
        $table = new XMLDBTable('style');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('css', XMLDB_TYPE_TEXT);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('style_property');
        $table->addFieldInfo('style', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('style', 'field'));
        $table->addKeyInfo('stylefk', XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        create_table($table);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('style');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('stylefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011082200) {
        // Doing a direct insert of the new artefact type instead of running upgrade_plugin(), in order to support the
        // transition from old profile fields to the new socialprofile artefact in Mahara 1.10
        if (!record_exists('artefact_installed_type', 'name', 'html', 'plugin', 'internal')) {
            insert_record('artefact_installed_type', (object) array('name' => 'html', 'plugin' => 'internal'));
        }
        // Move the textbox blocktype into artefact/internal
        set_field('blocktype_installed', 'artefactplugin', 'internal', 'name', 'textbox');
        if ($data = check_upgrades("blocktype.internal/textbox")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011082300) {
        // Add institution to view_access table
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
            // Add foreign key
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            if (is_postgres()) {
                // Update constraint checks
                execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {view_access_check}');
                execute_sql('ALTER TABLE {view_access} ADD CHECK (
                    (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NOT NULL))');
            } else {
                // MySQL doesn't support these types of constraints
            }
        }
    }
    if ($oldversion < 2011082400) {
        // Add cron entry for cache cleanup
        $cron = new StdClass();
        $cron->callfunction = 'file_cleanup_old_cached_files';
        $cron->minute = '0';
        $cron->hour = '1';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011082401) {
        // Set config value for logged-in profile view access
        set_config('loggedinprofileviewaccess', 1);
    }
    if ($oldversion < 2011083000) {
        // Jointype changes
        $table = new XMLDBTable('group');
        $field = new XMLDBField('request');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('group', 'request', 1, 'jointype', 'request');
        // Turn all request & invite groups into the 'approve' type
        $field = new XMLDBField('jointype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'request', 'invite', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        set_field('group', 'jointype', 'approve', 'jointype', 'request');
        set_field('group', 'jointype', 'approve', 'jointype', 'invite');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        // Move view submission from grouptype to group
        $field = new XMLDBField('submittableto');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        execute_sql("UPDATE {group} SET submittableto = 1 WHERE grouptype IN (SELECT name FROM {grouptype} WHERE submittableto = 1)");
        $table = new XMLDBTable('grouptype');
        $field = new XMLDBField('submittableto');
        drop_field($table, $field);
        // Any group can potentially take submissions, so make sure someone can assess them
        set_field('grouptype_roles', 'see_submitted_views', 1, 'role', 'admin');
        // Move group view editing permission from grouptype_roles to the group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editroles');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('all', 'notmember', 'admin'), 'all');
        add_field($table, $field);
        execute_sql("\n            UPDATE {group} SET editroles = 'notmember' WHERE grouptype IN (\n                SELECT grouptype FROM {grouptype_roles} WHERE role = 'member' AND edit_views = 0\n            )");
        $table = new XMLDBTable('grouptype_roles');
        $field = new XMLDBField('edit_views');
        drop_field($table, $field);
    }
    if ($oldversion < 2011090900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('password');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        change_field_type($table, $field, true, true);
    }
    if ($oldversion < 2011091200) {
        // Locked group views (only editable by group admins)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('locked');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('view', 'locked', 1, 'type', 'grouphomepage');
        // Setting to hide groups from the "Find Groups" listing
        $table = new XMLDBTable('group');
        $field = new XMLDBField('hidden');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members
        $field = new XMLDBField('hidemembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members from members
        $field = new XMLDBField('hidemembersfrommembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to invite friends
        $field = new XMLDBField('invitefriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to recommend the group to friends
        $field = new XMLDBField('suggestfriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2011091300) {
        $table = new XMLDBTable('blocktype_category');
        $field = new XMLDBField('sort');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('0', 'fileimagevideo'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('1', 'blog'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('2', 'general'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('3', 'internal'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('4', 'resume'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('5', 'external'));
        $index = new XMLDBIndex('sortuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('sort'));
        add_index($table, $index, false);
    }
    if ($oldversion < 2011092600) {
        // Move the taggedposts blocktype into artefact/blog/blocktype
        set_field('blocktype_installed', 'artefactplugin', 'blog', 'name', 'taggedposts');
    }
    if ($oldversion < 2011102700) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('logintries');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Every 5 minutes, reset everyone's login attempts to 0
        $cron = new StdClass();
        $cron->callfunction = 'user_login_tries_to_zero';
        $cron->minute = '*/5';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011111500) {
        $table = new XMLDBTable('blocktype_installed_category');
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('blocktype'));
        add_key($table, $key);
    }
    if ($oldversion < 2011120200) {
        if ($data = check_upgrades('blocktype.blog/taggedposts')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.watchlist')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2012011300) {
        $table = new XMLDBTable('group_member');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
    }
    if ($oldversion < 2012021000) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('unread');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012021700) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012022100) {
        reload_html_filters();
    }
    if ($oldversion < 2012042600 && !table_exists(new XMLDBTable('iframe_source'))) {
        // Tables for configurable safe iframe sources
        $table = new XMLDBTable('iframe_source_icon');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('domain', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $iframedomains = array('YouTube' => 'www.youtube.com', 'Vimeo' => 'vimeo.com', 'SlideShare' => 'www.slideshare.net', 'Glogster' => 'www.glogster.com', 'WikiEducator' => 'wikieducator.org', 'Voki' => 'voki.com');
        foreach ($iframedomains as $name => $domain) {
            insert_record('iframe_source_icon', (object) array('name' => $name, 'domain' => $domain));
        }
        $table = new XMLDBTable('iframe_source');
        $table->addFieldInfo('prefix', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('prefix'));
        $table->addKeyInfo('namefk', XMLDB_KEY_FOREIGN, array('name'), 'iframe_source_icon', array('name'));
        create_table($table);
        $iframesources = array('www.youtube.com/embed/' => 'YouTube', 'player.vimeo.com/video/' => 'Vimeo', 'www.slideshare.net/slideshow/embed_code/' => 'SlideShare', 'www.glogster.com/glog/' => 'Glogster', 'www.glogster.com/glog.php' => 'Glogster', 'edu.glogster.com/glog/' => 'Glogster', 'edu.glogster.com/glog.php' => 'Glogster', 'wikieducator.org/index.php' => 'WikiEducator', 'voki.com/php/' => 'Voki');
        foreach ($iframesources as $prefix => $name) {
            insert_record('iframe_source', (object) array('prefix' => $prefix, 'name' => $name));
        }
        $iframeregexp = '%^https?://(' . str_replace('.', '\\.', implode('|', array_keys($iframesources))) . ')%';
        set_config('iframeregexp', $iframeregexp);
    }
    if ($oldversion < 2012042800) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('extra');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2012051500) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('authtype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
        $key = new XMLDBKey('authtype');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('authtype'), 'auth_installed', array('name'));
        add_key($table, $key);
    }
    if ($oldversion < 2012053100) {
        // Clean url fields for usr, group, and view tables.
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('view');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid', 'owner', 'group', 'institution'));
        add_index($table, $index);
    }
    if ($oldversion < 2012060100) {
        // Collection submission
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedgroup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $key = new XMLDBKey('submittedgroupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedgroup'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('submittedhostfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedhost'), 'host', array('wwwroot'));
        add_key($table, $key);
    }
    if ($oldversion < 2012062900) {
        // Add site registration data tables
        $table = new XMLDBTable('site_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('site_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'site_registration', array('id'));
        create_table($table);
    }
    if ($oldversion < 2012062901) {
        // Add institution registration data tables
        $table = new XMLDBTable('institution_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        $table = new XMLDBTable('institution_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'institution_registration', array('id'));
        create_table($table);
        // Install a cron job to collection institution registration data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_registration_data';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = rand(0, 6);
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012062902) {
        // Add institution stats table
        $table = new XMLDBTable('institution_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'institution', 'type'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        // Insert cron jobs to save institution data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012070200) {
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('owner');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        change_field_notnull($table, $field);
        // For PostgresSQL, change_field_notnull of $field=owner with precision = 10 BIGINT(10)
        // will add a temporary column, move data from owner column, remove the column 'owner'
        // and then rename the temporary column to 'owner'. Therefore, all indexes and foreign keys
        // related to column 'owner' will be removed
        if (is_postgres()) {
            $key = new XMLDBKey('owner');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
            add_key($table, $key);
        }
        $key = new XMLDBKey('group');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('institution');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add constraints
        execute_sql('ALTER TABLE {collection} ADD CHECK (
            (owner IS NOT NULL AND "group" IS NULL     AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NOT NULL AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NULL     AND institution IS NOT NULL)
        )');
    }
    if ($oldversion < 2012070300) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('groupparticipationreports');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012080200) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'\n            AND u.password NOT LIKE '\$%'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012080300) {
        // For multi-tokens we need '|' aka pipe characters either side of their old single token
        execute_sql('UPDATE {usr_account_preference} SET value = \'|\' || value || \'|\'
                            WHERE field=\'mobileuploadtoken\' AND NOT value ' . db_ilike() . '\'|%|\'');
    }
    if ($oldversion < 2012080600) {
        // Every minute, poll an imap mailbox to see if there are new mail bounces
        $cron = new StdClass();
        $cron->callfunction = 'check_imap_for_bounces';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012080601) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editwindowstart');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $field = new XMLDBField('editwindowend');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
    }
    if ($oldversion < 2013011700) {
        set_config('defaultregistrationexpirylifetime', 1209600);
    }
    if ($oldversion < 2013012100) {
        $event = (object) array('name' => 'loginas');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2013012101) {
        $table = new XMLDBTable('event_log');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('realusr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('data', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('realusrfk', XMLDB_KEY_FOREIGN, array('realusr'), 'usr', array('id'));
        create_table($table);
        $cron = new StdClass();
        $cron->callfunction = 'cron_event_log_expire';
        $cron->minute = 7;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2013020500) {
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('license');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensor');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensorurl');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('licensedefault');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensemandatory');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('artefact_license');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('icon', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
    }
    if ($oldversion < 2013020501) {
        require_once 'license.php';
        install_licenses_default();
    }
    if ($oldversion < 2013032202) {
        require_once get_config('libroot') . 'license.php';
        set_field('usr_account_preference', 'value', LICENSE_INSTITUTION_DEFAULT, 'field', 'licensedefault', 'value', '-');
    }
    if ($oldversion < 2013050700) {
        $table = new XMLDBTable('collection_tag');
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('collection', 'tag'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013062600) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('dropdownmenu');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2013081400) {
        // We've made a change to how update_safe_iframe_regex() generates the regex
        // Call this function to make sure the stored value reflects that change.
        update_safe_iframe_regex();
    }
    if ($oldversion < 2013082100) {
        log_debug('Update database for flexible page layouts feature');
        log_debug('1. Create table view_rows_columns');
        $table = new XMLDBTable('view_rows_columns');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        log_debug('2. Remake the table view_layout as view_layout_columns');
        $table = new XMLDBTable('view_layout_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('widths', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('columnwidthuk', XMLDB_KEY_UNIQUE, array('columns', 'widths'));
        create_table($table);
        log_debug('3. Alter table view_layout');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('rows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $field = new XMLDBField('iscustom');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('layoutmenuorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug('4. Create table view_layout_rows_columns');
        $table = new XMLDBTable('view_layout_rows_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('viewlayout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('rowfk', XMLDB_KEY_FOREIGN, array('viewlayout'), 'view_layout', array('id'));
        $table->addKeyInfo('columnsfk', XMLDB_KEY_FOREIGN, array('columns'), 'view_layout_columns', array('id'));
        create_table($table);
        log_debug('5. Create table usr_custom_layout');
        $table = new XMLDBTable('usr_custom_layout');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('layout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('layoutfk', XMLDB_KEY_FOREIGN, array('layout'), 'view_layout', array('id'));
        create_table($table);
        log_debug('6. Convert existing view_layout records into new-style view_layouts with just one row');
        $oldlayouts = get_records_array('view_layout', '', '', 'id', 'id, columns, widths');
        foreach ($oldlayouts as $layout) {
            // We don't actually need to populate the "rows", "iscustom" or "layoutmenuorder" columns,
            // because their defaults take care of that.
            // Check to see if there's a view_layout_columns record that matches its widths.
            $colsid = get_field('view_layout_columns', 'id', 'widths', $layout->widths);
            if (!$colsid) {
                $colsid = insert_record('view_layout_columns', (object) array('columns' => $layout->columns, 'widths' => $layout->widths), 'id', true);
            }
            // Now insert a record for it in view_layout_rows_columns, to represent its one row
            insert_record('view_layout_rows_columns', (object) array('viewlayout' => $layout->id, 'row' => 1, 'columns' => $colsid));
            // And also it needs a record in usr_custom_layout saying it belongs to the root user
            insert_record('usr_custom_layout', (object) array('usr' => 0, 'layout' => $layout->id));
        }
        log_debug('7. Drop the obsolete view_layout.columns and view_layout.widths fields');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('columns');
        drop_field($table, $field);
        $field = new XMLDBField('widths');
        drop_field($table, $field);
        log_debug('8. Update default values for tables view_layout, view_layout_columns and view_layout_rows_columns');
        install_view_layout_defaults();
        log_debug('9. Update the table "block_instance"');
        $table = new XMLDBTable('block_instance');
        $field = new XMLDBField('row');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        // This one tends to take a while...
        set_time_limit(30);
        add_field($table, $field);
        set_time_limit(30);
        // Refactor the block_instance.viewcolumnorderuk key so it includes row.
        $key = new XMLDBKey('viewcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'column', 'order'));
        // If this particular site has been around since before Mahara 1.2, this
        // will actually have been created as a unique index rather than a unique
        // key, so check for that first.
        $indexname = find_index_name($table, $key);
        if (preg_match('/uix$/', $indexname)) {
            $index = new XMLDBIndex($indexname);
            $index->setAttributes(XMLDB_INDEX_UNIQUE, array('view', 'column', 'order'));
            drop_index($table, $index);
        } else {
            drop_key($table, $key);
        }
        $key = new XMLDBKey('viewrowcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'row', 'column', 'order'));
        add_key($table, $key);
        log_debug('10. Add a "numrows" column to the views table.');
        // The default value of "1" will be correct
        // for all existing views, because they're using the old one-row layout style
        $table = new XMLDBTable('view');
        $field = new XMLDBField('numrows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        log_debug('11. Update the table "view_rows_columns" for existing pages');
        execute_sql('INSERT INTO {view_rows_columns} ("view", "row", "columns") SELECT v.id, 1, v.numcolumns FROM {view} v');
    }
    if ($oldversion < 2013091900) {
        // Create skin table...
        $table = new XMLDBTable('skin');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 10, 'private', XMLDB_NOTNULL);
        $table->addFieldInfo('viewskin', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('bodybgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('viewbgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // Create skin_favorites table...
        $table = new XMLDBTable('skin_favorites');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('user', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('favorites', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userfk', XMLDB_KEY_FOREIGN, array('user'), 'usr', array('id'));
        create_table($table);
        // Create skin_fonts table...
        $table = new XMLDBTable('skin_fonts');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('licence', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('notice', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('previewfont', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('variants', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('fonttype', XMLDB_TYPE_CHAR, 10, 'site', XMLDB_NOTNULL);
        $table->addFieldInfo('onlyheading', XMLDB_TYPE_INTEGER, 1, 0, XMLDB_NOTNULL);
        $table->addFieldInfo('fontstack', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('genericfont', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('cursive', 'fantasy', 'monospace', 'sans-serif', 'serif'));
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('nameuk', XMLDB_KEY_UNIQUE, array('name'));
        create_table($table);
        // Set column 'skin' to 'view' table...
        $table = new XMLDBTable('view');
        $field = new XMLDBField('skin');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        require_once get_config('libroot') . 'skin.php';
        install_skins_default();
    }
    if ($oldversion < 2013091901) {
        // Add a "skins" table to institutions to record whether they've enabled skins or not
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('skins');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1, 'dropdownmenu');
        add_field($table, $field);
    }
    if ($oldversion < 2013092300) {
        $table = new XMLDBTable('import_entry_requests');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('importid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryparent', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('strategy', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ownerid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytype', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytitle', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrycontent', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('duplicateditemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('existingitemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('artefactmapping', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('decision', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('owneridfk', XMLDB_KEY_FOREIGN, array('ownerid'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013092600) {
        //  When uploading file as attachment and attaching it to an artefact, the artefact id
        //  (in artefact field) and uploaded file artefact id (in attachment filed) are stored.
        //  For Resume composite types (educationhistory, employmenthistory, books, etc.) this
        //  is not enough. So we have to add item field to differentiate between e.g. different
        //  employments in employmenhistory and to which employment the user actually whishes to
        //  attach certain attachment...
        $table = new XMLDBTable('artefact_attachment');
        $field = new XMLDBField('item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
    }
    if ($oldversion < 2013112100) {
        // Add a new column 'last_processed_userid' to the table 'activity_queue' in order to
        // split multiple user activity notifications into chunks
        $table = new XMLDBTable('activity_queue');
        $field = new XMLDBField('last_processed_userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('last_processed_useridfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('last_processed_userid'), 'usr', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2013112600) {
        // If a mahara site was upgraded from 1.0 then keys for the following tables
        // may be missing so we will check for them and if missing add them.
        // Normally when we create a foreign key, we create an index alongside it.
        // If these keys were created by the 1.1 upgrade script, they will be missing
        // those indexes. To get the index and the key in place, we have to re-create
        // the key.
        $table = new XMLDBTable('artefact_access_usr');
        $index = new XMLDBIndex('usrfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('usr'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.usr column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('usrfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.usr referencing usr.id (the column probably contains some nonexistent user id's");
            }
        }
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.artefact referencing artefact.id (the column probably contains some nonexistent artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('usr', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_usr across columns (usr, artefact). (Probably the table contains some non-unique values in those columns)");
            }
        }
        $table = new XMLDBTable('artefact_access_role');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_role.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_role.artefact referencing artefact.id (the column probably contains some nonexistente artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('role', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_role across columns (role, artefact). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('artefact_attachment');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            try {
                add_index($table, $index);
            } catch (SQLException $e) {
                log_warn("Couldn't set a non-unique index on column artefact_attachment.artefact");
            }
        }
        $table = new XMLDBTable('group');
        $key = new XMLDBKey('grouptypefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column group.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes)");
            }
        }
        $table = new XMLDBTable('grouptype_roles');
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column grouptype_roles.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('grouptype', 'role'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table grouptype_roles across columns (grouptype, role). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('view_autocreate_grouptype');
        $index = new XMLDBIndex('viewfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('view'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('view');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change column view_autocreate_grouptype.view to NOT NULL (probably the column contains some NULL values)");
            }
            $key = new XMLDBKey('viewfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.view referencing view.id (probably the column contains some nonexistent view IDs");
            }
        }
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.grouptype referencing grouptype.name (probably the column contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('view', 'grouptype'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table view_autocreate_grouptype across columns (view, grouptype). (Probably those columns contain some non-unique values.)");
            }
        }
    }
    if ($oldversion < 2013121300) {
        // view_rows_columns can be missing the 'id' column if upgrading from version
        // earlier than v1.8 and because we are adding a sequential primary column after
        // the table is already made we need to
        // - check that the column doesn't exist then add it without key or sequence
        // - update the values for the new id column to be sequential
        // - then add the primary key and finally make the column sequential
        if ($records = get_records_sql_array('SELECT * FROM {view_rows_columns}', array())) {
            if (empty($records[0]->id)) {
                $table = new XMLDBTable('view_rows_columns');
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'view');
                add_field($table, $field);
                $x = 1;
                foreach ($records as $record) {
                    execute_sql('UPDATE {view_rows_columns} SET id = ? WHERE view = ? AND row = ? AND columns = ?', array($x, $record->view, $record->row, $record->columns));
                    $x++;
                }
                // we can't add a sequence on a field unless it has a primary key
                $key = new XMLDBKey('primary');
                $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                add_key($table, $key);
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
                change_field_type($table, $field);
                // but when we change field type postgres drops the keys for the column so we need
                // to add the primary key back again - see line 2205 for more info
                if (is_postgres()) {
                    $key = new XMLDBKey('primary');
                    $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                    add_key($table, $key);
                }
            }
        }
    }
    if ($oldversion < 2014010700) {
        // If the usr_custom_layout.group column exists, it indicates that we this patch has already
        // been run and we should skip it.
        $table = new XMLDBTable('usr_custom_layout');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
        if (!field_exists($table, $field)) {
            // Add a log output line here so that we can tell whether this patch ran or not.
            log_debug('Correcting custom layout table structures.');
            // fix issue where custom layouts saved in groups, site pages and institutions
            // were set to have usr = 0 because view owner was null
            $table = new XMLDBTable('usr_custom_layout');
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
            change_field_notnull($table, $field);
            // For PostgresSQL, change_field_notnull creates a temporary column, moves data to new temp column
            // and then renames the temp column to 'usr'. Therefore, all indexes and foreign keys
            // related to column 'owner' will be removed
            if (is_postgres()) {
                $key = new XMLDBKey('usr');
                $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
                add_key($table, $key);
            }
            $field = new XMLDBField('group');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
            add_field($table, $field);
            $key = new XMLDBKey('groupfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
            add_key($table, $key);
            $field = new XMLDBField('institution');
            $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null, 'group');
            add_field($table, $field);
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            // update previous records
            // get custom layouts with usr = 0 which are not in default set
            $groupcustomlayouts = get_records_sql_array('SELECT ucl.layout FROM {usr_custom_layout} ucl
                                                         LEFT JOIN {view_layout} vl ON vl.id = ucl.layout
                                                         WHERE usr = 0 AND iscustom = 1
                                                         ORDER BY ucl.id', array());
            if ($groupcustomlayouts != false) {
                foreach ($groupcustomlayouts as $groupcustomlayout) {
                    // find views using this custom layout
                    $views = get_records_array('view', 'layout', $groupcustomlayout->layout, '', 'owner, "group", institution');
                    if ($views != false) {
                        foreach ($views as $view) {
                            if (isset($view->owner)) {
                                // view owned by individual
                                $recordexists = get_record('usr_custom_layout', 'usr', $view->owner, 'layout', $groupcustomlayout->layout);
                                if (!$recordexists) {
                                    // add new record into usr_custom_layout table
                                    $customlayout = new stdClass();
                                    $customlayout->usr = $view->owner;
                                    $customlayout->layout = $groupcustomlayout->layout;
                                    insert_record('usr_custom_layout', $customlayout, 'id');
                                }
                            } else {
                                if (isset($view->group)) {
                                    // view owned by group
                                    $recordexists = get_record('usr_custom_layout', 'group', $view->group, 'layout', $groupcustomlayout->layout);
                                    if (!$recordexists) {
                                        // add new record into usr_custom_layout table
                                        $customlayout = new stdClass();
                                        $customlayout->group = $view->group;
                                        $customlayout->layout = $groupcustomlayout->layout;
                                        insert_record('usr_custom_layout', $customlayout, 'id');
                                    }
                                } else {
                                    if (isset($view->institution)) {
                                        // view owned by group
                                        $recordexists = get_record('usr_custom_layout', 'institution', $view->institution, 'layout', $groupcustomlayout->layout);
                                        if (!$recordexists) {
                                            // add new record into usr_custom_layout table
                                            $customlayout = new stdClass();
                                            $customlayout->institution = $view->institution;
                                            $customlayout->layout = $groupcustomlayout->layout;
                                            insert_record('usr_custom_layout', $customlayout, 'id');
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // now remove this custom layout
                    $removedrecords = delete_records('usr_custom_layout', 'usr', '0', 'layout', $groupcustomlayout->layout);
                }
            }
        }
    }
    if ($oldversion < 2014010800) {
        $table = new XMLDBTable('institution_config');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('instfielduk', XMLDB_INDEX_UNIQUE, array('institution', 'field'));
        create_table($table);
    }
    if ($oldversion < 2014010801) {
        // adding institution column to allow for different site content for each institution
        $table = new XMLDBTable('site_content');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        // resetting the primary key and updating what is currently there to be
        // the 'mahara' institution's site pages
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name'));
        drop_key($table, $key);
        execute_sql("UPDATE {site_content} SET institution = ?", array('mahara'));
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name', 'institution'));
        add_key($table, $key);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // now add the default general pages for each existing institution with the values of
        // the 'mahara' institution. These can them be altered via Administration -> Institutions -> General pages
        $sitecontentarray = array();
        $sitecontents = get_records_array('site_content', 'institution', 'mahara');
        foreach ($sitecontents as $sitecontent) {
            $sitecontentarray[$sitecontent->name] = $sitecontent->content;
        }
        $pages = site_content_pages();
        $now = db_format_timestamp(time());
        $institutions = get_records_array('institution');
        foreach ($institutions as $institution) {
            if ($institution->name != 'mahara') {
                foreach ($pages as $name) {
                    $page = new stdClass();
                    $page->name = $name;
                    $page->ctime = $now;
                    $page->mtime = $now;
                    $page->content = $sitecontentarray[$name];
                    $page->institution = $institution->name;
                    insert_record('site_content', $page);
                    $pageconfig = new stdClass();
                    $pageconfig->institution = $institution->name;
                    $pageconfig->field = 'sitepages_' . $name;
                    $pageconfig->value = 'mahara';
                    insert_record('institution_config', $pageconfig);
                }
            }
        }
    }
    if ($oldversion < 2014021100) {
        // Reset the view's skin value, if the skin does not exist
        execute_sql("UPDATE {view} v SET skin = NULL WHERE v.skin IS NOT NULL AND NOT EXISTS (SELECT id FROM {skin} s WHERE v.skin = s.id)");
    }
    if ($oldversion < 2014021200) {
        // Adding new Creative Commons 4.0 licenses.
        // CC4.0 will be added only if:
        // -- The CC4.0 URL doesn't already exist;
        // -- And CC3.0 hasn't been deleted earlier.
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebysa', 'install');
        $license->shortname = get_string('licenseshortnamebysa', 'install');
        $license->icon = 'license:by-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by/4.0/';
        $license->displayname = get_string('licensedisplaynameby', 'install');
        $license->shortname = get_string('licenseshortnameby', 'install');
        $license->icon = 'license:by.png';
        $version30 = 'http://creativecommons.org/licenses/by/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebynd', 'install');
        $license->shortname = get_string('licenseshortnamebynd', 'install');
        $license->icon = 'license:by-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncsa', 'install');
        $license->shortname = get_string('licenseshortnamebyncsa', 'install');
        $license->icon = 'license:by-nc-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc/4.0/';
        $license->displayname = get_string('licensedisplaynamebync', 'install');
        $license->shortname = get_string('licenseshortnamebync', 'install');
        $license->icon = 'license:by-nc.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncnd', 'install');
        $license->shortname = get_string('licenseshortnamebyncnd', 'install');
        $license->icon = 'license:by-nc-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
    }
    if ($oldversion < 2014022400) {
        // Make sure artefacts are properly locked for submitted views.
        // Can be a problem for older sites
        $submitted = get_records_sql_array("SELECT v.owner FROM {view_artefact} va\n                        LEFT JOIN {view} v on v.id = va.view\n                        LEFT JOIN {artefact} a on a.id = va.artefact\n                        WHERE (v.submittedgroup IS NOT NULL OR v.submittedhost IS NOT NULL)", array());
        if ($submitted) {
            require_once get_config('docroot') . 'artefact/lib.php';
            foreach ($submitted as $record) {
                ArtefactType::update_locked($record->owner);
            }
        }
    }
    if ($oldversion < 2014022600) {
        $table = new XMLDBTable('host');
        $field = new XMLDBField('portno');
        drop_field($table, $field);
    }
    if ($oldversion < 2014032400) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('sendnow');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032500) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('probation');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032600) {
        set_config('watchlistnotification_delay', 20);
        if (!table_exists(new XMLDBTable('watchlist_queue'))) {
            $table = new XMLDBTable('watchlist_queue');
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('block', XMLDB_TYPE_INTEGER, 10, null, false);
            $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('changed_on', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
            $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            $table->addKeyInfo('blockfk', XMLDB_KEY_FOREIGN, array('block'), 'block_instance', array('id'));
            $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            create_table($table);
        }
        // new event type: delete blockinstance
        $e = new stdClass();
        $e->name = 'deleteblockinstance';
        ensure_record_exists('event_type', $e, $e);
        // install the core event subscriptions
        $subs = array(array('event' => 'blockinstancecommit', 'callfunction' => 'watchlist_record_changes'), array('event' => 'deleteblockinstance', 'callfunction' => 'watchlist_block_deleted'), array('event' => 'saveartefact', 'callfunction' => 'watchlist_record_changes'), array('event' => 'saveview', 'callfunction' => 'watchlist_record_changes'));
        foreach ($subs as $sub) {
            ensure_record_exists('event_subscription', (object) $sub, (object) $sub);
        }
        // install the cronjobs...
        $cron = new stdClass();
        $cron->callfunction = 'watchlist_process_notifications';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014032700) {
        // Remove bad data created by the upload user via csv where users in no institution
        // have 'licensedefault' set causing an error
        execute_sql("DELETE FROM {usr_account_preference} WHERE FIELD = 'licensedefault' AND usr IN (\n                        SELECT u.id FROM {usr} u\n                        LEFT JOIN {usr_institution} ui ON ui.usr = u.id\n                        WHERE ui.institution = 'mahara' OR ui.institution is null\n                     )");
    }
    if ($oldversion < 2014040300) {
        // Figure out where the magicdb is, and stick with that.
        require_once get_config('libroot') . 'file.php';
        update_magicdb_path();
    }
    // Add id field and corresponding index to institution table.
    if ($oldversion < 2014040400) {
        $table = new XMLDBTable('institution');
        // Add id field.
        $field = new XMLDBField('id');
        if (!field_exists($table, $field)) {
            // Field.
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'name');
            add_field($table, $field);
            // Update ids.
            $institutions = get_records_array('institution');
            $x = 1;
            foreach ($institutions as $institution) {
                execute_sql('UPDATE {institution} SET id = ? WHERE name = ?', array($x, $institution->name));
                $x++;
            }
            $key = new XMLDBKey('inst_id_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
            add_key($table, $key);
            // Add sequence.
            $field = new XMLDBField('id');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            change_field_type($table, $field);
            // In postgres, keys and indexes are removed when a field is changed ("Add sequence" above), so add the key back.
            if (is_postgres()) {
                $key = new XMLDBKey('inst_id_uk');
                $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
                add_key($table, $key);
            }
        }
    }
    if ($oldversion < 2014041401) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerallowed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, '0');
        change_field_default($table, $field);
    }
    if ($oldversion < 2014041600) {
        // Add allownonemethod and defaultmethod fields to activity_type table.
        $table = new XMLDBTable('activity_type');
        $field = new XMLDBField('allownonemethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 1, 'delay');
        add_field($table, $field);
        $field = new XMLDBField('defaultmethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, 'email', 'allownonemethod');
        add_field($table, $field);
        // Allow null method in usr_activity_preference.
        // Null indicates "none", no record indicates "not yet set" so use the default.
        $table = new XMLDBTable('usr_activity_preference');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        change_field_notnull($table, $field);
    }
    // Add about me block to existing profile template.
    if ($oldversion < 2014043000) {
        $systemprofileviewid = get_field('view', 'id', 'owner', 0, 'type', 'profile');
        // Find out how many blocks already exist.
        $maxorder = get_field_sql('select max("order") from {block_instance} where "view"=? and "row"=? and "column"=?', array($systemprofileviewid, 1, 1));
        // Create the block at the end of the cell.
        require_once get_config('docroot') . 'blocktype/lib.php';
        $aboutme = new BlockInstance(0, array('blocktype' => 'profileinfo', 'title' => get_string('aboutme', 'blocktype.internal/profileinfo'), 'view' => $systemprofileviewid, 'row' => 1, 'column' => 1, 'order' => $maxorder + 1));
        $aboutme->commit();
        // Move the block to the start of the cell.
        require_once get_config('libroot') . 'view.php';
        $view = new View($systemprofileviewid);
        $view->moveblockinstance(array('id' => $aboutme->get('id'), 'row' => 1, 'column' => 1, 'order' => 1));
    }
    if ($oldversion < 2014050901) {
        require_once get_config('docroot') . 'artefact/lib.php';
        // First drop artefact_parent_cache table.
        $table = new XMLDBTable('artefact_parent_cache');
        drop_table($table, true);
        // Remove cron jobs from DB.
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_dirty');
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_complete');
        // Add path field to artefact table.
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '1024', null, null, null, null, null);
        add_field($table, $field);
        // Fill the new field with path data.
        // Set all artefacts to the path they'd have if they have no parent.
        log_debug('Filling in parent artefact paths');
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug('Dropping elasticsearch artefact triggers');
            require_once get_config('docroot') . 'search/elasticsearch/lib.php';
            ElasticsearchIndexing::drop_triggers('artefact');
        }
        $count = 0;
        $limit = 1000;
        $limitsmall = 200;
        $total = count_records_select('artefact', 'path IS NULL AND parent IS NULL');
        for ($i = 0; $i <= $total; $i += $limitsmall) {
            if (is_mysql()) {
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall);
            } else {
                // Postgres can only handle limit in subquery
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE id IN (SELECT id FROM {artefact} WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall . ")");
            }
            $count += $limitsmall;
            if ($count % $limit == 0 || $count >= $total) {
                if ($count > $total) {
                    $count = $total;
                }
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
        $newcount = count_records_select('artefact', 'path IS NULL');
        if ($newcount) {
            $childlevel = 0;
            do {
                $childlevel++;
                $lastcount = $newcount;
                log_debug("Filling in level-{$childlevel} child artefact paths");
                if (is_postgres()) {
                    execute_sql("\n                        UPDATE {artefact}\n                        SET path = p.path || '/' || {artefact}.id\n                        FROM {artefact} p\n                        WHERE\n                            {artefact}.parent=p.id\n                            AND {artefact}.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                } else {
                    execute_sql("\n                        UPDATE\n                            {artefact} a\n                            INNER JOIN {artefact} p\n                            ON a.parent = p.id\n                        SET a.path=p.path || '/' || a.id\n                        WHERE\n                            a.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                }
                $newcount = count_records_select('artefact', 'path IS NULL');
                // There may be some bad records whose paths can't be filled in,
                // so stop looping if the count stops going down.
            } while ($newcount > 0 && $newcount < $lastcount);
            log_debug("Done filling in child artefact paths");
        }
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug("Add triggers back in");
            ElasticsearchIndexing::create_triggers('artefact');
        }
    }
    // Make objectionable independent of view_access page.
    if ($oldversion < 2014060300) {
        log_debug("Create 'objectionable' table.");
        $table = new XMLDBTable('objectionable');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('objecttype', XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL);
        $table->addFieldInfo('objectid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedby', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('report', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('resolvedby', XMLDB_TYPE_INTEGER, 10, null, null);
        $table->addFieldInfo('resolvedtime', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('reporterfk', XMLDB_KEY_FOREIGN, array('reportedby'), 'usr', array('id'));
        $table->addKeyInfo('resolverfk', XMLDB_KEY_FOREIGN, array('resolvedby'), 'usr', array('id'));
        $table->addIndexInfo('objectix', XMLDB_INDEX_NOTUNIQUE, array('objectid', 'objecttype'));
        create_table($table);
        // Migrate data to a new format.
        // Since we don't have report or name of the user, use root ID.
        // Table 'notification_internal_activity' contains data that is
        // not possible to extract in any reasonable way.
        $objectionable = get_records_array('view_access', 'accesstype', 'objectionable');
        db_begin();
        log_debug('Migrating objectionable records to new format');
        if (!empty($objectionable)) {
            $count = 0;
            $limit = 1000;
            $total = count($objectionable);
            foreach ($objectionable as $record) {
                $todb = new stdClass();
                $todb->objecttype = 'view';
                $todb->objectid = $record->view;
                $todb->reportedby = 0;
                $todb->report = '';
                $todb->reportedtime = $record->ctime ? $record->ctime : format_date(time());
                if (!empty($record->stopdate)) {
                    // Since we can't get an ID of a user who resolved an issue, use root ID.
                    $todb->resolvedby = 0;
                    $todb->resolvedtime = $record->stopdate;
                }
                insert_record('objectionable', $todb);
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        // Delete data from 'view_access' table as we don't need it any more.
        delete_records('view_access', 'accesstype', 'objectionable');
        db_commit();
        log_debug("Drop constraint on 'view_access'");
        // Need to run this to avoid contraints problems on Postgres.
        if (is_postgres()) {
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        log_debug("Update 'view_access' accesstype");
        // Update accesstype in 'view_access' not to use 'objectionable'.
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2014060500) {
        log_debug("Add 'artefact_access' table.");
        $table = new XMLDBTable('artefact_access');
        $table->addFieldInfo('artefact', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('accesstype', XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('artefactfk', XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('accesstypeix', XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        create_table($table);
    }
    if ($oldversion < 2014061100) {
        log_debug('Add module related tables');
        $table = new XMLDBTable('module_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('module_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2014062000) {
        log_debug('Fix up auth_clean_expired_password_requests cron');
        $where = array('callfunction' => 'auth_clean_expired_password_requests');
        $data = array('callfunction' => 'auth_clean_expired_password_requests', 'minute' => '5', 'hour' => '0', 'day' => '*', 'month' => '*', 'dayofweek' => '*');
        ensure_record_exists('cron', (object) $where, (object) $data);
    }
    if ($oldversion < 2014062500) {
        log_debug("Add 'feedbacknotify' option to 'group' table");
        require_once get_config('libroot') . 'group.php';
        $table = new XMLDBTable('group');
        $field = new XMLDBField('feedbacknotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, GROUP_ROLES_ALL);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
        }
    }
    if ($oldversion < 2014073100) {
        log_debug('Delete leftover data which are not associated to any institution');
        // Institution collections
        $collectionids = get_column_sql('
            SELECT id
            FROM {collection} c
            WHERE c.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = c.institution)');
        if ($collectionids) {
            require_once get_config('libroot') . 'collection.php';
            $count = 0;
            $limit = 200;
            $total = count($collectionids);
            foreach ($collectionids as $collectionid) {
                $collection = new Collection($collectionid);
                $collection->delete();
                $count++;
                if ($count % $limit == 0) {
                    log_debug("Deleting leftover collections: {$count}/{$total}");
                    set_time_limit(30);
                }
            }
            log_debug("Deleting leftover collections: {$count}/{$total}");
        }
        log_debug('Delete leftover custom layouts / usr registration');
        // Institution custom layouts and registration
        delete_records_sql('
            DELETE FROM {usr_custom_layout}
            WHERE {usr_custom_layout}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_custom_layout}.institution)');
        delete_records_sql('
            DELETE FROM {usr_registration}
            WHERE {usr_registration}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_registration}.institution)');
    }
    if ($oldversion < 2014081900) {
        log_debug("Check blocktype 'text' is installed");
        if ($data = check_upgrades('blocktype.text')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014091600) {
        log_debug('Allow anonymous pages');
        $table = new XMLDBTable('view');
        $field = new XMLDBField('anonymise');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_config('allowanonymouspages', 0);
    }
    if ($oldversion < 2014091800) {
        log_debug("Add 'allowarchives' column to the 'group' table");
        $table = new XMLDBTable('group');
        $field = new XMLDBField('allowarchives');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug("Add 'submittedstatus' column to 'view' table");
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug("Need to update the submitted status for any existing views that are submitted");
        execute_sql('UPDATE {view} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug("Add 'submittedstatus' column to 'collection' table");
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug('Need to update the submitted status for any existing collections that are submitted');
        execute_sql('UPDATE {collection} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug('Adding the export queue / submission tables');
        // Add export queue table - each export is one row.
        $table = new XMLDBTable('export_queue');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('exporttype', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('starttime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('submitter', XMLDB_TYPE_INTEGER, 10);
        // for when the submitter is not the owner
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('submitterfk', XMLDB_KEY_FOREIGN, array('submitter'), 'usr', array('id'));
        create_table($table);
        // Add export queue items table which maps what views/collections/artefacts relate to the queue item.
        $table = new XMLDBTable('export_queue_items');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('exportqueueid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('exportqueuefk', XMLDB_KEY_FOREIGN, array('exportqueueid'), 'export_queue', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        // Add export archive table to hold info that will allow one to download the zip file
        $table = new XMLDBTable('export_archive');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filename', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filetitle', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filepath', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('submission', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Add archived submissions table to hold submission info
        $table = new XMLDBTable('archived_submissions');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('archiveid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('externalhost', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('archivefk', XMLDB_KEY_FOREIGN, array('archiveid'), 'export_archive', array('id'));
        create_table($table);
        // install the cronjob to process export queue
        $cron = new StdClass();
        $cron->callfunction = 'export_process_queue';
        $cron->minute = '*/6';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
        // install the cronjob to clean up deleted archived submissions items
        $cron = new StdClass();
        $cron->callfunction = 'submissions_delete_removed_archive';
        $cron->minute = '15';
        $cron->hour = '1';
        $cron->day = '1';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014092300) {
        log_debug('Add the socialprofile artefacttype');
        // Need to insert directly into the table instead of running upgrade_plugin(), so that we can transition
        // all the old social network artefact types into the new unified socialprofile type before deleting
        // the old types from artefact_installed_type
        insert_record('artefact_installed_type', (object) array('name' => 'socialprofile', 'plugin' => 'internal'));
        // Convert existing messaging types to socialprofile types.
        $oldmessagingfieldsarray = array('icqnumber', 'msnnumber', 'aimscreenname', 'yahoochat', 'skypeusername', 'jabberusername');
        $oldmessagingfields = implode(',', array_map('db_quote', $oldmessagingfieldsarray));
        $sql = "SELECT * FROM {artefact}\n                WHERE artefacttype IN (" . $oldmessagingfields . ")";
        if ($results = get_records_sql_assoc($sql, array())) {
            $count = 0;
            $limit = 1000;
            $total = count($results);
            safe_require('artefact', 'internal');
            foreach ($results as $result) {
                $i = new ArtefactTypeSocialprofile($result->id, (array) $result);
                $i->set('artefacttype', 'socialprofile');
                switch ($result->artefacttype) {
                    case 'aimscreenname':
                        $i->set('note', 'aim');
                        $i->set('description', get_string('aim', 'artefact.internal'));
                        break;
                    case 'icqnumber':
                        $i->set('note', 'icq');
                        $i->set('description', get_string('icq', 'artefact.internal'));
                        break;
                    case 'jabberusername':
                        $i->set('note', 'jabber');
                        $i->set('description', get_string('jabber', 'artefact.internal'));
                        break;
                    case 'msnnumber':
                    case 'skypeusername':
                        // MSN no longer exists and has been replaced by Skype.
                        $i->set('note', 'skype');
                        $i->set('description', get_string('skype', 'artefact.internal'));
                        break;
                    case 'yahoochat':
                        $i->set('note', 'yahoo');
                        $i->set('description', get_string('yahoo', 'artefact.internal'));
                        break;
                }
                $i->set('title', $result->title);
                $i->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        $sql = "SELECT value FROM {search_config} WHERE plugin='elasticsearch' AND field='artefacttypesmap'";
        if ($result = get_field_sql($sql, array())) {
            log_debug('Clean up elasticsearch fields for the old messaging fields');
            $artefacttypesmap_array = explode("\n", $result);
            $elasticsearchartefacttypesmap = array();
            foreach ($artefacttypesmap_array as $key => $value) {
                $tmpkey = explode("|", $value);
                if (count($tmpkey) == 3) {
                    if (!in_array($tmpkey[0], $oldmessagingfieldsarray)) {
                        // we're going to keep this one.
                        $elasticsearchartefacttypesmap[] = $value;
                    }
                }
            }
            // add socialprofile field.
            $elasticsearchartefacttypesmap[] = "socialprofile|Profile|Text";
            // now save the data excluding the old messaging fields.
            set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', implode("\n", $elasticsearchartefacttypesmap));
        }
        log_debug('Delete unused, but still installed artefact types');
        delete_records_select("artefact_installed_type", "name IN (" . $oldmessagingfields . ")");
        log_debug('Install the social profile blocktype so users can see their migrated data');
        if ($data = check_upgrades('blocktype.internal/socialprofile')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014092300) {
        log_debug("Install 'multirecipientnotification' plugin");
        if ($data = check_upgrades('module.multirecipientnotification')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014101300) {
        log_debug("Make sure default notifications are not set to 'none'");
        // Make sure the 'system messages' and 'messages from other users' have a notification method set
        // It was possible after earlier upgrades to set method to 'none'.
        // Also make sure old defaultmethod is respected.
        $activitytypes = get_records_assoc('activity_type');
        foreach ($activitytypes as $type) {
            $type->defaultmethod = get_config('defaultnotificationmethod') ? get_config('defaultnotificationmethod') : 'email';
            if ($type->name == 'maharamessage' || $type->name == 'usermessage') {
                $type->allownonemethod = 0;
            }
            update_record('activity_type', $type);
        }
        // Make sure users have their 'system messages' and 'messages from other users' notification method set
        if ($useractivities = get_records_sql_assoc("SELECT * FROM {activity_type} at, {usr_activity_preference} uap\n                                                     WHERE at.id = uap.activity\n                                                     AND at.name IN ('maharamessage', 'usermessage')\n                                                     AND (method IS NULL OR method = '')", array())) {
            foreach ($useractivities as $activity) {
                $userprefs = new stdClass();
                $userprefs->method = $activity->defaultmethod;
                update_record('usr_activity_preference', $userprefs, array('usr' => $activity->usr, 'activity' => $activity->activity));
            }
        }
    }
    if ($oldversion < 2014101500) {
        log_debug('Place skin fonts in their correct directories');
        if ($fonts = get_records_assoc('skin_fonts', 'fonttype', 'google')) {
            $fontpath = get_config('dataroot') . 'skins/fonts/';
            foreach ($fonts as $font) {
                // if google font is not already in subdir
                if (!is_dir($fontpath . $font->name)) {
                    if (file_exists($fontpath . $font->previewfont)) {
                        // we need to create the subdir and move the file into it
                        $newfontpath = $fontpath . $font->name . '/';
                        check_dir_exists($newfontpath, true, true);
                        rename($fontpath . $font->previewfont, $newfontpath . $font->previewfont);
                        // and move the license file if it exists also
                        if (file_exists($fontpath . $font->licence)) {
                            rename($fontpath . $font->licence, $newfontpath . $font->licence);
                        }
                    } else {
                        // the file is not there for some reason so we might as well delete the font from the db
                        $result = delete_records('skin_fonts', 'name', $font->name);
                        if ($result !== false) {
                            // Check to see if the font is being used in a skin. If it is remove it from
                            // the skin's viewskin data
                            $skins = get_records_array('skin');
                            if (is_array($skins)) {
                                foreach ($skins as $skin) {
                                    $options = unserialize($skin->viewskin);
                                    foreach ($options as $key => $option) {
                                        if (preg_match('/font_family/', $key) && $option == $font->name) {
                                            require_once get_config('docroot') . 'lib/skin.php';
                                            $skinobj = new Skin($skin->id);
                                            $viewskin = $skinobj->get('viewskin');
                                            $viewskin[$key] = false;
                                            $skinobj->set('viewskin', $viewskin);
                                            $skinobj->commit();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($oldversion < 2014101501) {
        log_debug('Unlock root user grouphomepage template in case it is locked');
        set_field('view', 'locked', 0, 'type', 'grouphomepage', 'owner', 0);
    }
    if ($oldversion < 2014110500) {
        log_debug('Add cacheversion and assign random string');
        // Adding cacheversion, as an arbitrary number appended to the end of JS & CSS files in order
        // to tell cacheing software when they've been updated. (Without having to use the Mahara
        // minor version for that purpose.)
        // Set this to a random starting number to make minor version slightly harder to detect
        if (!get_config('cacheversion')) {
            set_config('cacheversion', rand(1000, 9999));
        }
    }
    if ($oldversion < 2014110700) {
        log_debug("Add in 'shortcut' category to 'blocktype_category'");
        // Increment all the existing sorts by 1 to make room...
        $cats = get_records_array('blocktype_category', '', '', 'sort desc');
        foreach ($cats as $cat) {
            $cat->sort = $cat->sort + 1;
            update_record('blocktype_category', $cat, 'name');
        }
        $todb = new stdClass();
        $todb->name = 'shortcut';
        $todb->sort = '0';
        insert_record('blocktype_category', $todb);
    }
    if ($oldversion < 2014112700) {
        log_debug("Fix up group homepages so that no duplicate 'groupview' blocks are present");
        // Need to find the group homepages that have more than one groupview on them
        // and merge their data into one groupview as we shouldn't allow more than one groupview block
        // as it breaks pagination
        // First get any pages that have more than one groupview on them
        // and find the status of the groupview blocks
        if ($records = get_records_sql_array("SELECT v.id AS view, bi.id AS block FROM {view} v\n            INNER JOIN {block_instance} bi ON v.id = bi.view\n            WHERE v.id IN (\n                SELECT v.id FROM {view} v\n                 INNER JOIN {block_instance} bi ON v.id = bi.view\n                 WHERE bi.blocktype = 'groupviews'\n                  AND v.type = 'grouphomepage'\n                 GROUP BY v.id\n                 HAVING COUNT(v.id) > 1\n            )\n            AND bi.blocktype='groupviews'\n            ORDER BY v.id, bi.id", array())) {
            require_once get_config('docroot') . 'blocktype/lib.php';
            $lastview = 0;
            // set default
            $info = array();
            $x = -1;
            foreach ($records as $record) {
                if ($lastview != $record->view) {
                    $x++;
                    $info[$x]['in']['showgroupviews'] = 0;
                    $info[$x]['in']['showsharedviews'] = 0;
                    $info[$x]['in']['view'] = $record->view;
                    $info[$x]['in']['block'] = $record->block;
                    $lastview = $record->view;
                } else {
                    $info[$x]['out'][] = $record->block;
                }
                $bi = new BlockInstance($record->block);
                $configdata = $bi->get('configdata');
                if (!empty($configdata['showgroupviews'])) {
                    $info[$x]['in']['showgroupviews'] = 1;
                }
                if (!empty($configdata['showsharedviews'])) {
                    $info[$x]['in']['showsharedviews'] = 1;
                }
            }
            // now that we have info on the state of play we need to save one of the blocks
            // with correct data and delete the not needed blocks
            $count = 0;
            $limit = 1000;
            $total = count($info);
            foreach ($info as $item) {
                $bi = new BlockInstance($item['in']['block']);
                $configdata = $bi->get('configdata');
                $configdata['showgroupviews'] = $item['in']['showgroupviews'];
                $configdata['showsharedviews'] = $item['in']['showsharedviews'];
                $bi->set('configdata', $configdata);
                $bi->commit();
                foreach ($item['out'] as $old) {
                    $bi = new BlockInstance($old);
                    $bi->delete();
                }
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2014121200) {
        log_debug('Remove layout preview thumbs directory');
        require_once 'file.php';
        $layoutdir = get_config('dataroot') . 'images/layoutpreviewthumbs';
        if (file_exists($layoutdir)) {
            rmdirr($layoutdir);
        }
    }
    if ($oldversion < 2015013000) {
        log_debug("Add a 'sortorder' column to 'blocktype_installed_category'");
        // Add a sortorder column to blocktype_installed_category
        $table = new XMLDBTable('blocktype_installed_category');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 100000, 'category');
        add_field($table, $field);
    }
    if ($oldversion < 2015021000) {
        log_debug('Need to update any dashboard pages to not have skins');
        // and seen as we are updating and selecting from the same table
        // we need to use a temptable for it to work in mysql
        execute_Sql("UPDATE {view} SET skin = NULL WHERE id IN ( SELECT vid FROM (SELECT id AS vid FROM {view} WHERE type = 'dashboard' AND skin IS NOT NULL) AS temptable)");
    }
    if ($oldversion < 2015021900) {
        log_debug('Remove bbcode formatting from existing wall posts');
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        if ($records = get_records_sql_array("SELECT id, text FROM {blocktype_wall_post} WHERE text LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                $r->text = parse_bbcode($r->text);
                update_record('blocktype_wall_post', $r);
            }
        }
    }
    if ($oldversion < 2015030400) {
        log_debug("Update search config settings");
        if (get_config('searchusernames') === 1) {
            set_config('nousernames', 0);
        } else {
            set_config('nousernames', 1);
        }
        delete_records('config', 'field', 'searchusernames');
    }
    if ($oldversion < 2015032600) {
        log_debug("Update block categories for plugins");
        if ($blocktypes = plugins_installed('blocktype', true)) {
            foreach ($blocktypes as $bt) {
                install_blocktype_categories_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
            }
        }
    }
    if ($oldversion < 2015033000) {
        log_debug("Updating TinyMCE emoticon locations in mahara database");
        // Seeing as tinymce has moved the location of the emoticons
        // we need to fix up a few places where users could have added emoticons.
        // $replacements is key = table, value = column
        $replacements = array('view' => 'description', 'artefact' => 'title', 'artefact' => 'description', 'group' => 'description', 'interaction_forum_post' => 'body', 'notification_internal_activity' => 'message', 'blocktype_wall_post' => 'text', 'site_content' => 'content');
        foreach ($replacements as $key => $value) {
            execute_sql("UPDATE {" . $key . "} SET " . $value . " = REPLACE(" . $value . ", '/emotions/img', '/emoticons/img') WHERE " . $value . " LIKE '%/emotions/img%'");
        }
        // we need to handle block_instance configdata in a special way
        if ($results = get_records_sql_array("SELECT id FROM {block_instance} WHERE configdata LIKE '%/emotions/img%'", array())) {
            log_debug("Updating 'block_instance' data for TinyMCE");
            require_once get_config('docroot') . 'blocktype/lib.php';
            $count = 0;
            $limit = 1000;
            $total = count($results);
            foreach ($results as $result) {
                $bi = new BlockInstance($result->id);
                $configdata = $bi->get('configdata');
                foreach ($configdata as $key => $value) {
                    $configdata[$key] = preg_replace('/\\/emotions\\/img/', '/emotions/img', $value);
                }
                $bi->set('configdata', $configdata);
                $bi->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2015041400) {
        log_debug('Force install of annotation and webservices plugins');
        if ($data = check_upgrades('artefact.annotation')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('auth.webservice')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2015042800) {
        log_debug('Clear Dwoo cache of unescaped institution names');
        require_once 'dwoo/dwoo/dwooAutoload.php';
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/view/accesslistrow.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/admin/users/accesslistitem.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
    }
    if ($oldversion < 2015071500) {
        log_debug('Expanding the size of the import_entry_requests.entrycontent column');
        $table = new XMLDBTable('import_entry_requests');
        $field = new XMLDBField('entrycontent');
        $field->setType(XMLDB_TYPE_TEXT);
        $field->setLength('big');
        change_field_precision($table, $field);
    }
    if ($oldversion < 2015072000) {
        // If we are upgrading from a site built before 2014092300 straight to 15.10
        // then the plugin won't exist as an artefact.
        if (table_exists(new XMLDBTable('artefact_multirecipient_userrelation'))) {
            log_debug('Change installation of artefact plugin multirecipentNotification to plugin module.');
            // first, drop the old triggers
            db_drop_trigger('update_unread_insert2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_update2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_delete2', 'artefact_multirecipient_userrelation');
            // rename tables artefact_multirecipientnotifiaction_notification and
            // Table: artefact_multirecipient_userrelation to module-prefix
            execute_sql("ALTER TABLE {artefact_multirecipient_notification} RENAME TO {module_multirecipient_notification}");
            execute_sql("ALTER TABLE {artefact_multirecipient_userrelation} RENAME TO {module_multirecipient_userrelation}");
            if (is_postgres()) {
                // Rename seq artefact_multirecipientnotifiaction_notification_id_seq and
                // artefact_multirecipient_userrelation_id_seq
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_notification_id_seq} RENAME TO {module_multirecipient_notification_id_seq}");
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_userrelation_id_seq} RENAME TO {module_multirecipient_userrelation_id_seq}");
            }
            //move event_subscrition entries for artefact plugin
            //multirecipientnotification to table module_event_subscription
            $subscriptions = get_records_array('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_installed_type', 'plugin', 'multirecipientnotification');
            $installrecord = get_record('artefact_installed', 'name', 'multirecipientnotification');
            if (is_object($installrecord)) {
                insert_record('module_installed', $installrecord);
                delete_records('artefact_installed', 'name', 'multirecipientnotification');
            }
            if (is_array($subscriptions)) {
                foreach ($subscriptions as $subscription) {
                    insert_record('module_event_subscription', $subscription, 'id');
                }
            }
            // recreate trigger
            safe_require('module', 'multirecipientnotification');
            PluginModuleMultirecipientnotification::postinst(0);
        }
    }
    if ($oldversion < 2015081000) {
        log_debug('Add user_login_data table to record when a user logs in');
        $table = new XMLDBTable('usr_login_data');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrloginfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Insert info about current users's logins
        $results = get_records_sql_array("SELECT id,lastlogin FROM {usr} WHERE deleted = 0 AND lastlogin IS NOT NULL");
        $count = 0;
        $limit = 1000;
        $total = count($results);
        foreach ($results as $result) {
            insert_record('usr_login_data', (object) array('usr' => $result->id, 'ctime' => $result->lastlogin));
            $count++;
            if ($count % $limit == 0 || $count == $total) {
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
    }
    if ($oldversion < 2015081700) {
        // In 15.10, we changed the registration site policy.
        // We need to remind the site admins to register the site again with the new policy.
        log_debug('Remind the site admins to register the site again with the new policy');
        if (get_config('new_registration_policy') != -1) {
            set_config('new_registration_policy', true);
        }
        if (get_config('registration_sendweeklyupdates')) {
            set_config('registration_sendweeklyupdates', false);
        }
    }
    if ($oldversion < 2015082500) {
        // Add a site default portfolio page template
        log_debug('Add a site default portfolio page template');
        require_once 'view.php';
        install_system_portfolio_view();
    }
    if ($oldversion < 2015091700) {
        log_debug('Update cached customizable theme CSS');
        $styles = get_records_array('institution', 'theme', 'custom', 'id', 'displayname, style');
        if ($styles) {
            foreach ($styles as $newinstitution) {
                $styleid = $newinstitution->style;
                $properties = array();
                $record = (object) array('style' => $styleid);
                $proprecs = get_records_array('style_property', 'style', $styleid, 'field', 'field, value');
                foreach ($proprecs as $p) {
                    $properties[$p->field] = $p->value;
                }
                // Update the css
                $smarty = smarty_core();
                $smarty->assign('data', $properties);
                set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);
            }
        }
    }
    return $status;
}
示例#17
0
function rss_client_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2005111400) {
        // title and description should be TEXT as we don't have control over their length.
        table_column('block_rss_client', 'title', 'title', 'text');
        table_column('block_rss_client', 'description', 'description', 'text');
    }
    if ($oldversion < 2005090201) {
        modify_database('', 'ALTER TABLE prefix_block_rss_client
            ALTER COLUMN title SET DEFAULT \'\',
            ALTER COLUMN description SET DEFAULT \'\'');
    }
    if ($oldversion < 2006091100) {
        // We need a new field to store whether an RSS feed is shared or private.
        table_column('block_rss_client', '', 'shared', 'integer');
        // Admin feeds used to be displayed to everybody (shared feeds).
        $admins = get_admins();
        if (!empty($admins)) {
            $count = 0;
            foreach ($admins as $admin) {
                if (!$count) {
                    $adminsql = 'userid = ' . $admin->id;
                } else {
                    $adminsql .= ' OR userid = ' . $admin->id;
                }
                $count++;
            }
            if ($rssfeeds = get_records_select('block_rss_client', $adminsql)) {
                foreach ($rssfeeds as $rssfeed) {
                    if (!set_field('block_rss_client', 'shared', 1)) {
                        notice('Could not set ' . $rssfeed->title . ' as a shared RSS feed.');
                    }
                }
            }
        }
    }
    /// see MDL-6707 for more info about problem that was here
    if ($oldversion < 2006100101) {
        // Upgrade block to use the Roles System.
        $block = get_record('block', 'name', 'rss_client');
        if ($blockinstances = get_records('block_instance', 'blockid', $block->id)) {
            if (!($adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW))) {
                notice('Default student role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notice('Default teacher role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notice('Default student role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            foreach ($blockinstances as $bi) {
                $context = get_context_instance(CONTEXT_BLOCK, $bi->id);
                if ($bi->pagetype == 'course-view' && $bi->pageid == SITEID) {
                    // Only the admin was allowed to manage the RSS feed block
                    // on the site home page.
                    // Since this is already the default behavior set in
                    // blocks/rss_client/db/access.php, we don't need to
                    // specifically assign the capabilities here.
                } else {
                    // Who can add shared feeds? This was defined in lib/rsslib.php
                    // for config var block_rss_client_submitters.
                    switch ($CFG->block_rss_client_submitters) {
                        case 0:
                            // SUBMITTERS_ALL_ACCOUNT_HOLDERS
                            foreach ($adminroles as $adminrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $adminrole->id, $context->id);
                            }
                            foreach ($teacherroles as $teacherrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $teacherrole->id, $context->id);
                            }
                            foreach ($studentroles as $studentrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $studentrole->id, $context->id);
                            }
                            break;
                        case 1:
                            // SUBMITTERS_ADMIN_ONLY
                            // Since this is already the default behavior set in
                            // blocks/rss_client/db/access.php, we don't need to
                            // specifically assign the capabilities here.
                            break;
                        case 2:
                            // SUBMITTERS_ADMIN_AND_TEACHER
                            foreach ($adminroles as $adminrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $adminrole->id, $context->id);
                            }
                            foreach ($teacherroles as $teacherrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $teacherrole->id, $context->id);
                            }
                            foreach ($studentroles as $studentrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_PREVENT, $studentrole->id, $context->id);
                            }
                            break;
                    }
                    // End switch.
                }
            }
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#18
0
function assignment_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2002080500) {
        execute_sql("\n        CREATE TABLE `assignment` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `course` int(10) unsigned NOT NULL default '0',\n          `name` varchar(255) NOT NULL default '',\n          `description` text NOT NULL,\n          `type` int(10) unsigned NOT NULL default '1',\n          `maxbytes` int(10) unsigned NOT NULL default '100000',\n          `timedue` int(10) unsigned NOT NULL default '0',\n          `grade` int(10) NOT NULL default '0',\n          `timemodified` int(10) unsigned NOT NULL default '0',\n          PRIMARY KEY  (`id`)\n        ) COMMENT='Defines assignments'\n        ");
        execute_sql("\n        CREATE TABLE `assignment_submissions` (\n          `id` int(10) unsigned NOT NULL default '0',\n          `assignment` int(10) unsigned NOT NULL default '0',\n          `user` 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          `numfiles` int(10) unsigned NOT NULL default '0',\n          `grade` int(11) NOT NULL default '0',\n          `comment` text NOT NULL,\n          `teacher` int(10) unsigned NOT NULL default '0',\n          `timemarked` int(10) unsigned NOT NULL default '0',\n          `mailed` tinyint(1) unsigned NOT NULL default '0',\n          PRIMARY KEY  (`id`)\n        ) COMMENT='Info about submitted assignments'\n        ");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('assignment', 'view', 'assignment', 'name') ");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('assignment', 'add', 'assignment', 'name') ");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('assignment', 'update', 'assignment', 'name') ");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('assignment', 'view submissions', 'assignment', 'name') ");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('assignment', 'upload', 'assignment', 'name') ");
    }
    if ($oldversion < 2002080701) {
        execute_sql(" ALTER TABLE `assignment_submissions` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ");
    }
    if ($oldversion < 2002082806) {
        // assignment file area was moved, so rename all the directories in existing courses
        notify("Moving location of assignment files...");
        $basedir = opendir("{$CFG->dataroot}");
        while (false !== ($dir = readdir($basedir))) {
            if ($dir == "." || $dir == ".." || $dir == "users") {
                continue;
            }
            if (filetype("{$CFG->dataroot}/{$dir}") != "dir") {
                continue;
            }
            $coursedir = "{$CFG->dataroot}/{$dir}";
            if (!($coursemoddata = make_mod_upload_directory($dir))) {
                echo "Error: could not create mod upload directory: {$coursemoddata}";
                continue;
            }
            if (file_exists("{$coursedir}/assignment")) {
                if (!rename("{$coursedir}/assignment", "{$coursemoddata}/assignment")) {
                    echo "Error: could not move {$coursedir}/assignment to {$coursemoddata}/assignment\n";
                }
            }
        }
    }
    if ($oldversion < 2002101600) {
        execute_sql(" ALTER TABLE `assignment` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `description` ");
    }
    if ($oldversion < 2002110302) {
        execute_sql(" UPDATE `assignment` SET `type` = '1'");
    }
    if ($oldversion < 2002111500) {
        execute_sql(" ALTER TABLE `assignment` ADD `resubmit` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `format` ");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `assignment_submissions` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2004021700) {
        set_field("log_display", "action", "view submission", "module", "assignment", "action", "view submissions");
    }
    if ($oldversion < 2004040100) {
        include_once "{$CFG->dirroot}/mod/assignment/lib.php";
        assignment_refresh_events();
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}assignment DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}assignment_submissions DROP INDEX assignment;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}assignment_submissions DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}assignment_submissions DROP INDEX mailed;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}assignment_submissions DROP INDEX timemarked;", false);
        modify_database('', 'ALTER TABLE prefix_assignment ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ADD INDEX assignment(assignment);');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ADD INDEX mailed (mailed);');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ADD INDEX timemarked (timemarked);');
    }
    if ($oldversion < 2005010500) {
        // New field for sending out mail to teachers
        table_column('assignment', '', 'emailteachers', 'integer', '2', 'unsigned', 0, 'not null', 'resubmit');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $wtm->update('assignment', 'description', 'format');
    }
    if ($oldversion < 2005041400) {
        // Add new fields for the new refactored version of assignment
        table_column('assignment', '', 'timeavailable', 'integer', '10', 'unsigned', 0, 'not null', 'timedue');
        table_column('assignment', '', 'assignmenttype', 'varchar', '50', '', '', 'not null', 'format');
        execute_sql("UPDATE {$CFG->prefix}assignment SET assignmenttype = 'offline' WHERE type = '0';");
        execute_sql("UPDATE {$CFG->prefix}assignment SET assignmenttype = 'uploadsingle' WHERE type = '1';");
        execute_sql('ALTER TABLE ' . $CFG->prefix . 'assignment DROP type;');
    }
    if ($oldversion < 2005041501) {
        // Add two new fields for general data handling,
        // so most assignment types won't need new fields and backups stay simple
        table_column('assignment_submissions', '', 'data2', 'MEDIUMTEXT', '', '', '', 'not null', 'numfiles');
        table_column('assignment_submissions', '', 'data1', 'MEDIUMTEXT', '', '', '', 'not null', 'numfiles');
    }
    if ($oldversion < 2005041600) {
        // Add five new fields for general assignment parameters
        // so most assignment types won't need new fields and backups stay simple
        table_column('assignment', '', 'var5', 'integer', '10', '', 0, 'null', 'emailteachers');
        table_column('assignment', '', 'var4', 'integer', '10', '', 0, 'null', 'emailteachers');
        table_column('assignment', '', 'var3', 'integer', '10', '', 0, 'null', 'emailteachers');
        table_column('assignment', '', 'var2', 'integer', '10', '', 0, 'null', 'emailteachers');
        table_column('assignment', '', 'var1', 'integer', '10', '', 0, 'null', 'emailteachers');
    }
    if ($oldversion < 2005041700) {
        // Allow comments to have a formatting
        table_column('assignment_submissions', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'comment');
    }
    if ($oldversion < 2005041800) {
        // Prevent late submissions?  (default no)
        table_column('assignment', '', 'preventlate', 'integer', '2', 'unsigned', '0', 'not null', 'resubmit');
    }
    if ($oldversion < 2005060100) {
        include_once "{$CFG->dirroot}/mod/assignment/lib.php";
        assignment_refresh_events();
    }
    if ($oldversion < 2006092100) {
        table_column('assignment_submissions', 'comment', 'submissioncomment', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#19
0
function journal_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    $result = true;
    if ($oldversion < 2002081000) {
        if (!execute_sql("ALTER TABLE `journal_entries` ADD `mailed` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL")) {
            $result = false;
        }
    }
    if ($oldversion < 2002101200) {
        execute_sql(" ALTER TABLE `journal_entries` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `text` ");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `journal_entries` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003081701) {
        table_column("journal", "assessed", "assessed", "integer", "10", "", "0");
        table_column("journal_entries", "rating", "rating", "integer", "10", "", "0");
    }
    if ($oldversion < 2003081705) {
        $defaultscale = NULL;
        $defaultscale->courseid = 0;
        $defaultscale->userid = 0;
        $defaultscale->timemodified = time();
        $defaultscale->name = get_string("journalrating2", "journal");
        $defaultscale->scale = get_string("journalrating1", "journal") . "," . get_string("journalrating2", "journal") . "," . get_string("journalrating3", "journal");
        if ($defaultscale->id = insert_record("scale", $defaultscale)) {
            execute_sql("UPDATE {$CFG->prefix}journal SET assessed = '-{$defaultscale->id}'", false);
        } else {
            notify("An error occurred while inserting the default journal scale");
            $result = false;
        }
    }
    if ($oldversion < 2004011400) {
        table_column("journal", "", "introformat", "integer", "2", "", "1", "not null", "intro");
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}journal DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}journal_entries DROP INDEX journal;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}journal_entries DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_journal ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_journal_entries ADD INDEX journal (journal);');
        modify_database('', 'ALTER TABLE prefix_journal_entries ADD INDEX userid (userid);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        // journal intro
        $wtm->update('journal', 'intro', 'introformat');
        // journal entries
        $sql = "select course from {$CFG->prefix}journal, {$CFG->prefix}journal_entries ";
        $sql .= "where {$CFG->prefix}journal.id = {$CFG->prefix}journal_entries.journal ";
        $sql .= "and {$CFG->prefix}journal_entries.id = ";
        $wtm->update('journal_entries', 'text', 'format', $sql);
    }
    if ($oldversion < 2006042800) {
        execute_sql("UPDATE {$CFG->prefix}journal SET name='' WHERE name IS NULL");
        table_column('journal', 'name', 'name', 'varchar', '255', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}journal SET intro='' WHERE intro IS NULL");
        table_column('journal', 'intro', 'intro', 'text', '', '', '', 'not null');
    }
    if ($oldversion < 2006092100) {
        table_column('journal_entries', 'comment', 'entrycomment', 'text', '', '', '', 'null');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
示例#20
0
function xmldb_feedback_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2007012310) {
        //create a new table feedback_completedtmp and the field-definition
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, true, null, null, null, null);
        $table->addField($field);
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('guestid');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, false, null, null, '', null);
        $table->addField($field);
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $key = new XMLDBKey('PRIMARY');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
        $table->addKey($key);
        $key = new XMLDBKey('feedback');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('feedback'), 'feedback', 'id');
        $table->addKey($key);
        $result = $result && create_table($table);
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        //create a new table feedback_valuetmp and the field-definition
        $table = new XMLDBTable('feedback_valuetmp');
        $field = new XMLDBField('id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, true, null, null, null, null);
        $table->addField($field);
        $field = new XMLDBField('course_id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('completed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('tmp_completed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('value');
        $field->setAttributes(XMLDB_TYPE_TEXT, null, null, null, false, null, null, '', null);
        $table->addField($field);
        $key = new XMLDBKey('PRIMARY');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
        $table->addKey($key);
        $key = new XMLDBKey('feedback');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('item'), 'feedback_item', 'id');
        $table->addKey($key);
        $result = $result && create_table($table);
        ////////////////////////////////////////////////////////////
    }
    if ($result && $oldversion < 2007050504) {
        /// Define field random_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completed');
        $field = new XMLDBField('random_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        /// Launch add field1
        $result = $result && add_field($table, $field);
        /// Define field anonymous_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completed');
        $field = new XMLDBField('anonymous_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '1', null);
        /// Launch add field2
        $result = $result && add_field($table, $field);
        /// Define field random_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('random_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        /// Launch add field1
        $result = $result && add_field($table, $field);
        /// Define field anonymous_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('anonymous_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '1', null);
        /// Launch add field2
        $result = $result && add_field($table, $field);
        ////////////////////////////////////////////////////////////
    }
    if ($result && $oldversion < 2007102600) {
        // public is a reserved word on Oracle
        $table = new XMLDBTable('feedback_template');
        $field = new XMLDBField('ispublic');
        if (!field_exists($table, $field)) {
            $result = $result && table_column('feedback_template', 'public', 'ispublic', 'integer', 1);
        }
    }
    if ($result && $oldversion < 2008042400) {
        //New version in version.php
        if ($all_nonanonymous_feedbacks = get_records('feedback', 'anonymous', 2)) {
            $update_sql = 'UPDATE ' . $CFG->prefix . 'feedback_completed SET anonymous_response = 2 WHERE feedback = ';
            foreach ($all_nonanonymous_feedbacks as $fb) {
                $result = $result && execute_sql($update_sql . $fb->id);
            }
        }
    }
    if ($result && $oldversion < 2008042401) {
        //New version in version.php
        if ($result) {
            $concat_radio = sql_concat("'r>>>>>'", 'presentation');
            $concat_check = sql_concat("'c>>>>>'", 'presentation');
            $concat_dropdown = sql_concat("'d>>>>>'", 'presentation');
            $update_sql1 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_radio . " WHERE typ IN('radio','radiorated')";
            $update_sql2 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_dropdown . " WHERE typ IN('dropdown','dropdownrated')";
            $update_sql3 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_check . " WHERE typ = 'check'";
            $result = $result && execute_sql($update_sql1);
            $result = $result && execute_sql($update_sql2);
            $result = $result && execute_sql($update_sql3);
        }
        if ($result) {
            $update_sql1 = "UPDATE " . $CFG->prefix . "feedback_item SET typ = 'multichoice' WHERE typ IN('radio','check','dropdown')";
            $update_sql2 = "UPDATE " . $CFG->prefix . "feedback_item SET typ = 'multichoicerated' WHERE typ IN('radiorated','dropdownrated')";
            $result = $result && execute_sql($update_sql1);
            $result = $result && execute_sql($update_sql2);
        }
    }
    if ($result && $oldversion < 2008042801) {
        $new_log_display = new object();
        $new_log_display->module = 'feedback';
        $new_log_display->action = 'startcomplete';
        $new_log_display->mtable = 'feedback';
        $new_log_display->field = 'name';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'submit';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'delete';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'view';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'view all';
        $new_log_display->mtable = 'course';
        $new_log_display->field = 'shortname';
        $result = $result && insert_record('log_display', $new_log_display);
    }
    if ($result && $oldversion < 2008042900) {
        /// Define field autonumbering to be added to feedback
        $table = new XMLDBTable('feedback');
        $field = new XMLDBField('autonumbering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'multiple_submit');
        /// Launch add field2
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008050104) {
        /// Define field site_after_submit to be added to feedback
        $table = new XMLDBTable('feedback');
        $field = new XMLDBField('site_after_submit');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, false, null, null, '', 'autonumbering');
        /// Launch add field2
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008050112) {
        $update_sql = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = '-|-' WHERE presentation = '0|0' AND typ = 'numeric'";
        $result = $result && execute_sql($update_sql);
    }
    return $result;
}
示例#21
0
function quiz_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $QTYPES, $db;
    $success = true;
    require_once "{$CFG->dirroot}/mod/quiz/locallib.php";
    if ($success && $oldversion < 2002101800) {
        $success = $success && execute_sql(" ALTER TABLE `quiz_attempts` " . " ADD `timestart` INT(10) UNSIGNED DEFAULT '0' NOT NULL AFTER `sumgrades` , " . " ADD `timefinish` INT(10) UNSIGNED DEFAULT '0' NOT NULL AFTER `timestart` ");
        $success = $success && execute_sql(" UPDATE `quiz_attempts` SET timestart = timemodified ");
        $success = $success && execute_sql(" UPDATE `quiz_attempts` SET timefinish = timemodified ");
    }
    if ($success && $oldversion < 2002102101) {
        $success = $success && execute_sql(" DELETE FROM log_display WHERE module = 'quiz' ");
        $success = $success && execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('quiz', 'view', 'quiz', 'name') ");
        $success = $success && execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('quiz', 'report', 'quiz', 'name') ");
        $success = $success && execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('quiz', 'attempt', 'quiz', 'name') ");
        $success = $success && execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('quiz', 'submit', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2002102600) {
        $success = $success && execute_sql(" ALTER TABLE `quiz_answers` CHANGE `feedback` `feedback` TEXT NOT NULL ");
    }
    if ($success && $oldversion < 2002122300) {
        $success = $success && execute_sql("ALTER TABLE `quiz_grades` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        $success = $success && execute_sql("ALTER TABLE `quiz_attempts` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    // prefixes required from here on, or use table_column()
    if ($success && $oldversion < 2003010100) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD review TINYINT(4) UNSIGNED DEFAULT '0' NOT NULL AFTER `grademethod` ");
    }
    if ($success && $oldversion < 2003010301) {
        $success = $success && table_column("quiz_truefalse", "true", "trueanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_truefalse", "false", "falseanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_questions", "type", "qtype", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2003022303) {
        $success = $success && modify_database("", "CREATE TABLE `prefix_quiz_randommatch` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `question` int(10) unsigned NOT NULL default '0',\n                             `choose` INT UNSIGNED DEFAULT '4' NOT NULL,\n                             PRIMARY KEY ( `id` )\n                          );");
    }
    if ($success && $oldversion < 2003030303) {
        $success = $success && table_column("quiz_questions", "", "defaultgrade", "INTEGER", "6", "UNSIGNED", "1", "NOT NULL", "image");
    }
    if ($success && $oldversion < 2003032601) {
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_answers` ADD INDEX(question) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_attempts` ADD INDEX(quiz) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_attempts` ADD INDEX(userid) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_grades` ADD INDEX(quiz) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_grades` ADD INDEX(userid) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_question_grades` ADD INDEX(quiz) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_question_grades` ADD INDEX(question) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_randommatch` ADD INDEX(question) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_responses` ADD INDEX(attempt) ");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz_responses` ADD INDEX(question) ");
    }
    if ($success && $oldversion < 2003033100) {
        $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_quiz_randomsamatch ");
        $success = $success && modify_database("", "CREATE TABLE `prefix_quiz_match` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `question` int(10) unsigned NOT NULL default '0',\n                             `subquestions` varchar(255) NOT NULL default '',\n                             PRIMARY KEY  (`id`),\n                             KEY `question` (`question`)\n                           );");
        $success = $success && modify_database("", "CREATE TABLE `prefix_quiz_match_sub` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `question` int(10) unsigned NOT NULL default '0',\n                             `questiontext` text NOT NULL,\n                             `answertext` varchar(255) NOT NULL default '',\n                             PRIMARY KEY  (`id`),\n                             KEY `question` (`question`)\n                           );");
    }
    if ($success && $oldversion < 2003040901) {
        $success = $success && table_column("quiz", "", "shufflequestions", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "review");
        $success = $success && table_column("quiz", "", "shuffleanswers", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "shufflequestions");
    }
    if ($success && $oldversion < 2003071001) {
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_numerical` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `question` int(10) unsigned NOT NULL default '0',\n                               `answer` int(10) unsigned NOT NULL default '0',\n                               `min` varchar(255) NOT NULL default '',\n                               `max` varchar(255) NOT NULL default '',\n                               PRIMARY KEY  (`id`),\n                               KEY `answer` (`answer`)\n                             ) TYPE=MyISAM COMMENT='Options for numerical questions'; ");
    }
    if ($success && $oldversion < 2003072400) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'review', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2003072901) {
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_multianswers` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                                `question` int(10) unsigned NOT NULL default '0',\n                                `answers` varchar(255) NOT NULL default '',\n                                `positionkey` varchar(255) NOT NULL default '',\n                                `answertype` smallint(6) NOT NULL default '0',\n                                `norm` int(10) unsigned NOT NULL default '1',\n                                PRIMARY KEY  (`id`),\n                                KEY `question` (`question`)\n                              ) TYPE=MyISAM COMMENT='Options for multianswer questions'; ");
    }
    if ($success && $oldversion < 2003080301) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD eachattemptbuildsonthelast TINYINT(4) DEFAULT '0' NOT NULL AFTER `attempts` ");
    }
    if ($success && $oldversion < 2003080400) {
        $success = $success && table_column("quiz", "eachattemptbuildsonthelast", "attemptonlast", "TINYINT", "4", "UNSIGNED", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2003082300) {
        $success = $success && table_column("quiz_questions", "", "stamp", "varchar", "255", "", "", "not null", "qtype");
    }
    if ($success && $oldversion < 2003082301) {
        $success = $success && table_column("quiz_questions", "stamp", "stamp", "varchar", "255", "", "", "not null");
        $success = $success && table_column("quiz_questions", "", "version", "integer", "10", "", "1", "not null", "stamp");
        if ($questions = get_records("quiz_questions")) {
            foreach ($questions as $question) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_questions", "stamp", $stamp, "id", $question->id))) {
                    notify("Error while adding stamp to question id = {$question->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003082700) {
        $success = $success && table_column("quiz_categories", "", "stamp", "varchar", "255", "", "", "not null");
        if ($categories = get_records("quiz_categories")) {
            foreach ($categories as $category) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_categories", "stamp", $stamp, "id", $category->id))) {
                    notify("Error while adding stamp to category id = {$category->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003111100) {
        $duplicates = get_records_sql("SELECT stamp as id,count(*) as cuenta\n                                       FROM {$CFG->prefix}quiz_questions\n                                       GROUP BY stamp\n                                       HAVING count(*)>1");
        if ($duplicates) {
            notify("You have some quiz questions with duplicate stamps IDs.  Cleaning these up.");
            foreach ($duplicates as $duplicate) {
                $questions = get_records("quiz_questions", "stamp", $duplicate->id);
                $add = 1;
                foreach ($questions as $question) {
                    echo "Changing question id {$question->id} stamp to " . $duplicate->id . $add . "<br />";
                    $success = $success && set_field("quiz_questions", "stamp", $duplicate->id . $add, "id", $question->id);
                    $add++;
                }
            }
        } else {
            notify("Checked your quiz questions for stamp duplication errors, but no problems were found.", "green");
        }
    }
    if ($success && $oldversion < 2004021300) {
        $success = $success && table_column("quiz_questions", "", "questiontextformat", "integer", "2", "", "0", "not null", "questiontext");
    }
    if ($success && $oldversion < 2004021900) {
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'add', 'quiz', 'name');");
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'update', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2004051700) {
        include_once "{$CFG->dirroot}/mod/quiz/lib.php";
        $success = $success && quiz_refresh_events();
    }
    if ($success && $oldversion < 2004060200) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD timelimit INT(2) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($success && $oldversion < 2004070700) {
        $success = $success && table_column("quiz", "", "password", "varchar", "255", "", "", "not null", "");
        $success = $success && table_column("quiz", "", "subnet", "varchar", "255", "", "", "not null", "");
    }
    if ($success && $oldversion < 2004073001) {
        // Six new tables:
        // One table for handling units for numerical questions
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_numerical_units` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `question` int(10) unsigned NOT NULL default '0',\n                               `multiplier` decimal(40,20) NOT NULL default '1.00000000000000000000',\n                               `unit` varchar(50) NOT NULL default '',\n                               PRIMARY KEY  (`id`)\n                ) TYPE=MyISAM COMMENT='Optional unit options for numerical questions'; ");
        // Four tables for handling distribution and storage of
        // individual data for dataset dependent question types
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_attemptonlast_datasets` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `category` int(10) unsigned NOT NULL default '0',\n                               `userid` int(10) unsigned NOT NULL default '0',\n                               `datasetnumber` int(10) unsigned NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               UNIQUE KEY `category` (`category`,`userid`)\n            ) TYPE=MyISAM COMMENT='Dataset number for attemptonlast attempts per user'; ");
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_dataset_definitions` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `category` int(10) unsigned NOT NULL default '0',\n                               `name` varchar(255) NOT NULL default '',\n                               `type` int(10) NOT NULL default '0',\n                               `options` varchar(255) NOT NULL default '',\n                               `itemcount` int(10) unsigned NOT NULL default '0',\n                               PRIMARY KEY  (`id`)\n            ) TYPE=MyISAM COMMENT='Organises and stores properties for dataset items'; ");
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_dataset_items` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `definition` int(10) unsigned NOT NULL default '0',\n                               `number` int(10) unsigned NOT NULL default '0',\n                               `value` varchar(255) NOT NULL default '',\n                               PRIMARY KEY  (`id`),\n                               KEY `definition` (`definition`)\n                             ) TYPE=MyISAM COMMENT='Individual dataset items'; ");
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_question_datasets` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `question` int(10) unsigned NOT NULL default '0',\n                               `datasetdefinition` int(10) unsigned NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               KEY `question` (`question`,`datasetdefinition`)\n            ) TYPE=MyISAM COMMENT='Many-many relation between questions and dataset definitions'; ");
        // One table for new question type calculated
        //  - the first dataset dependent question type
        $success = $success && modify_database("", " CREATE TABLE `prefix_quiz_calculated` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `question` int(10) unsigned NOT NULL default '0',\n                               `answer` int(10) unsigned NOT NULL default '0',\n                               `tolerance` varchar(20) NOT NULL default '0.0',\n                               `tolerancetype` int(10) NOT NULL default '1',\n                               `correctanswerlength` int(10) NOT NULL default '2',\n                               PRIMARY KEY  (`id`),\n                               KEY `question` (`question`)\n                ) TYPE=MyISAM COMMENT='Options for questions of type calculated'; ");
    }
    if ($success && $oldversion < 2004111400) {
        $success = $success && table_column("quiz_responses", "answer", "answer", "text", "", "", "", "not null");
    }
    if ($success && $oldversion < 2004111700) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz DROP INDEX course;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_calculated DROP INDEX answer;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_categories DROP INDEX course;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_definitions DROP INDEX category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical DROP INDEX question;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical_units DROP INDEX question;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_questions DROP INDEX category;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz ADD INDEX course (course);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_calculated ADD INDEX answer (answer);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_categories ADD INDEX course (course);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_dataset_definitions ADD INDEX category (category);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical ADD INDEX question (question);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical_units ADD INDEX question (question);');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_questions ADD INDEX category (category);');
    }
    if ($success && $oldversion < 2004120501) {
        $success = $success && table_column("quiz_calculated", "", "correctanswerformat", "integer", "10", "", "2", "not null", "correctanswerlength");
    }
    if ($success && $oldversion < 2004121400) {
        // New field to determine popup window behaviour
        $success = $success && table_column("quiz", "", "popup", "integer", "4", "", "0", "not null", "subnet");
    }
    if ($success && $oldversion < 2005010201) {
        $success = $success && table_column('quiz_categories', '', 'parent');
        $success = $success && table_column('quiz_categories', '', 'sortorder', 'integer', '10', '', '999');
    }
    if ($success && $oldversion < 2005010300) {
        $success = $success && table_column("quiz", "", "questionsperpage", "integer", "10", "", "0", "not null", "review");
    }
    if ($success && $oldversion < 2005012700) {
        $success = $success && table_column('quiz_grades', 'grade', 'grade', 'real', 2, '');
    }
    if ($success && $oldversion < 2005021400) {
        $success = $success && table_column("quiz", "", "decimalpoints", "integer", "4", "", "2", "not null", "grademethod");
    }
    if ($success && $oldversion < 2005022800) {
        $success = $success && table_column('quiz_questions', '', 'hidden', 'integer', '1', 'unsigned', '0', 'not null', 'version');
        $success = $success && table_column('quiz_responses', '', 'originalquestion', 'integer', '10', 'unsigned', '0', 'not null', 'question');
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_question_version` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `quiz` int(10) unsigned NOT NULL default '0',\n                              `oldquestion` int(10) unsigned NOT NULL default '0',\n                              `newquestion` int(10) unsigned NOT NULL default '0',\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `timestamp` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            ) TYPE=MyISAM COMMENT='The mapping between old and new versions of a question';");
    }
    if ($success && $oldversion < 2005032000) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'editquestions', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2005032300) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_version RENAME prefix_quiz_question_versions;');
    }
    if ($success && $oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}quiz_categories c, {$CFG->prefix}quiz_questions q ";
        $sql .= "where c.id = q.category ";
        $sql .= "and q.id = ";
        $wtm->update('quiz_questions', 'questiontext', 'questiontextformat', $sql);
    }
    if ($success && $oldversion < 2005041304) {
        // make random questions hidden
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET hidden = '1' WHERE qtype ='" . RANDOM . "';");
    }
    if ($success && $oldversion < 2005042002) {
        $success = $success && table_column('quiz_answers', 'answer', 'answer', 'text', '', '', '', 'not null', '');
    }
    if ($success && $oldversion < 2005042400) {
        // Changes to quiz table
        // The bits of the optionflags field will hold various option flags
        $success = $success && table_column('quiz', '', 'optionflags', 'integer', '10', 'unsigned', '0', 'not null', 'timeclose');
        // The penalty scheme
        $success = $success && table_column('quiz', '', 'penaltyscheme', 'integer', '4', 'unsigned', '0', 'not null', 'optionflags');
        // The review options are now all stored in the bits of the review field
        $success = $success && table_column('quiz', 'review', 'review', 'integer', 10, 'unsigned', 0, 'not null', '');
        /// Changes to quiz_attempts table
        // The preview flag marks teacher previews
        $success = $success && table_column('quiz_attempts', '', 'preview', 'tinyint', '2', 'unsigned', '0', 'not null', 'timemodified');
        // The layout is the list of questions with inserted page breaks.
        $success = $success && table_column('quiz_attempts', '', 'layout', 'text', '', '', '', 'not null', 'timemodified');
        // For old quiz attempts we will set this to the repaginated question list from $quiz->questions
        /// The following updates of field values require a loop through all quizzes
        // This is because earlier versions of mysql don't allow joins in UPDATE
        if ($quizzes = get_records('quiz')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            echo 'Now updating ' . count($quizzes) . ' quizzes';
            foreach ($quizzes as $quiz) {
                // repaginate
                if ($quiz->questionsperpage) {
                    $quiz->questions = quiz_repaginate($quiz->questions, $quiz->questionsperpage);
                    $success = $success && set_field('quiz', 'questions', $quiz->questions, 'id', $quiz->id);
                }
                $success = $success && set_field('quiz_attempts', 'layout', $quiz->questions, 'quiz', $quiz->id);
                // set preview flag
                if ($teachers = get_course_teachers($quiz->course)) {
                    $teacherids = implode(',', array_keys($teachers));
                    $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET preview = 1 WHERE userid IN ({$teacherids})");
                }
                // set review flags in quiz table
                $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
                if ($quiz->feedback) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
                }
                if ($quiz->correctanswers) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
                }
                if ($quiz->review & 1) {
                    $review += QUIZ_REVIEW_CLOSED;
                }
                if ($quiz->review & 2) {
                    $review += QUIZ_REVIEW_OPEN;
                }
                $success = $success && set_field('quiz', 'review', $review, 'id', $quiz->id);
            }
            $db->debug = $olddebug;
        }
        // We can now drop the fields whose data has been moved to the review field
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz` DROP feedback");
        $success = $success && execute_sql(" ALTER TABLE `{$CFG->prefix}quiz` DROP correctanswers");
        /// Renaming tables
        // rename the quiz_question_grades table to quiz_question_instances
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades RENAME prefix_quiz_question_instances;');
        // rename the quiz_responses table quiz_states
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses RENAME prefix_quiz_states;');
        /// add columns to quiz_states table
        // The sequence number of the state.
        $success = $success && table_column('quiz_states', '', 'seq_number', 'integer', '6', 'unsigned', '0', 'not null', 'originalquestion');
        // For existing states we leave this at 0 because in the old quiz code there was only one response allowed
        // The time the state was created.
        $success = $success && table_column('quiz_states', '', 'timestamp', 'integer', '10', 'unsigned', '0', 'not null', 'answer');
        // For existing states we will below set this to the timemodified field of the attempt
        // The type of event that led to the creation of the state
        $success = $success && table_column('quiz_states', '', 'event', 'integer', '4', 'unsigned', '0', 'not null', 'timestamp');
        // The raw grade
        $success = $success && table_column('quiz_states', '', 'raw_grade', 'varchar', '10', '', '', 'not null', 'grade');
        // For existing states (no penalties) this is equal to the grade
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_states SET raw_grade = grade");
        // The penalty that the response attracted
        $success = $success && table_column('quiz_states', '', 'penalty', 'varchar', '10', '', '0.0', 'not null', 'raw_grade');
        // For existing states this can stay at 0 because penalties did not exist previously.
        /// New table for pointers to newest and newest graded states
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_newest_states` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `attemptid` int(10) unsigned NOT NULL default '0',\n                             `questionid` int(10) unsigned NOT NULL default '0',\n                             `new` int(10) unsigned NOT NULL default '0',\n                             `newgraded` int(10) unsigned NOT NULL default '0',\n                             `sumpenalty` varchar(10) NOT NULL default '0.0',\n                             PRIMARY KEY  (`id`),\n                             UNIQUE KEY `attemptid` (`attemptid`,`questionid`)\n                           ) TYPE=MyISAM COMMENT='Gives ids of the newest open and newest graded states';");
        /// Now upgrade some fields in states and newest_states tables where necessary
        // to save time on large sites only do this for attempts that have not yet been finished.
        if ($attempts = get_records_select('quiz_attempts', 'timefinish = 0')) {
            echo 'Update the states for the ' . count($attempts) . ' open attempts';
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($attempts as $attempt) {
                quiz_upgrade_states($attempt);
            }
            $db->debug = $olddebug;
        }
        /// Entries for the log_display table
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'preview', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'start attempt', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'close attempt', 'quiz', 'name');");
        /// update the default settings in $CFG
        $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
        if (!empty($CFG->quiz_feedback)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
        }
        if (!empty($CFG->quiz_correctanswers)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 1) {
            $review += QUIZ_REVIEW_CLOSED;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 2) {
            $review += QUIZ_REVIEW_OPEN;
        }
        $success = $success && set_config('quiz_review', $review);
        /// Use tolerance instead of min and max in numerical question type
        $success = $success && table_column('quiz_numerical', '', 'tolerance', 'varchar', '255', '', '0.0', 'not null', 'answer');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_numerical SET tolerance = (max-min)/2");
        $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_numerical` DROP `min`');
        // Replaced by tolerance
        $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_numerical` DROP `max`');
        // Replaced by tolerance
        /// Tables for Remote Questions
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_rqp` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `question` int(10) unsigned NOT NULL default '0',\n                              `type` int(10) unsigned NOT NULL default '0',\n                              `source` longblob NOT NULL default '',\n                              `format` varchar(255) NOT NULL default '',\n                              `flags` tinyint(3) unsigned NOT NULL default '0',\n                              `maxscore` int(10) unsigned NOT NULL default '1',\n                              PRIMARY KEY  (`id`),\n                              KEY `question` (`question`)\n                              ) TYPE=MyISAM COMMENT='Options for RQP questions';");
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_rqp_type` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `name` varchar(255) NOT NULL default '',\n                              `rendering_server` varchar(255) NOT NULL default '',\n                              `cloning_server` varchar(255) NOT NULL default '',\n                              `flags` tinyint(3) NOT NULL default '0',\n                              PRIMARY KEY  (`id`),\n                              UNIQUE KEY `name` (`name`)\n                              ) TYPE=MyISAM COMMENT='RQP question types and the servers to be used to process them';");
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_rqp_states` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `stateid` int(10) unsigned NOT NULL default '0',\n                              `responses` text NOT NULL default '',\n                              `persistent_data` text NOT NULL default '',\n                              `template_vars` text NOT NULL default '',\n                              PRIMARY KEY  (`id`)\n                              ) TYPE=MyISAM COMMENT='RQP question type specific state information';");
    }
    if ($success && $oldversion < 2005050300) {
        // length of question determines question numbering. Currently all questions require one
        // question number except for DESCRIPTION questions.
        $success = $success && table_column('quiz_questions', '', 'length', 'integer', '10', 'unsigned', '1', 'not null', 'qtype');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET length = 0 WHERE qtype ='7'");
    }
    if ($success && $oldversion < 2005050408) {
        $success = $success && table_column('quiz_questions', '', 'penalty', 'float', '', '', '0.1', 'not null', 'defaultgrade');
        $success = $success && table_column('quiz_newest_states', 'new', 'newest', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($success && $oldversion < 2005051400) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_rqp_type RENAME prefix_quiz_rqp_types;');
        $success = $success && modify_database('', "CREATE TABLE `prefix_quiz_rqp_servers` (\n                      id int(10) unsigned NOT NULL auto_increment,\n                      typeid int(10) unsigned NOT NULL default '0',\n                      url varchar(255) NOT NULL default '',\n                      can_render tinyint(2) unsigned NOT NULL default '0',\n                      can_author tinyint(2) unsigned NOT NULL default '0',\n                      PRIMARY KEY  (id)\n                    ) TYPE=MyISAM COMMENT='Information about RQP servers';");
        if ($types = get_records('quiz_rqp_types')) {
            foreach ($types as $type) {
                $server = new stdClass();
                $server->typeid = $type->id;
                $server->url = $type->rendering_server;
                $server->can_render = 1;
                $success = $success && insert_record('quiz_rqp_servers', $server);
            }
        }
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_rqp_types DROP rendering_server');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_rqp_types DROP cloning_server');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_rqp_types DROP flags');
    }
    if ($success && $oldversion < 2005051401) {
        // Some earlier changes are undone here, so we need another condition
        if ($oldversion >= 2005042900) {
            // Restore the answer field
            $success = $success && table_column('quiz_numerical', '', 'answer', 'integer', '10', 'unsigned', '0', 'not null', 'answers');
            $singleanswer = array();
            if ($numericals = get_records('quiz_numerical')) {
                $numericals = array_values($numericals);
                $n = count($numericals);
                for ($i = 0; $i < $n; $i++) {
                    $numerical =& $numericals[$i];
                    if (strpos($numerical->answers, ',')) {
                        // comma separated list?
                        // Back this up to delete the record after the new ones are created
                        $id = $numerical->id;
                        unset($numerical->id);
                        // We need to create a record for each answer id
                        $answers = explode(',', $numerical->answers);
                        foreach ($answers as $answer) {
                            $numerical->answer = $answer;
                            $success = $success && insert_record('quiz_numerical', $numerical);
                        }
                        // ... and get rid of the old record
                        $success = $success && delete_records('quiz_numerical', 'id', $id);
                    } else {
                        $singleanswer[] = $numerical->id;
                    }
                }
            }
            // Do all of these at once
            if (!empty($singleanswer)) {
                $singleanswer = implode(',', $singleanswer);
                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET answer = answers WHERE id IN ({$singleanswer});");
            }
            // All answer fields are set, so we can delete the answers field
            $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_numerical` DROP `answers`');
            // If the earlier changes weren't made we can safely do only the
            // bits here.
        } else {
            // Comma separated questionids will be stored as sequence
            $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
            // Change the type of positionkey to int, so that the sorting works!
            $success = $success && table_column('quiz_multianswers', 'positionkey', 'positionkey', 'integer', '10', 'unsigned', '0', 'not null', '');
            $success = $success && table_column('quiz_questions', '', 'parent', 'integer', '10', 'unsigned', '0', 'not null', 'category');
            $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET parent = id WHERE qtype ='" . RANDOM . "';");
            // Each multianswer record is converted to a question object and then
            // inserted as a new question into the quiz_questions table.
            // After that the question fields in the quiz_answers table and the
            // qtype specific tables are updated to point to the new question id.
            // Note: The quiz_numerical table is different as it stores one record
            //       per defined answer (to allow different tolerance values for
            //       different possible answers. (Currently multiple answers are
            //       not supported by the numerical editing interface, but
            //       all processing code does support that possibility.
            if ($multianswers = get_records_sql("SELECT m.id, q.category, " . "q.id AS parent, " . "q.name, q.questiontextformat, " . "m.norm AS defaultgrade, " . "m.answertype AS qtype, " . "q.version, q.hidden, m.answers, " . "m.positionkey " . "FROM {$CFG->prefix}quiz_questions q, " . "     {$CFG->prefix}quiz_multianswers m " . "WHERE q.qtype = '" . MULTIANSWER . "' " . "AND   q.id = m.question " . "ORDER BY q.id ASC, m.positionkey ASC")) {
                // ordered by positionkey
                $multianswers = array_values($multianswers);
                $n = count($multianswers);
                $parent = $multianswers[0]->parent;
                $sequence = array();
                $positions = array();
                // Turn reporting off temporarily to avoid one line output per set_field
                global $db;
                $olddebug = $db->debug;
                $db->debug = false;
                echo 'Now updating ' . $n . ' cloze questions.';
                for ($i = 0; $i < $n; $i++) {
                    // Backup these two values before unsetting the object fields
                    $answers = $multianswers[$i]->answers;
                    unset($multianswers[$i]->answers);
                    $pos = $multianswers[$i]->positionkey;
                    unset($multianswers[$i]->positionkey);
                    // Needed for substituting multianswer ids with position keys in the $state->answer field
                    $positions[$multianswers[$i]->id] = $pos;
                    // Create questions for all the multianswer victims
                    unset($multianswers[$i]->id);
                    $multianswers[$i]->length = 0;
                    $multianswers[$i]->questiontext = '';
                    $multianswers[$i]->stamp = make_unique_id_code();
                    $multianswers[$i]->name = addslashes($multianswers[$i]->name);
                    // $multianswers[$i]->parent is set in the query
                    // $multianswers[$i]->defaultgrade is set in the query
                    // $multianswers[$i]->qtype is set in the query
                    $id = insert_record('quiz_questions', $multianswers[$i]);
                    $success = $success && $id;
                    $sequence[$pos] = $id;
                    // Update the quiz_answers table to point to these new questions
                    $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_answers SET question = '{$id}' WHERE id IN ({$answers})", false);
                    // Update the questiontype tables to point to these new questions
                    if (SHORTANSWER == $multianswers[$i]->qtype) {
                        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}'", false);
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}'", false);
                        } else {
                            if (NUMERICAL == $multianswers[$i]->qtype) {
                                $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_numerical SET question = '{$id}' WHERE answer IN ({$answers})", false);
                            }
                        }
                    }
                    // Whenever we're through with the subquestions of one multianswer
                    // question we delete the old records in the multianswers table,
                    // store a new record with the sequence in the multianswers table
                    // and point $parent to the next multianswer question.
                    if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                        // Substituting multianswer ids with position keys in the $state->answer field
                        if ($states = get_records('quiz_states', 'question', $parent)) {
                            foreach ($states as $state) {
                                $reg = array();
                                preg_match_all('/(?:^|,)([0-9]+)-([^,]*)/', $state->answer, $reg);
                                $state->answer = '';
                                $m = count($reg[1]);
                                for ($j = 0; $j < $m; $j++) {
                                    if (isset($positions[$reg[1][$j]])) {
                                        $state->answer .= $positions[$reg[1][$j]] . '-' . $reg[2][$j] . ',';
                                    } else {
                                        notify("Undefined multianswer id ({$reg[1][$j]}) used in state #{$state->id}!");
                                        $state->answer .= $j + 1 . '-' . $reg[2][$j] . ',';
                                    }
                                }
                                $state->answer = rtrim($state->answer, ',');
                                // strip trailing comma
                                $success = $success && update_record('quiz_states', $state);
                            }
                        }
                        $success = $success && delete_records('quiz_multianswers', 'question', $parent);
                        $multi = new stdClass();
                        $multi->question = $parent;
                        $multi->sequence = implode(',', $sequence);
                        $success = $success && insert_record('quiz_multianswers', $multi);
                        if (isset($multianswers[$i + 1])) {
                            $parent = $multianswers[$i + 1]->parent;
                            $sequence = array();
                            $positions = array();
                        }
                    }
                }
                $db->debug = $olddebug;
            }
            // Remove redundant fields from quiz_multianswers
            $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_multianswers` DROP `answers`');
            $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_multianswers` DROP `positionkey`');
            $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_multianswers` DROP `answertype`');
            $success = $success && modify_database('', 'ALTER TABLE `prefix_quiz_multianswers` DROP `norm`');
        }
    }
    if ($success && $oldversion < 2005052004) {
        // We need to remove some duplicate entries that may be present in some databases
        // due to a faulty restore script
        // Remove duplicate entries from quiz_numerical
        if ($dups = get_records_sql("\n                SELECT question, answer, count(*) as num\n                FROM {$CFG->prefix}quiz_numerical\n                GROUP BY question, answer\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_numerical\n                    WHERE question = '{$dup->question}'\n                    AND answer = '{$dup->answer}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_numerical', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_shortanswer
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_shortanswer\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_shortanswer\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_shortanswer', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_multichoice
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_multichoice\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_multichoice\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_multichoice', 'id', $id->id);
                    }
                }
            }
        }
    }
    if ($success && $oldversion < 2005060300) {
        //Search all the orphan categories (those whose course doesn't exist)
        //and process them, deleting or moving them to site course - Bug 2459
        //Set debug to false
        $olddebug = $db->debug;
        $db->debug = false;
        //Iterate over all the quiz_categories records to get their course id
        if ($courses = get_records_sql("SELECT DISTINCT course as id, course\n                                         FROM {$CFG->prefix}quiz_categories")) {
            //Iterate over courses
            foreach ($courses as $course) {
                //If the course doesn't exist, orphan category found!
                //Process it with question_delete_course(). It will do all the hard work.
                if (!record_exists('course', 'id', $course->id)) {
                    require_once "{$CFG->libdir}/questionlib.php";
                    $success = $success && question_delete_course($course);
                }
            }
        }
        //Reset rebug to its original state
        $db->debug = $olddebug;
    }
    if ($success && $oldversion < 2005062600) {
        $success = $success && modify_database('', "\n            CREATE TABLE `prefix_quiz_essay` (\n                `id` int(10) unsigned NOT NULL auto_increment,\n                `question` int(10) unsigned NOT NULL default '0',\n                `answer` varchar(255) NOT NULL default '',\n                PRIMARY KEY  (`id`),\n                KEY `question` (`question`)\n           ) TYPE=MyISAM COMMENT='Options for essay questions'");
        $success = $success && modify_database('', "\n            CREATE TABLE `prefix_quiz_essay_states` (\n              `id` int(10) unsigned NOT NULL auto_increment,\n              `stateid` int(10) unsigned NOT NULL default '0',\n              `graded` tinyint(4) unsigned NOT NULL default '0',\n              `fraction` varchar(10) NOT NULL default '0.0',\n              `response` text NOT NULL,\n              PRIMARY KEY  (`id`)\n            ) TYPE=MyISAM COMMENT='essay question type specific state information'");
    }
    if ($success && $oldversion < 2005070202) {
        // add new unique id to prepare the way for lesson module to have its own attempts table
        $success = $success && table_column('quiz_attempts', '', 'uniqueid', 'integer', '10', 'unsigned', '0', 'not null', 'id');
        // initially we can use the id as the unique id because no other modules use attempts yet.
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET uniqueid = id", false);
        // we set $CFG->attemptuniqueid to the next available id
        $record = get_record_sql("SELECT max(id)+1 AS nextid FROM {$CFG->prefix}quiz_attempts");
        $success = $success && set_config('attemptuniqueid', empty($record->nextid) ? 1 : $record->nextid);
    }
    if ($success && $oldversion < 2006020801) {
        // add new field to store time delay between the first and second quiz attempt
        $success = $success && table_column('quiz', '', 'delay1', 'integer', '10', 'unsigned', '0', 'not null', 'popup');
        // add new field to store time delay between the second and any additional quizes
        $success = $success && table_column('quiz', '', 'delay2', 'integer', '10', 'unsigned', '0', 'not null', 'delay1');
    }
    if ($success && $oldversion < 2006021101) {
        // set defaultgrade field properly (probably not necessary, but better make sure)
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '1' WHERE defaultgrade = '0'", false);
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '0' WHERE qtype = '7'", false);
    }
    if ($success && $oldversion < 2006021103) {
        // add new field to store the question-level shuffleanswers option
        $success = $success && table_column('quiz_match', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'subquestions');
        $success = $success && table_column('quiz_multichoice', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'single');
        $success = $success && table_column('quiz_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
    }
    if ($success && $oldversion < 2006021104) {
        // add originalversion field for the new versioning mechanism
        $success = $success && table_column('quiz_question_versions', '', 'originalquestion', 'int', '10', 'unsigned', '0', 'not null', 'newquestion');
    }
    if ($success && $oldversion < 2006021301) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attempts ADD UNIQUE INDEX uniqueid (uniqueid);');
    }
    if ($success && $oldversion < 2006021302) {
        $success = $success && table_column('quiz_match_sub', '', 'code', 'int', '10', 'unsigned', '0', 'not null', 'id');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_match_sub SET code = id", false);
    }
    if ($success && $oldversion < 2006021304) {
        // convert sequence field to text to accomodate very long sequences, see bug 4257
        $success = $success && table_column('quiz_multianswers', 'sequence', 'sequence', 'text', '', '', '', 'not null', 'question');
    }
    if ($success && $oldversion < 2006021501) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME {$CFG->prefix}question_sessions", false);
    }
    if ($success && $oldversion < 2006022200) {
        // convert grade fields to float
        $success = $success && set_field('quiz_attempts', 'sumgrades', 0, 'sumgrades', '');
        $success = $success && table_column('quiz_attempts', 'sumgrades', 'sumgrades', 'float', '', '', '0', 'not null');
        $success = $success && set_field('quiz_answers', 'fraction', 0, 'fraction', '');
        $success = $success && table_column('quiz_answers', 'fraction', 'fraction', 'float', '', '', '0', 'not null');
        $success = $success && set_field('quiz_essay_states', 'fraction', 0, 'fraction', '');
        $success = $success && table_column('quiz_essay_states', 'fraction', 'fraction', 'float', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'grade', 0, 'grade', '');
        $success = $success && table_column('quiz_states', 'grade', 'grade', 'float', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'raw_grade', 0, 'raw_grade', '');
        $success = $success && table_column('quiz_states', 'raw_grade', 'raw_grade', 'float', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'penalty', 0, 'penalty', '');
        $success = $success && table_column('quiz_states', 'penalty', 'penalty', 'float', '', '', '0', 'not null');
        $success = $success && set_field('question_sessions', 'sumpenalty', 0, 'sumpenalty', '');
        $success = $success && table_column('question_sessions', 'sumpenalty', 'sumpenalty', 'float', '', '', '0', 'not null');
    }
    if ($success && $oldversion < 2006022400) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_questions RENAME {$CFG->prefix}question", false);
    }
    if ($success && $oldversion < 2006022402) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_states RENAME {$CFG->prefix}question_states", false);
    }
    if ($success && $oldversion < 2006022800) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_answers RENAME {$CFG->prefix}question_answers", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_categories RENAME {$CFG->prefix}question_categories", false);
    }
    if ($success && $oldversion < 2006031202) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_truefalse RENAME {$CFG->prefix}question_truefalse", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_shortanswer RENAME {$CFG->prefix}question_shortanswer", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multianswers RENAME {$CFG->prefix}question_multianswer", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multichoice RENAME {$CFG->prefix}question_multichoice", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical RENAME {$CFG->prefix}question_numerical", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical_units RENAME {$CFG->prefix}question_numerical_units", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_randomsamatch RENAME {$CFG->prefix}question_randomsamatch", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match RENAME {$CFG->prefix}question_match", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match_sub RENAME {$CFG->prefix}question_match_sub", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_calculated RENAME {$CFG->prefix}question_calculated", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_definitions RENAME {$CFG->prefix}question_dataset_definitions", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_items RENAME {$CFG->prefix}question_dataset_items", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_question_datasets RENAME {$CFG->prefix}question_datasets", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp RENAME {$CFG->prefix}question_rqp", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_servers RENAME {$CFG->prefix}question_rqp_servers", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_states RENAME {$CFG->prefix}question_rqp_states", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_types RENAME {$CFG->prefix}question_rqp_types", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay RENAME {$CFG->prefix}question_essay", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay_states RENAME {$CFG->prefix}question_essay_states", false);
    }
    if ($success && $oldversion < 2006032100) {
        // change from the old questiontype numbers to using the questiontype names
        $success = $success && table_column('question', 'qtype', 'qtype', 'varchar', 20, '', '', 'not null');
        $success = $success && set_field('question', 'qtype', 'shortanswer', 'qtype', 1);
        $success = $success && set_field('question', 'qtype', 'truefalse', 'qtype', 2);
        $success = $success && set_field('question', 'qtype', 'multichoice', 'qtype', 3);
        $success = $success && set_field('question', 'qtype', 'random', 'qtype', 4);
        $success = $success && set_field('question', 'qtype', 'match', 'qtype', 5);
        $success = $success && set_field('question', 'qtype', 'randomsamatch', 'qtype', 6);
        $success = $success && set_field('question', 'qtype', 'description', 'qtype', 7);
        $success = $success && set_field('question', 'qtype', 'numerical', 'qtype', 8);
        $success = $success && set_field('question', 'qtype', 'multianswer', 'qtype', 9);
        $success = $success && set_field('question', 'qtype', 'calculated', 'qtype', 10);
        $success = $success && set_field('question', 'qtype', 'rqp', 'qtype', 11);
        $success = $success && set_field('question', 'qtype', 'essay', 'qtype', 12);
    }
    if ($success && $oldversion < 2006032200) {
        // set version for all questiontypes that already have their tables installed
        $success = $success && set_config('qtype_calculated_version', 2006032100);
        $success = $success && set_config('qtype_essay_version', 2006032100);
        $success = $success && set_config('qtype_match_version', 2006032100);
        $success = $success && set_config('qtype_multianswer_version', 2006032100);
        $success = $success && set_config('qtype_multichoice_version', 2006032100);
        $success = $success && set_config('qtype_numerical_version', 2006032100);
        $success = $success && set_config('qtype_randomsamatch_version', 2006032100);
        $success = $success && set_config('qtype_rqp_version', 2006032100);
        $success = $success && set_config('qtype_shortanswer_version', 2006032100);
        $success = $success && set_config('qtype_truefalse_version', 2006032100);
    }
    if ($success && $oldversion < 2006040600) {
        $success = $success && table_column('question_sessions', '', 'comment', 'text', '', '', '', 'not null', 'sumpenalty');
    }
    if ($success && $oldversion < 2006040900) {
        $success = $success && modify_database('', "UPDATE prefix_question SET parent = id WHERE qtype ='random';");
    }
    if ($success && $oldversion < 2006041000) {
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'continue attempt', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2006041001) {
        $success = $success && table_column('question', 'version', 'version', 'varchar', 255);
    }
    if ($success && $oldversion < 2006042800) {
        // Check we have some un-renamed tables (verified in some servers)
        if ($tables = $db->MetaTables('TABLES')) {
            if (in_array($CFG->prefix . 'quiz_randommatch', $tables) && !in_array($CFG->prefix . 'question_randomsamatch', $tables)) {
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_question_randomsamatch ");
            }
            // Check for one possible missing field in one table
            if ($columns = $db->MetaColumnNames($CFG->prefix . 'question_randomsamatch')) {
                if (!in_array('shuffleanswers', $columns)) {
                    $success = $success && table_column('question_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
                }
            }
        }
    }
    if ($oldversion < 2006051300) {
        // The newgraded field must always point to a valid state
        $success = $success && modify_database("", "UPDATE prefix_question_sessions SET newgraded = newest where newgraded = '0'");
        // Only perform this if hasn't been performed before (in MOODLE_16_STABLE branch - bug 5717)
        $tables = $db->MetaTables('TABLES');
        if (!in_array($CFG->prefix . 'question_attempts', $tables)) {
            // The following table is discussed in bug 5468
            $success = $success && modify_database("", "CREATE TABLE prefix_question_attempts (\n                                      id int(10) unsigned NOT NULL auto_increment,\n                                      modulename varchar(20) NOT NULL default 'quiz',\n                                      PRIMARY KEY  (id)\n                                    ) TYPE=MyISAM COMMENT='Student attempts. This table gets extended by the modules';");
            // create one entry for all the existing quiz attempts
            $success = $success && modify_database("", "INSERT INTO prefix_question_attempts (id)\n                                       SELECT uniqueid\n                                       FROM prefix_quiz_attempts;");
        }
    }
    if ($success && $oldversion < 2006060700) {
        // fix for 5720
        // Copy the teacher comments from the question_essay_states table to the new
        // question_sessions table.
        // Get the attempt unique ID, teacher comment, graded flag, state ID, and question ID
        // based on the quesiont_essay_states
        if ($results = get_records_sql("SELECT a.uniqueid, es.response AS essaycomment, es.graded AS isgraded, \n                                               qs.id AS stateid, qs.question AS questionid \n                                        FROM {$CFG->prefix}question_states as qs,\n                                             {$CFG->prefix}question_essay_states es, \n                                             {$CFG->prefix}quiz_attempts a \n                                        WHERE es.stateid = qs.id AND a.uniqueid = qs.attempt")) {
            foreach ($results as $result) {
                // Create a state object to be used for updating
                $state = new stdClass();
                $state->id = $result->stateid;
                if ($result->isgraded) {
                    // Graded - save comment to the sessions and change state event to QUESTION_EVENTMANUALGRADE
                    if (!($success = $success && set_field('question_sessions', 'comment', $result->essaycomment, 'attemptid', $result->uniqueid, 'questionid', $result->questionid))) {
                        notify("Essay Table Migration: Cannot save comment");
                        break;
                    }
                    $state->event = 9;
                    //QUESTION_EVENTMANUALGRADE;
                } else {
                    // Not graded
                    $state->event = 7;
                    //QUESTION_EVENTSUBMIT;
                }
                // Save the event
                if (!($success = $success && update_record('question_states', $state))) {
                    notify("Essay Table Migration: Cannot update state");
                    break;
                }
            }
        }
        // dropping unused tables
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay_states');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'quiz_attemptonlast_datasets', false);
    }
    if ($oldversion < 2006081000) {
        // Add a column to the the question table to store the question general feedback.
        $success = $success && table_column('question', '', 'commentarytext', 'text', '', '', '', 'not null', 'image');
        // Adjust the quiz review options so that general feedback is displayed whenever feedback is.
        $success = $success && execute_sql('UPDATE ' . $CFG->prefix . 'quiz SET review = ' . '(review & ~' . QUIZ_REVIEW_GENERALFEEDBACK . ') | ' . '((review & ' . QUIZ_REVIEW_FEEDBACK . ') * 8)');
        // Set the general feedback bits to be the same as the feedback ones.
        // Same adjustment to the defaults for new quizzes.
        $success = $success && set_config('quiz_review', $CFG->quiz_review & ~QUIZ_REVIEW_GENERALFEEDBACK | ($CFG->quiz_review & QUIZ_REVIEW_FEEDBACK) << 3);
    }
    if ($success && $oldversion < 2006081400) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_feedback (\n                id int(10) unsigned NOT NULL auto_increment,\n                quizid int(10) unsigned NOT NULL default '0',\n                feedbacktext text NOT NULL default '',\n                mingrade double NOT NULL default '0',\n                maxgrade double NOT NULL default '0',\n                PRIMARY KEY (id),\n                KEY quizid (quizid)\n            ) TYPE=MyISAM COMMENT='Feedback given to students based on their overall score on the test';\n        ");
        $success = $success && execute_sql("\n            INSERT INTO {$CFG->prefix}quiz_feedback (quizid, feedbacktext, maxgrade, mingrade)\n            SELECT id, '', grade + 1, 0 FROM {$CFG->prefix}quiz;\n        ");
    }
    if ($success && $oldversion < 2006082400) {
        $success = $success && table_column('question_sessions', 'comment', 'manualcomment', 'text', '', '', '');
    }
    if ($success && $oldversion < 2006091900) {
        $success = $success && table_column('question_dataset_items', 'number', 'itemnumber', 'integer');
    }
    if ($success && $oldversion < 2006091901) {
        $success = $success && table_column('question', 'commentarytext', 'generalfeedback', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $success;
}
示例#22
0
function wiki_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2004040200) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki` DROP `allowstudentstowiki`');
    }
    if ($oldversion < 2004040700) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki` CHANGE `ewikiallowsafehtml` `htmlmode` TINYINT( 4 ) DEFAULT \'0\' NOT NULL');
    }
    if ($oldversion < 2004042100) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki` ADD `pagename` VARCHAR( 255 ) AFTER `summary`');
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki_entries` CHANGE `name` `pagename` VARCHAR( 255 ) NOT NULL');
        if ($wikis = get_records('wiki')) {
            foreach ($wikis as $wiki) {
                if (empty($wiki->pagename)) {
                    set_field('wiki', 'pagename', $wiki->name, 'id', $wiki->id);
                }
            }
        }
    }
    if ($oldversion < 2004053100) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki` CHANGE `initialcontent` `initialcontent` VARCHAR( 255 ) NOT NULL DEFAULT \'\'');
        //      Remove obsolete 'initialcontent' values.
        if ($wikis = get_records('wiki')) {
            foreach ($wikis as $wiki) {
                if (!empty($wiki->initialcontent)) {
                    set_field('wiki', 'initialcontent', null, 'id', $wiki->id);
                }
            }
        }
    }
    if ($oldversion < 2004061300) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki`' . ' ADD `setpageflags` TINYINT DEFAULT \'1\' NOT NULL AFTER `ewikiacceptbinary`,' . ' ADD `strippages` TINYINT DEFAULT \'1\' NOT NULL AFTER `setpageflags`,' . ' ADD `removepages` TINYINT DEFAULT \'1\' NOT NULL AFTER `strippages`,' . ' ADD `revertchanges` TINYINT DEFAULT \'1\' NOT NULL AFTER `removepages`');
    }
    if ($oldversion < 2004062400) {
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'wiki`' . ' ADD `disablecamelcase` TINYINT DEFAULT \'0\' NOT NULL AFTER `ewikiacceptbinary`');
    }
    if ($oldversion < 2004082200) {
        table_column('wiki_pages', '', 'userid', "integer", "10", "unsigned", "0", "not null", "author");
    }
    if ($oldversion < 2004082303) {
        // Try to update userid for old records
        if ($pages = get_records('wiki_pages', 'userid', 0, 'pagename', 'lastmodified,author,pagename,version')) {
            foreach ($pages as $page) {
                $name = explode('(', $page->author);
                $name = trim($name[0]);
                $name = explode(' ', $name);
                $firstname = $name[0];
                unset($name[0]);
                $lastname = trim(implode(' ', $name));
                if ($user = get_record('user', 'firstname', $firstname, 'lastname', $lastname)) {
                    set_field('wiki_pages', 'userid', $user->id, 'pagename', addslashes($page->pagename), 'version', $page->version);
                }
            }
        }
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}wiki DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX groupid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX wikiid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX pagename;", false);
        modify_database('', 'ALTER TABLE prefix_wiki ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_wiki_entries ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_wiki_entries ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_wiki_entries ADD INDEX groupid (groupid);');
        modify_database('', 'ALTER TABLE prefix_wiki_entries ADD INDEX wikiid (wikiid);');
        modify_database('', 'ALTER TABLE prefix_wiki_entries ADD INDEX pagename (pagename);');
    }
    if ($oldversion < 2005022000) {
        // recreating the wiki_pages table completelly (missing id, bug 2608)
        if ($rows = count_records("wiki_pages")) {
            // we need to use the temp stuff
            modify_database("", "CREATE TABLE `prefix_wiki_pages_tmp` (\n                `pagename` VARCHAR(160) NOT NULL,\n                `version` INT(10) UNSIGNED NOT NULL DEFAULT 0,\n                `flags` INT(10) UNSIGNED DEFAULT 0,\n                `content` MEDIUMTEXT,\n                `author` VARCHAR(100) DEFAULT 'ewiki',\n                `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0,\n                `created` INT(10) UNSIGNED DEFAULT 0,\n                `lastmodified` INT(10) UNSIGNED DEFAULT 0,\n                `refs` MEDIUMTEXT,\n                `meta` MEDIUMTEXT,\n                `hits` INT(10) UNSIGNED DEFAULT 0,\n                `wiki` INT(10) UNSIGNED NOT NULL);");
            execute_sql("INSERT INTO {$CFG->prefix}wiki_pages_tmp (pagename, version, flags, content,\n                                                                   author, userid, created, lastmodified,\n                                                                   refs, meta, hits, wiki) \n                         SELECT pagename, version, flags, content,\n                                author, userid, created, lastmodified,\n                                refs, meta, hits, wiki\n                         FROM {$CFG->prefix}wiki_pages");
            $insertafter = true;
        }
        execute_sql("DROP TABLE {$CFG->prefix}wiki_pages");
        modify_database("", "CREATE TABLE `prefix_wiki_pages` (\n            `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n            `pagename` VARCHAR(160) NOT NULL,\n            `version` INT(10) UNSIGNED NOT NULL DEFAULT 0,\n            `flags` INT(10) UNSIGNED DEFAULT 0,\n            `content` MEDIUMTEXT,\n            `author` VARCHAR(100) DEFAULT 'ewiki',\n            `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0,\n            `created` INT(10) UNSIGNED DEFAULT 0,\n            `lastmodified` INT(10) UNSIGNED DEFAULT 0,\n            `refs` MEDIUMTEXT,\n            `meta` MEDIUMTEXT,\n            `hits` INT(10) UNSIGNED DEFAULT 0,\n            `wiki` INT(10) UNSIGNED NOT NULL,\n            PRIMARY KEY (`id`),\n            UNIQUE KEY `wiki_pages_uk` (`pagename`,`version`,`wiki`))\n            ENGINE=MyISAM COMMENT='Holds the Wiki-Pages';");
        if (!empty($insertafter)) {
            execute_sql("INSERT INTO {$CFG->prefix}wiki_pages (pagename, version, flags, content,\n                                                               author, userid, created, lastmodified,\n                                                               refs, meta, hits, wiki) \n                         SELECT pagename, version, flags, content,\n                                author, userid, created, lastmodified,\n                                refs, meta, hits, wiki\n                         FROM {$CFG->prefix}wiki_pages_tmp");
            execute_sql("DROP TABLE {$CFG->prefix}wiki_pages_tmp");
        }
    }
    if ($oldversion < 2006042800) {
        execute_sql("UPDATE {$CFG->prefix}wiki SET summary='' WHERE summary IS NULL");
        table_column('wiki', 'summary', 'summary', 'text', '', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}wiki SET pagename='' WHERE pagename IS NULL");
        table_column('wiki', 'pagename', 'pagename', 'varchar', '255', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}wiki SET initialcontent='' WHERE initialcontent IS NULL");
        table_column('wiki', 'initialcontent', 'initialcontent', 'varchar', '255', '', '', 'not null');
    }
    if ($oldversion < 2006092502) {
        modify_database("", "\nCREATE TABLE prefix_wiki_locks\n(\n  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n  wikiid INT(10) UNSIGNED NOT NULL,\n  pagename VARCHAR(160) NOT NULL DEFAULT '',\n  lockedby INT(10) NOT NULL DEFAULT 0,\n  lockedsince INT(10) NOT NULL DEFAULT 0,\n  lockedseen INT(10) NOT NULL DEFAULT 0,\n  PRIMARY KEY(id),\n  UNIQUE INDEX wiki_locks_uk(wikiid,pagename),\n  INDEX wiki_locks_ix(lockedseen)  \n);");
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#23
0
function blocks_upgrade($oldversion = 0)
{
    global $CFG;
    $result = true;
    if ($oldversion < 2004041000 && $result) {
        $result = execute_sql("CREATE TABLE `{$CFG->prefix}blocks` (\n                        `id` int(10) unsigned NOT NULL auto_increment,\n                        `name` varchar(40) NOT NULL default '',\n                        `version` int(10) NOT NULL default '0',\n                        `cron` int(10) unsigned NOT NULL default '0',\n                        `lastcron` int(10) unsigned NOT NULL default '0',\n                        `visible` tinyint(1) NOT NULL default '1',\n                        PRIMARY KEY (`id`)\n                     ) \n                     COMMENT = 'To register and update all the available blocks'");
    }
    if ($oldversion < 2004101900 && $result) {
        $result = execute_sql("CREATE TABLE `{$CFG->prefix}block` (\n                        `id` int(10) unsigned NOT NULL auto_increment,\n                        `name` varchar(40) NOT NULL default '',\n                        `version` int(10) NOT NULL default '0',\n                        `cron` int(10) unsigned NOT NULL default '0',\n                        `lastcron` int(10) unsigned NOT NULL default '0',\n                        `visible` tinyint(1) NOT NULL default '1',\n                        `multiple` tinyint(1) NOT NULL default '0',\n                        PRIMARY KEY (`id`)\n                     ) \n                     COMMENT = 'To register and update all the available blocks'");
        if (!$result) {
            return false;
        }
        $records = get_records('blocks');
        if (!empty($records)) {
            foreach ($records as $block) {
                $block->multiple = 0;
                insert_record('block', $block, false);
            }
        }
        execute_sql("DROP TABLE `{$CFG->prefix}blocks`");
        $result = execute_sql("CREATE TABLE `{$CFG->prefix}block_instance` (\n                        `id` int(10) not null auto_increment,\n                        `blockid` int(10) not null default '0',\n                        `pageid` int(10) not null default '0',\n                        `pagetype` varchar(12) not null default '',\n                        `position` enum('l', 'r') not null default 'l',\n                        `weight` tinyint(3) not null default '0',\n                        `visible` tinyint(1) not null default '0',\n                        `configdata` text not null default '',\n                        \n                        PRIMARY KEY(`id`),\n                        INDEX pageid(`pageid`)\n                    )");
        if (!$result) {
            return false;
        }
        $records = get_records('course', '', '', '', 'id, shortname, blockinfo');
        if (!empty($records)) {
            foreach ($records as $thiscourse) {
                // The @ suppresses a notice emitted if there is no : in the string
                @(list($left, $right) = split(':', $thiscourse->blockinfo));
                if (!empty($left)) {
                    $arr = explode(',', $left);
                    foreach ($arr as $weight => $blk) {
                        $instance = new stdClass();
                        $instance->blockid = abs($blk);
                        $instance->pageid = $thiscourse->id;
                        $instance->pagetype = PAGE_COURSE_VIEW;
                        $instance->position = BLOCK_POS_LEFT;
                        $instance->weight = $weight;
                        $instance->visible = $blk > 0 ? 1 : 0;
                        $instance->configdata = '';
                        insert_record('block_instance', $instance, false);
                    }
                }
                if (!empty($right)) {
                    $arr = explode(',', $right);
                    foreach ($arr as $weight => $blk) {
                        $instance = new stdClass();
                        $instance->blockid = abs($blk);
                        $instance->pageid = $thiscourse->id;
                        $instance->pagetype = PAGE_COURSE_VIEW;
                        $instance->position = BLOCK_POS_RIGHT;
                        $instance->weight = $weight;
                        $instance->visible = $blk > 0 ? 1 : 0;
                        $instance->configdata = '';
                        insert_record('block_instance', $instance, false);
                    }
                }
            }
        }
        execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP COLUMN blockinfo");
    }
    if ($oldversion < 2004112900 && $result) {
        $result = $result && table_column('block_instance', 'pagetype', 'pagetype', 'varchar', '20', '');
        $result = $result && table_column('block_instance', 'position', 'position', 'varchar', '10', '');
    }
    if ($oldversion < 2004112900 && $result) {
        execute_sql('UPDATE ' . $CFG->prefix . 'block_instance SET pagetype = \'' . PAGE_COURSE_VIEW . '\' WHERE pagetype = \'\'');
    }
    if ($oldversion < 2005043000 && $result) {
        $records = get_records('block');
        if (!empty($records)) {
            foreach ($records as $block) {
                if (!block_is_compatible($block->name)) {
                    $block->visible = 0;
                    update_record('block', $block);
                    notify('The ' . $block->name . ' block has been disabled because it is not compatible with Moodle 1.5 and needs to be updated by a programmer.');
                }
            }
        }
    }
    if ($oldversion < 2005081600) {
        $result = $result && modify_database('', "CREATE TABLE `prefix_block_pinned` (\n           `id` int(10) not null auto_increment,\n           `blockid` int(10) not null default '0',\n           `pagetype` varchar(20) not null default '',\n           `position` varchar(10) not null default '',\n           `weight` tinyint(3) not null default '0',\n           `visible` tinyint(1) not null default '0',\n           `configdata` text not null default '',\n           PRIMARY KEY(`id`)\n          ) TYPE=MyISAM;");
    }
    if ($oldversion < 2005090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}block_instance ADD INDEX pagetype (pagetype);", false);
        // do it silently, in case it's already there from 1.5
        modify_database('', 'ALTER TABLE prefix_block_pinned ADD INDEX pagetype (pagetype);');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    //Finally, return result
    return $result;
}
示例#24
0
function choice_upgrade($oldversion)
{
    global $CFG;
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    if ($oldversion < 2003010100) {
        execute_sql(" ALTER TABLE `choice` ADD `format` INTEGER DEFAULT '0' NOT NULL AFTER `text` ");
        execute_sql(" ALTER TABLE `choice` ADD `publish` INTEGER DEFAULT '0' NOT NULL AFTER `answer6` ");
    }
    if ($oldversion < 2004010100) {
        table_column("choice", "", "showunanswered", "integer", "4", "unsigned", "0", "", "publish");
    }
    if ($oldversion < 2004021700) {
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('choice', 'choose', 'choice', 'name');");
        modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('choice', 'choose again', 'choice', 'name');");
    }
    if ($oldversion < 2004070100) {
        table_column("choice", "", "timeclose", "integer", "10", "unsigned", "0", "", "showunanswered");
        table_column("choice", "", "timeopen", "integer", "10", "unsigned", "0", "", "showunanswered");
    }
    if ($oldversion < 2004070101) {
        table_column("choice", "", "release", "integer", "2", "unsigned", "0", "", "publish");
        table_column("choice", "", "allowupdate", "integer", "2", "unsigned", "0", "", "release");
    }
    if ($oldversion < 2004070102) {
        modify_database("", "UPDATE prefix_choice SET allowupdate = '1' WHERE publish = 0;");
        modify_database("", "UPDATE prefix_choice SET release = '1' WHERE publish > 0;");
        modify_database("", "UPDATE prefix_choice SET publish = publish - 1 WHERE publish > 0;");
    }
    if ($oldversion < 2004111200) {
        // drop first to avoid conflicts when upgrading from 1.4+
        execute_sql("DROP INDEX {$CFG->prefix}choice_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}choice_answers_choice_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}choice_answers_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_choice_course_idx ON prefix_choice (course);');
        modify_database('', 'CREATE INDEX prefix_choice_answers_choice_idx ON prefix_choice_answers (choice);');
        modify_database('', 'CREATE INDEX prefix_choice_answers_userid_idx ON prefix_choice_answers (userid);');
    }
    if ($oldversion < 2005033000) {
        if (execute_sql("CREATE TABLE {$CFG->prefix}choice_options (id SERIAL PRIMARY KEY, choiceid integer NOT NULL default '0', text TEXT, timemodified integer NOT NULL default '0');")) {
            execute_sql("CREATE INDEX {$CFG->prefix}choice_options_choice_idx ON {$CFG->prefix}choice_options (choiceid);");
            table_column('choice_answers', 'choice', 'choiceid', 'integer', '10', 'unsigned', 0, 'not null');
            table_column('choice_answers', 'answer', 'optionid', 'integer', '10', 'unsigned', 0, 'not null');
            table_column('choice', '', 'display', 'integer', '4', 'unsigned', 0, 'not null', 'release');
            // move old answers from choice to choice_options
            if ($choices = get_records('choice')) {
                foreach ($choices as $choice) {
                    for ($i = 1; $i <= 6; $i++) {
                        // We used to have six columns
                        $option = new stdClass();
                        $option->text = addslashes($choice->{'answer' . $i});
                        if ($option->text) {
                            /// Don't bother with blank options
                            $option->choiceid = $choice->id;
                            $option->timemodified = $choice->timemodified;
                            if ($option->id = insert_record('choice_options', $option)) {
                                /// Update all the user answers to fit the new value
                                execute_sql("UPDATE {$CFG->prefix}choice_answers\n                                                SET optionid={$option->id}\n                                              WHERE choiceid={$choice->id}\n                                                AND optionid={$i}");
                            }
                        }
                    }
                }
            }
            // drop old fields
            modify_database('', 'ALTER TABLE prefix_choice DROP answer1;');
            modify_database('', 'ALTER TABLE prefix_choice DROP answer2;');
            modify_database('', 'ALTER TABLE prefix_choice DROP answer3;');
            modify_database('', 'ALTER TABLE prefix_choice DROP answer4;');
            modify_database('', 'ALTER TABLE prefix_choice DROP answer5;');
            modify_database('', 'ALTER TABLE prefix_choice DROP answer6;');
        }
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $wtm->update('choice', 'text', 'format');
    }
    if ($oldversion < 2005041500) {
        //new limit feature
        table_column('choice', '', 'limitanswers', 'INTEGER', '2', 'unsigned', 0, 'not null', 'showunanswered');
        table_column('choice_options', '', 'maxanswers', 'INTEGER', '10', 'unsigned', 0, 'null', 'text');
    }
    if ($oldversion < 2005041501) {
        // Mass cleanup of bad upgrade scripts
        modify_database('', 'CREATE INDEX prefix_choice_answers_choice_idx ON prefix_choice_answers (choiceid)');
        notify('The above error can be ignored if the index already exists, its possible that it was cleaned up already before running this upgrade');
        modify_database('', 'ALTER TABLE prefix_choice ALTER display SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_choice ALTER limitanswers SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_choice_answers ALTER choiceid SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_choice_answers ALTER optionid SET NOT NULL');
    }
    if ($oldversion < 2006020900) {
        //rename release column to showanswers - Release is now reserved word in mySql
        table_column('choice', 'release', 'showresults', 'TINYINT', '2', 'unsigned', 0, 'not null');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#25
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;
}
示例#26
0
function main_upgrade($oldversion = 0)
{
    global $CFG, $db;
    $result = true;
    if ($oldversion < 0) {
        modify_database('', "CREATE TABLE {$CFG->prefix}datalists (\r\n                              ident SERIAL PRIMARY KEY,\r\n                              name varchar(32) NOT NULL default '',\r\n                              value text NOT NULL\r\n                            );");
        modify_database('', "CREATE INDEX {$CFG->prefix}datalists_name_idx ON {$CFG->prefix}datalists (name);");
    }
    if ($oldversion < 2006010600) {
        execute_sql("\r\n            CREATE TABLE {$CFG->prefix}weblog_watchlist (\r\n              ident SERIAL PRIMARY KEY,\r\n              owner integer NOT NULL default '0',\r\n              weblog_post integer NOT NULL default '0'\r\n            ) ;\r\n\r\n            CREATE INDEX {$CFG->prefix}weblog_watchlist_owner_idx ON {$CFG->prefix}weblog_watchlist (owner,weblog_post);");
        execute_sql("DROP INDEX {$CFG->prefix}friends_owner_idx ;");
        execute_sql("CREATE INDEX {$CFG->prefix}friends_owner_idx ON {$CFG->prefix}friends (owner) ;");
        execute_sql("CREATE INDEX {$CFG->prefix}friends_friend_idx ON {$CFG->prefix}friends (friend) ;");
        table_column('friends', '', 'status', 'varchar', '4', '', 'perm');
        execute_sql("CREATE INDEX {$CFG->prefix}friends_status_idx ON {$CFG->prefix}friends (status);");
        table_column('users', '', 'moderation', 'varchar', '4', '', 'no');
        execute_sql("CREATE INDEX {$CFG->prefix}users_moderation_idx ON {$CFG->prefix}users (moderation);");
    }
    if ($oldversion < 2006010601) {
        execute_sql("DROP INDEX {$CFG->prefix}file_folders_owner_idx ;");
        execute_sql("CREATE INDEX {$CFG->prefix}file_folders_files_owner_idx ON {$CFG->prefix}file_folders (files_owner);");
        execute_sql("CREATE INDEX {$CFG->prefix}file_folders_owner_idx ON {$CFG->prefix}file_folders (owner);");
        execute_sql("CREATE INDEX {$CFG->prefix}file_folders_access_idx ON {$CFG->prefix}file_folders (access);");
        execute_sql("CREATE INDEX {$CFG->prefix}file_folders_name_idx ON {$CFG->prefix}file_folders (name);");
        execute_sql("DROP INDEX {$CFG->prefix}icons_owner_idx ;");
        execute_sql("CREATE INDEX {$CFG->prefix}icons_owner_idx ON {$CFG->prefix}icons (owner) ;");
        execute_sql("DROP INDEX {$CFG->prefix}invitations_name_idx ;");
        execute_sql("CREATE INDEX {$CFG->prefix}invitations_code_idx ON {$CFG->prefix}invitations (code);");
        execute_sql("CREATE INDEX {$CFG->prefix}invitations_email_idx ON {$CFG->prefix}invitations (email);");
        execute_sql("CREATE INDEX {$CFG->prefix}invitations_added_idx ON {$CFG->prefix}invitations (added);");
        execute_sql("DROP INDEX {$CFG->prefix}tags_tag_idx ;");
        execute_sql("DROP INDEX {$CFG->prefix}tags_tag_2_idx ;");
        execute_sql("CREATE INDEX {$CFG->prefix}tags_tagtype_ref_idx ON {$CFG->prefix}tags (tagtype,ref);");
        execute_sql("CREATE INDEX {$CFG->prefix}tags_tag_idx ON {$CFG->prefix}tags (tag);");
    }
    if ($oldversion < 2006012600) {
        modify_database('', "CREATE TABLE {$CFG->prefix}users_alias (\r\n                               ident SERIAL PRIMARY KEY,\r\n                               installid varchar(32) NOT NULL default '',\r\n                               username varchar(32) NOT NULL default '',\r\n                               firstname varchar(64) NOT NULL default '',\r\n                               lastname varchar(64) NOT NULL default '',\r\n                               email varchar(128) NOT NULL default '',\r\n                               user_id integer NOT NULL default 0\r\n                             );");
        modify_database('', "CREATE INDEX {$CFG->prefix}users_alias_username_idx ON {$CFG->prefix}users_alias (username);");
        modify_database('', "CREATE INDEX {$CFG->prefix}users_alias_installid_idx ON {$CFG->prefix}users_alias (installid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}users_alias_user_id_idx ON {$CFG->prefix}users_alias (user_id);");
    }
    if ($oldversion < 2006021400) {
        modify_database('', "CREATE TABLE {$CFG->prefix}files_incoming (\r\n                               ident SERIAL PRIMARY KEY,\r\n                               installid varchar(32) NOT NULL default '',\r\n                               intentiondate integer NOT NULL default 0,\r\n                               size bigint NOT NULL default 0,\r\n                               foldername varchar(128) NOT NULL default '',\r\n                               user_id integer NOT NULL default 0\r\n                            );");
        modify_database('', "CREATE INDEX {$CFG->prefix}files_incoming_user_id_idx ON {$CFG->prefix}files_incoming (user_id);");
    }
    if ($oldversion < 2006022000) {
        modify_database('', "CREATE TABLE {$CFG->prefix}feed_posts (\r\n                              ident SERIAL PRIMARY KEY,\r\n                              posted varchar(64) NOT NULL default '',\r\n                              added integer NOT NULL default 0,\r\n                              feed integer NOT NULL default 0,\r\n                              title text NOT NULL,\r\n                              body text NOT NULL,\r\n                              url varchar(128) NOT NULL default ''\r\n                            );");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_posts_url_idx ON {$CFG->prefix}feed_posts (url);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_posts_feed_idx ON {$CFG->prefix}feed_posts (feed);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_posts_posted_idx ON {$CFG->prefix}feed_posts (posted,added);");
        modify_database('', "CREATE TABLE {$CFG->prefix}feed_subscriptions (\r\n                              ident SERIAL PRIMARY KEY,\r\n                              user_id integer NOT NULL default 0,\r\n                              feed_id integer NOT NULL default 0,\r\n                              autopost varchar(3) NOT NULL default 'no' check (autopost in ('yes', 'no')),\r\n                              autopost_tag varchar(128) NOT NULL default ''\r\n                            );");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_subscriptions_feed_idx ON {$CFG->prefix}feed_subscriptions (feed_id);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_subscriptions_user_idx ON {$CFG->prefix}feed_subscriptions (user_id);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feed_subscriptions_autopost_idx ON {$CFG->prefix}feed_subscriptions (autopost);");
        modify_database('', "CREATE TABLE {$CFG->prefix}feeds (\r\n                              ident SERIAL PRIMARY KEY,\r\n                              url varchar(128) NOT NULL default '',\r\n                              feedtype varchar(16) NOT NULL default '',\r\n                              name text NOT NULL,\r\n                              tagline varchar(128) NOT NULL default '',\r\n                              siteurl varchar(128) NOT NULL default '',\r\n                              last_updated integer NOT NULL default 0\r\n                            );");
        modify_database('', "CREATE INDEX {$CFG->prefix}feeds_url_idx ON {$CFG->prefix}feeds (url,feedtype);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feeds_last_updated_idx ON {$CFG->prefix}feeds (last_updated);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feeds_siteurl_idx ON {$CFG->prefix}feeds (siteurl);");
        modify_database('', "CREATE INDEX {$CFG->prefix}feeds_tagline_idx ON {$CFG->prefix}feeds (tagline);");
    }
    if ($oldversion < 2006022100) {
        modify_database('', "CREATE TABLE {$CFG->prefix}friends_requests (\r\n                              ident SERIAL PRIMARY KEY,\r\n                              owner integer NOT NULL default 0,\r\n                              friend integer NOT NULL default 0\r\n                            ) ;");
        modify_database('', "CREATE INDEX {$CFG->prefix}friends_requests_owner_idx ON {$CFG->prefix}friends_requests (owner);");
    }
    if ($oldversion < 2006022200) {
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements (name,content,template_id) VALUES ('pageshell', '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<title>{{title}}</title>\r\n{{metatags}}\r\n</head>\r\n<body>\r\n<!-- elgg banner and logo -->\r\n<div id=\"container\"><!-- start container -->\r\n    <div id=\"statusbar\"><!-- start statusbar -->\r\n        <div id=\"welcome\"><!-- start welcome -->\r\n            <p>Welcome {{userfullname}}</p>\r\n        </div><!-- end welcome -->\r\n        {{topmenu}}\r\n    </div><!-- end statusbar -->\r\n    <div id=\"header\"><!-- start header -->\r\n        <h1>Elgg</h1>\r\n            <h2>Community learning space</h2>\r\n            <ul id=\"navigation\">\r\n                {{menu}}\r\n            </ul>\r\n    </div><!-- end header -->\r\n    <div id=\"content_holder\"><!-- start contentholder -->\r\n        <div id=\"maincontent_container\"><!-- start main content -->\r\n            {{messageshell}}\r\n            {{mainbody}}\r\n        </div><!-- end main content -->\r\n        <div id=\"sidebar_container\">\r\n            <div id=\"sidebar\"><!-- start sidebar -->\r\n                <ul><!-- open sidebar lists -->\r\n                {{sidebar}}\r\n                </ul>\r\n            </div><!-- end sidebar -->\r\n        </div><!-- end sidebar_container -->\r\n    </div><!-- end contentholder -->\r\n    <div class=\"clearall\" />\r\n    <div id=\"footer\"><!-- start footer -->\r\n               Using the <a href=\"http://www.ifelse.co.uk/gentle-calm\">Gentle Calm theme</a> designed by <a href=\"http://www.ifelse.co.uk\">Phu Ly</a>.<br />\r\n        <a href=\"http://elgg.net\"><img src=\"http://development.apcala.com/_templates/elgg_powered.png\" alt=\"Powered by Elgg\" title=\"Powered by Elgg\" border=\"0\" /></a>\r\n    </div><!-- end footer -->\r\n</div><!-- end container -->\r\n</body>\r\n</html>', 5);");
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements (name,content,template_id) VALUES ( 'css', '/* \r\nTheme Name: Connections\r\nTheme URI: http://wpthemes.info\r\nVersion: 1.0\r\nDescription: A Theme from wpthemes.Info\r\nAuthor: Patricia Muller\r\nAuthor URI: http://www.vanillamist.com/blog/\r\n*/\r\nbody {\r\n    margin:0;\r\n    padding:0;\r\n    font-family: ''Trebuchet MS'',Georgia, Times, Times New Roman, sans-serif;\r\n    font-size: 80%;\r\n    text-align:center;\r\n    color:#29303B;\r\n    line-height:1.3em;\r\n    background: #F3F6ED;\r\n}\r\na {\r\n    color: #909D73;    \r\n    text-decoration:none;\r\n    font-size:100%;\r\n}\r\na:visited {\r\n    color: #8a3207;\r\n}\r\na:hover {\r\n    color: #753206;\r\n    text-decoration:underline;\r\n}\r\n\r\nh1 {\r\n       margin:0px 0px 15px 0px;\r\n    padding:0px;\r\n    font-size:120%;\r\n    font-weight:900;\r\n}\r\n\r\n\r\nh2, h3, h4, h5 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    font-size:100%\r\n}\r\n\r\nblockquote {\r\n    /*margin: 15px 30px 0 45px;*/\r\n    padding: 0 0 0 45px;\r\n    background: url(''/_templates/connections/blockquote.gif'') no-repeat left top;\r\n    font-style:italic;\r\n}\r\n\r\n\r\nh3 {\r\n    margin: 0;\r\n    padding: 0;\r\n    font-size:1.3em;\r\n}\r\np {\r\n    margin: 0 0 1em;\r\n    padding: 0;\r\n    line-height: 1.5em;\r\n}\r\nh1, h2, h3, h4 {\r\n    font-family: Georgia, \"Lucida Sans Unicode\", lucida, Verdana, sans-serif;\r\n    font-weight: normal;\r\n    letter-spacing: 1px;\r\n}\r\n\r\ninput, textarea \r\n{\r\n    background: #F3F6ED;\r\n    border: #E1D6C6 1px solid;\r\n}\r\n\r\n#container \r\n{\r\n    background:#fff url(''/_templates/connections/rap.jpg'') center repeat-y;\r\n    width:760px;\r\n    margin:0 auto;\r\n    padding:0px 8px;\r\n    text-align:left;\r\n    font-family: Trebuchet MS,Georgia, Arial, serif;\r\n}\r\n\r\n/*-----------------------------------------\r\nTOP STATUS BAR \r\n-------------------------------------------*/\r\n#header {\r\n    background:#fff url(''/_templates/connections/top.jpg'') no-repeat bottom;     \r\n     height: 183px;\r\n    margin: 0 auto;\r\n    width:760px;\r\n    padding:0;\r\n    border:#fc9 0px solid;\r\n}\r\n\r\n#welcome {\r\n    float: left;\r\n}\r\n\r\n#welcome p{\r\n    font-weight:bold;\r\n       font-size:110%;\r\n    padding:0 0 0 4px;\r\n    margin:0px;\r\n}\r\n\r\n#global_menuoptions {\r\n    text-align: right;\r\n    padding:0 5px 0 0;\r\n    margin:0px;\r\n    float:right;\r\n}\r\n\r\n#global_menuoptions ul {\r\n    margin: 0; \r\n    padding: 0;\r\n}\r\n\r\n#global_menuoptions li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n\r\n#global_menuoptions a {\r\n    text-decoration: none;\r\n    font-size:80%;\r\n}\r\n\r\n#global_menuoptions a:hover{\r\n    text-decoration:underline;\r\n}\r\n\r\n    \r\n/*-------------------------------------------------\r\nnavigation\r\n-------------------------------------------------*/\r\n\r\n#navigation {\r\n    height: 21px;\r\n    margin: 0;\r\n    padding-left: 20px;\r\n    text-align:left;\r\n    padding-top:155px;\r\n}\r\n\r\n#navigation li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n    \r\n#navigation a:link, #navigation a:visited {\r\n\r\n    background: #524B21; /*#9BBB38;*/\r\n    font-size:85%;\r\n    font-weight: normal;\r\n    padding: 4px 6px;\r\n    margin: 0 2px 0 0;\r\n    border: 0px solid #036;\r\n    border-bottom: #9BBB38;\r\n    text-decoration: none;\r\n    color: #fff;\r\n}\r\n\r\n#navigation a:link.current, #navigation a:visited.current {\r\n    border-bottom: 0px solid #9BBB38;\r\n    background: #F5F5E7;\r\n    color: #9BBB38;\r\n    font-weight: bold;\r\n}\r\n\r\n#navigation a:hover {\r\n    color: #fff;\r\n    background: #000;\r\n}\r\n#navigation li a:hover{\r\n    background:#000;\r\n    }\r\n\r\n#content_holder \r\n{\r\n    margin:0 auto;\r\n    padding:0;\r\n    background:#000 url(''/_templates/connections/content_bg.gif'') repeat;\r\n    width:740px;\r\n}\r\n#maincontent_container {\r\n    width:510px;\r\n    float:left;\r\n    padding:5px;\r\n    margin:0;\r\n    overflow:hidden;\r\n    display:inline;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\nDIV''s to help control look and feel - infoholder holds all the profile data\r\nand is always located in within ''maincontentdisplay''\r\n\r\n-------------------------------------------------------------------------*/\r\n\r\n/*------ holds profile data -------*/\r\n.infoholder {\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 5px 0;\r\n}\r\n\r\n.infoholder p {\r\n   padding:0 0 0 5px;\r\n}\r\n\r\n.infoholder .fieldname h2 {\r\n          border:0;\r\n          border-bottom:1px;\r\n          border-color:#eee;\r\n          border-style:solid;\r\n          padding:5px;\r\n          color:#666;\r\n          background:#fff;\r\n}   \r\n\r\n.infoholder_twocolumn {\r\n    padding:4px;\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 10px 0;\r\n }\r\n\r\n.infoholder_twocolumn .fieldname h3{\r\n    color:#666;\r\n    background:#fff;\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n}\r\n\r\n/*----------- holds administration data---------*/\r\n\r\n.admin_datatable {\r\n  border:1px;\r\n  border-color:#eee;\r\n  border-style:solid;\r\n  margin:0 0 5px 0;\r\n}\r\n\r\n.admin_datatable p {\r\n     padding:0px;\r\n     margin:0px;\r\n}\r\n\r\n.admin_datatable a {\r\n   \r\n}\r\n\r\n\r\n.admin_datatable td {\r\n   text-align:left;\r\n}\r\n\r\n.admin_datatable h3{\r\n     color:#666;\r\n     background:#fff;\r\n     font-size:85%;\r\n}\r\n\r\n.admin_datatable h5 {\r\n     padding:0px;\r\n     margin:0px;\r\n}\r\n\r\n/*---- header plus one row of content ------*/\r\n\r\n.databox_vertical {\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   padding:5px;\r\n }\r\n\r\n .databox_vertical p{\r\n   padding:0px;\r\n   margin:0px;\r\n }\r\n\r\n.databox_vertical .fieldname h3 {\r\n  padding:0px;\r\n  margin:0px;\r\n  font-size:90%;\r\n}\r\n\r\n/*------- holds file content ----*/\r\n\r\n.filetable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n .filetable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#000; /*#1181AA;*/\r\n   background:#fff;\r\n }\r\n\r\n.filetable a{\r\n   \r\n }\r\n\r\n\r\n.filetable table {\r\n    text-align:left;\r\n}\r\n\r\n#edit_files h4 {\r\n     \r\n}\r\n  \r\n\r\n/*------- holds fodler content ------*/\r\n\r\n.foldertable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n.foldertable a{\r\n  \r\n }\r\n\r\n .foldertable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#1181AA;\r\n   background:#fff;\r\n }\r\n\r\n.foldertable table {\r\n    text-align:left;\r\n}\r\n\r\n/*------- holds network data ------*/\r\n\r\n.networktable {\r\n   \r\n}\r\n\r\n#sidebar {\r\n    width:186px;\r\n    float:right;\r\n    padding:0px 8px 10px 8px;\r\n    margin:0;\r\n    font-size:1em;\r\n    color:#333;\r\n    display:inline;\r\n}\r\n\r\n\r\n#header h1 \r\n{\r\n    margin: 0;    \r\n    font-size: 1.6em;    \r\n    padding:10px 20px 0 0;\r\n    text-align:right;    \r\n}\r\n#header h1 a \r\n{\r\n    color:#B5C09D;\r\n    text-decoration:none;\r\n}\r\n#header h1 a:hover \r\n{\r\n    color:#F7F3ED;\r\n}\r\n\r\n#sidebar h2 {\r\n    margin: 10px 0 0 0;\r\n    padding:2px;\r\n    font-size: 90%;\r\n    color: #676E04;\r\n    text-align:center;\r\n    background:url(''/_templates/connections/sidenav_top.jpg'') no-repeat center;\r\n    border:#ccc 0px solid;\r\n    height:22px;\r\n    font-weight:bold;\r\n}\r\n#sidebar ul {\r\n    list-style-type: none;\r\n    padding: 0px;\r\n    margin: 0;\r\n}\r\n\r\n#sidebar ul li ul{\r\n    list-style-type: none;\r\n    padding: 0;\r\n    margin: 0;\r\n    font-size: 0.9em;    \r\n    padding-bottom:3em;\r\n    background:#F3F6ED url(''/_templates/connections/sidenav_bottom.jpg'') no-repeat bottom;\r\n    border:#E1D6c6 1px solid;\r\n    border-top:#f3f6ed 1px solid;\r\n}\r\n\r\n#sidebar ul li ul li{\r\n    margin: 0.1em 0 0 0;\r\n    padding: 2px;    \r\n}\r\n#sidebar li a {\r\n    text-decoration: none;\r\n    border:none;\r\n}\r\n#sidebar li a:link {\r\n    color: #909D73;    \r\n}\r\n#sidebar li a:visited {\r\n    color: #999999;    \r\n}\r\n#sidebar li a:hover, #sidebar li a:active {\r\n    color: #990000;\r\n}\r\n\r\n/*-------------------------------------------\r\nSIDEBAR DISPLAY COMPONENTS \r\n----------------------------------------------*/\r\n\r\n#sidebar_user {\r\n}\r\n\r\n#recent_activity {\r\n}\r\n\r\n#community_owned {\r\n}\r\n\r\n#community_membership {\r\n}\r\n\r\n#sidebar_friends {\r\n}\r\n\r\n#search {\r\n}\r\n\r\n/*--- extra div''s when looking at someone else''s page ---*/\r\n\r\n#sidebar_weblog {\r\n}\r\n\r\n#sidebar_files {\r\n}\r\n\r\n#me {\r\n        padding: 0 3px 3px 3px;\r\n    min-height: 71px;\r\n    font-size: 0.9em;    \r\n    padding-bottom:3em;\r\n    background:#F3F6ED url(''/_templates/connections/sidenav_bottom.jpg'') no-repeat bottom;\r\n    border:#E1D6c6 1px solid;\r\n    border-top:#f3f6ed 1px solid;\r\n}\r\n\r\n#me a {\r\n   \r\n  }\r\n\r\n#me #icon {\r\n   margin:3px 0 0 0;\r\n   float: left; \r\n   width: 70px;\r\n}\r\n\r\n#me #contents {\r\n   margin: 0 0 0 75px;\r\n   text-align: left;\r\n}\r\n\r\n#searchform {\r\n    font-size: 0.9em;    \r\n    padding-bottom:1em;\r\n    background:#F3F6ED;\r\n    border:#E1D6c6 1px solid;\r\n    border-top:#f3f6ed 1px solid;\r\n    text-align:center;\r\n}\r\n\r\n#maincontent_holder ul {\r\n    margin-left: 0;\r\n    padding-left: 45px;\r\n    list-style-type: none;\r\n}\r\n\r\n#maincontent_holder ul li {\r\n    background: url(''img/bullet.gif'') no-repeat 0 7px;\r\n    padding-left: 1.5em;\r\n}\r\n\r\n/*-------------------------------------------\r\n  INDIVIDUAL BLOG POSTS \r\n  -------------------------------------------*/\r\n\r\n\r\n.weblog_posts {\r\n}\r\n\r\n.user {\r\n    float: left;\r\n    margin: 4px;\r\n        padding:0 0 5px 0;\r\n    width: 105px;\r\n    text-align: left;\r\n}\r\n\r\n.entry  \r\n{\r\n    font-size:0.85em;\r\n    font-family: Verdana, Arial, Sans-Serif;\r\n    margin:0 0 30px 0;\r\n    padding:0;\r\n    color:#333;\r\n}\r\n.entry  a\r\n{\r\n    color:#990000;\r\n}\r\n.entry  a:hover \r\n{\r\n    color:#000;\r\n}\r\n\r\n.weblog_title h3 {\r\n    font-family:Georgia, Arial, Serif;\r\n    font-size:1.3em;\r\n    margin:0;\r\n    font-weight:bold;\r\n        text-decoration:none;\r\n    color:#676E04;\r\n    border:0px\r\n    font-size:80%;\r\n        margin: 3px 10px 5px 0;\r\n        padding: 8px 3px;\r\n}\r\n\r\n/* .entry h3 {\r\n    color:#676E04;\r\n    font-family: Georgia,''Lucida sans ms'', Verdana, Arial, Helvetica, sans-serif;\r\n    text-align: center;\r\n    font-size:80%;\r\n    font-weight: bold;\r\n    margin: 3px 10px 5px 0;\r\n    padding: 8px 3px;\r\n    /*background: #E7EBDE;*/\r\n    line-height:1em;\r\n    border:0px;\r\n        text-decoration:none;\r\n} */\r\n\r\n.post {\r\n    padding:10px 0;\r\n    margin:3px 0;\r\n    border-top:#BBC4A3 1px solid;    \r\n    font-family: Georgia, Verdana, Arial, serif;\r\n    font-size:100%;\r\n}\r\n\r\n.info\r\n{\r\n    padding-top:20px;\r\n    background:url(''/_templates/connections/divider.gif'') no-repeat center;\r\n}\r\n\r\n.weblog_dateheader {\r\n    padding: 0px;\r\n    margin: 0px;\r\n    color: #333;\r\n    background:#fff;\r\n    font-weight: normal;\r\n       font-size:90%;\r\n    font-style: italic;\r\n    line-height: 12px;\r\n    border:0px;\r\n    border-bottom: 1px solid #ccc;\r\n}\r\n\r\n#footer {\r\n    margin:0 auto;\r\n    padding: 7px 0;\r\n    border-top:#BBC4A3 1px solid;\r\n    clear: both;\r\n    font-size: 0.8em;\r\n    color: #999;\r\n    text-align:center;\r\n    width:740px;\r\n}\r\n#footer a {\r\nborder:none;\r\ncolor:#7A7636;\r\n}\r\n\r\n.comments {\r\n    font-size:1em;\r\n    font-weight:normal;    \r\n}\r\n#comments\r\n{\r\n    margin:0 0 0 40px;\r\n}\r\n#comments textarea {\r\n    width: 80%;\r\n}\r\n#comments p {\r\n    margin: 0 0 1em;\r\n}\r\n#comments,#respond {\r\n    text-transform: uppercase;\r\n    margin: 3em 0 1em 40px;\r\n    color: #676E04;\r\n    font: 0.9em verdana, helvetica, sans-serif;\r\n}\r\n#comments li \r\n{\r\n    margin:5px 0;\r\n    padding:10px 10px 20px 10px;\r\n    background:#F3F6ED url(_template/connections/comments_bottom.jpg) repeat-x bottom;\r\n    border:#E1D6C6 1px solid;\r\n}\r\n#comments .alt \r\n{\r\n\r\n}\r\n\r\n#global_menuoptions \r\n{\r\n    list-style:none;\r\n    font-size:0.9em;\r\n    margin:0 auto;    \r\n    padding:12px 20px 0 0;\r\n    text-align:right;    \r\n    font-family:Verdana, Arial, Sans-Serif;\r\n}\r\n#global_menuoptions li \r\n{\r\n    list-style:none;\r\n    display:inline;\r\n    padding:0;\r\n    margin:0;\r\n    font-weight:bold;\r\n}\r\n\r\n#global_menuoptions li a:link, #global_menuoptions li a:visited\r\n{\r\n    text-decoration:none;    \r\n    color:#BBC4A3;\r\n}\r\n#global_menuoptions li a:hover, #global_menuoptions li a:active\r\n{\r\n    color:#F7F3ED;    \r\n}\r\n\r\n/*-------------------------------------\r\n  Input forms\r\n--------------------------------------*/\r\n\r\n.textarea{\r\n    border: 1px solid #7F9DB9;\r\n    color:#71717B;\r\n    width: 95%;\r\n       height:200px;\r\n    padding:3px;\r\n    -moz-border-radius: 3px;\r\n}\r\n\r\n.medium_textarea {\r\n   width:95%;\r\n   height:100px;\r\n}\r\n\r\n.small_textarea {\r\n    width:95%;\r\n}\r\n\r\n.keywords_textarea {\r\n    width:95%;\r\n    height:100px;\r\n}', 4);");
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements (name,content,template_id) VALUES ( 'css', '/*\r\n    Theme Name: Gentle Calm\r\n    Theme URI: http://ifelse.co.uk/gentlecalm\r\n    Description: Liquid Serenity\r\n    Version: 1.0\r\n    Author: Phu Ly\r\n    Author URI: http://ifelse.co.uk/\r\n*/\r\n\r\n/************************************************\r\n *    Main structure                                                            *\r\n ************************************************/\r\nbody {\r\n  margin:0px;\r\n  padding:0px;\r\n  text-align:center;\r\n  font:11px \"Lucida Grande\", \"Lucida Sans Unicode\", Verdana, Helvetica, Arial, sans-serif;\r\n    color: #474E44;\r\n    background:#F3F4EC;\r\n}\r\n\r\n/*-------------------------------------------------\r\nSTATUS BAR\r\n-------------------------------------------------*/\r\n\r\n#statusbar {\r\n    padding: 3px 10px 2px 0;\r\n    margin: 0px;\r\n    text-align: bottom;\r\n    height:15px;\r\n}\r\n\r\n\r\n#welcome {\r\n    float: left;\r\n}\r\n\r\n#welcome p{\r\n    font-weight:bold;\r\n       font-size:110%;\r\n    padding:0 0 0 4px;\r\n    margin:0px;\r\n}\r\n\r\n#global_menuoptions {\r\n    text-align: right;\r\n    padding:0 5px 0 0;\r\n    margin:0px;\r\n    float:right;\r\n}\r\n\r\n#global_menuoptions a:hover{\r\n    text-decoration:underline;\r\n}\r\n\r\n#global_menuoptions ul {\r\n    margin: 0; \r\n    padding: 0;\r\n}\r\n\r\n#global_menuoptions li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n\r\n#global_menuoptions a {\r\n    text-decoration: none;\r\n}\r\n\r\n#global_menuoptions a:hover{\r\n    text-decoration:underline;\r\n}\r\n\r\n#maincontent_container {\r\n  width:72%;\r\n  float:left;\r\n}\r\n#maincontent_container .col {\r\n    padding-bottom: 0.5em;\r\n    padding-left:2.5em;\r\n    padding-right:8.5em;\r\n    line-height:1.6em;\r\n}\r\n#sidebar {\r\n    padding:0.5em;\r\n    padding-top: 2em;\r\n    clear:right;\r\n    width:25%;\r\n  right:0px;\r\n    float:right;\r\n  font-size:1em; \r\n}\r\n#content_holder {    \r\n width:80%;\r\n text-align:left;\r\n margin-left: auto;\r\n display:block;\r\n margin-right: auto;\r\n padding-bottom:0;\r\n}\r\n\r\n#content_holder:after {\r\n    content: \".\"; \r\n    display: block; \r\n    height: 0; \r\n    clear: both; \r\n    visibility: hidden;\r\n}\r\n#footer{\r\n    border-top:1px solid #324031;\r\n    border-bottom:1px solid #324031;\r\n    color: #eee;\r\n    background: #87a284;\r\n    clear:both;\r\n    padding: 0.8em;\r\n    text-align:center;\r\n    margin-left: auto;\r\n    display:block;\r\n  margin-right: auto;\r\n  font-size: 0.9em;\r\n  margin-top:5em;\r\n}\r\n#footer a{\r\n    color: #fff;\r\n    font-weight:bold;\r\n}\r\na{\r\n    color: #3C657B;\r\n    text-decoration: none;\r\n}\r\na:hover {\r\n    text-decoration:underline;\r\n}\r\n/************************************************\r\n *    Header                                                                            *\r\n ************************************************/\r\n#header {\r\n    padding: 0px;    \r\n    margin-top: 0.3em;\r\n    padding-top:1em;    \r\n    padding-bottom:1em;\r\n    margin-bottom:0px;\r\n    border-bottom: 1px solid #bab1b1;\r\n    background: #CCCFBC;\r\n    text-align:right;\r\n    padding-right:2em;\r\n    padding-left:-.5em;\r\n}\r\n\r\n#header h1{\r\n    padding:0px;\r\n    margin: 0px;\r\n    font-size: 1.6em;\r\n    letter-spacing:0.2em;\r\n}\r\n#header h1 {\r\n    color:#5B7B57;\r\n}\r\n#header h1 a:hover {\r\n    text-decoration:none;\r\n    color: #bb4444;\r\n    \r\n}\r\n#header img {\r\n    border:none;\r\n}\r\n#header h2 {\r\n    margin-bottom:0.3em;\r\n    font-size: 0.8em;\r\n    text-transform:uppercase;\r\n    color:#A37B45;\r\n}\r\n\r\n/*-------------------------------------------------\r\nnavigation\r\n-------------------------------------------------*/\r\n\r\n#navigation {\r\n    height: 21px;\r\n    margin: 0;\r\n    padding: 0 0 0 20px;\r\n    text-align:left;\r\n}\r\n\r\n#navigation li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n    \r\n#navigation a:link, #navigation a:visited {\r\n\r\n    background: #524B21; /*#9BBB38;*/\r\n    font-size:85%;\r\n    font-weight: normal;\r\n    padding: 4px 6px;\r\n    margin: 0 2px 0 0;\r\n    border: 0px solid #036;\r\n    border-bottom: #9BBB38;\r\n    text-decoration: none;\r\n    color: #fff;\r\n}\r\n\r\n#navigation a:link.current, #navigation a:visited.current {\r\n    border-bottom: 0px solid #9BBB38;\r\n    background: #F5F5E7;\r\n    color: #9BBB38;\r\n    font-weight: bold;\r\n}\r\n\r\n#navigation a:hover {\r\n    color: #fff;\r\n    background: #000;\r\n}\r\n#navigation li a:hover{\r\n    background:#000;\r\n    }\r\n\r\n/************************************************\r\n *    Content                                                                            *\r\n ************************************************/\r\nh1, h2, h3, h4 {\r\n    font-family:\"Century Gothic\", \"Lucida Grande\", \"Lucida Sans Unicode\", Verdana, Helvetica, Arial, sans-serif;\r\n}\r\nh1 {\r\n  font-size:130%;\r\n  padding:10px 0 0 0;\r\n }\r\nh3 {\r\n  font-size:100%;\r\n }\r\n\r\nh4 {\r\n  font-size:100%;\r\n }\r\n\r\nh2 {\r\n    font-size: 1.2em;\r\n    margin-bottom:0.5em;\r\n}\r\nh2.entrydate{\r\n    margin-bottom:0.3em;\r\n    font-size: 1.8em;\r\n    font-weight:normal;\r\n    color:#86942A;\r\n    text-transform:uppercase;\r\n}\r\n.entrymeta{\r\n    font-weight:bold;\r\n    color:#99A879;\r\n}\r\nh3.entrytitle a{\r\n    color: #507642;\r\n}\r\nh3.weblog_title{\r\n    margin-top:0px;\r\n    margin-bottom:0.1em;\r\n    font-size: 1.8em;\r\n}\r\n\r\n.user {\r\n    float: left;\r\n    margin: 4px;\r\n        padding:0 0 5px 0;\r\n    width: 105px;\r\n    text-align: left;\r\n}\r\n\r\n.post p {\r\n    margin-top:0.8em;\r\n    margin-bottom:1.6em;\r\n}\r\n.weblog_posts{\r\n    padding-bottom: 2em;\r\n    font-family:\"Trebuchet MS\",\"Lucida Grande\", \"Lucida Sans Unicode\", Verdana, Helvetica, Arial, sans-serif;\r\n}\r\n/************************************************\r\n *    Navigation Sidebar                                                    *\r\n ************************************************/\r\nul {\r\n margin:0 0 1em 0;\r\n padding-left:0px;\r\n list-style-type:none;\r\n}\r\n/************************************************\r\n *    Comments                                                    *\r\n ************************************************/\r\nh2#comments{\r\n    text-align:center;\r\n    border-top:1px solid #9ba1aa;\r\n    background:#E2ECD5;\r\n    padding:0.7em;\r\n    border-bottom:1px solid #9ba1aa;\r\n    margin-bottom:1em;\r\n    margin-top:8em;\r\n}\r\nol#commentlist {\r\n    margin-top:0px;\r\n    padding: 0.5em;\r\n    margin-left: 0px;\r\n    color: #9b9b9b;\r\n    list-style-type: none;\r\n    font-size:0.9em;\r\n}\r\n#comments li  p{\r\n    padding: 0px;\r\n    margin: 0px;\r\n}\r\n.commentname {\r\n    float: left;\r\n    margin: 0;\r\n    padding: 0 0 0.2em 0;\r\n}\r\n.commentinfo{\r\n    width: 20em;\r\n    float: right;\r\n    text-align: right;\r\n}\r\n.commenttext {\r\n    clear: both;\r\n    padding-top: 0px;\r\n    margin-top: 0px;\r\n    margin-bottom: 3em;\r\n    border-top: 1px solid #ebebeb;\r\n    line-height:1.2em;\r\n    color: #5b5b5b;\r\n}\r\n#commentsformheader{\r\n    padding-left:1.5em;\r\n    font-size: 1.4em;\r\n}\r\n#commentsform{\r\n    margin-top:none;\r\n    text-align:center;\r\n    border:1px solid #ddd;\r\n    background:#ecefdf;\r\n    padding:0em 1em;\r\n}\r\n#commentsform form{\r\n    text-align:left;\r\n    margin:0px;\r\n}\r\n#commentsform p{\r\n    margin:0.5em;\r\n}\r\n#commentsform form textarea{\r\n    width:100%;\r\n}\r\n/************************************************\r\n *    Extra                                                                                *\r\n ************************************************/\r\ncode{\r\n    font-family: ''lucida console'', ''Courier New'', monospace;\r\n    font-size: 0.8em;\r\n    display:block;\r\n    padding:0.5em;\r\n    background-color: #E5EaE4;\r\n    border: 1px solid #d2d8d1;\r\n}\r\ninput[type=\"text\"], textarea {\r\n    padding:0.3em;\r\n    border: 1px solid #CCCFBC;\r\n    color: #656F5C;\r\n    -moz-border-radius: 0.5em;\r\n}\r\ninput[type=\"submit\"]{\r\n    padding:0.2em;\r\n    font-size: 1.25em;\r\n    border: 1px solid #CCCFBC;\r\n    color: #353F2f;\r\n    background: #fefff8;\r\n    -moz-border-radius: 0.5em;\r\n}\r\nblockquote {\r\n    border-left: 3px solid #686868;\r\n    color: #888;\r\n    padding-left: 0.8em;\r\n    margin-left: 2.5em;\r\n}\r\na img {\r\n    border:none;\r\n}\r\n.imgborder img{\r\n    border: 1px solid #87a284;\r\n    background:#CCCFBC;\r\n    padding:0.3em;\r\n}\r\n.imgborder{\r\n    text-align: center;\r\n}\r\n\r\n#system_message{ \r\n    border:1px solid #5B7B57;\r\n    background:#CCCFBC;\r\n    margin:20px 0 0 0;\r\n}\r\n\r\n#system_message p{\r\n   padding:0px;\r\n   margin:2px;\r\n }\r\n\r\n /*-------------------------------------\r\n  Input forms\r\n--------------------------------------*/\r\n\r\n.textarea{\r\n    border: 1px solid #7F9DB9;\r\n    color:#71717B;\r\n    width: 95%;\r\n       height:200px;\r\n    padding:3px;\r\n    -moz-border-radius: 3px;\r\n}\r\n\r\n.medium_textarea {\r\n   width:95%;\r\n   height:100px;\r\n}\r\n\r\n.small_textarea {\r\n    width:95%;\r\n}\r\n\r\n.keywords_textarea {\r\n    width:95%;\r\n    height:100px;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\nDIV''s to help control look and feel - infoholder holds all the profile data\r\nand is always located in within ''maincontentdisplay''\r\n\r\n-------------------------------------------------------------------------*/\r\n\r\n/*------ holds profile data -------*/\r\n.infoholder {\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 5px 0;\r\n}\r\n\r\n.infoholder p {\r\n   padding:0 0 0 5px;\r\n}\r\n\r\n.infoholder .fieldname h2 {\r\n          border:0;\r\n          border-bottom:1px;\r\n          border-color:#eee;\r\n          border-style:solid;\r\n          padding:5px;\r\n}   \r\n\r\n.infoholder_twocolumn {\r\n    padding:4px;\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 10px 0;\r\n }\r\n\r\n.infoholder_twocolumn .fieldname h3{\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n}', 5);");
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements  (name,content,template_id) VALUES ( 'pageshell', '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<title>{{title}}</title>\r\n{{metatags}}\r\n</head>\r\n<body>\r\n <!-- elgg banner and logo -->\r\n<div id=\"container\"><!-- start container -->\r\n<div id=\"header\"><!-- start header -->\r\n             {{topmenu}}\r\n        <ul id=\"navigation\">\r\n          {{menu}}\r\n         </ul>\r\n</div><!-- end header -->\r\n<div id=\"content_holder\"><!-- start contentholder -->\r\n<div id=\"maincontent_container\"><!-- start main content -->\r\n        {{messageshell}}\r\n      {{mainbody}}\r\n</div><!-- end main content -->\r\n<div id=\"sidebar_container\">\r\n<div id=\"sidebar\"><!-- start sidebar -->\r\n    <ul><!-- open sidebar lists -->\r\n        {{sidebar}}\r\n    </ul>\r\n</div><!-- end sidebar -->\r\n</div>\r\n</div><!-- end contentholder -->\r\n<div class=\"clearall\" />\r\n <div id=\"footer\"><!-- start footer -->\r\n        <a href=\"http://elgg.net\"><img src=\"/_templates/elgg_powered.png\" border=\"0\"></a>\r\n </div><!-- end footer -->\r\n</div><!-- end container -->\r\n </body>\r\n </html>', 4);");
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements  (name,content,template_id) VALUES ( 'css', '/*\r\nTheme Name: Northern-Web-Coders\r\nTheme URI: http://www.northern-web-coders.de/\r\nDescription: Northern-Web-Coders Theme\r\nVersion: 1.0\r\n\r\nAuthor: Kai Ackermann\r\n*/\r\n\r\nbody\r\n{\r\nbackground: #d8d8d3;\r\nfont-family: Lucida Grande, Verdana, sans-serif;\r\nmargin: 0;\r\npadding: 0;\r\nfont-size:80%;\r\ntext-align: center;\r\n}\r\n\r\na\r\n{\r\nfont-size:100%;\r\ncolor: #495865;\r\n}\r\n\r\na:hover\r\n{\r\ncolor: #6F6F6F;\r\n}\r\n\r\nh2, h3, h4, h5 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    font-size:100%\r\n}\r\n\r\n#container\r\n{\r\nbackground: #FFFFFF;\r\nmargin: 0 auto 0 auto;\r\nwidth: 769px;\r\ntext-align: left;\r\nborder: 2px solid #5F707A;\r\n}\r\n\r\n/*-----------------------------------------\r\nSTATUS BAR \r\n-------------------------------------------*/\r\n\r\n#statusbar {\r\n    padding: 3px 5px 0 0;\r\n    margin: 0px;\r\n    height:16px;\r\n    background:#eee;\r\n    color: #333;\r\n    font-size:80%;\r\n}\r\n\r\n#statusbar a {\r\n    color: #666;\r\n    background:#eee;\r\n}\r\n\r\n#welcome {\r\n    float: left;\r\n}\r\n\r\n#welcome p{\r\n    font-weight:bold;\r\n    padding:0 0 0 4px;\r\n    margin:0px;\r\n}\r\n\r\n#global_menuoptions {\r\n    text-align: right;\r\n    padding:0px;\r\n    margin:0px;\r\n    float:right;\r\n}\r\n\r\n#global_menuoptions ul {\r\n    margin: 0; \r\n    padding: 0;\r\n}\r\n\r\n#global_menuoptions li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n\r\n#global_menuoptions a {\r\n    text-decoration: none;\r\n}\r\n\r\n#global_menuoptions a:hover{\r\n    text-decoration:underline;\r\n}\r\n\r\n/*--------------------------------------------\r\n  Header\r\n  -------------------------------------------*/\r\n\r\n#header\r\n{\r\nbackground: url(/_templates/northern/totems_2.jpg);\r\nwidth: 769px;\r\nheight: 200px;\r\nmargin: 0;\r\npadding: 0;\r\ntext-align: right;\r\n}\r\n\r\n#header h1 {\r\n    padding:0 5px 0 5px;\r\n    margin:0px;\r\n    color:#fff;\r\n    }\r\n\r\n#header h2 {\r\n    padding:0 5px 0 5px;\r\n    margin:0px;\r\n    color:#fff;\r\n    }\r\n\r\n/*--------------------------------------------\r\nNAVIGATION \r\n----------------------------------------------*/\r\n\r\n#navigation ul\r\n{\r\npadding: 0;\r\nmargin: 0;\r\nbackground: #5F707A;\r\nborder-top: 1px solid #DFDFDF;\r\nborder-bottom: 0px solid #DFDFDF;\r\nfloat: left;\r\nwidth: 769px;\r\nfont-family: arial, helvetica, sans-serif;\r\n}\r\n\r\n\r\n\r\n#navigation ul li { display: inline; }\r\n\r\n#navigation ul li a\r\n{\r\npadding: 10px 14px 11px 14px;\r\nbackground: #9C9D95;\r\ncolor: #ffffff;\r\ntext-decoration: none;\r\nfont-weight: bold;\r\nfloat: left;\r\nfont-size:85%;\r\nborder-right: 1px solid #FFFFFF;\r\n}\r\n\r\n#navigation ul li a:hover\r\n{\r\ncolor: #990000;\r\nbackground: #C9C0B0;\r\n}\r\n\r\n#navigation a:link.current, #navigation a:visited.current\r\n{\r\npadding: 10px 14px 11px 14px;\r\nbackground: #C9C0B0;\r\ncolor: #990000;\r\ntext-decoration: none;\r\nfont-weight: bold;\r\nfloat: left;\r\nborder-right: 1px solid #DFDFDF;\r\n}\r\n\r\n#navigation a:link.current, #navigation a:visited.current a:hover\r\n{\r\nbackground: #6F6F6F;\r\n}\r\n\r\n\r\n/*-------------------------------------------------\r\nHOLDS THE MAIN CONTENT E.G. BLOG, PROFILE ETC \r\n----------------------------------------------------*/\r\n\r\n#maincontent_container\r\n{\r\nposition: relative;\r\nleft: 20px;\r\nfloat: left;\r\npadding: 0;\r\nwidth: 68%;\r\ncolor: #495865;\r\nfont-size:85%;\r\n}\r\n\r\n/*#maincontent_container h2\r\n{\r\nborder-bottom: 1px solid #6F6F6F;\r\ncolor: #5F707A;\r\nmargin: 20px 0 5px 0;\r\npadding: 0 0 3px 3px;\r\ntext-align: right;\r\n}*/\r\n\r\n/*-------------------------------------------------------------\r\nTHIS DISPLAYS THE ACTUAL CONTENT WITHIN maincontent_container\r\n--------------------------------------------------------------*/\r\n\r\n#maincontent_display h1 {\r\n    padding-bottom: 2px;\r\n    border-bottom: 1px solid #666;\r\n    margin: 10px 0 0 0;\r\n    font-size:120%;\r\n    color: #666;\r\n}\r\n\r\n#maincontent_display #sub_menu {\r\n    font-family: verdana;\r\n    padding: 2px 0 0 0;\r\n    margin: 0 0 15px 0;\r\n    font-weight: normal;\r\n    color: #990000;\r\n}\r\n\r\n#maincontent_display #sub_menu a {\r\n    font-weight:bold;\r\n    margin:0px;\r\n    padding:0px;\r\n    color: #990000;\r\n}\r\n\r\n#maincontent_display #sub_menu a:hover {\r\n    text-decoration: underline;\r\n}\r\n\r\n#maincontent_display #sub_menu p {\r\n      margin:0px;\r\n      padding:0px;\r\n}\r\n\r\n/*-----------------------------------------\r\n  SIDEBAR\r\n  ----------------------------------------*/\r\n\r\n#sidebar\r\n{\r\nclear: right;\r\nfloat: left;\r\nposition: relative;\r\ntop: 10px;\r\nleft: 50px;\r\nmargin: 0 0 10px 0;\r\nwidth: 30%;\r\nfont-size:90%;\r\n}\r\n\r\n#sidebar ul\r\n{\r\nlist-style-type: none;\r\nmargin: 10px 0;\r\npadding: 0;\r\n}\r\n\r\n#sidebar ul li\r\n{\r\ncolor: #5F5F5F;\r\nmargin: 0;\r\npadding: 0;\r\n}\r\n\r\n#sidebar ul li p\r\n{\r\nwidth: 190px;\r\nfont-weight: bold;\r\n}\r\n\r\n#sidebar ul li h2\r\n{\r\nborder-bottom: 1px solid;\r\nwidth: 190px;\r\nfont-weight: bold;\r\nmargin: 0;\r\npadding: 0;\r\n}\r\n\r\n#sidebar ul li ul\r\n{\r\n/*margin: 5px 0 15px 10px;*/\r\n}\r\n\r\n#sidebar ul li ul li\r\n{\r\nfont-weight: normal;\r\nmargin: 0 0 3px 0;\r\npadding: 0;\r\nline-height: 12px\r\n}\r\n\r\n#sidebar ul li#winamp ul li\r\n{\r\nwidth: 190px\r\n}\r\n\r\n#sidebar ul li ul li a\r\n{\r\ncolor: #5F5F5F;\r\ntext-decoration: none;\r\n}\r\n\r\n#sidebar ul li ul li a:hover\r\n{\r\nfont-weight: bold;\r\ntext-decoration: none\r\n}\r\n\r\n/*-------------------------------------------\r\nSIDEBAR DISPLAY COMPONENTS \r\n----------------------------------------------*/\r\n\r\n#sidebar_user {\r\n}\r\n\r\n#recent_activity {\r\n}\r\n\r\n#community_owned {\r\n}\r\n\r\n#community_membership {\r\n}\r\n\r\n#sidebar_friends {\r\n}\r\n\r\n#search {\r\n}\r\n\r\n#me {\r\n     padding: 3px;\r\n     margin:0;\r\n}\r\n\r\n#me p{\r\n   font-weight:normal;\r\n   font-weight: normal;\r\n   margin:0;\r\n }\r\n\r\n#sidebar #sidebar_user p {\r\n  padding:4px 0 0 0;\r\n  font-weight: normal;\r\n }\r\n\r\n\r\n/*--- extra div''s when looking at someone else''s page ---*/\r\n\r\n#sidebar_weblog {\r\n}\r\n\r\n#sidebar_files {\r\n}\r\n\r\n#searchform\r\n{\r\nmargin: 2px 0 15px 0;\r\n}\r\n\r\n#searchform input\r\n{\r\nbackground: #FFFFFF;\r\nborder: 1px solid #6F6F6F;\r\nfont-size: 11px;\r\nmargin-top: 3px;\r\npadding: 2px;\r\n}\r\n\r\n/*--------------------------------------\r\n  FOOTER\r\n  --------------------------------------*/\r\n\r\n#footer\r\n{\r\ncolor: #FFFFFF;\r\nbackground: #5F707A;\r\nborder-top: 1px solid #DFDFDF;\r\nclear: both;\r\nmargin: 0 auto 0 auto;\r\npadding: 16px 0 17px 0;\r\ntext-align: center;\r\nwidth: 769px;\r\n}\r\n\r\n#footer a\r\n{\r\ncolor: #ffffff\r\n}\r\n\r\n/*-------------------------------------\r\n  Blog classes\r\n  ------------------------------------*/\r\n\r\n.weblog_posts {\r\n    margin:0 0 30px 0;\r\n}\r\n\r\n.weblog_posts .entry h3 {\r\n   color:#1181AA;\r\n   background:#fff;\r\n   padding: 0 0 10px 110px;\r\n}\r\n\r\n.user {\r\n    float: left;\r\n    margin: 0px;\r\n    /* padding: 0.3em 2em 2em 0; */\r\n    width: 105px;\r\n    text-align: left;\r\n}\r\n\r\n.post {\r\n    margin: 0 0 0 77px;\r\n    padding:0 0 0 40px;\r\n    font-family: arial;\r\n}\r\n\r\n.post p {\r\n    padding: 0;\r\n    margin: 3px 0 10px 0;\r\n    line-height: 16px;\r\n}\r\n\r\n.post ol, .post ul {\r\n    margin: 3px 0 10px 0;\r\n    padding: 0;\r\n}\r\n\r\n.post li {\r\n    margin: 0 0 0 30px;\r\n    line-height: 16px;\r\n}\r\n\r\n.post ul li {\r\n    list-style-type: square;\r\n}\r\n\r\n.post .blog_edit_functions p {\r\n      \r\n}\r\n\r\n.post .blog_edit_functions a {\r\n      \r\n}\r\n\r\n.post .weblog_keywords p {\r\n     \r\n}\r\n\r\n.post .weblog_keywords a {\r\n     \r\n}\r\n\r\n.info p {\r\n    padding: 0px;\r\n    margin: 0 0 5px 0;\r\n    color: #666;\r\n    background:#fff;\r\n    font-family: verdana;\r\n    font-weight: normal;\r\n    line-height: 14px;\r\n    text-align: left;\r\n}\r\n\r\n.info p a {\r\n    color: #666;\r\n    background:#fff;\r\n    text-decoration: none;\r\n    border-bottom: 1px dotted #666;\r\n    padding-bottom: 0;\r\n}\r\n\r\n#comments ol, #comments ul {\r\n    margin: 3px 0 10px 0;\r\n    padding: 0;\r\n}\r\n\r\n#comments li {\r\n    margin: 0 0 0 30px;\r\n    line-height: 16px;\r\n}\r\n\r\n#comments ul li {\r\n    list-style-type: square;\r\n}\r\n\r\n#comments h4 {\r\n    color:#1181AA;\r\n}\r\n\r\n.weblog_dateheader {\r\n    padding: 0px;\r\n    margin: 0 0 5px 0;\r\n    color: #333;\r\n       background:#fff;\r\n    font-weight: normal;\r\n    font-style: italic;\r\n    line-height: 12px;\r\n       border:0px;\r\n    border-bottom: 1px solid #ccc;\r\n}\r\n\r\n.clearing{clear:both;}\r\n\r\n.post p, post li\r\n{\r\nfont-family: Lucida Grande, Verdana, sans-serif;\r\nline-height: 130%;\r\n}\r\n\r\n.post blockquote\r\n{\r\nbackground: #fef7e9;\r\nborder: 1px solid #e6ddcb;\r\nborder-left: 2px solid #6F6F6F;\r\nfont-family: Georgia, Times New Roman, serif;\r\npadding: 4px 4px 4px 7px;\r\n}\r\n\r\n/*-------------------------------------\r\n  Input forms\r\n--------------------------------------*/\r\n\r\n.textarea {\r\n    border: 1px solid #7F9DB9;\r\n    color:#71717B;\r\n    width: 95%;\r\n    height:200px;\r\n    padding:3px;\r\n}\r\n\r\n.medium_textarea {\r\n    width:95%;\r\n    height:100px;\r\n}\r\n\r\n.small_textarea {\r\n    width:95%;\r\n}\r\n\r\n.keywords_textarea {\r\n    width:95%;\r\n    height:100px;\r\n}\r\n\r\n/*----- System Messages ------*/\r\n\r\n#system_message { \r\n    border:1px solid #D3322A;\r\n    background:#F7DAD8;\r\n    padding:3px 50px;\r\n    margin:5px 0 0 0;    \r\n}\r\n\r\n#system_message p{\r\n   padding:0px;\r\n   margin:2px;\r\n }\r\n\r\n/*-----------------------------------------------------------------------\r\nDIV''s to help control look and feel - infoholder holds all the profile data\r\nand is always located in within ''maincontentdisplay''\r\n\r\n-------------------------------------------------------------------------*/\r\n\r\n/*------ holds profile data -------*/\r\n.infoholder {\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 5px 0;\r\n}\r\n\r\n.infoholder p {\r\n   padding:0 0 0 5px;\r\n}\r\n\r\n.infoholder .fieldname {\r\n        /*  border:0;\r\n          margin:0;\r\n          border-bottom:1px;\r\n          border-color:#eee;\r\n          border-style:solid;\r\n          padding:5px;\r\n          color:#666;\r\n          background:#fff; */\r\ncolor: #5F707A;\r\nmargin: 0px 0 5px 0;\r\npadding: 0 0 0px 3px;\r\ntext-align: left;\r\nborder:0px;\r\n}   \r\n\r\n.infoholder_twocolumn {\r\n    padding:4px;\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 10px 0;\r\n }\r\n\r\n.infoholder_twocolumn .fieldname h3{\r\n    color:#666;\r\n    background:#fff;\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n}\r\n\r\n/*----------- holds administration data---------*/\r\n\r\n.admin_datatable {\r\n  border:1px;\r\n  border-color:#eee;\r\n  border-style:solid;\r\n  margin:0 0 5px 0;\r\n}\r\n\r\n.admin_datatable p {\r\n     padding:0px;\r\n     margin:0px;\r\n}\r\n\r\n.admin_datatable a {\r\n   \r\n}\r\n\r\n\r\n.admin_datatable td {\r\n   text-align:left;\r\n}\r\n\r\n.admin_datatable h3{\r\n     color:#666;\r\n     background:#fff;\r\n}\r\n\r\n.admin_datatable h4 {\r\n}\r\n\r\n/*---- header plus one row of content ------*/\r\n\r\n.databox_vertical {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   padding:5px;\r\n }\r\n\r\n .databox_vertical p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#1181AA;\r\n   background:#fff;\r\n }\r\n\r\n.databox_vertical .fieldname h3 {\r\n  padding:0px;\r\n  margin:0px;\r\n  color:#1181AA;\r\n  background:#fff;\r\n}\r\n\r\n/*------- holds file content ----*/\r\n\r\n.filetable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n .filetable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#000; /*#1181AA;*/\r\n   background:#fff;\r\n }\r\n\r\n.filetable a{\r\n   \r\n }\r\n\r\n\r\n.filetable table {\r\n    text-align:left;\r\n}\r\n\r\n#edit_files h4 {\r\n     \r\n}\r\n  \r\n\r\n/*------- holds fodler content ------*/\r\n\r\n.foldertable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n.foldertable a{\r\n  \r\n }\r\n\r\n .foldertable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#1181AA;\r\n   background:#fff;\r\n }\r\n\r\n.foldertable table {\r\n    text-align:left;\r\n}\r\n\r\n/*------- holds network data ------*/\r\n\r\n.networktable {\r\n   \r\n}\r\n\r\n/*---------------------------------------------\r\n  Your Resources\r\n-----------------------------------------------*/\r\n\r\n.feeds {\r\n  border-bottom: 1px dotted #aaaaaa;\r\n  background: transparent url(\"//_templates/sunflower.jpg\") bottom right no-repeat;\r\n}\r\n\r\n.feed_content a {\r\n    color:black;\r\n    border:0px;\r\n}\r\n\r\n.feed_content a:hover{\r\n    background:#fff;\r\n    }\r\n\r\n.feed_content img {\r\n  border: 1px solid #666666;\r\n  padding:5px;\r\n}\r\n\r\n.feed_content h3 {\r\n      padding:0 0 4px 0;\r\n      margin:0px;\r\n}\r\n\r\n.feed_content h3 a{\r\n     color:black;\r\n     border:0px;\r\n     border-bottom:1px;\r\n     border-style:dotted;\r\n     border-color:grey;\r\n}\r\n\r\n.feed_content h3 a:hover{\r\n    background:#FCD63F;\r\n       color:#000;\r\n    }\r\n\r\n.feed_date {\r\n    line-height: 21px;\r\n  font-weight: bold;\r\n  padding: 5px 10px 4px 5px;\r\n  margin:0 0 10px 0;\r\n  background-color: #D0DEDF;\r\n  color:#000;\r\n  text-decoration:none;\r\n}\r\n\r\n.via a {\r\n    color:#1181AA;\r\n    background:#fff;\r\n    border:0px;\r\n}\r\n\r\n.via a:hover {\r\n    background:#ffc;\r\n    color:#1181AA;\r\n}', 3);");
        modify_database('', "INSERT INTO {$CFG->prefix}template_elements (name,content,template_id) VALUES ( 'pageshell', '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<title>{{title}}</title>\r\n{{metatags}}\r\n</head>\r\n<body>\r\n <!-- elgg banner and logo -->\r\n<div id=\"container\"><!-- start container -->\r\n<div id=\"statusbar\"><!-- start statusbar -->\r\n    <div id=\"welcome\"><!-- start welcome -->\r\n        <p>Welcome {{userfullname}}</p>\r\n    </div><!-- end welcome -->\r\n         {{topmenu}}\r\n</div><!-- end statusbar -->\r\n<div id=\"header\"><!-- start header -->\r\n             <h1>Elgg</h1>\r\n               <h2>Community learning space</h2>\r\n</div><!-- end header -->\r\n<div id=\"navigation\">\r\n   <ul>\r\n       {{menu}}\r\n   </ul>\r\n</div>\r\n<div id=\"content_holder\"><!-- start contentholder -->\r\n<div id=\"maincontent_container\"><!-- start main content -->\r\n        {{messageshell}}\r\n      {{mainbody}}\r\n</div><!-- end main content -->\r\n<div id=\"sidebar_container\">\r\n<div id=\"sidebar\"><!-- start sidebar -->\r\n    <ul><!-- open sidebar lists -->\r\n        {{sidebar}}\r\n    </ul>\r\n</div><!-- end sidebar -->\r\n</div>\r\n</div><!-- end contentholder -->\r\n<div class=\"clearall\" />\r\n <div id=\"footer\"><!-- start footer -->\r\n        <a href=\"http://elgg.net\"><img src=\"/_templates/elgg_powered.png\" border=\"0\"></a>\r\n </div><!-- end footer -->\r\n</div><!-- end container -->\r\n </body>\r\n </html>', 3);");
        modify_database('', "INSERT INTO {$CFG->prefix}templates VALUES (4, 'Connections', 1, 'yes');");
        modify_database('', "INSERT INTO {$CFG->prefix}templates VALUES (3, 'Northern', 1, 'yes');");
        modify_database('', "INSERT INTO {$CFG->prefix}templates VALUES (5, 'Gentle Calm', 1, 'yes');");
        // because this is postgres, we need to reset the sequence since we're hard coding the ids
        // that were used in the template_elements table. yuk.
        modify_database('', "SELECT setval('{$CFG->prefix}templates_ident_seq', (select max(ident) from {$CFG->prefix}templates))");
    }
    if ($oldversion < 2006022300) {
        // Display errors
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
        // Set time limit to 60 minutes
        @set_time_limit(3600);
        if ($users = get_records('users')) {
            foreach ($users as $user) {
                $ident = $user->ident;
                echo "<p>" . sprintf(gettext("Publishing RSS for user %d"), $ident) . "</p>";
                $rssresult = run("weblogs:rss:publish", array($ident, false));
                $rssresult = run("files:rss:publish", array($ident, false));
                $rssresult = run("profile:rss:publish", array($ident, false));
            }
        }
    }
    if ($oldversion < 2006022301) {
        // This handles upgrades from _files/data to $CFG->dataroot too...
        // Alter file repository to remove path information
        echo "<h2>" . gettext("Adjusting file repository information") . "</h2>";
        // Get all files with path in the location
        $tostrip = $CFG->dirroot . '_files/data/';
        if ($files = get_records_select('files', 'location LIKE ?', array($tostrip . '%'))) {
            foreach ($files as $file) {
                $ident = $file->ident;
                $filename = str_replace($tostrip, "files/", $file->location);
                set_field('files', 'location', $filename, 'ident', $ident);
                echo "<p>" . sprintf(gettext("Updating file %d: %s"), $ident, $filename) . "</p>";
            }
        }
        // Get all files that start with _files
        $tostrip = '_files/data/';
        if ($files = get_records_select('files', 'location LIKE ?', array($tostrip . '%'))) {
            foreach ($files as $file) {
                $ident = $file->ident;
                $filename = str_replace($tostrip, "files/", $file->location);
                set_field('files', 'location', $filename, 'ident', $ident);
                echo "<p>" . sprintf(gettext("Updating file %d: %s"), $ident, $filename) . "</p>";
            }
        }
        // copy the files across.
        if ($dir = opendir($CFG->dirroot . '_files/data/')) {
            while ($file = readdir($dir)) {
                if ($file == "." || $file == ".." || $file == '.htaccess') {
                    continue;
                }
                copy_file($CFG->dirroot . "_files/data/{$file}", $CFG->dataroot . "files/{$file}");
            }
        }
        // now the profile images.. this is harder.
        if ($icons = get_records_sql("SELECT i.*,u.username FROM {$CFG->prefix}icons i JOIN {$CFG->prefix}users u ON i.owner = u.ident")) {
            foreach ($icons as $icon) {
                $upload_folder = $textlib->substr($icon->username, 0, 1);
                $fromfile = $CFG->dirroot . '_icons/data/' . $icon->filename;
                $tofile = $CFG->dataroot . 'icons/' . $upload_folder . '/' . $icon->username . '/' . $icon->filename;
                copy_file($fromfile, $tofile);
            }
        }
    }
    if ($oldversion < 2006052100) {
        // add some missing indexes
        modify_database('', 'CREATE INDEX {$CFG->prefix}tags_access_idx ON {$CFG->prefix}tags (access)');
    }
    if ($oldversion < 2006052200) {
        // homogenise access field, shortest one was vc16, longest vc255
        table_column('file_folders', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
        table_column('files', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
        table_column('groups', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
        table_column('profile_data', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
        table_column('tags', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
        table_column('weblog_posts', 'access', 'access', 'varchar', 20, '', 'PUBLIC');
    }
    if ($oldversion < 2006052300) {
        // shorten another keyword field
        table_column('tags', 'tagtype', 'tagtype', 'varchar', 20);
    }
    if ($oldversion < 2006052400) {
        // purge owner=0 watchlist entries from watchlist-on-comment bug
        delete_records('weblog_watchlist', 'owner', 0);
    }
    if ($oldversion < 2006060600) {
        modify_database('', 'CREATE INDEX {$CFG->prefix}feed_posts_added_idx ON {$CFG->prefix}feed_posts (added)');
    }
    if ($oldversion < 2006061600) {
        modify_database('', 'DROP INDEX {$CFG->prefix}feed_posts_url_idx');
        table_column('feed_posts', 'url', 'url', 'varchar', 255, '', '');
    }
    if ($oldversion < 2006061700) {
        modify_database('', 'DROP INDEX {$CFG->prefix}weblog_watchlist_owner_idx');
        modify_database('', 'CREATE INDEX {$CFG->prefix}weblog_watchlist_owner_idx ON {$CFG->prefix}weblog_watchlist (owner)');
        modify_database('', 'CREATE INDEX {$CFG->prefix}weblog_watchlist_weblog_post_idx ON {$CFG->prefix}weblog_watchlist (weblog_post)');
    }
    if ($oldversion < 2006081000) {
        // Add old Elgg default template as Classic Elgg
        $template = new StdClass();
        $template->name = "Classic Elgg";
        $template->owner = 1;
        $template->public = "yes";
        $template_id = insert_record('templates', $template);
        execute_sql("INSERT INTO `{$CFG->prefix}template_elements` (`name`,`content`,`template_id`) VALUES ('pageshell', '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<title>{{title}}</title>\r\n{{metatags}}\r\n</head>\r\n<body>\r\n<!-- elgg banner and logo -->\r\n<div id=\"container\"><!-- start container -->\r\n    <div id=\"statusbar\"><!-- start statusbar -->\r\n        <div id=\"welcome\"><!-- start welcome -->\r\n            <p>Welcome {{userfullname}}</p>\r\n        </div><!-- end welcome -->\r\n        {{topmenu}}\r\n    </div><!-- end statusbar -->\r\n    <div id=\"header\"><!-- start header -->\r\n        <h1>{{sitename}}</h1>\r\n            <h2>Personal Learning Landscape</h2>\r\n            <ul id=\"navigation\">\r\n                {{menu}}\r\n            </ul>\r\n    </div><!-- end header -->\r\n    <div id=\"content_holder\"><!-- start contentholder -->\r\n        <div id=\"maincontent_container\"><!-- start main content -->\r\n            {{messageshell}}\r\n            {{mainbody}}\r\n        </div><!-- end main content -->\r\n        <div id=\"sidebar_container\">\r\n            <div id=\"sidebar\"><!-- start sidebar -->\r\n                <ul><!-- open sidebar lists -->\r\n                {{sidebar}}\r\n                </ul>\r\n            </div><!-- end sidebar -->\r\n        </div><!-- end sidebar_container -->\r\n    </div><!-- end contentholder -->\r\n    <div class=\"clearall\" />\r\n    <div id=\"footer\"><!-- start footer -->\r\n        <a href=\"http://elgg.net/\"><img src=\"{{url}}_templates/elgg_powered.png\" alt=\"Powered by Elgg\" title=\"Powered by Elgg\" border=\"0\" /></a>\r\n    </div><!-- end footer -->\r\n</div><!-- end container -->\r\n</body>\r\n</html>', {$template_id})");
        execute_sql("INSERT INTO `{$CFG->prefix}template_elements` (`name`,`content`,`template_id`) VALUES ('css', '/*\r\n    CSS for Elgg Classic default\r\n*/\r\n\r\nbody{\r\n    padding: 0;\r\n    font-family: arial, verdana, helvetica, sans-serif;\r\n    color: #333;\r\n       background: #eee;\r\n    width:97%;\r\n    margin:auto;\r\n       font-size:80%;\r\n    }\r\n\r\na {\r\n        text-decoration: none;\r\n        color: #7289AF;\r\n        background: #fff;\r\n        font-family:verdana, arial, helvetica, sans-serif;\r\n        font-size:100%;\r\n\r\n    }\r\n\r\np {\r\n    font-size: 100%;    \r\n}\r\n\r\nh1 {\r\n       margin:0px 0px 15px 0px;\r\n    padding:0px;\r\n    font-size:120%;\r\n    font-weight:900;\r\n}\r\n\r\n\r\nh2 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    font-size:100%\r\n}\r\n\r\n\r\nh3 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    font-size:100%\r\n}\r\n\r\nh4 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    font-size:100%\r\n}\r\n\r\nh5 {\r\n    margin:0px 0px 5px 0px;\r\n    padding:0px;\r\n    color:#1181AA;\r\n       background:#fff;\r\n    font-size:100%\r\n}\r\n\r\nblockquote {\r\n    padding: 0 1pc 1pc 1pc;\r\n    border: 1px solid #ddd;\r\n    background-color: #F0F0F0;\r\n       color:#000;\r\n    background-image: url(\"{{url}}_templates/double-quotes.png\");\r\n    background-repeat: no-repeat;\r\n    background-position: -10px -7px;\r\n}\r\n\r\n/*---------------------------------------\r\nWraps the entire page \r\n-----------------------------------------*/\r\n\r\n#container {\r\n    margin: 0 auto;\r\n    text-align: center;\r\n    width: 100%;\r\n    min-width: 750px;\r\n    }\r\n\r\n\r\n/*-----------------------------------------\r\nTOP STATUS BAR \r\n-------------------------------------------*/\r\n\r\n#statusbar {\r\n    padding: 3px 0px 2px 0;\r\n    margin: 0px;\r\n    height:19px;\r\n    background:#eee;\r\n    color: #333;\r\n   font-size:85%;\r\n}\r\n\r\n#statusbar a {\r\n    color: #666;\r\n    background:#eee;\r\n}\r\n\r\n#welcome {\r\n    float: left;\r\n}\r\n\r\n#welcome p{\r\n    font-weight:bold;\r\n       font-size:110%;\r\n    padding:0 0 0 4px;\r\n    margin:0px;\r\n}\r\n\r\n#global_menuoptions {\r\n    text-align: right;\r\n    padding:0px;\r\n    margin:0px;\r\n    float:right;\r\n}\r\n\r\n#global_menuoptions ul {\r\n    margin: 0; \r\n    padding: 0;\r\n}\r\n\r\n#global_menuoptions li {\r\n    margin: 0; \r\n    padding: 0 8px 0 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n\r\n#global_menuoptions a {\r\n    text-decoration: none;\r\n}\r\n\r\n#global_menuoptions a:hover{\r\n    text-decoration:underline;\r\n}\r\n\r\n\r\n/*---------------------------------------------\r\nHEADER \r\n------------------------------------------------*/\r\n\r\n#header {\r\n    width: 100%;\r\n    background: #1181AA;\r\n    color:#fff;\r\n    border: 1px solid #ccc;\r\n    border-bottom: none;\r\n    padding: 0px;\r\n    margin: 0px;\r\n    text-align: left;\r\n    }\r\n\r\n#header h1 {\r\n    padding: 0 0 4px 0;\r\n    margin: 7px 0 0 20px;\r\n    color: #FAC83D;\r\n    background: #1181AA;\r\n    text-align: left;\r\n       font-size:140%;\r\n       font-weight:normal;\r\n    }    \r\n\r\n#header h2 {\r\n    padding: 0 0 7px 0;\r\n    margin: 0 0 0 20px;\r\n    font-weight: normal;\r\n    color: #fff;\r\n    background: #1181AA;\r\n    border: none;\r\n    font-family: \"Lucida Grande\", arial, sans-serif;\r\n       font-size:120%;\r\n    }    \r\n\r\n/*--------------------------------------------\r\nNAVIGATION \r\n----------------------------------------------*/\r\n\r\n#navigation {\r\n    height: 19px;\r\n    margin: 0;\r\n    padding-left: 20px;\r\n    text-align:left;\r\n}\r\n\r\n#navigation li {\r\n    margin: 0; \r\n    padding: 0;\r\n    display: inline;\r\n    list-style-type: none;\r\n    border: none;\r\n}\r\n\r\n#navigation a:link, #navigation a:visited {\r\n\r\n    background: #eaeac7;\r\n    font-weight: normal;\r\n    padding: 5px;\r\n    margin: 0 2px 0 0;\r\n    border: 0px solid #036;\r\n    text-decoration: none;\r\n    color: #333;\r\n       font-size:85%;\r\n}\r\n\r\n#navigation a:link.selected, #navigation a:visited.selected {\r\n    border-bottom: 1px solid #fff;\r\n    background: #fff;\r\n    color: #393;\r\n    font-weight: bold;\r\n}\r\n\r\n#navigation a:hover {\r\n    color: #000;\r\n    background: #ffc;\r\n}\r\n\r\n#navigation li a:hover{\r\n    background:#FCD63F;\r\n       color: #000;\r\n    }\r\n\r\n\r\n/*-----------------------------------------------\r\nSITE CONTENT WRAPPER \r\n-------------------------------------------------*/\r\n\r\n#content_holder {\r\n    margin: 0;\r\n    padding: 20px 0;\r\n    width: 100%;\r\n    text-align: left;\r\n    float: left;\r\n    border: 1px solid #ccc;\r\n    border-top: none;\r\n    background-color: #fff;\r\n    color:#000;\r\n}\r\n\r\n/*-------------------------------------------------\r\nHOLDS THE MAIN CONTENT E.G. BLOG, PROFILE ETC \r\n----------------------------------------------------*/\r\n\r\n#maincontent_container {\r\n    margin: 0;\r\n    padding: 5px;\r\n    text-align: left;\r\n    width: 65%;\r\n    float: left;\r\n    }\r\n\r\n#maincontent_container h2 {\r\n    padding-bottom: 5px;\r\n    padding-top: 5px;\r\n    margin: 0;\r\n    /*color: #666;\r\n    background-color:#fff;*/\r\n}\r\n\r\n#maincontent_container h1 {\r\n    padding-bottom: 5px;\r\n    padding-top: 5px;\r\n    margin: 0;\r\n    color: #666;\r\n    background-color:#fff;\r\n}\r\n\r\n#maincontent_container h3 {\r\n    padding-bottom: 5px;\r\n    padding-top: 5px;\r\n    margin: 0;\r\n    /*color: #666;\r\n    background-color:#fff;*/\r\n}\r\n\r\n#Footer .performanceinfo {\r\n    color: #000;\r\n}\r\n\r\n/*-------------------------------------------------------------\r\nTHIS DISPLAYS THE ACTUAL CONTENT WITHIN maincontent_container\r\n--------------------------------------------------------------*/\r\n\r\n#maincontent_display {\r\n    margin: 0;\r\n    padding: 0 0 20px 20px;\r\n    width: 100%;\r\n    text-align: left;\r\n    float: left;\r\n    background-color: #fff;\r\n    color:#000;\r\n}\r\n\r\n#maincontent_display h1 {\r\n    padding-bottom: 2px;\r\n    border-bottom: 1px solid #666;\r\n    margin: 0;\r\n    font-size:130%;\r\n    color: #666;\r\n    background-color: #fff;\r\n}\r\n\r\n/*---- Sub Menu attributes ----*/\r\n\r\n#maincontent_display #sub_menu {\r\n    font-family: verdana;\r\n    padding: 0px;\r\n    margin: 5px 0 20px 0;\r\n    color: #000;\r\n    background-color:#fff;\r\n}\r\n\r\n#maincontent_display #sub_menu a {\r\n    font-weight:bold;\r\n    margin:0px;\r\n    padding:0px;\r\n}\r\n\r\n#maincontent_display #sub_menu a:hover {\r\n    text-decoration: underline;\r\n}\r\n\r\n#maincontent_display #sub_menu p {\r\n      margin:0px;\r\n      padding:0px;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\nDIV''s to help control look and feel - infoholder holds all the profile data\r\nand is always located in within ''maincontentdisplay''\r\n\r\n-------------------------------------------------------------------------*/\r\n\r\n/*------ holds profile data -------*/\r\n.infoholder {\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 5px 0;\r\n}\r\n\r\n.infoholder p {\r\n   padding:0 0 0 5px;\r\n}\r\n\r\n.infoholder .fieldname h2 {\r\n          border:0;\r\n          border-bottom:1px;\r\n          border-color:#eee;\r\n          border-style:solid;\r\n          padding:5px;\r\n          color:#666;\r\n          background:#fff;\r\n}   \r\n\r\n.infoholder_twocolumn {\r\n    padding:4px;\r\n    border:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n    margin:0 0 10px 0;\r\n }\r\n\r\n.infoholder_twocolumn .fieldname h3{\r\n    color:#666;\r\n    background:#fff;\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-color:#eee;\r\n    border-style:solid;\r\n}\r\n\r\n/*----------- holds administration data---------*/\r\n\r\n.admin_datatable {\r\n  border:1px;\r\n  border-color:#eee;\r\n  border-style:solid;\r\n  margin:0 0 5px 0;\r\n}\r\n\r\n.admin_datatable p {\r\n     padding:0px;\r\n     margin:0px;\r\n}\r\n\r\n.admin_datatable a {\r\n   \r\n}\r\n\r\n\r\n.admin_datatable td {\r\n   text-align:left;\r\n}\r\n\r\n.admin_datatable h3{\r\n     color:#666;\r\n     background:#fff;\r\n}\r\n\r\n.admin_datatable h4 {\r\n}\r\n\r\n/*---- header plus one row of content ------*/\r\n\r\n.databox_vertical {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   padding:5px;\r\n }\r\n\r\n .databox_vertical p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#1181AA;\r\n   background:#fff;\r\n }\r\n\r\n.databox_vertical .fieldname h3 {\r\n  padding:0px;\r\n  margin:0px;\r\n  color:#1181AA;\r\n  background:#fff;\r\n}\r\n\r\n/*------- holds file content ----*/\r\n\r\n.filetable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n .filetable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#000; /*#1181AA;*/\r\n   background:#fff;\r\n }\r\n\r\n.filetable a{\r\n   \r\n }\r\n\r\n\r\n.filetable table {\r\n    text-align:left;\r\n}\r\n\r\n#edit_files h4 {\r\n     \r\n}\r\n  \r\n\r\n/*------- holds fodler content ------*/\r\n\r\n.foldertable {\r\n   background-color: #F9F9F9;\r\n   color:#000;\r\n   border:1px;\r\n   border-style:solid;\r\n   border-color:#DDD;\r\n   margin:0 0 5px 0;\r\n   width:100%;\r\n }\r\n\r\n.foldertable a{\r\n  \r\n }\r\n\r\n .foldertable p{\r\n   padding:0px;\r\n   margin:0px;\r\n   color:#1181AA;\r\n   background:#fff;\r\n }\r\n\r\n.foldertable table {\r\n    text-align:left;\r\n}\r\n\r\n/*------- holds network data ------*/\r\n\r\n.networktable {\r\n   \r\n}\r\n\r\n\r\n/*-------------------------------------------\r\nSIDEBAR CONTAINER \r\n---------------------------------------------*/\r\n\r\n#sidebar_container {\r\n    margin: 0px;\r\n    text-align: left;\r\n    float: right;\r\n    width: 26%;\r\n       min-width: 100px;\r\n    border-left: 1px dotted #dcdcdc;\r\n    padding: 0 10px;\r\n  /*width:220px;*/\r\n      /*overflow: hidden;*/\r\n    }\r\n\r\n/*-----------------------------------------\r\nACTUAL SIDEBAR CONTENT\r\n-------------------------------------------*/\r\n\r\n#sidebar {\r\nmin-width: 100px;\r\n    padding: 0 10px;\r\n    }\r\n\r\n#sidebar ul {\r\n    margin: 0;\r\n    padding: 0;\r\n    list-style: none;\r\n}\r\n\r\n#sidebar ul li ul {\r\n    \r\n}\r\n\r\n#sidebar ul li {\r\n    margin: 10px 0;\r\n    padding-left: 5px;\r\n}\r\n\r\n\r\n#sidebar h2 {\r\n    font-family: \"Lucida Grande\", arial, sans-serif;\r\n    font-weight: bold;\r\n    color: #333;\r\n       background:#fff;\r\n    margin: 20px 0 3px 0;\r\n    padding: 0;\r\n    border: none;\r\n}\r\n\r\n#sidebar h2 {\r\n    border-bottom: 1px solid #666; \r\n}\r\n\r\n/*-------------------------------------------\r\nSIDEBAR DISPLAY COMPONENTS \r\n----------------------------------------------*/\r\n\r\n#sidebar_user {\r\n}\r\n\r\n#recent_activity {\r\n}\r\n\r\n#community_owned {\r\n}\r\n\r\n#community_membership {\r\n}\r\n\r\n#sidebar_friends {\r\n}\r\n\r\n#search {\r\n}\r\n\r\n#me {\r\n        padding: 0 3px 3px 3px;\r\n     background-color:#FAC83D;\r\n     min-height: 71px;\r\n}\r\n\r\n#me a {\r\n   background-color:#FAC83D;\r\n   color: #7289AF;\r\n  }\r\n\r\n#me #icon {\r\n   margin:3px 0 0 0;\r\n   float: left; \r\n   width: 70px;\r\n}\r\n\r\n#me #contents {\r\n   margin: 0 0 0 75px;\r\n   text-align: left;\r\n}\r\n\r\n\r\n/*--- extra div''s when looking at someone else''s page ---*/\r\n\r\n#sidebar_weblog {\r\n}\r\n\r\n#sidebar_files {\r\n}\r\n\r\n\r\n\r\n/*------------------------------------------\r\n  FOOTER \r\n  ------------------------------------------*/\r\n\r\n#footer {\r\n    margin: 10px 0 20px 20px;\r\n    text-align: center;\r\n    padding:5px;\r\n}\r\n\r\n#footer a:link, #footer a:visited {\r\n    text-align:right;\r\n}\r\n\r\n\r\n/*-------------------------------------------\r\n  INDIVIDUAL BLOG POSTS \r\n  -------------------------------------------*/\r\n\r\n\r\n/*------ wraps all blog components ------*/\r\n\r\n.weblog_posts {\r\n}\r\n\r\n.weblog_posts .entry h3 {\r\n   color:#1181AA;\r\n   background:#fff;\r\n   padding: 0 0 10px 110px;\r\n}\r\n\r\n.user {\r\n    float: left;\r\n    margin: 0px;\r\n    padding:0 0 5px 0;\r\n    width: 105px;\r\n    text-align: left;\r\n}\r\n\r\n.user a {\r\n    \r\n}\r\n\r\n.post {\r\n    margin: 0 0 10px 0;\r\n    padding: 0 0 20px 110px;\r\n    font-family: arial;\r\n}\r\n\r\n.post p {\r\n    padding: 0;\r\n    margin: 3px 0 10px 0;\r\n    line-height: 16px;\r\n}\r\n\r\n.post ol, .post ul {\r\n    margin: 3px 0 10px 0;\r\n    padding: 0;\r\n}\r\n\r\n.post li {\r\n    margin: 0 0 0 30px;\r\n    line-height: 16px;\r\n}\r\n\r\n.post ul li {\r\n    list-style-type: square;\r\n}\r\n\r\n.post .blog_edit_functions p {\r\n      \r\n}\r\n\r\n.post .blog_edit_functions a {\r\n      \r\n}\r\n\r\n.post .weblog_keywords p {\r\n     \r\n}\r\n\r\n.post .weblog_keywords a {\r\n     \r\n}\r\n\r\n.info p {\r\n    padding: 0px;\r\n    margin: 0 0 5px 0;\r\n    color: #666;\r\n    background:#fff;\r\n    font-family: verdana;\r\n    font-weight: normal;\r\n    line-height: 14px;\r\n    text-align: left;\r\n}\r\n\r\n.info p a {\r\n    color: #666;\r\n    background:#fff;\r\n    text-decoration: none;\r\n    border-bottom: 1px dotted #666;\r\n    padding-bottom: 0;\r\n}\r\n\r\n#comments ol, #comments ul {\r\n    margin: 3px 0 10px 0;\r\n    padding: 0;\r\n}\r\n\r\n#comments li {\r\n    margin: 10px 0 10px 30px;\r\n    line-height: 16px;\r\n}\r\n\r\n#comments ul li {\r\n    list-style-type: square;\r\n}\r\n\r\n#comments h4 {\r\n    color:#1181AA;\r\n}\r\n\r\n.comment_owner {\r\n    border:1px solid #eee;\r\n\tbackground:#f2f7fb;\r\n\tpadding:5px;\r\n\theight:50px;\r\n}\r\n\r\n.comment_owner img {\r\n   margin:0px 5px 0px 0px;\r\n}\r\n\r\n.comment_owner a {\r\n   background:#f2f7fb;\r\n}\r\n\r\n.comment_owner p {\r\n  padding:0;\r\n  margin:0 0 10px 0;\r\n}\r\n\r\n.weblog_dateheader {\r\n    padding: 0px;\r\n    margin: 0 0 5px 0;\r\n    color: #333;\r\n       background:#fff;\r\n    font-weight: normal;\r\n    font-style: italic;\r\n    line-height: 12px;\r\n       border:0px;\r\n    border-bottom: 1px solid #ccc;\r\n}\r\n\r\n.clearing{clear:both;}\r\n\r\n/*---------------------------------------------\r\n  Your Resources\r\n-----------------------------------------------*/\r\n\r\n.feeds {\r\n  border-bottom: 1px dotted #aaaaaa;\r\n  background: transparent url(\"{{url}}_templates/sunflower.jpg\") bottom right no-repeat;\r\n}\r\n\r\n.feed_content a {\r\n    color:black;\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-style:dotted;\r\n    border-color:#eee;\r\n}\r\n\r\n.feed_content a:hover{\r\n    background:#fff;\r\n    }\r\n\r\n.feed_content img {\r\n  border: 1px solid #666666;\r\n  padding:5px;\r\n}\r\n\r\n.feed_content h3 {\r\n      padding:0 0 4px 0;\r\n      margin:0px;\r\n}\r\n\r\n.feed_content h3 a{\r\n     color:black;\r\n     border:0px;\r\n     border-bottom:1px;\r\n     border-style:dotted;\r\n     border-color:#eee;\r\n}\r\n\r\n.feed_content h3 a:hover{\r\n    background:#FCD63F;\r\n       color:#000;\r\n    }\r\n\r\n.feed_date h2 {\r\n    font-size:13px;\r\n    line-height: 21px;\r\n  font-weight: bold;\r\n  padding: 5px 10px 5px 5px;\r\n  background: #D0DEDF;\r\n  color:#000;\r\n  text-decoration:none;\r\n}\r\n\r\n.via a {\r\n    font-size:80%;\r\n    color:#1181AA;\r\n    background:#fff;\r\n    border:0px;\r\n    border-bottom:1px;\r\n    border-style:dashed;\r\n    border-color:#ebebeb;\r\n}\r\n\r\n.via a:hover {\r\n    background:#ffc;\r\n    color:#1181AA;\r\n}\r\n\r\n\r\n/*---------------------------------------\r\n  SYSTEM MESSAGES \r\n  ---------------------------------------*/\r\n\r\n#system_message{ \r\n    border:1px solid #D3322A;\r\n    background:#F7DAD8;\r\n    color:#000;\r\n    padding:3px 50px;\r\n    margin:0 0 0 20px;\r\n}\r\n\r\n#system_message p{\r\n   padding:0px;\r\n   margin:2px;\r\n }\r\n\r\n\r\n/* -------------  help files -------------*/\r\n\r\n.helpfiles ul {\r\n    font-family: arial, helvetica, Tahoma;\r\n    color: #000000;\r\n    background:#fff;\r\n}\r\n\r\n.helpfiles h4 {\r\n \r\n}\r\n\r\n/*------ site news for home.php ---------*/\r\n\r\n.sitenews {\r\n     background:#ebebeb;\r\n     color:#000;\r\n}\r\n\r\n.sitenews h2 {\r\n     background:#1181AA;\r\n     color:#FAC83D;\r\n     padding:0 0 5px 0;\r\n}\r\n\r\n/*-------------------------------------\r\n  Input forms\r\n--------------------------------------*/\r\n\r\n.textarea {\r\n    border: 1px solid #7F9DB9;\r\n    color:#71717B;\r\n    width: 95%;\r\n       height:200px;\r\n    padding:3px;\r\n}\r\n\r\n.medium_textarea {\r\n   width:95%;\r\n   height:100px;\r\n}\r\n\r\n.small_textarea {\r\n    width:95%;\r\n}\r\n\r\n.keywords_textarea {\r\n    width:95%;\r\n    height:100px;\r\n}\r\n\r\n\r\n/*--------------------------------------\r\n   MISC \r\n--------------------------------------*/\r\n\r\n.clearall {\r\n    padding: 0px;\r\n    clear: both;\r\n    font-size: 0px;\r\n    }\r\n\r\n.flagcontent {\r\n   background:#eee;\r\n   color:#000;\r\n   border:1px;\r\n   border-color:#000;\r\n   border-style:solid;\r\n   padding:3px;\r\n}\r\n\r\n.flagcontent h5 {\r\n  background:#eee;\r\n  color:#1181AA;\r\n}', {$template_id})");
        // Clean up slashes
        execute_sql("update {$CFG->prefix}weblog_posts set title = replace(title,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}weblog_posts set title = replace(title,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}weblog_posts set body = replace(body,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}weblog_posts set body = replace(body,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}weblog_comments set body = replace(body,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}weblog_comments set body = replace(body,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}weblog_comments set postedname = replace(postedname,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}weblog_comments set postedname = replace(postedname,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}tags set tag = replace(tag,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}tags set tag = replace(tag,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}files set title = replace(title,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}files set title = replace(title,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}files set description = replace(description,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}files set description = replace(description,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}file_folders set name = replace(name,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}file_folders set name = replace(name,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}profile_data set value = replace(value,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}profile_data set value = replace(value,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}users set name = replace(name,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}users set name = replace(name,'\\\"','\"')");
        execute_sql("update {$CFG->prefix}groups set name = replace(name,'\\\\'','\\'')");
        execute_sql("update {$CFG->prefix}groups set name = replace(name,'\\\"','\"')");
    }
    return $result;
}
示例#27
0
function main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion < 2003010101) {
        delete_records("log_display", "module", "user");
        $new->module = "user";
        $new->action = "view";
        $new->mtable = "user";
        $new->field = "CONCAT(firstname,\" \",lastname)";
        insert_record("log_display", $new);
        delete_records("log_display", "module", "course");
        $new->module = "course";
        $new->action = "view";
        $new->mtable = "course";
        $new->field = "fullname";
        insert_record("log_display", $new);
        $new->action = "update";
        insert_record("log_display", $new);
        $new->action = "enrol";
        insert_record("log_display", $new);
    }
    //support user based course creating
    if ($oldversion < 2003032400) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_coursecreators (\n                                  id int8 SERIAL PRIMARY KEY,\n                                  userid int8  NOT NULL default '0'\n                                  )");
    }
    if ($oldversion < 2003041400) {
        table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
    }
    if ($oldversion < 2003042104) {
        // Try to update permissions of all files
        if ($files = get_directory_list($CFG->dataroot)) {
            echo "Attempting to update permissions for all files... ignore any errors.";
            foreach ($files as $file) {
                echo "{$CFG->dataroot}/{$file}<br />";
                @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions);
            }
        }
    }
    if ($oldversion < 2003042400) {
        // Rebuild all course caches, because of changes to do with visible variable
        if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2003042500) {
        //  Convert all usernames to lowercase.
        $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
        $cerrors = "";
        $rarray = array();
        foreach ($users as $user) {
            // Check for possible conflicts
            $lcname = trim(moodle_strtolower($user->username));
            if (in_array($lcname, $rarray)) {
                $cerrors .= $user->id . "->" . $lcname . '<br/>';
            } else {
                array_push($rarray, $lcname);
            }
        }
        if ($cerrors != '') {
            notify("Error: Cannot convert usernames to lowercase. \n                    Following usernames would overlap (id->username):<br/> {$cerrors} . \n                    Please resolve overlapping errors.");
            $result = false;
        }
        $cerrors = "";
        echo "Checking userdatabase:<br />";
        foreach ($users as $user) {
            $lcname = trim(moodle_strtolower($user->username));
            if ($lcname != $user->username) {
                $convert = set_field("user", "username", $lcname, "id", $user->id);
                if (!$convert) {
                    if ($cerrors) {
                        $cerrors .= ", ";
                    }
                    $cerrors .= $item;
                } else {
                    echo ".";
                }
            }
        }
        if ($cerrors != '') {
            notify("There were errors when converting following usernames to lowercase. \n                   '{$cerrors}' . Sorry, but you will need to fix your database by hand.");
            $result = false;
        }
    }
    if ($oldversion < 2003042700) {
        /// Changing to multiple indexes
        execute_sql(" CREATE INDEX {$CFG->prefix}log_coursemoduleaction_idx ON {$CFG->prefix}log (course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}log_courseuserid_idx ON {$CFG->prefix}log (course,userid) ");
    }
    if ($oldversion < 2003042801) {
        execute_sql("CREATE TABLE {$CFG->prefix}course_display (\n                         id SERIAL PRIMARY KEY,\n                         course integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         display integer NOT NULL default '0'\n                      )");
        execute_sql("CREATE INDEX {$CFG->prefix}course_display_courseuserid_idx ON {$CFG->prefix}course_display (course,userid)");
    }
    if ($oldversion < 2003050400) {
        table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050401) {
        table_column("user", "", "lang", "VARCHAR", "5", "", "{$CFG->lang}", "NOT NULL", "");
    }
    if ($oldversion < 2003050900) {
        table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050902) {
        if (get_records("modules", "name", "pgassignment")) {
            print_simple_box("Note: the pgassignment module will soon be deleted from CVS!  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        }
    }
    if ($oldversion < 2003051600) {
        print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
    }
    if ($oldversion < 2003052300) {
        table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
    }
    if ($oldversion < 2003072100) {
        table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
    }
    if ($oldversion < 2003072101) {
        table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
    }
    if ($oldversion < 2003072800) {
        print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        flush();
        execute_sql(" CREATE INDEX {$CFG->prefix}log_timecoursemoduleaction_idx ON {$CFG->prefix}log (time,course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_students_courseuserid_idx ON {$CFG->prefix}user_students (course,userid) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_teachers_courseuserid_idx ON {$CFG->prefix}user_teachers (course,userid) ");
    }
    if ($oldversion < 2003072802) {
        table_column("course_categories", "", "description", "text", "", "", "");
        table_column("course_categories", "", "parent", "integer", "10", "unsigned");
        table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
        table_column("course_categories", "", "courseorder", "text", "", "", "");
        table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
        table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
    }
    if ($oldversion < 2003080400) {
        notify("If the following command fails you may want to change the type manually, from TEXT to INTEGER.  Moodle should keep working even if you don't.");
        table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
        table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
    }
    if ($oldversion < 2003081502) {
        execute_sql(" CREATE TABLE {$CFG->prefix}scale (\n                         id SERIAL PRIMARY KEY,\n                         courseid integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         name varchar(255) NOT NULL default '',\n                         scale text,\n                         description text,\n                         timemodified integer NOT NULL default '0'\n                      )");
    }
    if ($oldversion < 2003081503) {
        table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
        get_scales_menu(0);
        // Just to force the default scale to be created
    }
    if ($oldversion < 2003081600) {
        table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
        table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
    }
    if ($oldversion < 2003081900) {
        table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003080700) {
        notify("Cleaning up categories and course ordering...");
        fix_course_sortorder();
    }
    if ($oldversion < 2003082001) {
        table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
    }
    if ($oldversion < 2003082101) {
        execute_sql(" CREATE INDEX {$CFG->prefix}course_category_idx ON {$CFG->prefix}course (category) ");
    }
    if ($oldversion < 2003082702) {
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
    }
    if ($oldversion < 2003091000) {
        # Old field that was never added!
        table_column("course", "", "showrecent", "integer", "10", "unsigned", "1", "", "numsections");
    }
    if ($oldversion < 2003091400) {
        table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
    }
    if ($oldversion < 2003092900) {
        table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
    }
    if ($oldversion < 2003102700) {
        table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
        table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
        $db->debug = false;
        $CFG->debug = 0;
        notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
        flush();
        if ($courses = get_records_select("course", "category > 0")) {
            foreach ($courses as $course) {
                notify("Processing " . format_string($course->fullname) . " ...", "green");
                flush();
                if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '{$course->id}' and userid = '{$user->userid}'                                                               ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
                if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log \n                                                   WHERE course = '{$course->id}' and userid = '{$user->userid}' \n                                                   ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_students \n                                     SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
            }
        }
        notify("All courses complete.", "green");
        $db->debug = true;
    }
    if ($oldversion < 2003103100) {
        table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
    }
    if ($oldversion < 2003121600) {
        execute_sql("CREATE TABLE {$CFG->prefix}groups (\n                        id SERIAL PRIMARY KEY,\n                        courseid integer NOT NULL default '0',\n                        name varchar(255) NOT NULL default '',\n                        description text,\n                        lang varchar(10) NOT NULL default '',\n                        picture integer NOT NULL default '0',\n                        timecreated integer NOT NULL default '0',\n                        timemodified integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_idx ON {$CFG->prefix}groups (courseid) ");
        execute_sql("CREATE TABLE {$CFG->prefix}groups_members (\n                        id SERIAL PRIMARY KEY,\n                        groupid integer NOT NULL default '0',\n                        userid integer NOT NULL default '0',\n                        timeadded integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_members_idx ON {$CFG->prefix}groups_members (groupid) ");
    }
    if ($oldversion < 2003122600) {
        table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
        table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
    }
    if ($oldversion < 2004010900) {
        table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
    }
    if ($oldversion < 2004011700) {
        modify_database("", "CREATE TABLE prefix_event (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(255) NOT NULL default '',\n                                description text,\n                                courseid integer NOT NULL default '0',\n                                groupid integer NOT NULL default '0',\n                                userid integer NOT NULL default '0',\n                                modulename varchar(20) NOT NULL default '',\n                                instance integer NOT NULL default '0',\n                                eventtype varchar(20) NOT NULL default '',\n                                timestart integer NOT NULL default '0',\n                                timeduration integer NOT NULL default '0',\n                                timemodified integer NOT NULL default '0'\n                             ); ");
        modify_database("", "CREATE INDEX prefix_event_courseid_idx ON prefix_event (courseid);");
        modify_database("", "CREATE INDEX prefix_event_userid_idx ON prefix_event (userid);");
    }
    if ($oldversion < 2004012800) {
        modify_database("", "CREATE TABLE prefix_user_preferences (\n                                id SERIAL PRIMARY KEY,\n                                userid integer NOT NULL default '0',\n                                name varchar(50) NOT NULL default '',\n                                value varchar(255) NOT NULL default ''\n                             ); ");
        modify_database("", "CREATE INDEX prefix_user_preferences_useridname_idx ON prefix_user_preferences (userid,name);");
    }
    if ($oldversion < 2004012900) {
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004013101) {
        table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
        set_config("upgrade", "logs");
    }
    if ($oldversion < 2004020900) {
        table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
    }
    if ($oldversion < 2004020903) {
        modify_database("", "CREATE TABLE prefix_cache_text (\n                                id SERIAL PRIMARY KEY,\n                                md5key varchar(32) NOT NULL default '',\n                                formattedtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004021000) {
        $textfilters = array();
        for ($i = 1; $i <= 10; $i++) {
            $variable = "textfilter{$i}";
            if (!empty($CFG->{$variable})) {
                /// No more filters
                if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) {
                    $textfilters[] = $CFG->{$variable};
                }
            }
        }
        $textfilters = implode(',', $textfilters);
        if (empty($textfilters)) {
            $textfilters = 'mod/glossary/dynalink.php';
        }
        set_config('textfilters', $textfilters);
    }
    if ($oldversion < 2004021201) {
        modify_database("", "CREATE TABLE prefix_cache_filters (\n                                id SERIAL PRIMARY KEY,\n                                filter varchar(32) NOT NULL default '',\n                                version integer NOT NULL default '0',\n                                md5key varchar(32) NOT NULL default '',\n                                rawtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
        modify_database("", "CREATE INDEX prefix_cache_filters_filtermd5key_idx ON prefix_cache_filters (filter,md5key);");
        modify_database("", "CREATE INDEX prefix_cache_text_md5key_idx ON prefix_cache_text (md5key);");
    }
    if ($oldversion < 2004021500) {
        table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
    }
    if ($oldversion < 2004021700) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004022000) {
        table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
    }
    if ($oldversion < 2004022200) {
        /// Final renaming I hope.  :-)
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
            $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
            $textfilters = explode(',', $CFG->textfilters);
            foreach ($textfilters as $key => $textfilter) {
                $textfilters[$key] = trim($textfilter);
            }
            set_config("textfilters", implode(',', $textfilters));
        }
    }
    if ($oldversion < 2004030702) {
        /// Because of the renaming of Czech language pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
    }
    if ($oldversion < 2004041800) {
        /// Integrate Block System from contrib
        table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
    }
    if ($oldversion < 2004042600) {
        /// Rebuild course caches for resource icons
        //include_once("$CFG->dirroot/course/lib.php");
        //rebuild_course_cache();
    }
    if ($oldversion < 2004042700) {
        /// Increase size of lang fields
        table_column("user", "lang", "lang", "varchar", "10", "", "en");
        table_column("groups", "lang", "lang", "varchar", "10", "", "");
        table_column("course", "lang", "lang", "varchar", "10", "", "");
    }
    if ($oldversion < 2004042701) {
        /// Add hiddentopics field to control hidden topics behaviour
        #table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
        #See 'hiddensections' further down
    }
    if ($oldversion < 2004042702) {
        /// Add a format field for the description
        table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
    }
    if ($oldversion < 2004043001) {
        /// Add hiddentopics field to control hidden topics behaviour
        table_column("course", "", "hiddensections", "integer", "2", "unsigned", "0", "not null", "visible");
    }
    if ($oldversion < 2004050400) {
        /// add a visible field for events
        table_column("event", "", "visible", "smallint", "1", "", "1", "not null", "timeduration");
        if ($events = get_records('event')) {
            foreach ($events as $event) {
                if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
                    if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
                        set_field('event', 'visible', 0, 'id', $event->id);
                    }
                }
            }
        }
    }
    if ($oldversion < 2004052800) {
        /// First version tagged "1.4 development", version.php 1.227
        set_config('siteblocksadded', true);
        /// This will be used later by the block upgrade
    }
    if ($oldversion < 2004053000) {
        /// set defaults for site course
        $site = get_site();
        set_field('course', 'numsections', 0, 'id', $site->id);
        set_field('course', 'groupmodeforce', 1, 'id', $site->id);
        set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
        set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
        set_field('course', 'student', get_string('user'), 'id', $site->id);
        set_field('course', 'students', get_string('users'), 'id', $site->id);
    }
    if ($oldversion < 2004060100) {
        set_config('digestmailtime', 0);
        table_column('user', "", 'maildigest', 'smallint', '1', '', '0', 'not null', 'mailformat');
    }
    if ($oldversion < 2004062400) {
        table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
        table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
    }
    if ($oldversion < 2004062401) {
        table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
        execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname');
        // By default
    }
    if ($oldversion < 2004062600) {
        table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
    }
    if ($oldversion < 2004072900) {
        table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
    }
    if ($oldversion < 2004072901) {
        // Fixing error in schema
        if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
            delete_records('log_display', 'module', 'course', 'action', 'update');
            insert_record('log_display', $record, false);
        }
    }
    if ($oldversion < 2004081200) {
        // Fixing version errors in some blocks
        set_field('blocks', 'version', 2004081200, 'name', 'admin');
        set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
        set_field('blocks', 'version', 2004081200, 'name', 'course_list');
    }
    if ($oldversion < 2004081500) {
        // Adding new "auth" field to user table to allow more flexibility
        table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
        execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");
        // Set everyone to 'manual' to be sure
        if ($admins = get_admins()) {
            // Set all the NON-admins to whatever the current auth module is
            $adminlist = array();
            foreach ($admins as $user) {
                $adminlist[] = $user->id;
            }
            $adminlist = implode(',', $adminlist);
            execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})");
        }
    }
    if ($oldversion < 2004082600) {
        //update auth-fields for external users
        // following code would not work in 1.8
        /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
                if (function_exists('auth_get_userlist')) {
                    $externalusers = auth_get_userlist();
                    if (!empty($externalusers)){
                        $externalusers = '\''. implode('\',\'',$externalusers).'\'';
                        execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
                    }
                }*/
    }
    if ($oldversion < 2004082900) {
        // Make sure guest is "manual" too.
        set_field('user', 'auth', 'manual', 'username', 'guest');
    }
    /* Just commenteed unused fields out
       if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
               table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
               execute_sql("CREATE INDEX {$CFG->prefix}user_auth_guid_idx ON {$CFG->prefix}user (auth, guid)"); 
       }
       */
    if ($oldversion < 2004091900) {
        //Modify idnumber to hold longer keys
        set_field('user', 'auth', 'manual', 'username', 'guest');
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
        execute_sql("DROP INDEX {$CFG->prefix}user_idnumber_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("DROP INDEX {$CFG->prefix}user_auth_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("CREATE INDEX {$CFG->prefix}user_idnumber_idx ON {$CFG->prefix}user (idnumber)");
        execute_sql("CREATE INDEX {$CFG->prefix}user_auth_idx ON {$CFG->prefix}user (auth)");
    }
    if ($oldversion < 2004092000) {
        //redoing this just to be sure that column type is text (postgres type changes didnt work when this was done first time)
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004093001) {
        // add new table for sessions storage
        execute_sql(" CREATE TABLE {$CFG->prefix}sessions (\n                          sesskey char(32) PRIMARY KEY,\n                          expiry integer NOT null,\n                          expireref varchar(64),\n                          data text NOT null\n                      );");
        execute_sql(" CREATE INDEX {$CFG->prefix}sessions_expiry_idx ON {$CFG->prefix}sessions (expiry)");
    }
    if ($oldversion < 2004111500) {
        // Update any users/courses using wrongly-named lang pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
    }
    if ($oldversion < 2004111700) {
        // add indexes- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_idnumber_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_shortname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_userid_idx;", false);
        modify_database("", "CREATE INDEX {$CFG->prefix}course_idnumber_idx ON {$CFG->prefix}course (idnumber);");
        modify_database("", "CREATE INDEX {$CFG->prefix}course_shortname_idx ON {$CFG->prefix}course (shortname);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_userid_idx ON {$CFG->prefix}user_students (userid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_userid_idx ON {$CFG->prefix}user_teachers (userid);");
    }
    if ($oldversion < 2004111700) {
        // add an index to event for timestart and timeduration- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}event_timestart_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}event_timeduration_idx;", false);
        modify_database('', 'CREATE INDEX prefix_event_timestart_idx ON prefix_event (timestart);');
        modify_database('', 'CREATE INDEX prefix_event_timeduration_idx ON prefix_event (timeduration);');
    }
    if ($oldversion < 2004117000) {
        // add an index on the groups_members table- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}groups_members_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_groups_members_userid_idx ON prefix_groups_members (userid);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on modules and course_modules- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_visible_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_module_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_instance_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}modules_name_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_modules_visible_idx ON prefix_course_modules (visible);');
        modify_database('', 'CREATE INDEX prefix_course_modules_course_idx ON prefix_course_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_modules_module_idx ON prefix_course_modules (module);');
        modify_database('', 'CREATE INDEX prefix_course_modules_instance_idx ON prefix_course_modules (instance);');
        modify_database('', 'CREATE INDEX prefix_course_modules_deleted_idx ON prefix_course_modules (deleted);');
        modify_database('', 'CREATE INDEX prefix_modules_name_idx ON prefix_modules (name);');
    }
    if ($oldversion < 2004111700) {
        // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
        execute_sql("DROP INDEX {$CFG->prefix}user_students_timeaccess_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_students_timeaccess_idx ON prefix_user_students (timeaccess);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on faux foreign keys  - drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_sections_coursesection_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}scale_courseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_admins_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_coursecreators_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_sections_coursesection_idx ON prefix_course_sections (course,section);');
        modify_database('', 'CREATE INDEX prefix_scale_courseid_idx ON prefix_scale (courseid);');
        modify_database('', 'CREATE INDEX prefix_user_admins_userid_idx ON prefix_user_admins (userid);');
        modify_database('', 'CREATE INDEX prefix_user_coursecreators_userid_idx ON prefix_user_coursecreators (userid);');
    }
    if ($oldversion < 2004111700) {
        // make new indexes on user table.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk;", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder)");
        execute_sql("DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        modify_database("", "CREATE INDEX prefix_user_deleted_idx ON prefix_user (deleted)");
        modify_database("", "CREATE INDEX prefix_user_confirmed_idx ON prefix_user (confirmed)");
        modify_database("", "CREATE INDEX prefix_user_firstname_idx ON prefix_user (firstname)");
        modify_database("", "CREATE INDEX prefix_user_lastname_idx ON prefix_user (lastname)");
        modify_database("", "CREATE INDEX prefix_user_city_idx ON prefix_user (city)");
        modify_database("", "CREATE INDEX prefix_user_country_idx ON prefix_user (country)");
        modify_database("", "CREATE INDEX prefix_user_lastaccess_idx ON prefix_user (lastaccess)");
    }
    if ($oldversion < 2004111700) {
        // one more index for email (for sorting)
        execute_sql("DROP INDEX {$CFG->prefix}user_email_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_email_idx ON prefix_user (email);');
    }
    if ($oldversion < 2004112200) {
        // new 'enrol' field for enrolment tables
        table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
        table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_enrol_idx ON {$CFG->prefix}user_students (enrol);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_enrol_idx ON {$CFG->prefix}user_teachers (enrol);");
    }
    if ($oldversion < 2004112300) {
        // update log display to use correct postgres friendly sql
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='user' AND action='view' AND mtable='user'");
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='course' AND action='user report' AND mtable='user'");
    }
    if ($oldversion < 2004112400) {
        /// Delete duplicate enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_students_courseuserid_uk ON prefix_user_students (course,userid);');
        /// Delete duplicate teacher enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_teachers_courseuserid_uk ON prefix_user_teachers (course,userid);');
    }
    if ($oldversion < 2004112401) {
        // some postgres databases may have a non-unique index mislabeled unique.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk  ", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx  ", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder);");
        // odd! username was missing its unique index!
        // first silently drop it just in case...
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP CONSTRAINT {$CFG->prefix}user_username_uk;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_username_uk", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_user_username_uk ON prefix_user (username);");
    }
    if ($oldversion < 2004112900) {
        table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
    }
    if ($oldversion < 2004121400) {
        table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
    }
    if ($oldversion < 2004121600) {
        modify_database('', "CREATE TABLE prefix_dst_preset (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(48) NOT NULL default '',\n                                apply_offset integer NOT NULL default '0',\n                                activate_index integer NOT NULL default '1',\n                                activate_day integer NOT NULL default '1',\n                                activate_month integer NOT NULL default '1',\n                                activate_time char(5) NOT NULL default '03:00',\n                                deactivate_index integer NOT NULL default '1',\n                                deactivate_day integer NOT NULL default '1',\n                                deactivate_month integer NOT NULL default '2',\n                                deactivate_time char(5) NOT NULL default '03:00',\n                                last_change integer NOT NULL default '0',\n                                next_change integer NOT NULL default '0',\n                                current_offset integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004122800) {
        execute_sql("DROP TABLE {$CFG->prefix}message", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_contacts_useridcontactid_idx", false);
        modify_database('', "CREATE TABLE prefix_message (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default ''\n                            );\n\n                            CREATE INDEX prefix_message_useridfrom_idx ON prefix_message (useridfrom);\n                            CREATE INDEX prefix_message_useridto_idx ON prefix_message (useridto);\n\n                            CREATE TABLE prefix_message_read (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               timeread integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default '',\n                               mailed integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_read_useridfrom_idx ON prefix_message_read (useridfrom);\n                            CREATE INDEX prefix_message_read_useridto_idx ON prefix_message_read (useridto);\n                            ");
        modify_database('', "CREATE TABLE prefix_message_contacts (\n                               id SERIAL PRIMARY KEY,\n                               userid integer NOT NULL default '0',\n                               contactid integer NOT NULL default '0',\n                               blocked integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_contacts_useridcontactid_idx ON prefix_message_contacts (userid,contactid);\n                            ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2004122801) {
        table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
        table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
    }
    if ($oldversion < 2005010100) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2005011000) {
        // Create a .htaccess file in dataroot, just in case
        if (!file_exists($CFG->dataroot . '/.htaccess')) {
            if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) {
                // For safety
                @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
                @fclose($handle);
                notify("Created a default .htaccess file in {$CFG->dataroot}");
            }
        }
    }
    if ($oldversion < 2005012500) {
        // add new table for meta courses.
        /*
        modify_database("","CREATE TABLE prefix_meta_course (
             id SERIAL primary key,
             parent_course integer NOT NULL,
             child_course integer NOT NULL
             );");
        
        modify_database("","CREATE INDEX prefix_meta_course_parent_idx ON prefix_meta_course (parent_course);");
        modify_database("","CREATE INDEX prefix_meta_course_child_idx ON prefix_meta_course (child_course);");
        table_column('course','','meta_course','integer','1','','0','not null');
        */
        // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
    }
    if ($oldversion < 2005012501) {
        //fix table names for consistency
        execute_sql("DROP TABLE {$CFG->prefix}meta_course", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false);
        // drop silently
        modify_database("", "CREATE TABLE prefix_course_meta (\n             id SERIAL primary key,\n             parent_course integer NOT NULL,\n             child_course integer NOT NULL\n             );");
        modify_database("", "CREATE INDEX prefix_course_meta_parent_idx ON prefix_course_meta (parent_course);");
        modify_database("", "CREATE INDEX prefix_course_meta_child_idx ON prefix_course_meta (child_course);");
        table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005020100) {
        fix_course_sortorder(0, 1, 1);
    }
    if ($oldversion < 2005021000) {
        // New fields for theme choices
        table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        set_config('theme', 'standardwhite');
        // Reset to a known good theme
    }
    if ($oldversion < 2005021700) {
        table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
    }
    if ($oldversion < 2005021800) {
        modify_database("", "CREATE TABLE adodb_logsql (\n                              created timestamp NOT NULL,\n                              sql0 varchar(250) NOT NULL,\n                              sql1 text NOT NULL,\n                              params text NOT NULL,\n                              tracer text NOT NULL,\n                              timer decimal(16,6) NOT NULL\n                           );");
    }
    if ($oldversion < 2005022400) {
        table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
        table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
    }
    if ($oldversion < 2005030501) {
        table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
    }
    if ($oldversion < 2005032300) {
        table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
        execute_sql('UPDATE ' . $CFG->prefix . 'user SET timezonename = \'\'');
    }
    if ($oldversion < 2005032600) {
        execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false);
        modify_database('', "CREATE TABLE prefix_timezone (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(100) NOT NULL default '',\n                              year integer NOT NULL default '0',\n                              rule varchar(20) NOT NULL default '',\n                              gmtoff integer NOT NULL default '0',\n                              dstoff integer NOT NULL default '0',\n                              dst_month integer NOT NULL default '0',\n                              dst_startday integer NOT NULL default '0',\n                              dst_weekday integer NOT NULL default '0',\n                              dst_skipweeks integer NOT NULL default '0',\n                              dst_time varchar(5) NOT NULL default '00:00',\n                              std_month integer NOT NULL default '0',\n                              std_startday integer NOT NULL default '0',\n                              std_weekday integer NOT NULL default '0',\n                              std_skipweeks integer NOT NULL default '0',\n                              std_time varchar(5) NOT NULL default '00:00'\n                            );");
    }
    if ($oldversion < 2005032800) {
        modify_database('', "CREATE TABLE prefix_grade_category (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(64) default NULL,\n                              courseid integer NOT NULL default '0',\n                              drop_x_lowest integer NOT NULL default '0',\n                              bonus_points integer NOT NULL default '0',\n                              hidden integer NOT NULL default '0',\n                              weight decimal(4,2) default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_category_courseid_idx ON prefix_grade_category (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_exceptions (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer  NOT NULL default '0',\n                              grade_itemid integer  NOT NULL default '0',\n                              userid integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_exceptions_courseid_idx ON prefix_grade_exceptions (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_item (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              category integer default NULL,\n                              modid integer default NULL,\n                              cminstance integer default NULL,\n                              scale_grade float(11) default '1.0000000000',\n                              extra_credit integer NOT NULL default '0',\n                              sort_order integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_item_courseid_idx ON prefix_grade_item (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_letter (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer NOT NULL default '0',\n                              letter varchar(8) NOT NULL default 'NA',\n                              grade_high decimal(6,2) NOT NULL default '100.00',\n                              grade_low decimal(6,2) NOT NULL default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_letter_courseid_idx ON prefix_grade_letter (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_preferences (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              preference integer NOT NULL default '0',\n                              value integer NOT NULL default '0'\n                            );");
        modify_database('', "CREATE UNIQUE INDEX prefix_grade_prefs_courseidpref_uk ON prefix_grade_preferences (courseid,preference);");
    }
    if ($oldversion < 2005033100) {
        // Get rid of defunct field from course modules table
        delete_records('course_modules', 'deleted', 1);
        // Delete old records we don't need any more
        execute_sql('DROP INDEX ' . $CFG->prefix . 'course_modules_deleted_idx;');
        // Old index
        execute_sql('ALTER TABLE ' . $CFG->prefix . 'course_modules DROP deleted;');
        // Old field
    }
    if ($oldversion < 2005040800) {
        table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
        execute_sql(" ALTER TABLE {$CFG->prefix}user DROP timezonename ");
    }
    if ($oldversion < 2005041101) {
        require_once $CFG->libdir . '/filelib.php';
        if (is_readable($CFG->dirroot . '/lib/timezones.txt')) {
            // Distribution file
            if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) {
                $db->debug = false;
                update_timezone_records($timezones);
                notify(count($timezones) . ' timezones installed');
                $db->debug = true;
            }
        }
    }
    if ($oldversion < 2005041900) {
        // Copy all Dialogue entries into Messages, and hide Dialogue module
        if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
                                          FROM ' . $CFG->prefix . 'dialogue_conversations c,
                                               ' . $CFG->prefix . 'dialogue_entries e
                                         WHERE e.conversationid = c.id')) {
            foreach ($entries as $entry) {
                $message = NULL;
                $message->useridfrom = $entry->userid;
                $message->useridto = $entry->recipientid;
                $message->message = addslashes($entry->text);
                $message->format = FORMAT_HTML;
                $message->timecreated = $entry->timecreated;
                $message->messagetype = 'direct';
                insert_record('message_read', $message);
            }
        }
        set_field('modules', 'visible', 0, 'name', 'dialogue');
        notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
    }
    if ($oldversion < 2005042100) {
        $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
    }
    if ($oldversion < 2005042400) {
        // Add user tracking prefs field.
        table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
    }
    if ($oldversion < 2005051500) {
        // Add user tracking prefs field.
        table_column('grade_category', 'weight', 'weight', 'numeric(5,2)', '', '', '0.00', '', '');
    }
    if ($oldversion < 2005053000) {
        // Add config_plugins table
        // this table was created on the MOODLE_15_STABLE branch
        // so it may already exist. Therefore we hide potential errors
        // (Postgres doesn't support CREATE TABLE IF NOT EXISTS)
        execute_sql("CREATE TABLE {$CFG->prefix}config_plugins (\n                        id     SERIAL PRIMARY KEY,\n                        plugin varchar(100) NOT NULL default 'core',\n                        name   varchar(100) NOT NULL default '',\n                        value  text NOT NULL default '',\n                        CONSTRAINT {$CFG->prefix}config_plugins_plugin_name_uk UNIQUE (plugin, name)\n                     );", false);
    }
    if ($oldversion < 2005060200) {
        // migrate some config items to config_plugins table
        // NOTE: this block is in both postgres AND mysql upgrade
        // files. If you edit either, update the otherone.
        $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang");
        if (!empty($CFG->auth)) {
            // if we have no auth, just pass
            foreach ($user_fields as $field) {
                $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
                foreach ($suffixes as $suffix) {
                    $key = 'auth_user_' . $field . $suffix;
                    if (isset($CFG->{$key})) {
                        // translate keys & values
                        // to the new convention
                        // this should support upgrading
                        // even 1.5dev installs
                        $newkey = $key;
                        $newval = $CFG->{$key};
                        if ($suffix === '') {
                            $newkey = 'field_map_' . $field;
                        } elseif ($suffix === '_editlock') {
                            $newkey = 'field_lock_' . $field;
                            $newval = $newval == 1 ? 'locked' : 'unlocked';
                            // translate 0/1 to locked/unlocked
                        } elseif ($suffix === '_updateremote') {
                            $newkey = 'field_updateremote_' . $field;
                        } elseif ($suffix === '_updatelocal') {
                            $newkey = 'field_updatelocal_' . $field;
                            $newval = $newval == 1 ? 'onlogin' : 'oncreate';
                            // translate 0/1 to locked/unlocked
                        }
                        if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) {
                            notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} .");
                            $result = false;
                        }
                    }
                    // end if isset key
                }
                // end foreach suffix
            }
            // end foreach field
        }
    }
    if ($oldversion < 2005060201) {
        // Close down the Attendance module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) {
            if (count_records('attendance')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'attendance');
                notify('The Attendance module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Attendance activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false);
                delete_records('modules', 'name', 'attendance');
                notify("The Attendance module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005060223) {
        // Mass cleanup of bad postgres upgrade scripts
        execute_sql("DROP TABLE {$CFG->prefix}attendance_roll", false);
        // There are no attendance module anymore
        modify_database('', 'ALTER TABLE prefix_config ALTER value SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER metacourse SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_event ALTER repeatid SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER password SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message_read ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER aim DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER idnumber DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER msn DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER policyagreed SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER skype DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER timezone SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER trackforums SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER yahoo DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user_students ALTER enrol SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user_teachers ALTER enrol SET NOT NULL');
    }
    if ($oldversion < 2005071700) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (count_records('dialogue')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'dialogue');
                notify('The Dialogue module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Dialogue activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false);
                delete_records('modules', 'name', 'dialogue');
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005072000) {
        // Add a couple fields to mdl_event to work towards iCal import/export
        table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
        table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
    }
    if ($oldversion < 2005072100) {
        // run the online assignment cleanup code
        include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php';
        if (function_exists('online_assignment_cleanup')) {
            online_assignment_cleanup();
        }
    }
    if ($oldversion < 2005072200) {
        // fix the mistakenly-added currency stuff from enrol/authorize
        execute_sql("DROP TABLE {$CFG->prefix}currencies", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
        $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
        table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
    }
    if ($oldversion < 2005081600) {
        //set up the course requests table
        modify_database('', "CREATE TABLE prefix_course_request (\n           id SERIAL PRIMARY KEY,\n           fullname varchar(254) NOT NULL default '',\n           shortname varchar(15) NOT NULL default '',\n           summary text NOT NULL default '',\n           reason text NOT NULL default '',\n           requester INTEGER NOT NULL default 0\n         );");
        modify_database('', 'CREATE INDEX prefix_course_request_shortname_idx ON prefix_course_request (shortname);');
        table_column('course', '', 'requested');
    }
    if ($oldversion < 2005081601) {
        modify_database('', 'CREATE TABLE prefix_course_allowed_modules (
            id SERIAL PRIMARY KEY,
            course INTEGER NOT NULL default 0,
            module INTEGER NOT NULL default 0
         );');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_course_idx ON prefix_course_allowed_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_module_idx ON prefix_course_allowed_modules (module);');
        table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005081700) {
        table_column('course_categories', '', 'depth', 'integer');
        table_column('course_categories', '', 'path', 'varchar', '255');
    }
    if ($oldversion < 2005090100) {
        // stats!
        modify_database('', 'CREATE TABLE prefix_stats_daily (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_daily_courseid_idx ON prefix_stats_daily (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_daily_timeend_idx ON prefix_stats_daily (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_weekly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_courseid_idx ON prefix_stats_weekly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_timeend_idx ON prefix_stats_weekly (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_monthly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_courseid_idx ON prefix_stats_monthly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_timeend_idx ON prefix_stats_monthly (timeend);');
        modify_database("", "CREATE TABLE prefix_stats_user_daily (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_courseid_idx ON prefix_stats_user_daily (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_userid_idx ON prefix_stats_user_daily (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_roleid_idx ON prefix_stats_user_daily (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_timeend_idx ON prefix_stats_user_daily (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_courseid_idx ON prefix_stats_user_weekly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_userid_idx ON prefix_stats_user_weekly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_roleid_idx ON prefix_stats_user_weekly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_timeend_idx ON prefix_stats_user_weekly (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_courseid_idx ON prefix_stats_user_monthly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_userid_idx ON prefix_stats_user_monthly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_roleid_idx ON prefix_stats_user_monthly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_timeend_idx ON prefix_stats_user_monthly (timeend);");
    }
    if ($oldversion < 2005100300) {
        table_column('course', '', 'expirynotify', 'integer', '1');
        table_column('course', '', 'expirythreshold', 'integer');
        table_column('course', '', 'notifystudents', 'integer', '1');
        $new = new stdClass();
        $new->name = 'lastexpirynotify';
        $new->value = 0;
        insert_record('config', $new);
    }
    if ($oldversion < 2005100400) {
        table_column('course', '', 'enrollable', 'integer', '1', 'unsigned', '1');
        table_column('course', '', 'enrolstartdate', 'integer');
        table_column('course', '', 'enrolenddate', 'integer');
    }
    if ($oldversion < 2005101200) {
        // add enrolment key to course_request.
        table_column('course_request', '', 'password', 'text');
    }
    if ($oldversion < 2006030800) {
        # add extra indexes to log (see bug #4112)
        modify_database('', "CREATE INDEX prefix_log_userid_idx ON prefix_log (userid);");
        modify_database('', "CREATE INDEX prefix_log_info_idx ON prefix_log (info);");
    }
    if ($oldversion < 2006030900) {
        table_column('course', '', 'enrol', 'varchar', '20', '', '');
        if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
            set_config('enrol_plugins_enabled', 'manual');
            set_config('enrol', 'manual');
        } else {
            set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol);
        }
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            // switch enrollable to off for all courses in this case
            modify_database('', 'UPDATE prefix_course SET enrollable = 0');
        }
        execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
        execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
    }
    if ($oldversion < 2006031000) {
        modify_database("", "CREATE TABLE prefix_post (\n          id SERIAL PRIMARY KEY,\n          userid INTEGER NOT NULL default 0,\n          courseid INTEGER NOT NULL default 0,\n          groupid INTEGER NOT NULL default 0,\n          moduleid INTEGER NOT NULL default 0,\n          coursemoduleid INTEGER NOT NULL default 0,\n          subject varchar(128) NOT NULL default '',\n          summary text,\n          content text,\n          uniquehash varchar(128) NOT NULL default '',\n          rating INTEGER NOT NULL default 0,\n          format INTEGER NOT NULL default 0,\n          publishstate varchar(10) CHECK (publishstate IN ('draft','site','public')) NOT NULL default 'draft',\n          lastmodified INTEGER NOT NULL default '0',\n          created INTEGER NOT NULL default '0'\n        );");
        modify_database("", "CREATE INDEX id_user_idx ON prefix_post  (id, courseid);");
        modify_database("", "CREATE INDEX post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX post_subject_idx ON prefix_post (subject);");
        modify_database("", "CREATE TABLE prefix_tags (\n          id SERIAL PRIMARY KEY,\n          type varchar(255) NOT NULL default 'official',\n          userid INTEGER NOT NULL default 0,\n          text varchar(255) NOT NULL default ''\n        );");
        modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n          id SERIAL PRIMARY KEY,\n          entryid integer NOT NULL default 0,\n          tagid integer NOT NULL default 0,\n          groupid integer NOT NULL default 0,\n          courseid integer NOT NULL default 0,\n          userid integer NOT NULL default 0\n        );");
    }
    if ($oldversion < 2006031400) {
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            set_config('enrol', 'manual');
        }
    }
    if ($oldversion < 2006032000) {
        table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id');
        modify_database('', "CREATE INDEX post_module_idx ON prefix_post (module);");
        modify_database('', "UPDATE prefix_post SET module = 'blog';");
    }
    if ($oldversion < 2006032001) {
        table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid');
        modify_database('', "CREATE INDEX bti_entryid_idx ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX bti_tagid_idx ON prefix_blog_tag_instance (tagid);");
        modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';");
    }
    if ($oldversion < 2006040500) {
        // Add an index to course_sections that was never upgraded (bug 5100)
        execute_sql(" CREATE INDEX {$CFG->prefix}course_sections_coursesection_idx ON {$CFG->prefix}course_sections (course,section) ", false);
    }
    if ($oldversion < 2006041100) {
        table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible');
    }
    if ($oldversion < 2006042400) {
        // Look through table log_display and get rid of duplicates.
        $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display');
        // Drop the log_display table and create it back with an id field.
        execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
        modify_database('', "CREATE TABLE prefix_log_display (\n                               id SERIAL PRIMARY KEY,\n                               module varchar(30) NOT NULL default '',\n                               action varchar(40) NOT NULL default '',\n                               mtable varchar(30) NOT NULL default '',\n                               field varchar(50) NOT NULL default '')");
        // Add index to ensure that module and action combination is unique.
        modify_database('', 'CREATE INDEX prefix_log_display_moduleaction ON prefix_log_display (module,action)');
        // Insert the records back in, sans duplicates.
        if ($rs) {
            while (!$rs->EOF) {
                $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')";
                execute_sql($sql, false);
                $rs->MoveNext();
            }
            rs_close($rs);
        }
    }
    // add 2 indexes to tags table
    if ($oldversion < 2006042401) {
        modify_database('', "CREATE INDEX tags_typeuserid_idx ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX tags_text_idx ON prefix_tags (text);");
    }
    if ($oldversion < 2006050500) {
        table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
    }
    if ($oldversion < 2006050502) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (!count_records('dialogue_conversations')) {
                // no data, drop the extra tables
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_conversations', false);
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_entries', false);
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
        table_column('course_request', 'password', 'password', 'varchar', '50', '', '');
        table_column('course', 'currency', 'currency', 'varchar', '3');
        modify_database('', 'ALTER TABLE prefix_course_categories
            ALTER COLUMN path SET DEFAULT \'\'');
        table_column('log_display', 'module', 'module', 'varchar', '20');
        modify_database("", "DROP INDEX id_user_idx");
        modify_database("", "DROP INDEX post_lastmodified_idx");
        modify_database("", "DROP INDEX post_subject_idx");
        modify_database('', "DROP INDEX bti_entryid_idx");
        modify_database('', "DROP INDEX bti_tagid_idx");
        modify_database('', "DROP INDEX post_module_idx");
        modify_database('', "DROP INDEX tags_typeuserid_idx");
        modify_database('', "DROP INDEX tags_text_idx");
        modify_database("", "CREATE INDEX {$CFG->prefix}id_user_idx           ON prefix_post (id, courseid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_subject_idx      ON prefix_post (subject);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_entryid_idx       ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_tagid_idx         ON prefix_blog_tag_instance (tagid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}post_module_idx       ON prefix_post (moduleid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_typeuserid_idx   ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_text_idx         ON prefix_tags (text);");
    }
    // renaming of reads and writes for stats_user_xyz
    if ($oldversion < 2006052400) {
        // change this later
        // we are using this because we want silent updates
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN writes TO statswrites", false);
    }
    // Adding some missing log actions
    if ($oldversion < 2006060400) {
        // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
        if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
        }
    }
    //Renaming lastIP to lastip (all fields lowercase)
    if ($oldversion < 2006060900) {
        //Not needed unded PG because it stores fieldnames lowecase by default
        //Only if it exists (because MOODLE_16_STABLE could have done this work before. Bug 5763)
        //$fields = $db->MetaColumnNames($CFG->prefix.'user');
        //if (in_array('lastIP',$fields)) {
        //    table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "", "currentlogin");
        //}
    }
    if ($oldversion < 2006080400) {
        modify_database('', "CREATE TABLE prefix_role (\n                                  id SERIAL PRIMARY KEY,\n                                  name varchar(255) NOT NULL default '',\n                                  shortname varchar(100) NOT NULL default '',     \n                                  description text NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_context (\n                                  id SERIAL PRIMARY KEY,\n                                  level integer NOT NULL default 0,\n                                  instanceid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_assignments (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default 0,\n                                  contextid integer NOT NULL default 0,\n                                  userid integer NOT NULL default 0,\n                                  hidden integer NOT NULL default 0,\n                                  timestart integer NOT NULL default 0,\n                                  timeend integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0,\n                                  enrol varchar(20) NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_role_capabilities (\n                                  id SERIAL PRIMARY KEY,\n                                  contextid integer NOT NULL default 0,\n                                  roleid integer NOT NULL default 0,\n                                  capability varchar(255) NOT NULL default '',\n                                  permission integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_deny_grant (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default '0',\n                                  unviewableroleid integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_capabilities ( \n                              id SERIAL PRIMARY KEY,\n                              name varchar(255) NOT NULL default '', \n                              captype varchar(50) NOT NULL default '', \n                              contextlevel integer NOT NULL default 0, \n                              component varchar(100) NOT NULL default ''\n                                );");
        modify_database('', "CREATE TABLE prefix_role_names ( \n                              id SERIAL PRIMARY KEY,\n                              roleid integer NOT NULL default 0,\n                              contextid integer NOT NULL default 0, \n                              text text NOT NULL default ''\n                                );");
    }
    if ($oldversion < 2006081000) {
        modify_database('', "CREATE INDEX prefix_role_sortorder_idx ON prefix_role (sortorder);");
        modify_database('', "CREATE INDEX prefix_context_instanceid_idx ON prefix_context (instanceid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_context_levelinstanceid_idx ON prefix_context (level, instanceid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_roleid_idx ON prefix_role_assignments (roleid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_contextidid_idx ON prefix_role_assignments (contextid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_userid_idx ON prefix_role_assignments (userid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_assignments_contextidroleiduserid_idx ON prefix_role_assignments (contextid, roleid, userid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_sortorder_idx ON prefix_role_assignments (sortorder);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_roleid_idx ON prefix_role_capabilities (roleid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_contextid_idx ON prefix_role_capabilities (contextid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_modifierid_idx ON prefix_role_capabilities (modifierid);");
        // MDL-10640  adding missing index from upgrade
        modify_database('', "CREATE INDEX prefix_role_capabilities_capability_idx ON prefix_role_capabilities (capability);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_capabilities_roleidcontextidcapability_idx ON prefix_role_capabilities (roleid, contextid, capability);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_roleid_idx ON prefix_role_deny_grant (roleid);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_unviewableroleid_idx ON prefix_role_deny_grant (unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_deny_grant_roleidunviewableroleid_idx ON prefix_role_deny_grant (roleid, unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_capabilities_name_idx ON prefix_capabilities (name);");
        modify_database('', "CREATE INDEX prefix_role_names_roleid_idx ON prefix_role_names (roleid);");
        modify_database('', "CREATE INDEX prefix_role_names_contextid_idx ON prefix_role_names (contextid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_names_roleidcontextid_idx ON prefix_role_names (roleid, contextid);");
    }
    if ($oldversion < 2006081700) {
        modify_database('', "DROP TABLE prefix_role_deny_grant");
        modify_database('', "CREATE TABLE prefix_role_allow_assign (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowassign integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_roleid_idx ON prefix_role_allow_assign (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_allowassign_idx ON prefix_role_allow_assign (allowassign);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_assign_roleidallowassign_idx ON prefix_role_allow_assign (roleid, allowassign);");
        modify_database('', "CREATE TABLE prefix_role_allow_override (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowoverride integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_override_roleid_idx ON prefix_role_allow_override (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_override_allowoverride_idx ON prefix_role_allow_override (allowoverride);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_override_roleidallowoverride_idx ON prefix_role_allow_override (roleid, allowoverride);");
    }
    if ($oldversion < 2006082100) {
        execute_sql("DROP INDEX {$CFG->prefix}context_levelinstanceid_idx;", false);
        table_column('context', 'level', 'aggregatelevel', 'integer', '10', 'unsigned', '0', 'not null', '');
        modify_database('', "CREATE UNIQUE INDEX prefix_context_aggregatelevelinstanceid_idx ON prefix_context (aggregatelevel, instanceid);");
    }
    if ($oldversion < 2006082200) {
        table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
    }
    if ($oldversion < 2006082800) {
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(255) NOT NULL default '',\n                expiry TIMESTAMP NOT NULL,\n                expireref VARCHAR(255),\n                created TIMESTAMP NOT NULL,\n                modified TIMESTAMP NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT {$CFG->prefix}sess_ses_pk PRIMARY KEY (sesskey)\n            );", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP DEFAULT");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP DEFAULT");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP DEFAULT");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    id SERIAL PRIMARY KEY,     \n                    userid integer NOT NULL default 0,\n                    courseid integer NOT NULL default 0, \n                    timeaccess integer NOT NULL default 0\n                    );", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_userid_idx ON {$CFG->prefix}user_lastaccess (userid);", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_courseid_idx ON {$CFG->prefix}user_lastaccess (courseid);", true);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}user_lastaccess_useridcourseid_idx ON {$CFG->prefix}user_lastaccess (userid, courseid);", true);
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
                                $updated->id = $role->id;
                                $updated->shortname = $name . $i;
                                update_record('role', $updated);
                                $i++;
                            }
                        }
                    }
                }
            }
        }
    }
    /// Tables for customisable user profile fields
    if ($oldversion < 2006092000) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        datatype VARCHAR(255) NOT NULL default '',\n                        categoryid BIGINT NOT NULL default 0,\n                        sortorder BIGINT NOT NULL default 0,\n                        required SMALLINT NOT NULL default 0,\n                        locked SMALLINT NOT NULL default 0,\n                        visible SMALLINT NOT NULL default 0,\n                        defaultdata TEXT,\n                        CONSTRAINT {$CFG->prefix}userinfofiel_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_field IS 'Customisable user profile fields';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        sortorder BIGINT NOT NULL default 0,\n                        CONSTRAINT {$CFG->prefix}userinfocate_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_category IS 'Customisable fields categories';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n                        id BIGSERIAL,\n                        userid BIGINT NOT NULL default 0,\n                        fieldid BIGINT NOT NULL default 0,\n                        data TEXT NOT NULL,\n                        CONSTRAINT {$CFG->prefix}userinfodata_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_data IS 'Data for the customisable user fields';", true);
    }
    if ($oldversion < 2006092200) {
        table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
        /*      execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
                execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);  // see 2006092409 below */
    }
    if ($oldversion < 2006092302) {
        // fix sortorder first if needed
        if ($roles = get_all_roles()) {
            $i = 0;
            foreach ($roles as $rolex) {
                if ($rolex->sortorder != $i) {
                    $r = new object();
                    $r->id = $rolex->id;
                    $r->sortorder = $i;
                    update_record('role', $r);
                }
                $i++;
            }
        }
        /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;");
                execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)");*/
    }
    if ($oldversion < 2006092400) {
        table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092409) {
        // ok, once more and now correctly!
        execute_sql("DROP INDEX \"aggregatelevel-instanceid\";", false);
        execute_sql("DROP INDEX \"contextlevel-instanceid\";", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix;", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
    }
    if ($oldversion < 2006092410) {
        /// Convert all the PG unique keys into their corresponding unique indexes
        /// we don't want such keys inside Moodle 1.7 and above
        /// Look for all the UNIQUE CONSTRAINSTS existing in DB
        $uniquecons = get_records_sql("SELECT conname, relname, conkey, clas.oid AS tableoid\n                                          FROM pg_constraint cons,\n                                               pg_class clas\n                                         WHERE cons.contype='u'\n                                           AND cons.conrelid = clas.oid");
        /// Iterate over every unique constraint, calculating its fields
        if ($uniquecons) {
            foreach ($uniquecons as $uniquecon) {
                $conscols = trim(trim($uniquecon->conkey, '}'), '{');
                $conscols = explode(',', $conscols);
                /// Iterate over each column to fetch its name
                $indexcols = array();
                foreach ($conscols as $conscol) {
                    $column = get_record_sql("SELECT attname, attname\n                                                 FROM pg_attribute\n                                                WHERE attrelid = {$uniquecon->tableoid}\n                                                  AND attnum   = {$conscol}");
                    $indexcols[] = $column->attname;
                }
                /// Drop the old UNIQUE CONSTRAINT
                execute_sql("ALTER TABLE {$uniquecon->relname} DROP CONSTRAINT {$uniquecon->conname}", false);
                /// Create the new UNIQUE INDEX
                execute_sql("CREATE UNIQUE INDEX {$uniquecon->relname}_" . implode('_', $indexcols) . "_uix ON {$uniquecon->relname} (" . implode(', ', $indexcols) . ')', false);
            }
        }
    }
    if ($oldversion < 2006092601) {
        table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
示例#28
0
function data_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2006011900) {
        table_column("data_content", "", "content1", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content2", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content3", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content4", "longtext", "", "", "", "not null");
    }
    if ($oldversion < 2006011901) {
        table_column("data", "", "approval", "tinyint", "4");
        table_column("data_records", "", "approved", "tinyint", "4");
    }
    if ($oldversion < 2006020801) {
        table_column("data", "", "scale", "integer", "10", "signed");
        table_column("data", "", "assessed", "integer", "10");
        table_column("data", "", "assesspublic", "integer", "4");
    }
    if ($oldversion < 2006022700) {
        table_column("data_comments", "", "created", "integer", "10");
        table_column("data_comments", "", "modified", "integer", "10");
    }
    if ($oldversion < 2006030700) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'add', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'update', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'record delete', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'fields add', 'data_fields', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'fields update', 'data_fields', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'templates saved', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'templates def', 'data', 'name')");
    }
    if ($oldversion < 2006032700) {
        table_column('data', '', 'defaultsort', 'integer', '10', 'unsigned', '0');
        table_column('data', '', 'defaultsortdir', 'tinyint', '4', 'unsigned', '0', 'not null', 'defaultsort');
        table_column('data', '', 'editany', 'tinyint', '4', 'unsigned', '0', 'not null', 'defaultsortdir');
    }
    if ($oldversion < 2006032900) {
        table_column('data', '', 'csstemplate', 'text', '', '', '', 'not null', 'rsstemplate');
    }
    if ($oldversion < 2006050500) {
        // 2 fields have got no default null values
        table_column('data_comments', 'content', 'content', 'text', '', '', '', 'not null');
        table_column('data_fields', 'description', 'description', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param1', 'param1', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param2', 'param2', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param3', 'param3', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param4', 'param4', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param5', 'param5', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param6', 'param6', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param7', 'param7', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param8', 'param8', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param9', 'param9', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param10', 'param10', 'text', '', '', '', 'not null');
    }
    if ($oldversion < 2006052400) {
        table_column('data', '', 'rsstitletemplate', 'text', '', '', '', 'not null', 'rsstemplate');
    }
    if ($oldversion < 2006081700) {
        table_column('data', '', 'jstemplate', 'text', '', '', '', 'not null', 'csstemplate');
    }
    if ($oldversion < 2006092000) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/data/lib.php';
        $datamod = get_record('modules', 'name', 'data');
        if ($data = get_records('data')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($data as $d) {
                if (!data_convert_to_roles($d, $teacherroles, $studentroles)) {
                    notify('Data with id ' . $d->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            include_once "{$CFG->dirroot}/course/lib.php";
            rebuild_course_cache();
        }
        // End if.
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN participants;');
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN assesspublic;');
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN ratings;');
    }
    if ($oldversion < 2006092302) {
        // Changing some TEXT fields to NULLable and no default
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE singletemplate singletemplate text NULL AFTER rssarticles");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplate listtemplate text NULL AFTER singletemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplateheader listtemplateheader text NULL AFTER listtemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplatefooter listtemplatefooter text NULL AFTER listtemplateheader");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE addtemplate addtemplate text NULL AFTER listtemplatefooter");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE rsstemplate rsstemplate text NULL AFTER addtemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE rsstitletemplate rsstitletemplate text NULL AFTER rsstemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE csstemplate csstemplate text NULL AFTER rsstitletemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE jstemplate jstemplate text NULL AFTER csstemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param1 param1 text NULL AFTER description");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param2 param2 text NULL AFTER param1");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param3 param3 text NULL AFTER param2");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param4 param4 text NULL AFTER param3");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param5 param5 text NULL AFTER param4");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param6 param6 text NULL AFTER param5");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param7 param7 text NULL AFTER param6");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param8 param8 text NULL AFTER param7");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param9 param9 text NULL AFTER param8");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param10 param10 text NULL AFTER param9");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content content longtext NULL AFTER recordid");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content1 content1 longtext NULL AFTER content");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content2 content2 longtext NULL AFTER content1");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content3 content3 longtext NULL AFTER content2");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content4 content4 longtext NULL AFTER content3");
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
示例#29
0
<?php

/**
 * Format Version
 *
 * @author Jeff Graham
 * @version $Id$
 * @package format_page
 **/
$plugin->version = 2007071806;
// Plugin version (update when tables change) if this line is changed ensure that the following line
// in blocks/course_format_page/block_course_format_page.php is changed to reflect the proper version number
// set_config('format_page_version', '2007071806');        // trick the page course format into thinking its already installed.
$plugin->requires = 2007021501;
// Required Moodle version
// This format can generate a huge number of block instances per course.
// Eventually, the weight field can grow past 127 and without this
// modification we run into a nasty bug with block API because
// all weights after 127 are 127
if (!($blocks_upgraded = get_config('format/page', 'blocks_updated'))) {
    $result = table_column('block_instance', 'weight', 'weight', 'integer', '10', 'signed');
    if ($result) {
        set_config('blocks_updated', 1, 'format/page');
    }
}
示例#30
-1
function forum_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2002073008) {
        execute_sql("DELETE FROM modules WHERE name = 'discuss' ");
        execute_sql("ALTER TABLE `discuss` RENAME `forum_discussions` ");
        execute_sql("ALTER TABLE `discuss_posts` RENAME `forum_posts` ");
        execute_sql("ALTER TABLE `discuss_ratings` RENAME `forum_ratings` ");
        execute_sql("ALTER TABLE `forum` CHANGE `intro` `intro` TEXT NOT NULL ");
        execute_sql("ALTER TABLE `forum` ADD `forcesubscribe` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `assessed`");
        execute_sql("ALTER TABLE `forum` CHANGE `type` `type` ENUM( 'single', 'news', 'social', 'general', \n                             'eachuser', 'teacher' ) DEFAULT 'general' NOT NULL ");
        execute_sql("ALTER TABLE `forum_posts` CHANGE `discuss` `discussion` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name') ");
        execute_sql("DELETE FROM log_display WHERE module = 'discuss' ");
        execute_sql("UPDATE log SET action = 'view discussion' WHERE module = 'discuss' AND action = 'view' ");
        execute_sql("UPDATE log SET action = 'add discussion' WHERE module = 'discuss' AND action = 'add' ");
        execute_sql("UPDATE log SET module = 'forum' WHERE module = 'discuss' ");
        notify("Renamed all the old discuss tables (now part of forum) and created new forum_types");
    }
    if ($oldversion < 2002080100) {
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update', 'forum', 'name') ");
    }
    if ($oldversion < 2002082900) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002091000) {
        if (!execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ")) {
            echo "<p>Don't worry about this error - your server already had this upgrade applied";
        }
    }
    if ($oldversion < 2002100300) {
        execute_sql(" ALTER TABLE `forum` CHANGE `open` `open` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL ");
        execute_sql(" UPDATE `forum` SET `open` = 2 WHERE `open` = 1 ");
        execute_sql(" UPDATE `forum` SET `open` = 1 WHERE `open` = 0 ");
    }
    if ($oldversion < 2002101001) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `forum_posts` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_ratings` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_subscriptions` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003042402) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name')");
    }
    if ($oldversion < 2003081403) {
        table_column("forum", "assessed", "assessed", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003082500) {
        table_column("forum", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("forum", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
    }
    if ($oldversion < 2003082502) {
        table_column("forum", "scale", "scale", "integer", "10", "", "0");
        execute_sql("UPDATE {$CFG->prefix}forum SET scale = (- scale)");
    }
    if ($oldversion < 2003100600) {
        table_column("forum", "", "maxbytes", "integer", "10", "unsigned", "0", "", "scale");
    }
    if ($oldversion < 2004010100) {
        table_column("forum", "", "assesspublic", "integer", "4", "unsigned", "0", "", "assessed");
    }
    if ($oldversion < 2004011404) {
        table_column("forum_discussions", "", "userid", "integer", "10", "unsigned", "0", "", "firstpost");
        if ($discussions = get_records_sql("SELECT d.id, p.userid\n                                            FROM {$CFG->prefix}forum_discussions as d, \n                                                 {$CFG->prefix}forum_posts as p\n                                           WHERE d.firstpost = p.id")) {
            foreach ($discussions as $discussion) {
                update_record("forum_discussions", $discussion);
            }
        }
    }
    if ($oldversion < 2004012200) {
        table_column("forum_discussions", "", "groupid", "integer", "10", "unsigned", "0", "", "userid");
    }
    if ($oldversion < 2004013000) {
        table_column("forum_posts", "mailed", "mailed", "tinyint", "2");
    }
    if ($oldversion < 2004020600) {
        table_column("forum_discussions", "", "usermodified", "integer", "10", "unsigned", "0", "", "timemodified");
    }
    if ($oldversion < 2004050300) {
        table_column("forum", "", "rsstype", "tinyint", "2", "unsigned", "0", "", "forcesubscribe");
        table_column("forum", "", "rssarticles", "tinyint", "2", "unsigned", "0", "", "rsstype");
        set_config("forum_enablerssfeeds", 0);
    }
    if ($oldversion < 2004060100) {
        modify_database('', "CREATE TABLE `prefix_forum_queue` (\n                                `id` int(11) unsigned NOT NULL auto_increment,\n                                `userid` int(11) unsigned default 0 NOT NULL,\n                                `discussionid` int(11) unsigned default 0 NOT NULL,\n                                `postid` int(11) unsigned default 0 NOT NULL,\n                                PRIMARY KEY  (`id`),\n                                KEY `user` (userid),\n                                KEY `post` (postid)\n                              ) TYPE=MyISAM COMMENT='For keeping track of posts that will be mailed in digest form';");
    }
    if ($oldversion < 2004070700) {
        // This may be redoing it from STABLE but that's OK
        table_column("forum_discussions", "groupid", "groupid", "integer", "10", "", "0", "");
    }
    if ($oldversion < 2004111700) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_parent_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_discussion_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_forum_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_parent_idx (parent) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_discussion_idx (discussion) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_userid_idx (userid) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_forum_idx (forum) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_userid_idx (userid) ");
    }
    if ($oldversion < 2004111700) {
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX post;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX forum;", false);
        modify_database('', 'ALTER TABLE prefix_forum ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX post (post);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX forum (forum);');
    }
    if ($oldversion < 2005011500) {
        modify_database('', 'CREATE TABLE prefix_forum_read (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  `discussionid` int(10) NOT NULL default \'0\',
                  `postid` int(10) NOT NULL default \'0\',
                  `firstread` int(10) NOT NULL default \'0\',
                  `lastread` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `prefix_forum_user_forum_idx` (`userid`,`forumid`),
                  KEY `prefix_forum_user_discussion_idx` (`userid`,`discussionid`),
                  KEY `prefix_forum_user_post_idx` (`userid`,`postid`)
                  ) COMMENT=\'Tracks each users read posts\';');
        set_config('upgrade', 'forumread');
        // The upgrade of this table will be done later by admin/upgradeforumread.php
    }
    if ($oldversion < 2005032900) {
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_created_idx (created);');
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_mailed_idx (mailed);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}forum_discussions, {$CFG->prefix}forum_posts ";
        $sql .= "where {$CFG->prefix}forum_posts.discussion = {$CFG->prefix}forum_discussions.id ";
        $sql .= "and {$CFG->prefix}forum_posts.id = ";
        $wtm->update('forum_posts', 'message', 'format', $sql);
    }
    if ($oldversion < 2005042300) {
        // Add tracking prefs table
        modify_database('', 'CREATE TABLE prefix_forum_track_prefs (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `user_forum_idx` (`userid`,`forumid`)
                  ) COMMENT=\'Tracks each users untracked forums.\';');
    }
    if ($oldversion < 2005042500) {
        table_column('forum', '', 'trackingtype', 'tinyint', '2', 'unsigned', '1', '', 'forcesubscribe');
    }
    if ($oldversion < 2005111100) {
        table_column('forum_discussions', '', 'timestart', 'integer');
        table_column('forum_discussions', '', 'timeend', 'integer');
    }
    if ($oldversion < 2006011600) {
        execute_sql("alter table " . $CFG->prefix . "forum change column type type enum('single','news','general','social','eachuser','teacher','qanda') not null default 'general'");
    }
    if ($oldversion < 2006011601) {
        table_column('forum', '', 'warnafter');
        table_column('forum', '', 'blockafter');
        table_column('forum', '', 'blockperiod');
    }
    if ($oldversion < 2006011700) {
        table_column('forum_posts', '', 'mailnow', 'integer');
    }
    if ($oldversion < 2006011702) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'CONCAT(firstname,\\' \\',lastname)')");
    }
    if ($oldversion < 2006081800) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        $forummod = get_record('modules', 'name', 'forum');
        if ($forums = get_records('forum')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                notify('Default guest role was not found. Roles and permissions ' . 'for teacher forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($forums as $forum) {
                if (!forum_convert_to_roles($forum, $forummod->id, $teacherroles, $studentroles, $guestroles)) {
                    notify('Forum with id ' . $forum->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            include_once "{$CFG->dirroot}/course/lib.php";
            rebuild_course_cache();
        }
        // End if.
        // Drop column forum.open.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN open;');
        // Drop column forum.assesspublic.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN assesspublic;');
    }
    if ($oldversion < 2006082700) {
        $sql = "UPDATE {$CFG->prefix}forum_posts SET message = REPLACE(message, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('forum_posts', "message {$likecond}")) {
                break;
            }
            execute_sql($sql);
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}