Exemplo n.º 1
0
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;
}
Exemplo n.º 2
0
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;
}
Exemplo n.º 3
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;
}
Exemplo n.º 4
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;
}
Exemplo n.º 5
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` SERIAL PRIMARY KEY,\n          `course` integer NOT NULL default '0',\n          `name` varchar(255) NOT NULL default '',\n          `description` text NOT NULL,\n          `type` integer NOT NULL default '1',\n          `maxbytes` integer NOT NULL default '100000',\n          `timedue` integer NOT NULL default '0',\n          `grade` integer NOT NULL default '0',\n          `timemodified` integer NOT NULL default '0'\n        )\n        ");
        execute_sql("\n        CREATE TABLE `assignment_submissions` (\n          `id` integer NOT NULL PRIMARY KEY default '0',\n          `assignment` integer NOT NULL default '0',\n          `user` integer NOT NULL default '0',\n          `timecreated` integer NOT NULL default '0',\n          `timemodified` integer NOT NULL default '0',\n          `numfiles` integer NOT NULL default '0',\n          `grade` integer NOT NULL default '0',\n          `comment` text NOT NULL,\n          `teacher` integer NOT NULL default '0',\n          `timemarked` integer NOT NULL default '0',\n          `mailed` integer NOT NULL default '0'\n        )\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` SERIAL PRIMARY KEY ");
    }
    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` INTEGER DEFAULT '0' NOT NULL AFTER `description` ");
    }
    if ($oldversion < 2002110302) {
        execute_sql(" UPDATE `assignment` SET `type` = '1'");
    }
    if ($oldversion < 2003091000) {
        # Old field that was never added!
        table_column("assignment", "", "resubmit", "integer", "2", "unsigned", "0", "", "format");
    }
    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("DROP INDEX {$CFG->prefix}assignment_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}assignment_submissions_assignment_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}assignment_submissions_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}assignment_submissions_mailed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}assignment_submissions_timemarked_idx;", false);
        modify_database('', 'CREATE INDEX prefix_assignment_course_idx ON prefix_assignment (course);');
        modify_database('', 'CREATE INDEX prefix_assignment_submissions_assignment_idx ON prefix_assignment_submissions (assignment);');
        modify_database('', 'CREATE INDEX prefix_assignment_submissions_userid_idx ON prefix_assignment_submissions (userid);');
        modify_database('', 'CREATE INDEX prefix_assignment_submissions_mailed_idx ON prefix_assignment_submissions (mailed);');
        modify_database('', 'CREATE INDEX prefix_assignment_submissions_timemarked_idx ON prefix_assignment_submissions (timemarked);');
    }
    if ($oldversion < 2005010500) {
        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';", false);
        execute_sql("UPDATE {$CFG->prefix}assignment SET assignmenttype = 'uploadsingle' WHERE type = '1';", false);
        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', 'TEXT', '', '', '', 'not null', 'numfiles');
        table_column('assignment_submissions', '', 'data1', 'TEXT', '', '', '', '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 < 2005060101) {
        // Mass cleanup of bad upgrade scripts
        modify_database('', 'ALTER TABLE prefix_assignment ALTER assignmenttype SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment ALTER emailteachers SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment ALTER preventlate SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment ALTER timeavailable SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ALTER data1 SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ALTER data2 SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_assignment_submissions ALTER format SET NOT NULL');
    }
    if ($oldversion < 2006092100) {
        table_column('assignment_submissions', 'comment', 'submissioncomment', 'text', '', '', '');
    }
    /// These lines ALWAYS need to be here at the end of this file.  Don't mess with them. :-)
    include_once "{$CFG->dirroot}/mod/assignment/lib.php";
    assignment_upgrade_submodules();
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function kaltura_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    return $status;
    //Convert resource->alltext
    if ($records = get_records_sql("SELECT r.id, r.alltext, r.options\n                                         FROM {$CFG->prefix}resource r,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE r.course = {$restore->course_id} AND\n                                               options = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'resource' AND\n                                               b.new_id = r.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->alltext = restore_decode_wiki_content($record->alltext, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->alltext = $wtm->convert($record->alltext, $restore->course_id);
            $record->options = FORMAT_MARKDOWN;
            $status = update_record('resource', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 7
0
function assignment_restore_wiki2markdown($restore)
{
    global $CFG, $DB;
    $status = true;
    //Convert assignment->description
    if ($records = $DB->get_records_sql("SELECT a.id, a.intro, a.introformat\n                                                FROM {assignment} a, {backup_ids} b\n                                               WHERE a.course = ? AND\n                                               a.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = ? AND\n                                               b.table_name = 'assignment' AND\n                                               b.new_id = a.id", array($restore->course_id, $restore->backup_unique_code))) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->intro = restore_decode_wiki_content($record->intro, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->intro = $wtm->convert($record->intro, $restore->course_id);
            $record->introformat = FORMAT_MARKDOWN;
            $status = $DB->update_record('assignment', $record);
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
function quiz_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert question->questiontext
    if ($records = get_records_sql("SELECT q.id, q.questiontext, q.questiontextformat\n                                         FROM {$CFG->prefix}question q,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'question' AND\n                                               q.id = b.new_id AND\n                                               q.questiontextformat = " . FORMAT_WIKI)) {
        $i = 0;
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->questiontext = restore_decode_wiki_content($record->questiontext, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->questiontext = $wtm->convert($record->questiontext, $restore->course_id);
            $record->questiontextformat = FORMAT_MARKDOWN;
            $status = update_record('question', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 10
0
function forum_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003042402) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name')");
    }
    if ($oldversion < 2003082500) {
        table_column("forum", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("forum", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
    }
    if ($oldversion < 2003082502) {
        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 < 2004020600) {
        table_column("forum_discussions", "", "usermodified", "integer", "10", "unsigned", "0", "", "timemodified");
    }
    if ($oldversion < 2004050300) {
        table_column("forum", "", "rsstype", "integer", "2", "unsigned", "0", "", "forcesubscribe");
        table_column("forum", "", "rssarticles", "integer", "2", "unsigned", "0", "", "rsstype");
        set_config("forum_enablerssfeeds", 0);
    }
    if ($oldversion < 2004060100) {
        modify_database('', "CREATE TABLE prefix_forum_queue (\n                           id SERIAL PRIMARY KEY,\n                           userid integer default 0 NOT NULL,\n                           discussionid integer default 0 NOT NULL,\n                           postid integer default 0 NOT NULL\n                           );");
    }
    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(" DROP INDEX {$CFG->prefix}forum_posts_parent_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_posts_discussion_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_posts_userid_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_discussions_forum_idx;", false);
        execute_sql(" DROP INDEX {$CFG->prefix}forum_discussions_userid_idx;", false);
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_parent_idx ON {$CFG->prefix}forum_posts (parent) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_discussion_idx ON {$CFG->prefix}forum_posts (discussion) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_posts_userid_idx ON {$CFG->prefix}forum_posts (userid) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_discussions_forum_idx ON {$CFG->prefix}forum_discussions (forum) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}forum_discussions_userid_idx ON {$CFG->prefix}forum_discussions (userid) ");
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}forum_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_discussion_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_queue_postid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_ratings_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_ratings_post_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_subscriptions_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}forum_subscriptions_forum_idx;", false);
        modify_database('', 'CREATE INDEX prefix_forum_course_idx ON prefix_forum (course);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_userid_idx ON prefix_forum_queue (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_discussion_idx ON prefix_forum_queue (discussionid);');
        modify_database('', 'CREATE INDEX prefix_forum_queue_postid_idx ON prefix_forum_queue (postid);');
        modify_database('', 'CREATE INDEX prefix_forum_ratings_userid_idx ON prefix_forum_ratings (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_ratings_post_idx ON prefix_forum_ratings (post);');
        modify_database('', 'CREATE INDEX prefix_forum_subscriptions_userid_idx ON prefix_forum_subscriptions (userid);');
        modify_database('', 'CREATE INDEX prefix_forum_subscriptions_forum_idx ON prefix_forum_subscriptions (forum);');
    }
    if ($oldversion < 2005011500) {
        modify_database('', 'CREATE TABLE prefix_forum_read (
                          id SERIAL PRIMARY KEY,
                          userid integer default 0 NOT NULL,
                          forumid integer default 0 NOT NULL,
                          discussionid integer default 0 NOT NULL,
                          postid integer default 0 NOT NULL,
                          firstread integer default 0 NOT NULL,
                          lastread integer default 0 NOT NULL
                        );');
        modify_database('', 'CREATE INDEX prefix_forum_user_forum_idx ON prefix_forum_read (userid, forumid);');
        modify_database('', 'CREATE INDEX prefix_forum_user_discussion_idx ON prefix_forum_read (userid, discussionid);');
        modify_database('', 'CREATE INDEX prefix_forum_user_post_idx ON prefix_forum_read (userid, postid);');
        set_config('upgrade', 'forumread');
        // The upgrade of this table will be done later by admin/upgradeforumread.php
    }
    if ($oldversion < 2005032900) {
        modify_database('', 'CREATE INDEX prefix_forum_posts_created_idx ON prefix_forum_posts (created);');
        modify_database('', 'CREATE INDEX prefix_forum_posts_mailed_idx ON prefix_forum_posts (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 SERIAL PRIMARY KEY, 
                          userid integer default 0 NOT NULL,
                          forumid integer default 0 NOT NULL
                        );');
    }
    if ($oldversion < 2005042600) {
        table_column('forum', '', 'trackingtype', 'integer', '2', 'unsigned', '1', '', 'forcesubscribe');
        modify_database('', 'CREATE INDEX prefix_forum_track_user_forum_idx ON prefix_forum_track_prefs (userid, forumid);');
    }
    if ($oldversion < 2005042601) {
        // Mass cleanup of bad postgres upgrade scripts
        modify_database('', 'ALTER TABLE prefix_forum ALTER trackingtype SET NOT NULL');
    }
    if ($oldversion < 2005111100) {
        table_column('forum_discussions', '', 'timestart', 'integer');
        table_column('forum_discussions', '', 'timeend', 'integer');
    }
    if ($oldversion < 2006011600) {
        notify('forum_type does not exists, you can ignore and this will properly removed');
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type");
        execute_sql("ALTER TABLE {$CFG->prefix}forum ADD CONSTRAINT {$CFG->prefix}forum_type CHECK (type IN ('single','news','general','social','eachuser','teacher','qanda')) ");
    }
    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 < 2006011701) {
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type_check");
    }
    if ($oldversion < 2006011702) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', '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.
            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;
}
Exemplo n.º 11
0
function glossary_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2004022200) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004050900) {
        table_column("glossary", "", "rsstype", "integer", "2", "unsigned", "0", "", "entbypage");
        table_column("glossary", "", "rssarticles", "integer", "2", "unsigned", "0", "", "rsstype");
        set_config("glossary_enablerssfeeds", 0);
    }
    if ($oldversion < 2004051400) {
        print_simple_box("This update might take several seconds.<p>The more glossaries, entries and aliases you have created, the more it will take so please be patient.", "center", "50%", '', "20", "noticebox");
        if ($entries = get_records("glossary_entries", '', '', '', 'id,concept')) {
            foreach ($entries as $entry) {
                set_field("glossary_entries", "concept", addslashes(trim($entry->concept)), "id", $entry->id);
            }
        }
        if ($aliases = get_records("glossary_alias")) {
            foreach ($aliases as $alias) {
                set_field("glossary_alias", "alias", addslashes(trim($alias->alias)), "id", $alias->id);
            }
        }
    }
    if ($oldversion < 2004072300) {
        table_column("glossary_alias", "alias", "alias", "VARCHAR", "255", "", "", "NOT NULL");
    }
    if ($oldversion < 2004072400) {
        //Create new table glossary_formats to store format info
        execute_sql("CREATE TABLE {$CFG->prefix}glossary_formats (\n                       id SERIAL8 PRIMARY KEY,\n                       name VARCHAR(50) NOT NULL,\n                       popupformatname VARCHAR(50) NOT NULL, \n                       visible int2  NOT NULL default '1',\n                       showgroup int2  NOT NULL default '1',\n                       defaultmode VARCHAR(50) NOT NULL default '',\n                       defaulthook VARCHAR(50) NOT NULL default '',\n                       sortkey VARCHAR(50) NOT NULL default '',\n                       sortorder VARCHAR(50) NOT NULL default ''\n                   ) ");
        //Define current 0-6 format names
        $formatnames = array('dictionary', 'continuous', 'fullwithauthor', 'encyclopedia', 'faq', 'fullwithoutauthor', 'entrylist');
        //Fill the new table from the old one (only 'valid', 0-6, formats)
        if ($formats = get_records('glossary_displayformats')) {
            foreach ($formats as $format) {
                //Format names
                if ($format->fid >= 0 && $format->fid <= 6) {
                    $format->name = $formatnames[$format->fid];
                }
                //Format popupformatname
                $format->popupformatname = 'dictionary';
                //Default format
                if ($format->relatedview >= 0 && $format->relatedview <= 6) {
                    $format->popupformatname = $formatnames[$format->relatedview];
                }
                //Insert the new record
                //Only if $format->name is set (ie. formats 0-6)
                if ($format->name) {
                    insert_record('glossary_formats', $format);
                }
            }
        }
        //Drop the old formats table
        execute_sql("DROP TABLE {$CFG->prefix}glossary_displayformats");
        //Modify the glossary->displayformat field
        table_column('glossary', 'displayformat', 'displayformat', 'VARCHAR', '50', '', 'dictionary', 'NOT NULL');
        //Update glossary->displayformat field
        if ($glossaries = get_records('glossary')) {
            foreach ($glossaries as $glossary) {
                $displayformat = 'dictionary';
                //Default format
                if ($glossary->displayformat >= 0 && $glossary->displayformat <= 6) {
                    $displayformat = $formatnames[$glossary->displayformat];
                }
                set_field('glossary', 'displayformat', $displayformat, 'id', $glossary->id);
            }
        }
    }
    if ($oldversion < 2004080800) {
        table_column("glossary", "", "editalways", "integer", "2", "unsigned", "0", "", "entbypage");
    }
    //Activate editalways in old secondary glossaries (old behaviour)
    if ($oldversion < 2004080900) {
        set_field('glossary', 'editalways', '1', 'mainglossary', '0');
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}glossary_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_alias_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_categories_glossaryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_comments_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_comments_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_glossaryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_concept_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_categories_category_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_entries_categories_entryid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_ratings_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}glossary_ratings_entryid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_glossary_course_idx ON prefix_glossary (course);');
        modify_database('', 'CREATE INDEX prefix_glossary_alias_entryid_idx ON prefix_glossary_alias (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_categories_glossaryid_idx ON prefix_glossary_categories (glossaryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_comments_entryid_idx ON prefix_glossary_comments (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_comments_userid_idx ON prefix_glossary_comments (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_glossaryid_idx ON prefix_glossary_entries (glossaryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_userid_idx ON prefix_glossary_entries (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_concept_idx ON prefix_glossary_entries (concept);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_categories_category_idx ON prefix_glossary_entries_categories (categoryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_entries_categories_entryid_idx ON prefix_glossary_entries_categories (entryid);');
        modify_database('', 'CREATE INDEX prefix_glossary_ratings_userid_idx ON prefix_glossary_ratings (userid);');
        modify_database('', 'CREATE INDEX prefix_glossary_ratings_entryid_idx ON prefix_glossary_ratings (entryid);');
    }
    //Delete orphaned categories (bug 2140)
    if ($oldversion < 2005011100) {
        $categories = get_records('glossary_categories', '', '', '', 'id, glossaryid');
        if ($categories) {
            foreach ($categories as $category) {
                $glossary = get_record('glossary', 'id', "{$category->glossaryid}");
                if (!$glossary) {
                    delete_records('glossary_categories', 'id', "{$category->id}");
                }
            }
        }
    }
    //Allowprintview flag
    if ($oldversion < 2005011200) {
        table_column('glossary', '', 'allowprintview', 'integer', '2', 'unsigned', '1', '', 'allowcomments');
        $glossaries = get_records('glossary', '', '', '', 'id, name');
        if ($glossaries) {
            foreach ($glossaries as $glossary) {
                set_field('glossary', 'allowprintview', '1', 'id', "{$glossary->id}");
            }
        }
    }
    if ($oldversion < 2005031001) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('glossary', 'view entry', 'glossary_entries', 'concept');");
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        // update glossary_entries->definition
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = ";
        $wtm->update('glossary_entries', 'definition', 'format');
        // update glossary_comments->text
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries,{$CFG->prefix}glossary_comments ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = {$CFG->prefix}glossary_comments.entryid ";
        $sql .= "and {$CFG->prefix}glossary_comments.id = ";
        $wtm->update('glossary_comments', 'text', 'format', $sql);
    }
    if ($oldversion < 2005041901) {
        // Mass cleanup of bad postgres upgrade scripts
        table_column('glossary', 'allowprintview', 'allowprintview', 'smallint', '4', 'unsigned', '1');
    }
    if ($oldversion < 2006082600) {
        $sql1 = "UPDATE {$CFG->prefix}glossary_entries SET definition = REPLACE(definition, '" . TRUSTTEXT . "', '');";
        $sql2 = "UPDATE {$CFG->prefix}glossary_comments SET comment = REPLACE(comment, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('glossary_entries', "definition {$likecond}")) {
                break;
            }
            execute_sql($sql1);
        }
        while (true) {
            if (!count_records_select('glossary_comments', "comment {$likecond}")) {
                break;
            }
            execute_sql($sql2);
        }
    }
    if ($oldversion < 2006090400) {
        table_column('glossary_comments', 'comment', 'entrycomment', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Exemplo n.º 12
0
function glossary_restore_wiki2markdown($restore)
{
    global $CFG, $DB;
    $status = true;
    //Convert glossary_comments->entrycomment
    if ($records = $DB->get_records_sql("SELECT c.id, c.entrycomment, c.entrycommentformat\n                                               FROM {glossary_comments} c,\n                                                    {glossary_entries} e,\n                                                    {glossary} g,\n                                                    {backup_ids} b\n                                              WHERE e.id = c.entryid AND\n                                                    g.id = e.glossaryid AND\n                                                    g.course = ? AND\n                                                    c.entrycommentformat = " . FORMAT_WIKI . " AND\n                                                    b.backup_code = ? AND\n                                                    b.table_name = 'glossary_comments' AND\n                                                    b.new_id = c.id", array($restore->course_id, $restore->backup_unique_code))) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->entrycomment = restore_decode_wiki_content($record->entrycomment, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->entrycomment = $wtm->convert($record->entrycomment, $restore->course_id);
            $record->entrycommentformat = FORMAT_MARKDOWN;
            $status = $DB->update_record('glossary_comments', $record);
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    //Convert glossary_entries->definition
    if ($records = $DB->get_records_sql("SELECT e.id, e.definition, e.definitionformat\n                                               FROM {glossary_entries} e,\n                                                    {glossary} g,\n                                                    {backup_ids} b\n                                              WHERE g.id = e.glossaryid AND\n                                                    g.course = ? AND\n                                                    e.definitionformat = " . FORMAT_WIKI . " AND\n                                                    b.backup_code = ? AND\n                                                    b.table_name = 'glossary_entries' AND\n                                                    b.new_id = e.id", array($restore->course_id, $restore->backup_unique_code))) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->definition = restore_decode_wiki_content($record->definition, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->definition = $wtm->convert($record->definition, $restore->course_id);
            $record->definitionformat = FORMAT_MARKDOWN;
            $status = $DB->update_record('glossary_entries', $record);
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 13
0
function choice_upgrade($oldversion)
{
    global $CFG;
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    if ($oldversion < 2002090800) {
        execute_sql(" ALTER TABLE `choice` CHANGE `answer1` `answer1` VARCHAR( 255 )");
        execute_sql(" ALTER TABLE `choice` CHANGE `answer2` `answer2` VARCHAR( 255 )");
    }
    if ($oldversion < 2002102400) {
        execute_sql(" ALTER TABLE `choice` ADD `answer3` varchar(255) NOT NULL AFTER `answer2`");
        execute_sql(" ALTER TABLE `choice` ADD `answer4` varchar(255) NOT NULL AFTER `answer3`");
        execute_sql(" ALTER TABLE `choice` ADD `answer5` varchar(255) NOT NULL AFTER `answer4`");
        execute_sql(" ALTER TABLE `choice` ADD `answer6` varchar(255) NOT NULL AFTER `answer5`");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `choice_answers` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003010100) {
        execute_sql(" ALTER TABLE `choice` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `text` ");
        execute_sql(" ALTER TABLE `choice` ADD `publish` TINYINT(2) UNSIGNED 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("ALTER TABLE {$CFG->prefix}choice DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}choice_answers DROP INDEX choice;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}choice_answers DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_choice ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_choice_answers ADD INDEX choice (choice);');
        modify_database('', 'ALTER TABLE prefix_choice_answers ADD INDEX userid (userid);');
    }
    if ($oldversion < 2005033001) {
        if (execute_sql("CREATE TABLE {$CFG->prefix}choice_options (\n                             `id` int(10) unsigned NOT NULL auto_increment, \n                             `choiceid` int(10) unsigned NOT NULL default '0', \n                             `text` TEXT, \n                             `timemodified` int(10) NOT NULL default '0', \n                             PRIMARY KEY  (id), \n                             UNIQUE KEY id (id), \n                             KEY choiceid (choiceid)\n                         ) TYPE=MyISAM;")) {
            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`;');
        } else {
            notify('SERIOUS PROBLEM OCCURRED WHILE UPGRADING A TABLE - you may have to manually upgrade your tables ... see mod/choice/db/mysql.php');
            return false;
        }
    }
    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', 'TINYINT', '2', 'unsigned', 0, 'not null', 'showunanswered');
        table_column('choice_options', '', 'maxanswers', 'INTEGER', '10', 'unsigned', 0, 'null', 'text');
    }
    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;
}
Exemplo n.º 14
0
function glossary_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2003091000) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}glossary` " . " ADD `allowduplicatedentries` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `studentcanpost` , " . " ADD `displayformat` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `allowduplicatedentries` , " . " ADD `mainglossary` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `displayformat` ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}glossary_entries` " . " ADD timecreated INT(10) UNSIGNED NOT NULL default '0' AFTER `format` , " . " ADD timemodified INT(10) UNSIGNED NOT NULL default '0' AFTER `timecreated` , " . " ADD teacherentry TINYINT(2) UNSIGNED NOT NULL default '0' AFTER `timemodified` ");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'delete', 'glossary', 'name') ");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'delete entry', 'glossary', 'name') ");
    }
    if ($oldversion < 2003091500) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}glossary_entries` " . " ADD attachment VARCHAR(100) NOT NULL default '' AFTER `format`");
    }
    if ($oldversion < 2003091600) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}glossary` " . " ADD `showspecial` TINYINT(2) UNSIGNED DEFAULT '1' NOT NULL AFTER `mainglossary` , " . " ADD `showalphabet` TINYINT(2) UNSIGNED DEFAULT '1' NOT NULL AFTER `showspecial` , " . " ADD `showall` TINYINT(2) UNSIGNED DEFAULT '1' NOT NULL AFTER `showalphabet` ");
    }
    if ($oldversion < 2003091800) {
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_categories` (\n                    `id` INT(10) unsigned NOT NULL auto_increment,\n                    `glossaryid` INT(10) UNSIGNED NOT NULL default '0',\n                    `name` VARCHAR(255) NOT NULL default '',\n                    PRIMARY KEY  (`id`)\n                    ) ENGINE=MyISAM COMMENT='all categories for glossary entries'");
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_entries_categories` (\n                    `categoryid` INT(10) UNSIGNED NOT NULL default '1',\n                    `entryid` INT(10) UNSIGNED NOT NULL default '0',\n                    PRIMARY KEY  (`categoryid`, `entryid`)\n                    ) ENGINE=MyISAM COMMENT='categories of each glossary entry'");
    }
    if ($oldversion < 2003092100) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries_categories` CHANGE `categoryid` `categoryid` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003092102) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries_categories` DROP PRIMARY KEY ");
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries_categories` ADD `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST");
    }
    if ($oldversion < 2003092400) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries` " . "ADD `sourceglossaryid` INT(10) unsigned NOT NULL DEFAULT '0' AFTER `attachment` ");
    }
    if ($oldversion < 2003101500) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary` " . "ADD `intro`  text NOT NULL DEFAULT '' AFTER `name` ");
    }
    if ($oldversion < 2003101501) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary` " . "ADD `allowcomments`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '0' AFTER `showall` ");
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_comments` (\n                    `id` INT(10) unsigned NOT NULL auto_increment,\n                    `entryid` INT(10) UNSIGNED NOT NULL default '0',\n                    `userid` INT(10) UNSIGNED NOT NULL default '0',\n                    `comment` TEXT NOT NULL default '',\n                    `timemodified` INT(10) UNSIGNED NOT NULL default '0',\n                    `format` TINYINT(2) UNSIGNED NOT NULL default '0',\n                    PRIMARY KEY  (`id`)\n                    ) ENGINE=MyISAM COMMENT='comments on glossary entries'");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'add comment', 'glossary', 'name') ");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'update comment', 'glossary', 'name') ");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'delete comment', 'glossary', 'name') ");
    }
    if ($oldversion < 2003101600) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary` " . "ADD `usedynalink`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '1' AFTER `allowcomments` ");
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries` " . "ADD `usedynalink`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '1' AFTER `sourceglossaryid`, " . "ADD `casesensitive`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '0' AFTER `usedynalink` ");
    }
    if ($oldversion < 2003101601) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries` " . "ADD `fullmatch`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '1' AFTER `casesensitive` ");
    }
    if ($oldversion < 2003101800) {
        execute_sql("UPDATE `{$CFG->prefix}glossary`" . " SET displayformat = 5 WHERE displayformat = 1");
    }
    if ($oldversion < 2003102000) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary`" . " ADD `defaultapproval` TINYINT(2) UNSIGNED NOT NULL default '1' AFTER `usedynalink`");
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_entries`" . " ADD `approved` TINYINT(2) UNSIGNED NOT NULL default '1' AFTER `fullmatch`");
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('glossary', 'approve entry', 'glossary', 'name') ");
    }
    if ($oldversion < 2003102800) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary`" . " ADD `globalglossary` TINYINT(2) UNSIGNED NOT NULL default '0' AFTER `defaultapproval`");
    }
    if ($oldversion < 2003103100) {
        print_simple_box('This update might take several seconds.<br />The more glossaries, entries and categories you have created, the more it will take so please be patient.', 'center', '50%', '', '20', 'noticebox');
        if ($glossaries = get_records("glossary")) {
            $gids = "";
            foreach ($glossaries as $glossary) {
                $gids .= "{$glossary->id},";
            }
            $gids = substr($gids, 0, -1);
            // ID's of VALID glossaries
            if ($categories = get_records_select("glossary_categories", "glossaryid NOT IN ({$gids})")) {
                $cids = "";
                foreach ($categories as $cat) {
                    $cids .= "{$cat->id},";
                }
                $cids = substr($cids, 0, -1);
                // ID's of INVALID categories
                if ($cids) {
                    delete_records_select("glossary_entries_categories", "categoryid IN ({$cids})");
                    delete_records_select("glossary_categories", "id in ({$cids})");
                }
            }
            if ($entries = get_records_select("glossary_entries")) {
                $eids = "";
                foreach ($entries as $entry) {
                    $eids .= "{$entry->id},";
                }
                $eids = substr($eids, 0, -1);
                // ID's of VALID entries
                if ($eids) {
                    delete_records_select("glossary_comments", "entryid NOT IN ({$eids})");
                }
            }
        }
    }
    if ($oldversion < 2003110400) {
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_alias` (\n                    `id` INT(10) unsigned NOT NULL auto_increment,\n                    `entryid` INT(10) UNSIGNED NOT NULL default '0',\n                    `alias` TEXT NOT NULL default '',\n                    PRIMARY KEY  (`id`)\n                    ) ENGINE=MyISAM COMMENT='entries alias'");
    }
    if ($oldversion < 2003111500) {
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary_categories`\n                     ADD `usedynalink`  TINYINT(2) UNSIGNED NOT NULL DEFAULT '1' AFTER `name`");
        execute_sql("ALTER TABLE `{$CFG->prefix}glossary`\n                     ADD `entbypage`  TINYINT(3) UNSIGNED NOT NULL DEFAULT '10' AFTER `globalglossary`");
    }
    if ($oldversion < 2003111800) {
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_displayformats` (\n                    `id` INT(10) unsigned NOT NULL auto_increment,\n                    `fid` INT(10) UNSIGNED NOT NULL default '0',\n                    `visible` TINYINT(2) UNSIGNED NOT NULL default '1',\n                    `relatedview` TINYINT(3) NOT NULL default '-1',\n                    `showgroup` TINYINT(2) UNSIGNED NOT NULL default '1',\n                    `defaultmode` VARCHAR(50) NOT NULL default '',\n                    `defaulthook` VARCHAR(50) NOT NULL default '',\n                    `sortkey` VARCHAR(50) NOT NULL default '',\n                    `sortorder` VARCHAR(50) NOT NULL default '',\n                    PRIMARY KEY  (`id`)\n                    ) ENGINE=MyISAM COMMENT='Setting of the display formats'");
        // Default format
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (0,0,'letter','ALL','CREATION','asc',1,1)");
        // Continuous format
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (1,1,'date','ALL','CREATION','asc',0,1)");
        // Full w/author View
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (2,2,'letter','ALL','CREATION','asc',1,1)");
        // Encyclopedia
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (3,3,'letter','ALL','CREATION','asc',1,1)");
        // FAQ View
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (4,4,'date','ALL','CREATION','asc',0,1)");
        // Full w/o author View
        execute_sql(" INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (5,5,'letter','ALL','CREATION','asc',1,1)");
        // Entry list
        execute_sql("INSERT INTO {$CFG->prefix}glossary_displayformats \n                      (fid, relatedview, defaultmode, defaulthook, sortkey, sortorder, showgroup, visible)\n                      VALUES (6,0,'letter','ALL','CREATION','asc',1,1)");
    }
    if ($oldversion < 2003112100) {
        table_column("glossary", "", "assessed", "integer", "10", "unsigned", "0");
        table_column("glossary", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("glossary", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
        execute_sql("CREATE TABLE {$CFG->prefix}glossary_ratings (\n                      `id` int(10) unsigned NOT NULL auto_increment,\n                      `userid` int(10) unsigned NOT NULL default '0',\n                      `entryid` int(10) unsigned NOT NULL default '0',\n                      `time` int(10) unsigned NOT NULL default '0',\n                      `rating` tinyint(4) NOT NULL default '0',\n                      PRIMARY KEY  (`id`)\n                    ) COMMENT='Contains user ratings for entries'");
    }
    if ($oldversion < 2003112101) {
        table_column("glossary", "", "scale", "integer", "10", "", "0", "", "assesstimefinish");
    }
    if ($oldversion < 2003112701) {
        delete_records("glossary_alias", "entryid", 0);
    }
    if ($oldversion < 2004022200) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004050900) {
        table_column("glossary", "", "rsstype", "tinyint", "2", "unsigned", "0", "", "entbypage");
        table_column("glossary", "", "rssarticles", "tinyint", "2", "unsigned", "0", "", "rsstype");
        set_config("glossary_enablerssfeeds", 0);
    }
    if ($oldversion < 2004051400) {
        print_simple_box("This update might take several seconds.<p>The more glossaries, entries and aliases you have created, the more it will take so please be patient.", "center", "50%", '', "20", "noticebox");
        if ($entries = get_records("glossary_entries", '', '', '', 'id,concept')) {
            foreach ($entries as $entry) {
                set_field("glossary_entries", "concept", addslashes(trim($entry->concept)), "id", $entry->id);
            }
        }
        if ($aliases = get_records("glossary_alias")) {
            foreach ($aliases as $alias) {
                set_field("glossary_alias", "alias", addslashes(trim($alias->alias)), "id", $alias->id);
            }
        }
    }
    if ($oldversion < 2004072300) {
        table_column("glossary_alias", "alias", "alias", "VARCHAR", "255", "", "", "NOT NULL");
    }
    if ($oldversion < 2004072400) {
        //Create new table glossary_formats to store format info
        execute_sql("CREATE TABLE `{$CFG->prefix}glossary_formats` (\n                       `id` INT(10) unsigned NOT NULL auto_increment,\n                       `name` VARCHAR(50) NOT NULL,\n                       `popupformatname` VARCHAR(50) NOT NULL, \n                       `visible` TINYINT(2) UNSIGNED NOT NULL default '1',\n                       `showgroup` TINYINT(2) UNSIGNED NOT NULL default '1',\n                       `defaultmode` VARCHAR(50) NOT NULL default '',\n                       `defaulthook` VARCHAR(50) NOT NULL default '',\n                       `sortkey` VARCHAR(50) NOT NULL default '',\n                       `sortorder` VARCHAR(50) NOT NULL default '',\n                   PRIMARY KEY  (`id`)                    \n                   ) ENGINE=MyISAM COMMENT='Setting of the display formats'");
        //Define current 0-6 format names
        $formatnames = array('dictionary', 'continuous', 'fullwithauthor', 'encyclopedia', 'faq', 'fullwithoutauthor', 'entrylist');
        //Fill the new table from the old one (only 'valid', 0-6, formats)
        if ($formats = get_records('glossary_displayformats')) {
            foreach ($formats as $format) {
                //Format names
                if ($format->fid >= 0 && $format->fid <= 6) {
                    $format->name = $formatnames[$format->fid];
                }
                //Format popupformatname
                $format->popupformatname = 'dictionary';
                //Default format
                if ($format->relatedview >= 0 && $format->relatedview <= 6) {
                    $format->popupformatname = $formatnames[$format->relatedview];
                }
                //Insert the new record
                //Only if $format->name is set (ie. formats 0-6)
                if ($format->name) {
                    insert_record('glossary_formats', $format);
                }
            }
        }
        //Drop the old formats table
        execute_sql("DROP TABLE `{$CFG->prefix}glossary_displayformats`");
        //Modify the glossary->displayformat field
        table_column('glossary', 'displayformat', 'displayformat', 'VARCHAR', '50', '', 'dictionary', 'NOT NULL');
        //Update glossary->displayformat field
        if ($glossaries = get_records('glossary')) {
            foreach ($glossaries as $glossary) {
                $displayformat = 'dictionary';
                //Default format
                if ($glossary->displayformat >= 0 && $glossary->displayformat <= 6) {
                    $displayformat = $formatnames[$glossary->displayformat];
                }
                set_field('glossary', 'displayformat', $displayformat, 'id', $glossary->id);
            }
        }
    }
    if ($oldversion < 2004080800) {
        table_column("glossary", "", "editalways", "tinyint", "2", "unsigned", "0", "", "entbypage");
    }
    //Activate editalways in old secondary glossaries (old behaviour)
    if ($oldversion < 2004080900) {
        set_field('glossary', 'editalways', '1', 'mainglossary', '0');
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}glossary DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_alias DROP INDEX entryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_categories DROP INDEX glossaryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_comments DROP INDEX entryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_comments DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_entries DROP INDEX glossaryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_entries DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_entries DROP INDEX concept;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_entries_categories DROP INDEX entryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_entries_categories DROP INDEX categoryid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_ratings DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}glossary_ratings DROP INDEX entryid;", false);
        modify_database('', 'ALTER TABLE prefix_glossary ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_glossary_alias ADD INDEX entryid (entryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_categories ADD INDEX glossaryid (glossaryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_comments ADD INDEX entryid (entryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_comments ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_glossary_entries ADD INDEX glossaryid (glossaryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_entries ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_glossary_entries ADD INDEX concept (concept);');
        modify_database('', 'ALTER TABLE prefix_glossary_entries_categories ADD INDEX entryid (entryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_entries_categories ADD INDEX categoryid (categoryid);');
        modify_database('', 'ALTER TABLE prefix_glossary_ratings ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_glossary_ratings ADD INDEX entryid (entryid);');
    }
    //Delete orphaned categories (bug 2140)
    if ($oldversion < 2005011100) {
        $categories = get_records('glossary_categories', '', '', '', 'id, glossaryid');
        if ($categories) {
            foreach ($categories as $category) {
                $glossary = get_record('glossary', 'id', "{$category->glossaryid}");
                if (!$glossary) {
                    delete_records('glossary_categories', 'id', "{$category->id}");
                }
            }
        }
    }
    //Allowprintview flag
    if ($oldversion < 2005011200) {
        table_column('glossary', '', 'allowprintview', 'tinyint', '2', 'unsigned', '1', '', 'allowcomments');
        $glossaries = get_records('glossary', '', '', '', 'id, name');
        if ($glossaries) {
            foreach ($glossaries as $glossary) {
                set_field('glossary', 'allowprintview', '1', 'id', "{$glossary->id}");
            }
        }
    }
    if ($oldversion < 2005031001) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('glossary', 'view entry', 'glossary_entries', 'concept');");
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        // update glossary_entries->definition
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = ";
        $wtm->update('glossary_entries', 'definition', 'format');
        // update glossary_comments->text
        $sql = "select course from {$CFG->prefix}glossary,{$CFG->prefix}glossary_entries,{$CFG->prefix}glossary_comments ";
        $sql .= "where {$CFG->prefix}glossary.id = {$CFG->prefix}glossary_entries.glossaryid ";
        $sql .= "and {$CFG->prefix}glossary_entries.id = {$CFG->prefix}glossary_comments.entryid ";
        $sql .= "and {$CFG->prefix}glossary_comments.id = ";
        $wtm->update('glossary_comments', 'text', 'format', $sql);
    }
    if ($oldversion < 2006082600) {
        $sql1 = "UPDATE {$CFG->prefix}glossary_entries SET definition = REPLACE(definition, '" . TRUSTTEXT . "', '');";
        $sql2 = "UPDATE {$CFG->prefix}glossary_comments SET comment = REPLACE(comment, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('glossary_entries', "definition {$likecond}")) {
                break;
            }
            execute_sql($sql1);
        }
        while (true) {
            if (!count_records_select('glossary_comments', "comment {$likecond}")) {
                break;
            }
            execute_sql($sql2);
        }
    }
    if ($oldversion < 2006090400) {
        table_column('glossary_comments', 'comment', 'entrycomment', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Exemplo n.º 15
0
function forum_restore_wiki2markdown($restore)
{
    global $CFG, $DB;
    $status = true;
    //Convert forum_posts->message
    if ($records = $DB->get_records_sql("SELECT p.id, p.message, p.messageformat\n                                               FROM {forum_posts} p,\n                                                    {forum_discussions} d,\n                                                    {forum} f,\n                                                    {backup_ids} b\n                                              WHERE d.id = p.discussion AND\n                                                    f.id = d.forum AND\n                                                    f.course = ? AND\n                                                    p.messageformat = " . FORMAT_WIKI . " AND\n                                                    b.backup_code = ? AND\n                                                    b.table_name = 'forum_posts' AND\n                                                    b.new_id = p.id", array($restore->course_id, $restore->backup_unique_code))) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->message = restore_decode_wiki_content($record->message, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->message = $wtm->convert($record->message, $restore->course_id);
            $record->messageformat = FORMAT_MARKDOWN;
            $status = $DB->update_record('forum_posts', $record);
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 16
0
function workshop_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2003050400) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop` CHANGE `graded` `agreeassessments` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL");
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop` CHANGE `showgrades` `hidegrades` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL");
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop_assessments` ADD `timeagreed` INT(10) UNSIGNED DEFAULT '0' NOT NULL AFTER `timecreated`");
        execute_sql("\n        CREATE TABLE `{$CFG->prefix}workshop_comments` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          # workshopid not necessary just makes deleting instance easier\n          `workshopid` int(10) unsigned NOT NULL default '0',\n          `assessmentid` int(10) unsigned NOT NULL default '0',\n          `userid` int(10) unsigned NOT NULL default '0',\n          `timecreated` int(10) unsigned NOT NULL default '0',\n          `mailed` tinyint(2) unsigned NOT NULL default '0',\n          `comments` text NOT NULL,\n          PRIMARY KEY  (`id`)\n        ) COMMENT='Defines comments'\n        ");
    }
    if ($oldversion < 2003051400) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop` ADD `showleaguetable` TINYINT(3) UNSIGNED NOT NULL  DEFAULT '0' AFTER `gradingweight`");
        execute_sql("\n        CREATE TABLE `{$CFG->prefix}workshop_rubrics` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `workshopid` int(10) unsigned NOT NULL default '0',\n          `elementid` int(10) unsigned NOT NULL default '0',\n          `rubricno` tinyint(3) unsigned NOT NULL default '0',\n          `description` text NOT NULL,\n          PRIMARY KEY  (`id`)\n        ) COMMENT='Info about the rubrics marking scheme'\n        ");
    }
    if ($oldversion < 2003082200) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop_rubrics` CHANGE `elementid` `elementno` INT(10) UNSIGNED NOT NULL DEFAULT '0'");
    }
    if ($oldversion < 2003092500) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop` ADD `overallocation` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0' AFTER `nsassessments`");
    }
    if ($oldversion < 2003100200) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop_assessments` ADD `resubmission` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0' AFTER `mailed`");
    }
    if ($oldversion < 2003100800) {
        // tidy up log_display entries
        execute_sql("DELETE FROM `{$CFG->prefix}log_display` WHERE `module` = 'workshop'");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES('workshop', 'assessments', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'close', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'display', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'resubmit', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'set up', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'submissions', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'view', 'workshop', 'name')");
        execute_sql("INSERT INTO `{$CFG->prefix}log_display` VALUES ('workshop', 'update', 'workshop', 'name')");
    }
    if ($oldversion < 2003113000) {
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` ADD `teacherloading` tinyint(3) unsigned\n                NOT NULL default '5'");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` ADD `assessmentstodrop` tinyint(3) unsigned\n                NOT NULL default '0'");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_assessments` ADD `donotuse` tinyint(3) unsigned\n                NOT NULL default '0' AFTER `resubmission`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_grades` ADD INDEX (`assessmentid`)");
    }
    if ($oldversion < 2004052100) {
        include_once "{$CFG->dirroot}/mod/workshop/lib.php";
        workshop_refresh_events();
    }
    if ($oldversion < 2004081100) {
        table_column("workshop", "", "gradinggrade", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "grade");
        table_column("workshop", "", "assessmentcomps", "INTEGER", "4", "UNSIGNED", "2", "NOT NULL", "ntassessments");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `gradingweight`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `mergegrades`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `peerweight`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `includeteachersgrade`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `biasweight`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `reliabilityweight`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `teacherloading`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop` DROP COLUMN `assessmentstodrop`");
    }
    if ($oldversion < 2004092400) {
        table_column("workshop", "", "nattachments", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "nelements");
        table_column("workshop_submissions", "", "description", "TEXT", "", "", "", "", "mailed");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_submissions` ADD INDEX (`userid`)");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_assessments` ADD INDEX (`submissionid`)");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_assessments` ADD INDEX (`userid`)");
    }
    if ($oldversion < 2004092700) {
        table_column("workshop", "", "wtype", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "description");
        table_column("workshop", "", "usepassword", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        table_column("workshop", "", "password", "VARCHAR", "32", "", "", "NOT NULL");
        table_column("workshop_submissions", "", "late", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        // update wkey value
        if ($workshops = get_records("workshop")) {
            foreach ($workshops as $workshop) {
                $wtype = 0;
                // 3 phases, no grading grades
                if ($workshop->includeself or $workshop->ntassessments) {
                    $wtype = 1;
                }
                // 3 phases with grading grades
                if ($workshop->nsassessments) {
                    $wtype = 2;
                }
                // 5 phases with grading grades
                set_field("workshop", "wtype", $wtype, "id", $workshop->id);
            }
        }
    }
    if ($oldversion < 2004102800) {
        table_column("workshop", "", "releasegrades", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "deadline");
        execute_sql("\n        CREATE TABLE `{$CFG->prefix}workshop_stockcomments` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `workshopid` int(10) unsigned NOT NULL default '0',\n          `elementno` int(10) unsigned NOT NULL default '0',\n          `comments` text NOT NULL,\n          PRIMARY KEY  (`id`)\n        ) COMMENT='Defines stockcomments, the teacher comment bank'\n        ");
    }
    if ($oldversion < 2004111000) {
        table_column("workshop_elements", "", "stddev", "FLOAT", "", "", "0", "NOT NULL");
        table_column("workshop_elements", "", "totalassessments", "INTEGER", "10", "", "0", "NOT NULL");
        execute_sql(" ALTER TABLE `{$CFG->prefix}workshop_elements` CHANGE `weight` `weight` INT(4) UNSIGNED NOT NULL DEFAULT '11'");
        table_column("workshop_submissions", "", "nassessments", "INTEGER", "10", "", "0", "NOT NULL");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_submissions` DROP COLUMN `teachergrade`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_submissions` DROP COLUMN `peergrade`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_submissions` DROP COLUMN `biasgrade`");
        execute_sql("ALTER TABLE `{$CFG->prefix}workshop_submissions` DROP COLUMN `reliabilitygrade`");
    }
    if ($oldversion < 2004111200) {
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_assessments DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_assessments DROP INDEX workshopid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_assessments DROP INDEX submissionid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_assessments DROP INDEX mailed;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_comments DROP INDEX workshopid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_comments DROP INDEX assessmentid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_comments DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_comments DROP INDEX mailed;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_elements DROP INDEX workshopid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_grades DROP INDEX workshopid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_grades DROP INDEX assessmentid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP INDEX workshopid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP INDEX mailed;", false);
        modify_database('', 'ALTER TABLE prefix_workshop ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_workshop_assessments ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_workshop_assessments ADD INDEX workshopid (workshopid);');
        modify_database('', 'ALTER TABLE prefix_workshop_assessments ADD INDEX submissionid (submissionid);');
        modify_database('', 'ALTER TABLE prefix_workshop_assessments ADD INDEX mailed (mailed);');
        modify_database('', 'ALTER TABLE prefix_workshop_comments ADD INDEX workshopid (workshopid);');
        modify_database('', 'ALTER TABLE prefix_workshop_comments ADD INDEX assessmentid (assessmentid);');
        modify_database('', 'ALTER TABLE prefix_workshop_comments ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_workshop_comments ADD INDEX mailed (mailed);');
        modify_database('', 'ALTER TABLE prefix_workshop_elements ADD INDEX workshopid (workshopid);');
        modify_database('', 'ALTER TABLE prefix_workshop_grades ADD INDEX workshopid (workshopid);');
        modify_database('', 'ALTER TABLE prefix_workshop_grades ADD INDEX assessmentid (assessmentid);');
        modify_database('', 'ALTER TABLE prefix_workshop_submissions ADD INDEX workshopid (workshopid);');
        modify_database('', 'ALTER TABLE prefix_workshop_submissions ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_workshop_submissions ADD INDEX mailed (mailed);');
    }
    if ($oldversion < 2004120402) {
        table_column('workshop', '', 'submissionstart', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'maxbytes');
        table_column('workshop', '', 'assessmentstart', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'submissionstart');
        table_column('workshop', 'deadline', 'submissionend', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL');
        table_column('workshop', '', 'assessmentend', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'submissionend');
        $workshops = get_records('workshop');
        if (!empty($workshops)) {
            foreach ($workshops as $workshop) {
                $early = time() < $workshop->submissionend ? 0 : $workshop->submissionend;
                $late = time() > $workshop->submissionend ? 0 : $workshop->submissionend;
                set_field('workshop', 'submissionstart', $workshop->phase > 1 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'assessmentstart', $workshop->phase > 2 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'submissionend', $workshop->phase > 3 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'assessmentend', $workshop->phase > 4 ? $early : $late, 'id', $workshop->id);
            }
        }
        execute_sql('ALTER TABLE  ' . $CFG->prefix . 'workshop DROP COLUMN phase');
        execute_sql("UPDATE {$CFG->prefix}event SET eventtype = 'submissionend' WHERE eventtype = 'deadline' AND modulename = 'workshop'", false);
    }
    if ($oldversion < 2004120900) {
        table_column('workshop_assessments', '', 'teachergraded', 'INTEGER', '4', 'UNSIGNED', '0', 'NOT NULL', 'gradinggrade');
    }
    if ($oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $wtm->update('workshop', 'description', 'format');
    }
    if ($oldversion < 2006090500) {
        $columns = $db->MetaColumns($CFG->prefix . 'workshop_assessments');
        $columns = array_change_key_case($columns, CASE_LOWER);
        if (!isset($columns['teachergraded'])) {
            table_column('workshop_assessments', '', 'teachergraded', 'INTEGER', '4', 'UNSIGNED', '0', 'NOT NULL', 'gradinggrade');
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Exemplo n.º 17
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;
}
Exemplo n.º 18
0
function workshop_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2003050400) {
        table_column("workshop", "graded", "agreeassessments", "INT", "2", "", "0", "NOT NULL");
        table_column("workshop", "showgrades", "hidegrades", "INT", "2", "", "0", "NOT NULL");
        table_column("workshop_assessments", "", "timeagreed", "INT", "8", "UNSIGNED", "0", "NOT NULL");
        execute_sql("\n            CREATE TABLE {$CFG->prefix}workshop_comments (\n            id SERIAL8 PRIMARY KEY  ,\n            workshopid int8 NOT NULL default '0',\n            assessmentid int8  NOT NULL default '0',\n            userid int8 NOT NULL default '0',\n            timecreated int8  NOT NULL default '0',\n            mailed int2  NOT NULL default '0',\n            comments text NOT NULL\n        )\n        ");
    }
    if ($oldversion < 2003051400) {
        table_column("workshop", "", "showleaguetable", "INTEGER", "4", "unsigned", "0", "not null", "gradingweight");
        execute_sql("\n        CREATE TABLE {$CFG->prefix}workshop_rubrics (\n          id SERIAL8 PRIMARY KEY,\n          workshopid int8 NOT NULL default '0',\n          elementid int8 NOT NULL default '0',\n          rubricno int4  NOT NULL default '0',\n          description text NOT NULL,\n        )\n        ");
    }
    if ($oldversion < 2003082200) {
        table_column("workshop_rubrics", "elementid", "elementno", "INTEGER", "10", "unsigned", "0", "not null", "id");
    }
    if ($oldversion < 2003092500) {
        table_column("workshop", "", "overallocation", "INTEGER", "4", "unsigned", "0", "not null", "nsassesments");
    }
    if ($oldversion < 2003100200) {
        table_column("workshop_assesments", "", "resubmission", "INTEGER", "4", "unsigned", "0", "not null", "mailed");
    }
    if ($oldversion < 2003100800) {
        // tidy up log_display entries
        execute_sql("DELETE FROM {$CFG->prefix}log_display WHERE module = 'workshop'");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES('workshop', 'assessments', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'close', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'display', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'resubmit', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'set up', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'submissions', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'view', 'workshop', 'name')");
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('workshop', 'update', 'workshop', 'name')");
    }
    if ($oldversion < 2003113000) {
        table_column("workshop", "", "teacherloading", "INTEGER", "4", "unsigned", "5", "NOT NULL", "mailed");
        table_column("workshop", "", "assessmentstodrop", "INTEGER", "4", "unsigned", "0", "NOT NULL", "");
        table_column("workshop_assessments", "", "donotuse", "INTEGER", "4", "unsigned", "0", "NOT NULL", "resubmission");
        execute_sql("CREATE INDEX {$CFG->prefix}workshop_grades_assesmentid_idx ON {$CFG->prefix}workshop_grades (assessmentid)");
    }
    if ($oldversion < 2004052100) {
        include_once "{$CFG->dirroot}/mod/workshop/lib.php";
        workshop_refresh_events();
    }
    if ($oldversion < 2004081100) {
        table_column("workshop", "", "gradinggrade", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "grade");
        table_column("workshop", "", "assessmentcomps", "INTEGER", "4", "UNSIGNED", "2", "NOT NULL", "ntassessments");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN gradingweight");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN mergegrades");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN peerweight");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN includeteachersgrade");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN biasweight");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN reliabilityweight");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN teacherloading", false);
        //silent
        execute_sql("ALTER TABLE {$CFG->prefix}workshop DROP COLUMN assessmentstodrop", false);
        //silent
    }
    if ($oldversion < 2004092400) {
        table_column("workshop", "", "nattachments", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "nelements");
        table_column("workshop_submissions", "", "description", "TEXT", "", "", "", "", "mailed");
        // these need to be dropped first in case we're upgrading from 1.4.3 and they already exist
        execute_sql("DROP INDEX {$CFG->prefix}workshop_submissions_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_submissionid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_userid_idx;", false);
        execute_sql("CREATE INDEX {$CFG->prefix}workshop_submissions_userid_idx ON {$CFG->prefix}workshop_submissions (userid)");
        execute_sql("CREATE INDEX {$CFG->prefix}workshop_assessments_submissionid_idx ON {$CFG->prefix}workshop_assessments (submissionid)");
        execute_sql("CREATE INDEX {$CFG->prefix}workshop_assessments_userid_idx ON {$CFG->prefix}workshop_assessments (userid)");
    }
    if ($oldversion < 2004092700) {
        table_column("workshop", "", "wtype", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "description");
        table_column("workshop", "", "usepassword", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        table_column("workshop", "", "password", "VARCHAR", "32", "", "", "NOT NULL");
        table_column("workshop_submissions", "", "late", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL");
        // update wkey value
        if ($workshops = get_records("workshop")) {
            foreach ($workshops as $workshop) {
                $wtype = 0;
                // 3 phases, no grading grades
                if ($workshop->includeself or $workshop->ntassessments) {
                    $wtype = 1;
                }
                // 3 phases with grading grades
                if ($workshop->nsassessments) {
                    $wtype = 2;
                }
                // 5 phases with grading grades
                set_field("workshop", "wtype", $wtype, "id", $workshop->id);
            }
        }
    }
    if ($oldversion < 2004102800) {
        table_column("workshop", "", "releasegrades", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "deadline");
        execute_sql("\n        CREATE TABLE {$CFG->prefix}workshop_stockcomments (\n          id SERIAL PRIMARY KEY,\n          workshopid INT8 NOT NULL default '0',\n          elementno INT8 NOT NULL default '0',\n          comments text NOT NULL\n        )\n        ");
    }
    if ($oldversion < 2004111000) {
        table_column("workshop_elements", "", "stddev", "FLOAT", "", "", "0", "NOT NULL");
        table_column("workshop_elements", "", "totalassessments", "INTEGER", "10", "", "0", "NOT NULL");
        table_column("workshop_elements", "weight", "weight", "INTEGER", "4", "UNSIGNED", "11", "NOT NULL");
        table_column("workshop_submissions", "", "nassessments", "INTEGER", "10", "", "0", "NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP COLUMN teachergrade");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP COLUMN peergrade");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP COLUMN biasgrade");
        execute_sql("ALTER TABLE {$CFG->prefix}workshop_submissions DROP COLUMN reliabilitygrade");
    }
    if ($oldversion < 2004111200) {
        execute_sql("DROP INDEX {$CFG->prefix}workshop_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_workshopid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_submissionid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_assessments_mailed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_comments_workshopid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_comments_assessmentid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_comments_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_comments_mailed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_elements_workshopid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_grades_workshopid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_grades_assessmentid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_submissions_workshopid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_submissions_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}workshop_submissions_mailed_idx;", false);
        modify_database('', 'CREATE INDEX prefix_workshop_course_idx ON prefix_workshop (course);');
        modify_database('', 'CREATE INDEX prefix_workshop_assessments_workshopid_idx ON prefix_workshop_assessments (workshopid);');
        modify_database('', 'CREATE INDEX prefix_workshop_assessments_submissionid_idx ON prefix_workshop_assessments (submissionid);');
        modify_database('', 'CREATE INDEX prefix_workshop_assessments_userid_idx ON prefix_workshop_assessments (userid);');
        modify_database('', 'CREATE INDEX prefix_workshop_assessments_mailed_idx ON prefix_workshop_assessments (mailed);');
        modify_database('', 'CREATE INDEX prefix_workshop_comments_workshopid_idx ON prefix_workshop_comments (workshopid);');
        modify_database('', 'CREATE INDEX prefix_workshop_comments_assessmentid_idx ON prefix_workshop_comments (assessmentid);');
        modify_database('', 'CREATE INDEX prefix_workshop_comments_userid_idx ON prefix_workshop_comments (userid);');
        modify_database('', 'CREATE INDEX prefix_workshop_comments_mailed_idx ON prefix_workshop_comments (mailed);');
        modify_database('', 'CREATE INDEX prefix_workshop_elements_workshopid_idx ON prefix_workshop_elements (workshopid);');
        modify_database('', 'CREATE INDEX prefix_workshop_grades_workshopid_idx ON prefix_workshop_grades (workshopid);');
        modify_database('', 'CREATE INDEX prefix_workshop_grades_assessmentid_idx ON prefix_workshop_grades (assessmentid);');
        modify_database('', 'CREATE INDEX prefix_workshop_submissions_workshopid_idx ON prefix_workshop_submissions (workshopid);');
        modify_database('', 'CREATE INDEX prefix_workshop_submissions_userid_idx ON prefix_workshop_submissions (userid);');
        modify_database('', 'CREATE INDEX prefix_workshop_submissions_mailed_idx ON prefix_workshop_submissions (mailed);');
    }
    if ($oldversion < 2004120402) {
        table_column('workshop', '', 'submissionstart', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'maxbytes');
        table_column('workshop', '', 'assessmentstart', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'submissionstart');
        table_column('workshop', 'deadline', 'submissionend', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL');
        table_column('workshop', '', 'assessmentend', 'INTEGER', '10', 'UNSIGNED', '0', 'NOT NULL', 'submissionend');
        $workshops = get_records('workshop');
        if (!empty($workshops)) {
            foreach ($workshops as $workshop) {
                $early = time() < $workshop->submissionend ? 0 : $workshop->submissionend;
                $late = time() > $workshop->submissionend ? 0 : $workshop->submissionend;
                set_field('workshop', 'submissionstart', $workshop->phase > 1 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'assessmentstart', $workshop->phase > 2 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'submissionend', $workshop->phase > 3 ? $early : $late, 'id', $workshop->id);
                set_field('workshop', 'assessmentend', $workshop->phase > 4 ? $early : $late, 'id', $workshop->id);
            }
        }
        execute_sql('ALTER TABLE  ' . $CFG->prefix . 'workshop DROP COLUMN phase');
        execute_sql("UPDATE {$CFG->prefix}event SET eventtype = 'submissionend' WHERE eventtype = 'deadline' AND modulename = 'workshop'", false);
    }
    if ($oldversion < 2004120900) {
        table_column('workshop_assessments', '', 'teachergraded', 'INTEGER', '4', 'UNSIGNED', '0', 'NOT NULL', 'gradinggrade');
    }
    if ($oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $wtm->update('workshop', 'description', 'format');
    }
    if ($oldversion < 2005041201) {
        // Mass cleanup of bad upgrade scripts
        // Some of those steps might fail, it is normal.
        table_column('workshop', 'assessmentend', 'assessmentend', 'integer', '16');
        table_column('workshop', 'assessmentstart', 'assessmentstart', 'integer', '16');
        table_column('workshop', '', 'phase', 'integer', '4');
        table_column('workshop', '', 'showleaguetable', 'integer', '8');
        table_column('workshop', 'releasegrades', 'releasegrades', 'integer', '16');
        table_column('workshop', 'submissionend', 'submissionend', 'integer', '16');
        table_column('workshop', 'submissionstart', 'submissionstart', 'integer', '16');
        modify_database('', 'ALTER TABLE prefix_workshop ALTER teacherweight SET DEFAULT 1');
        modify_database('', 'ALTER TABLE prefix_workshop DROP timeagreed');
        modify_database('', 'ALTER TABLE prefix_workshop RENAME inalgrade TO finalgrade');
        table_column('workshop_assessments', '', 'donotuse', 'integer', '8');
        table_column('workshop_assessments', '', 'timeagreed', 'integer', '16');
        modify_database('', 'ALTER TABLE prefix_workshop_assessments DROP teachergraded');
        modify_database('', 'ALTER TABLE prefix_workshop_elements RENAME totalrassesments TO totalassessments');
        modify_database('', 'ALTER TABLE prefix_workshop_submissions ALTER description DROP DEFAULT');
        table_column('workshop_submissions', 'nassessments', 'nassessments', 'integer', '16');
        table_column('workshop_elements', 'totalassessments', 'totalassessments', 'integer', '16');
        execute_sql("\n        CREATE TABLE {$CFG->prefix}workshop_rubrics (\n          id SERIAL PRIMARY KEY,\n          workshopid int8 NOT NULL default '0',\n          elementno int8  NOT NULL default '0',\n          rubricno int4  NOT NULL default '0',\n          description text NOT NULL\n        )\n        ");
    }
    if ($oldversion < 2006090500) {
        $columns = $db->MetaColumns($CFG->prefix . 'workshop_assessments');
        $columns = array_change_key_case($columns, CASE_LOWER);
        if (!isset($columns['teachergraded'])) {
            table_column('workshop_assessments', '', 'teachergraded', 'INTEGER', '4', 'UNSIGNED', '0', 'NOT NULL', 'gradinggrade');
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Exemplo n.º 19
0
function assignment_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert assignment->description
    if ($records = get_records_sql("SELECT a.id, a.description, a.format\n                                         FROM {$CFG->prefix}assignment a,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE a.course = {$restore->course_id} AND\n                                               a.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'assignment' AND\n                                               b.new_id = a.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->description = restore_decode_wiki_content($record->description, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->description = $wtm->convert($record->description, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('assignment', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 20
0
function quiz_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    $success = true;
    include_once "{$CFG->dirroot}/mod/quiz/locallib.php";
    if ($success && $oldversion < 2003010100) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD review integer 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 SERIAL PRIMARY KEY,\n                                  question integer NOT NULL default '0',\n                                  choose integer NOT NULL default '4'\n                              );");
    }
    if ($success && $oldversion < 2003030303) {
        $success = $success && table_column("quiz_questions", "", "defaultgrade", "INTEGER", "6", "UNSIGNED", "1", "NOT NULL", "image");
    }
    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_sub (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 questiontext text NOT NULL default '',\n                                 answertext varchar(255) NOT NULL default ''\n                              );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_sub_question_idx ON prefix_quiz_match_sub (question);");
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_multichoice (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 layout integer NOT NULL default '0',\n                                 answers varchar(255) NOT NULL default '',\n                                 single integer NOT NULL default '0'\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multichoice_question_idx ON prefix_quiz_multichoice (question);");
    }
    if ($success && $oldversion < 2003040901) {
        $success = $success && table_column("quiz", "", "shufflequestions", "INTEGER", "5", "UNSIGNED", "0", "NOT NULL", "review");
        $success = $success && table_column("quiz", "", "shuffleanswers", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "shufflequestions");
    }
    if ($success && $oldversion < 2003042702) {
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_match (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 subquestions varchar(255) NOT NULL default ''\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_question_idx ON prefix_quiz_match (question);");
    }
    if ($success && $oldversion < 2003071001) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answer integer NOT NULL default '0',\n                               min varchar(255) NOT NULL default '',\n                               max varchar(255) NOT NULL default ''\n                               ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_numerical_answer_idx ON prefix_quiz_numerical (answer);");
    }
    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 < 2003082300) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_multianswers (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answers varchar(255) NOT NULL default '',\n                               positionkey varchar(255) NOT NULL default '',\n                               answertype integer NOT NULL default '0',\n                               norm integer NOT NULL default '1'\n                              ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multianswers_question_idx ON prefix_quiz_multianswers (question);");
        $success = $success && table_column("quiz", "", "attemptonlast", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "attempts");
        $success = $success && table_column("quiz_questions", "", "stamp", "varchar", "255", "", "qtype");
    }
    if ($success && $oldversion < 2003082301) {
        $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) {
        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 && table_column("quiz", "", "timelimit", "integer", "", "", "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:
        $success = $success && modify_database("", "BEGIN;");
        // One table for handling units for numerical questions
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical_units (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               multiplier decimal(40,20) NOT NULL default '1.00000000000000000000',\n                               unit varchar(50) NOT NULL default ''\n                );");
        // 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 SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               userid INT8  NOT NULL default '0',\n                               datasetnumber INT8  NOT NULL default '0',\n                               CONSTRAINT prefix_quiz_attemptonlast_datasets_category_userid UNIQUE (category,userid)\n            ) ;");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_definitions (\n                               id SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               name varchar(255) NOT NULL default '',\n                               type INT8 NOT NULL default '0',\n                               options varchar(255) NOT NULL default '',\n                               itemcount INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_items (\n                               id SERIAL8 PRIMARY KEY,\n                               definition INT8  NOT NULL default '0',\n                               number INT8  NOT NULL default '0',\n                               value varchar(255) NOT NULL default ''\n                             ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_dataset_items_definition_idx ON prefix_quiz_dataset_items (definition);");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_question_datasets (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               datasetdefinition INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx ON prefix_quiz_question_datasets (question,datasetdefinition);");
        // One table for new question type calculated
        //  - the first dataset dependent question type
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_calculated (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               answer INT8  NOT NULL default '0',\n                               tolerance varchar(20) NOT NULL default '0.0',\n                               tolerancetype INT8 NOT NULL default '1',\n                               correctanswerlength INT8 NOT NULL default '2'\n                ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_calculated_question_idx ON  prefix_quiz_calculated (question);");
        $success = $success && modify_database("", "COMMIT;");
    }
    if ($success && $oldversion < 2004111400) {
        $success = $success && table_column("quiz_responses", "answer", "answer", "text", "", "", "", "not null");
    }
    if ($success && $oldversion < 2004111700) {
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_answers_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_calculated_answer_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_categories_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_dataset_definitions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_units_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_questions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_randomsamatch_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_attempt_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_question_idx;", false);
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_course_idx ON prefix_quiz (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_answers_question_idx ON prefix_quiz_answers (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_quiz_idx ON prefix_quiz_attempts (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_userid_idx ON prefix_quiz_attempts (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_calculated_answer_idx ON prefix_quiz_calculated (answer);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_categories_course_idx ON prefix_quiz_categories (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_dataset_definitions_category_idx ON prefix_quiz_dataset_definitions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_quiz_idx ON prefix_quiz_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_userid_idx ON prefix_quiz_grades (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_question_idx ON prefix_quiz_numerical (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_units_question_idx ON prefix_quiz_numerical_units (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_quiz_idx ON prefix_quiz_question_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_question_idx ON prefix_quiz_question_grades (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_questions_category_idx ON prefix_quiz_questions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_randomsamatch_question_idx ON prefix_quiz_randomsamatch (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_attempt_idx ON prefix_quiz_responses (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_question_idx ON prefix_quiz_responses (question);');
    }
    if ($success && $oldversion < 2004112300) {
        //try and clean up an old mistake - try and bring us up to what is in postgres7.sql today.
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2004120501) {
        $success = $success && table_column("quiz_calculated", "", "correctanswerformat", "integer", "10", "", "0", "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 SERIAL PRIMARY KEY,\n                              quiz integer NOT NULL default '0',\n                              oldquestion integer NOT NULL default '0',\n                              newquestion integer NOT NULL default '0',\n                              userid integer NOT NULL default '0',\n                              timestamp integer NOT NULL default '0');");
    }
    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 TO 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, {$CFG->prefix}quiz_questions ";
        $sql .= "where {$CFG->prefix}quiz_category.id = {$CFG->prefix}quiz_questions.category ";
        $sql .= "and {$CFG->prefix}quiz_questions.id = ";
        $wtm->update('quiz_questions', 'questiontext', 'questiontextformat', $sql);
    }
    if ($success && $oldversion < 2005041300) {
        $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) {
        begin_sql();
        // 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;
            foreach ($quizzes as $quiz) {
                // repaginate
                $quiz->questions = $quiz->questionsperpage ? quiz_repaginate($quiz->questions, $quiz->questionsperpage) : $quiz->questions;
                if ($quiz->questionsperpage) {
                    $quiz->questions = quiz_repaginate($quiz->questions, $quiz->questionsperpage);
                    $success = $success && set_field('quiz', 'questions', $quiz->questions, 'id', $quiz->id);
                }
                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 COLUMN feedback");
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz DROP COLUMN correctanswers");
        /// Renaming tables
        // rename the quiz_question_grades table to quiz_question_instances
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades RENAME TO prefix_quiz_question_instances;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades_id_seq RENAME TO prefix_quiz_question_instances_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_instances ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_question_instances_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_quiz_idx');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_quiz_idx ON prefix_quiz_question_instances (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_question_idx ON prefix_quiz_question_instances (question);');
        // rename the quiz_responses table quiz_states
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses RENAME TO prefix_quiz_states;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses_id_seq RENAME TO prefix_quiz_states_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_states ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_states_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_attempt_idx;');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_attempt_idx ON prefix_quiz_states (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_question_idx ON prefix_quiz_states (question);');
        /// 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 SERIAL PRIMARY KEY,\n                               attemptid integer NOT NULL default '0',\n                               questionid integer NOT NULL default '0',\n                               newest integer NOT NULL default '0',\n                               newgraded integer NOT NULL default '0',\n                               sumpenalty varchar(10) NOT NULL default '0.0'\n                             );");
        $success = $success && modify_database('CREATE UNIQUE INDEX prefix_quiz_newest_states_attempt_idx ON prefix_quiz_newest_states (attemptid,questionid);');
        /// 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')) {
            // 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', 'question');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_numerical SET tolerance = (max::text::real-min::text::real)/2");
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN min');
        // Replaced by tolerance
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN max');
        // Replaced by tolerance
        /// Tables for Remote Questions
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 type integer NOT NULL default '0',\n                                 source text NOT NULL,\n                                 format varchar(255) NOT NULL default '',\n                                 flags integer NOT NULL default '0',\n                                 maxscore integer NOT NULL default '1'\n                               );");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_rqp_question_idx ON prefix_quiz_rqp (question);");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_states (\n                                 id SERIAL PRIMARY KEY,\n                                 stateid integer NOT NULL default '0',\n                                 responses text NOT NULL,\n                                 persistent_data text NOT NULL,\n                                 template_vars text NOT NULL\n                               );");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_types (\n                                id SERIAL PRIMARY KEY,\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 integer NOT NULL default '0'\n                              );");
        $success = $success && modify_database('', "CREATE UNIQUE INDEX prefix_quiz_rqp_types_name_uk ON prefix_quiz_rqp_types (name);");
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    if ($success && $oldversion < 2005042900 && false) {
        // We don't want this to be executed any more!!!
        begin_sql();
        $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
        $success = $success && table_column('quiz_numerical', '', 'answers', 'varchar', '255', '', '', 'not null', 'answer');
        $success = $success && modify_database('', 'UPDATE prefix_quiz_numerical SET answers = answer');
        $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 . "';");
        // convert multianswer questions to the new model
        if ($multianswers = get_records_sql("SELECT m.id, q.category, q.id AS parent,\n                                        q.name, q.questiontextformat, m.norm AS\n                                        defaultgrade, m.answertype AS qtype,\n                                        q.version, q.hidden, m.answers,\n                                        m.positionkey\n                                        FROM {$CFG->prefix}quiz_questions q,\n                                             {$CFG->prefix}quiz_multianswers m\n                                        WHERE q.qtype = '" . MULTIANSWER . "'\n                                        AND   q.id = m.question\n                                        ORDER BY q.id ASC, m.positionkey ASC")) {
            $multianswers = array_values($multianswers);
            $n = count($multianswers);
            $parent = $multianswers[0]->parent;
            $sequence = array();
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            for ($i = 0; $i < $n; $i++) {
                $answers = $multianswers[$i]->answers;
                unset($multianswers[$i]->answers);
                $pos = $multianswers[$i]->positionkey;
                unset($multianswers[$i]->positionkey);
                // 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();
                $id = insert_record('quiz_questions', $multianswers[$i]);
                $success = $success && $id;
                $sequence[$pos] = $id;
                // update the answers table to point to these new questions
                $success = $success && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                // update the questiontype tables to point to these new questions
                if (SHORTANSWER == $multianswers[$i]->qtype) {
                    $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                } else {
                    if (NUMERICAL == $multianswers[$i]->qtype) {
                        if (strpos($answers, ',')) {
                            $numerical = get_records_list('quiz_numerical', 'answer', $answers);
                            // Get the biggest tolerance value
                            $tolerance = 0;
                            foreach ($numerical as $num) {
                                $tolerance = $tolerance < $num->tolerance ? $num->tolerance : $tolerance;
                            }
                            $success = $success && delete_records_select('quiz_numerical', "answer IN ({$answers})");
                            $new = new stdClass();
                            $new->question = $id;
                            $new->tolerance = $tolerance;
                            $new->answers = $answers;
                            $success = $success && insert_record('quiz_numerical', $new);
                            unset($numerical, $new, $tolerance);
                        } else {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}', answers = '{$answers}' WHERE answer IN ({$answers});");
                        }
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        }
                    }
                }
                if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                    $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();
                    }
                }
            }
            $db->debug = $olddebug;
        }
        // Remove redundant fields from quiz_multianswers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answers');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN positionkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answertype');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN norm');
        // Change numerical from answer to answers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN answer');
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    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');
    }
    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
            //       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;
                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]->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 && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                    // Update the questiontype tables to point to these new questions
                    if (SHORTANSWER == $multianswers[$i]->qtype) {
                        $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        } else {
                            if (NUMERICAL == $multianswers[$i]->qtype) {
                                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}' WHERE answer IN ({$answers});");
                            }
                        }
                    }
                    // 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 < 2005051402) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2005060300) {
        // 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);
                    }
                }
            }
        }
        //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 < 2005060301) {
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type RENAME TO ' . $CFG->prefix . 'quiz_rqp_types');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type_id_seq RENAME TO ' . $CFG->prefix . 'rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_rqp_types_id_seq\')');
        $success = $success && execute_sql('DROP INDEX ' . $CFG->prefix . 'quiz_rqp_type_name_uk');
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_rqp_types_name_uk ON ' . $CFG->prefix . 'quiz_rqp_types (name);');
    }
    if ($success && $oldversion < 2005060302) {
        // Mass cleanup of bad postgres upgrade scripts
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_newest_states_attempt_idx ON ' . $CFG->prefix . 'quiz_newest_states (attemptid, questionid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets DROP CONSTRAINT ' . $CFG->prefix . 'quiz_category_userid_unique', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets ADD CONSTRAINT ' . $CFG->prefix . 'quiz_attemptonlast_datasets_category_userid UNIQUE (category, userid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_grades_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_instances_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_version_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_versions_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states DROP CONSTRAINT ' . $CFG->prefix . 'quiz_responses_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states ADD CONSTRAINT ' . $CFG->prefix . 'quiz_states_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER decimalpoints SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER optionflags SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER penaltyscheme SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER popup SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER questionsperpage SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER review SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER layout SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER preview SET NOT NULL', false);
        $success = $success && table_column('quiz_calculated', 'correctanswerformat', 'correctanswerformat', 'integer', '16', 'unsigned', '2');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER parent SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER sortorder SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_grades ALTER grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers ALTER sequence SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical ALTER tolerance SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER hidden SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER length SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER parent SET NOT NULL', false);
        $success = $success && table_column('quiz_questions', 'penalty', 'penalty', 'real', '', 'UNSIGNED', '0.1');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER event SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER originalquestion SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER penalty SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER raw_grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER seq_number SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER timestamp SET NOT NULL', false);
    }
    if ($success && $oldversion < 2005100500) {
        // clean up an old mistake. This mistake may not have been made, so don't worry about failures.
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_version_id_seq RENAME TO ' . $CFG->prefix . 'quiz_question_versions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_versions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_question_versions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006020801) {
        $success = $success && table_column("quiz", "", "delay1", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "popup");
        $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 && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '1' WHERE defaultgrade = '0'", false);
        $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 < 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 < 2006021400) {
        // modify_database('','CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // this index will not be created since uniqueid was not added, proper upgrade will be on 2006042801
    }
    if ($success && $oldversion < 2006021501) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
    }
    if ($success && $oldversion < 2006021900) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay (\n                id SERIAL PRIMARY KEY,\n                question integer NOT NULL default '0',\n                answer varchar(255) NOT NULL default ''\n            ) ");
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay_states (\n                id SERIAL PRIMARY KEY,\n                stateid integer NOT NULL default '0',\n                graded integer NOT NULL default '0',\n                fraction varchar(10) NOT NULL default '0.0',\n                response text NOT NULL default ''\n            );");
        // convert grade fields to real
        $success = $success && table_column('quiz_attempts', 'sumgrades', 'sumgrades', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_answers', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_essay_states', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'grade', 0, 'grade', '');
        // Some values may be wrong, which caused errors in the following table_column calls.
        $success = $success && set_field('quiz_states', 'raw_grade', 0, 'raw_grade', '');
        $success = $success && set_field('quiz_states', 'penalty', 0, 'penalty', '');
        $success = $success && table_column('quiz_states', 'grade', 'grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'raw_grade', 'raw_grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'penalty', 'penalty', 'real', '', '', '0', 'not null');
        $success = $success && table_column('question_sessions', 'sumpenalty', 'sumpenalty', 'real', '', '', '0', 'not null');
    }
    if ($success && $oldversion < 2006030100) {
        // Fix up another table rename :(
        // THIS caused the mistake: execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_newest_states_id_seq RENAME TO ' . $CFG->prefix . 'question_sessions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_sessions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_sessions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006030101) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_questions RENAME TO {$CFG->prefix}question");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions_id_seq RENAME TO ' . $CFG->prefix . 'question_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_states RENAME TO {$CFG->prefix}question_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states_id_seq RENAME TO ' . $CFG->prefix . 'question_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_answers RENAME TO {$CFG->prefix}question_answers");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers_id_seq RENAME TO ' . $CFG->prefix . 'question_answers_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_answers ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_answers_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_categories RENAME TO {$CFG->prefix}question_categories");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories_id_seq RENAME TO ' . $CFG->prefix . 'question_categories_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_categories ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_categories_id_seq\')');
    }
    if ($success && $oldversion < 2006031202) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_truefalse RENAME TO {$CFG->prefix}question_truefalse");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_truefalse_id_seq RENAME TO ' . $CFG->prefix . 'question_truefalse_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_truefalse ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_truefalse_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_shortanswer RENAME TO {$CFG->prefix}question_shortanswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_shortanswer_id_seq RENAME TO ' . $CFG->prefix . 'question_shortanswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_shortanswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_shortanswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multianswers RENAME TO {$CFG->prefix}question_multianswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers_id_seq RENAME TO ' . $CFG->prefix . 'question_multianswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multianswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multianswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multichoice RENAME TO {$CFG->prefix}question_multichoice");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multichoice_id_seq RENAME TO ' . $CFG->prefix . 'question_multichoice_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multichoice ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multichoice_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical RENAME TO {$CFG->prefix}question_numerical");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical_units RENAME TO {$CFG->prefix}question_numerical_units");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_units_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_units_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical_units ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_units_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_randomsamatch RENAME TO {$CFG->prefix}question_randomsamatch");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_randomsamatch_id_seq RENAME TO ' . $CFG->prefix . 'question_randomsamatch_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match RENAME TO {$CFG->prefix}question_match");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_id_seq RENAME TO ' . $CFG->prefix . 'question_match_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match_sub RENAME TO {$CFG->prefix}question_match_sub");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_sub_id_seq RENAME TO ' . $CFG->prefix . 'question_match_sub_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match_sub ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_sub_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_calculated RENAME TO {$CFG->prefix}question_calculated");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_calculated_id_seq RENAME TO ' . $CFG->prefix . 'question_calculated_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_calculated ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_calculated_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_definitions RENAME TO {$CFG->prefix}question_dataset_definitions");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_definitions_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_definitions_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_definitions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_definitions_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_items RENAME TO {$CFG->prefix}question_dataset_items");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_items_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_items_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_items ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_items_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_question_datasets RENAME TO {$CFG->prefix}question_datasets");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_datasets_id_seq RENAME TO ' . $CFG->prefix . 'question_datasets_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_datasets ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_datasets_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp RENAME TO {$CFG->prefix}question_rqp");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_states RENAME TO {$CFG->prefix}question_rqp_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_states_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_types RENAME TO {$CFG->prefix}question_rqp_types");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_types_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay RENAME TO {$CFG->prefix}question_essay");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay_states RENAME TO {$CFG->prefix}question_essay_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_states_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_states_id_seq\')');
    }
    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 ");
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch_id_seq RENAME prefix_question_randomsamatch_id_seq ");
                $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
            }
            // 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 ($success && $oldversion < 2006051300) {
        // this block also exec'ed by 2006042801 on MOODLE_16_STABLE
        // 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 SERIAL PRIMARY KEY,\n                                     modulename varchar(20) NOT NULL default 'quiz'\n                                  );");
        }
    }
    if ($success && $oldversion < 2006051700) {
        // this block also exec'd by 2006042802 on MOODLE_16_STABLE
        notify("The next set of upgrade operations may report an \n                error if you are upgrading from v1.6. \n                This error mesage is normal, and can be ignored.");
        // this block is taken from mysql.php 2005070202
        // add new unique id to prepare the way for lesson module to have its own attempts table
        table_column('quiz_attempts', '', 'uniqueid', 'integer', '10', 'unsigned', '0', 'not null', 'id');
        // create one entry for all the existing quiz attempts
        // 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");
        // we set $CFG->attemptuniqueid to the next available id
        $record = get_record_sql("SELECT nextval('{$CFG->prefix}quiz_attempts_id_seq')");
        $success = $success && set_config('attemptuniqueid', empty($record->nextid) ? 1 : $record->nextid);
        // the above will be a race condition, see bug 5468
        modify_database('', 'CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // 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 < 2006042802) {
        // 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');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN qtype SET DEFAULT \'0\'');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN version SET DEFAULT \'\'');
        // recreate the indexes that was not moved while quiz was transitioning to question lib
        $success && notify('Errors on indexes not being able to drop or already exists can be ignored as they may have been properly upgraded previously');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_question_idx ON prefix_question_numerical (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_answer_idx ON prefix_question_numerical (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_datasets_question_datasetdefinition_idx ON prefix_question_datasets (question, datasetdefinition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multichoice_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multichoice_question_idx ON prefix_question_multichoice (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_categories_course_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_categories_course_idx ON prefix_question_categories (course)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_shortanswer_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_shortanswer_question_idx ON prefix_question_shortanswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_questions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_category_idx ON prefix_question (category)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_question_idx ON prefix_question_calculated (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_answer_idx ON prefix_question_calculated (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_answers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_answers_question_idx ON prefix_question_answers (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_items_definition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_items_definition_idx ON prefix_question_dataset_items (definition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_units_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_units_question_idx ON prefix_question_numerical_units (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_randomsamatch_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_randomsamatch_question_idx ON prefix_question_randomsamatch (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_question_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_attempt_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_question_idx ON prefix_question_states (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_attempt_idx ON prefix_question_states (attempt)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_question_idx ON prefix_question_match (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_sub_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_sub_question_idx ON prefix_question_match_sub (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multianswers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multianswer_question_idx ON prefix_question_multianswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_definitions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_definitions_category_idx ON prefix_question_dataset_definitions (category)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_timecoursemoduleaction_idx ON prefix_log ("time", course, module, "action")');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_coursemoduleaction_idx ON prefix_log (course, module, "action")');
        $success && modify_database('', 'DROP INDEX prefix_quiz_rqp_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_rqp_question_idx ON prefix_question_rqp (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_truefalse_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_truefalse_question_idx ON prefix_question_truefalse (question)');
        $success && notify('End of upgrading of indexes');
        $success && notify('Renaming primary key names');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical DROP CONSTRAINT prefix_quiz_numerical_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical ADD CONSTRAINT prefix_question_numerical_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets DROP CONSTRAINT prefix_quiz_question_datasets_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets ADD CONSTRAINT prefix_question_datasets_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice DROP CONSTRAINT prefix_quiz_multichoice_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice ADD CONSTRAINT prefix_question_multichoice_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states DROP CONSTRAINT prefix_quiz_rqp_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states ADD CONSTRAINT prefix_question_rqp_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories DROP CONSTRAINT prefix_quiz_categories_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories ADD CONSTRAINT prefix_question_categories_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer DROP CONSTRAINT prefix_quiz_shortanswer_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer ADD CONSTRAINT prefix_question_shortanswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question DROP CONSTRAINT prefix_quiz_questions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question ADD CONSTRAINT prefix_question_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions DROP CONSTRAINT prefix_quiz_newest_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions ADD CONSTRAINT prefix_question_sessions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated DROP CONSTRAINT prefix_quiz_calculated_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated ADD CONSTRAINT prefix_question_calculated_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers DROP CONSTRAINT prefix_quiz_answers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers ADD CONSTRAINT prefix_question_answers_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items DROP CONSTRAINT prefix_quiz_dataset_items_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items ADD CONSTRAINT prefix_question_dataset_items_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units DROP CONSTRAINT prefix_quiz_numerical_units_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units ADD CONSTRAINT prefix_question_numerical_units_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch DROP CONSTRAINT prefix_quiz_randomsamatch_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch ADD CONSTRAINT prefix_question_randomsamatch_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types DROP CONSTRAINT prefix_quiz_rqp_types_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types ADD CONSTRAINT prefix_question_rqp_types_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states DROP CONSTRAINT prefix_quiz_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states ADD CONSTRAINT prefix_question_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match DROP CONSTRAINT prefix_quiz_match_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match ADD CONSTRAINT prefix_question_match_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub DROP CONSTRAINT prefix_quiz_match_sub_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub ADD CONSTRAINT prefix_question_match_sub_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer DROP CONSTRAINT prefix_quiz_multianswers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer ADD CONSTRAINT prefix_question_multianswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions DROP CONSTRAINT prefix_quiz_dataset_definitions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions ADD CONSTRAINT prefix_question_dataset_definitions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp DROP CONSTRAINT prefix_quiz_rqp_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp ADD CONSTRAINT prefix_question_rqp_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse DROP CONSTRAINT prefix_quiz_truefalse_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse ADD CONSTRAINT prefix_question_truefalse_pkey PRIMARY KEY (id)');
        $success && notify('End of renaming primary keys');
    }
    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 SERIAL PRIMARY KEY,\n                quizid integer NOT NULL default '0',\n                feedbacktext text NOT NULL default '',\n                maxgrade real NOT NULL default '0',\n                mingrade real NOT NULL default '0'\n            );\n        ");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_feedback_quizid_idx ON prefix_quiz_feedback (quizid);");
        $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;
}
Exemplo n.º 21
0
function journal_restore_wiki2markdown($restore)
{
    global $CFG;
    $status = true;
    //Convert journal_entries->text
    if ($records = get_records_sql("SELECT e.id, e.text, e.format\n                                         FROM {$CFG->prefix}journal_entries e,\n                                              {$CFG->prefix}journal j,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE j.id = e.journal AND\n                                               j.course = {$restore->course_id} AND\n                                               e.format = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'journal_entries' AND\n                                               b.new_id = e.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->text = restore_decode_wiki_content($record->text, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->text = $wtm->convert($record->text, $restore->course_id);
            $record->format = FORMAT_MARKDOWN;
            $status = update_record('journal_entries', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    //Convert journal->intro
    if ($records = get_records_sql("SELECT j.id, j.intro, j.introformat\n                                         FROM {$CFG->prefix}journal j,\n                                              {$CFG->prefix}backup_ids b\n                                         WHERE j.course = {$restore->course_id} AND\n                                               j.introformat = " . FORMAT_WIKI . " AND\n                                               b.backup_code = {$restore->backup_unique_code} AND\n                                               b.table_name = 'journal' AND\n                                               b.new_id = j.id")) {
        foreach ($records as $record) {
            //Rebuild wiki links
            $record->intro = restore_decode_wiki_content($record->intro, $restore);
            //Convert to Markdown
            $wtm = new WikiToMarkdown();
            $record->intro = $wtm->convert($record->intro, $restore->course_id);
            $record->introformat = FORMAT_MARKDOWN;
            $status = update_record('journal', addslashes_object($record));
            //Do some output
            $i++;
            if (($i + 1) % 1 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i + 1) % 20 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
    }
    return $status;
}
Exemplo n.º 22
-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;
}