コード例 #1
0
ファイル: upgrade.php プロジェクト: nadavkav/MoodleTAO
function xmldb_taoresource_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    //===== 1.9.0 upgrade line ======//
    // change the remoteid key to be non-unique
    if ($result && $oldversion < 2007101510) {
        $table = new XMLDBTable('taoresource_entry');
        $index = new XMLDBIndex('remoteid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('remoteid'));
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        $result = $result && add_index($table, $index);
    }
    // change the remoteid key to be non-unique
    if ($result && $oldversion < 2007101511) {
        $table = new XMLDBTable('taoresource_metadata');
        $field = new XMLDBField('entry_id');
        // change the field type from ext to int
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
            $result = $result && change_field_type($table, $field);
        }
    }
    return $result;
}
コード例 #2
0
function xmldb_lesson_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2006091802) {
        /// Changing nullability of field response on table lesson_answers to null
        $table = new XMLDBTable('lesson_answers');
        $field = new XMLDBField('response');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'answer');
        /// Launch change of nullability for field response
        $result = $result && change_field_notnull($table, $field);
    }
    if ($result && $oldversion < 2006091803) {
        /// Changing nullability of field useranswer on table lesson_attempts to null
        $table = new XMLDBTable('lesson_attempts');
        $field = new XMLDBField('useranswer');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'correct');
        /// Launch change of nullability for field useranswer
        $result = $result && change_field_notnull($table, $field);
    }
    if ($result && $oldversion < 2007020201) {
        /// Changing nullability of field answer on table lesson_answers to null
        $table = new XMLDBTable('lesson_answers');
        $field = new XMLDBField('answer');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'timemodified');
        /// Launch change of nullability for field answer
        $result = $result && change_field_notnull($table, $field);
    }
    //===== 1.9.0 upgrade line ======//
    if ($result && $oldversion < 2007072201) {
        $table = new XMLDBTable('lesson');
        $field = new XMLDBField('usegrademax');
        $field2 = new XMLDBField('usemaxgrade');
        /// Rename lesson->usegrademax to lesson->usemaxgrade. Some old sites can have it incorrect. MDL-13177
        if (field_exists($table, $field) && !field_exists($table, $field2)) {
            /// Set field specs
            $field->setAttributes(XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, null, null, '0', 'ongoing');
            /// Launch rename field usegrademax to usemaxgrade
            $result = $result && rename_field($table, $field, 'usemaxgrade');
        }
    }
    if ($result && $oldversion < 2008112601) {
        require_once $CFG->dirroot . '/mod/lesson/lib.php';
        // too much debug output
        $db->debug = false;
        lesson_update_grades();
        $db->debug = true;
    }
    return $result;
}
コード例 #3
0
function xmldb_enrol_authorize_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2006111700) {
        $table = new XMLDBTable('enrol_authorize');
        if (!field_exists($table, new XMLDBField('refundinfo'))) {
            $field = new XMLDBField('cclastfour');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'paymentmethod');
            $result = $result && rename_field($table, $field, 'refundinfo');
        }
    }
    if ($result && $oldversion < 2006112900) {
        if (isset($CFG->an_login)) {
            if (empty($CFG->an_login)) {
                unset_config('an_login');
            } else {
                $result = $result && set_config('an_login', rc4encrypt($CFG->an_login), 'enrol/authorize') && unset_config('an_login');
            }
        }
        if (isset($CFG->an_tran_key)) {
            if (empty($CFG->an_tran_key)) {
                unset_config('an_tran_key');
            } else {
                $result = $result && set_config('an_tran_key', rc4encrypt($CFG->an_tran_key), 'enrol/authorize') && unset_config('an_tran_key');
            }
        }
        if (isset($CFG->an_password)) {
            if (empty($CFG->an_password)) {
                unset_config('an_password');
            } else {
                $result = $result && set_config('an_password', rc4encrypt($CFG->an_password), 'enrol/authorize') && unset_config('an_password');
            }
        }
    }
    return $result;
}
コード例 #4
0
function xmldb_tab_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    if ($result && $oldversion < 2010072101) {
        /// Define field anonymous_response to be added to feedback_completed
        $table = new XMLDBTable('tab');
        $field = new XMLDBField('displayfp');
        if (!field_exists($table, $field)) {
            // if field does not exists... add it
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
            $result = $result && add_field($table, $field);
        }
        // original mysql sql code: "ALTER TABLE `mdl_tab` CHANGE `displayfp` `displayfp` TINYINT( 1 ) NOT NULL DEFAULT '0'"
    }
    return $result;
}
コード例 #5
0
ファイル: upgrade.php プロジェクト: r007/PMoodle
function xmldb_data_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    if ($result && $oldversion < 2006121300) {
        /// Define field format to be added to data_comments
        $table = new XMLDBTable('data_comments');
        $field = new XMLDBField('format');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'content');
        /// Launch add field format
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007022600) {
        /// Define field asearchtemplate to be added to data
        $table = new XMLDBTable('data');
        $field = new XMLDBField('asearchtemplate');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'jstemplate');
        /// Launch add field asearchtemplate
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007072200) {
        require_once $CFG->dirroot . '/mod/data/lib.php';
        // too much debug output
        $db->debug = false;
        data_update_grades();
        $db->debug = true;
    }
    if ($result && $oldversion < 2007081400) {
        /// Define field notification to be added to data
        $table = new XMLDBTable('data');
        $field = new XMLDBField('notification');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null, 'editany');
        /// Launch add field notification
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007081402) {
        /// Define index type-dataid (not unique) to be added to data_fields
        $table = new XMLDBTable('data_fields');
        $index = new XMLDBIndex('type-dataid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('type', 'dataid'));
        /// Launch add index type-dataid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Define index course (not unique) to be added to data
        $table = new XMLDBTable('data');
        $index = new XMLDBIndex('course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course'));
        /// Launch add index course
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
    }
    //===== 1.9.0 upgrade line ======//
    if ($result && $oldversion < 2007101512) {
        /// Launch add field asearchtemplate again if does not exists yet - reported on several sites
        $table = new XMLDBTable('data');
        $field = new XMLDBField('asearchtemplate');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'jstemplate');
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    return $result;
}
コード例 #6
0
ファイル: upgrade.php プロジェクト: patkira/mahara
function xmldb_core_upgrade($oldversion = 0)
{
    global $SESSION;
    raise_time_limit(120);
    raise_memory_limit('256M');
    $status = true;
    if ($oldversion < 2009022700) {
        // Get rid of all blocks with position 0 caused by 'about me' block on profile views
        if (count_records('block_instance', 'order', 0) && !count_records_select('block_instance', '"order" < 0')) {
            if (is_mysql()) {
                $ids = get_column_sql('
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column)');
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (' . join(',', $ids) . ')');
            } else {
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column))');
            }
            execute_sql('UPDATE {block_instance} SET "order" = 1 WHERE "order" = 0');
            execute_sql('UPDATE {block_instance} SET "order" = -1 * ("order" - 1) WHERE "order" < 0');
        }
    }
    if ($oldversion < 2009031000) {
        reload_html_filters();
    }
    if ($oldversion < 2009031300) {
        $table = new XMLDBTable('institution');
        $expiry = new XMLDBField('expiry');
        $expiry->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $expiry);
        $expirymailsent = new XMLDBField('expirymailsent');
        $expirymailsent->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $expirymailsent);
        $suspended = new XMLDBField('suspended');
        $suspended->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $suspended);
        // Insert a cron job to check for soon expiring and expired institutions
        if (!record_exists('cron', 'callfunction', 'auth_handle_institution_expiries')) {
            $cron = new StdClass();
            $cron->callfunction = 'auth_handle_institution_expiries';
            $cron->minute = '5';
            $cron->hour = '9';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2009031800) {
        // Files can only attach blogpost artefacts, but we would like to be able to attach them
        // to other stuff.  Rename the existing attachment table artefact_blog_blogpost_file to
        // artefact_file_attachment so we don't end up with many tables doing the same thing.
        execute_sql("ALTER TABLE {artefact_blog_blogpost_file} RENAME TO {artefact_attachment}");
        if (is_postgres()) {
            // Ensure all of the indexes and constraints are renamed
            execute_sql("\n            ALTER TABLE {artefact_attachment} RENAME blogpost TO artefact;\n            ALTER TABLE {artefact_attachment} RENAME file TO attachment;\n\n            ALTER INDEX {arteblogblogfile_blofil_pk} RENAME TO {arteatta_artatt_pk};\n            ALTER INDEX {arteblogblogfile_blo_ix} RENAME TO {arteatta_art_ix};\n            ALTER INDEX {arteblogblogfile_fil_ix} RENAME TO {arteatta_att_ix};\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_blo_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY (artefact) REFERENCES {artefact}(id);\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_fil_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY (attachment) REFERENCES {artefact}(id);\n            ");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_blo_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_blo_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE blogpost artefact BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY {arteatta_art_ix} (artefact) REFERENCES {artefact}(id)");
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_fil_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_fil_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE file attachment BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY {arteatta_att_ix} (attachment) REFERENCES {artefact}(id)");
            }
        }
        // Drop the _pending table. From now on files uploaded as attachments will become artefacts
        // straight away.  Hopefully changes to the upload/file browser form will make it clear to
        // the user that these attachments sit in his/her files area as soon as they are uploaded.
        $table = new XMLDBTable('artefact_blog_blogpost_file_pending');
        drop_table($table);
    }
    if ($oldversion < 2009040900) {
        // The view access page has been putting the string 'null' in as a group role in IE.
        set_field('view_access_group', 'role', null, 'role', 'null');
    }
    if ($oldversion < 2009040901) {
        $table = new XMLDBTable('import_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('import_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
        $table = new XMLDBTable('export_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('export_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2009050700) {
        if ($data = check_upgrades('export.html')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('export.leap')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('import.leap')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009051200) {
        // Rename submittedto column to submittedgroup
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} RENAME submittedto TO submittedgroup");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} DROP FOREIGN KEY {view_sub_fk}");
                execute_sql("ALTER TABLE {view} DROP INDEX {view_sub_ix}");
                execute_sql("ALTER TABLE {view} CHANGE submittedto submittedgroup BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_sub_fk} FOREIGN KEY {view_sub_ix} (submittedgroup) REFERENCES {group}(id)");
            }
        }
        // Add submittedhost column for views submitted to remote moodle hosts
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        // Do this manually because xmldb tries to create a key with the same name (view_sub_vk) as an existing one, and fails.
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY (submittedhost) REFERENCES {host}(wwwroot)");
            execute_sql("CREATE INDEX {view_subh_ix} ON {view} (submittedhost)");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY {view_subh_ix} (submittedhost) REFERENCES {host}(wwwroot)");
            }
        }
    }
    if ($oldversion < 2009051201) {
        // Invisible view access keys for roaming moodle teachers
        $table = new XMLDBTable('view_access_token');
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2009052700) {
        // Install a cron job to clean out old exports
        $cron = new StdClass();
        $cron->callfunction = 'export_cleanup_old_exports';
        $cron->minute = '0';
        $cron->hour = '3,13';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009070600) {
        // This was forgotten as part of the 1.0 -> 1.1 upgrade
        if ($data = check_upgrades('blocktype.file/html')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009070700) {
        foreach (array('addfriend', 'removefriend', 'addfriendrequest', 'removefriendrequest') as $eventtype) {
            $event = (object) array('name' => $eventtype);
            ensure_record_exists('event_type', $event, $event);
        }
    }
    if ($oldversion < 2009070900) {
        if (is_mysql()) {
            execute_sql("ALTER TABLE {usr} DROP FOREIGN KEY {usr_las_fk}");
            execute_sql("ALTER TABLE {usr} DROP INDEX {usr_las_ix}");
        }
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastauthinstance');
        drop_field($table, $field);
    }
    if ($oldversion < 2009080600) {
        $table = new XMLDBTable('view');
        $index = new XMLDBIndex('view_own_type_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('owner'));
        if (!index_exists($table, $index)) {
            // Delete duplicate profile views if there are any, then add an index
            // that will prevent it happening again - but only on postgres, as it's
            // the only db that supports partial indexes
            if ($viewdata = get_records_sql_array("\n                SELECT owner, id\n                FROM {view}\n                WHERE owner IN (\n                    SELECT owner\n                    FROM {view}\n                    WHERE type = 'profile'\n                    GROUP BY owner\n                    HAVING COUNT(*) > 1\n                )\n                AND type = 'profile'\n                ORDER BY owner, id", array())) {
                require_once 'view.php';
                $seen = array();
                foreach ($viewdata as $record) {
                    $seen[$record->owner][] = $record->id;
                }
                foreach ($seen as $owner => $views) {
                    // Remove the first one, which is their real profile view
                    array_shift($views);
                    foreach ($views as $viewid) {
                        delete_records('artefact_feedback', 'view', $viewid);
                        delete_records('view_feedback', 'view', $viewid);
                        delete_records('view_access', 'view', $viewid);
                        delete_records('view_access_group', 'view', $viewid);
                        delete_records('view_access_usr', 'view', $viewid);
                        delete_records('view_access_token', 'view', $viewid);
                        delete_records('view_autocreate_grouptype', 'view', $viewid);
                        delete_records('view_tag', 'view', $viewid);
                        delete_records('usr_watchlist_view', 'view', $viewid);
                        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $viewid)) {
                            foreach ($blockinstanceids as $id) {
                                if (table_exists(new XMLDBTable('blocktype_wall_post'))) {
                                    delete_records('blocktype_wall_post', 'instance', $id);
                                }
                                delete_records('view_artefact', 'block', $id);
                                delete_records('block_instance', 'id', $id);
                            }
                        }
                        delete_records('view', 'id', $viewid);
                    }
                }
            }
            if (is_postgres()) {
                execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
            }
        }
    }
    if ($oldversion < 2009080601) {
        execute_sql("DELETE FROM {group_member_invite} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'invite')");
        execute_sql("DELETE FROM {group_member_request} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'request')");
    }
    if ($oldversion < 2009081800) {
        $event = (object) array('name' => 'creategroup');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009082400) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('username');
        drop_field($table, $field);
        $field = new XMLDBField('salt');
        drop_field($table, $field);
        $field = new XMLDBField('password');
        drop_field($table, $field);
    }
    if ($oldversion < 2009082600) {
        $captcha = get_config('captcha_on_contact_form');
        set_config('captchaoncontactform', (int) (is_null($captcha) || $captcha));
        $captcha = get_config('captcha_on_register_form');
        set_config('captchaonregisterform', (int) (is_null($captcha) || $captcha));
    }
    if ($oldversion < 2009090700) {
        set_config('showselfsearchsideblock', 1);
        set_config('showtagssideblock', 1);
        set_config('tagssideblockmaxtags', 20);
    }
    if ($oldversion < 2009092100) {
        if ($data = check_upgrades('import.file')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.creativecommons')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009092900) {
        $event = (object) array('name' => 'deleteartefacts');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009101600) {
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        // Remove bbcode formatting from existing feedback
        if ($records = get_records_sql_array("SELECT * FROM {view_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('view_feedback', $r);
            }
        }
        if ($records = get_records_sql_array("SELECT * FROM {artefact_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('artefact_feedback', $r);
            }
        }
    }
    if ($oldversion < 2009102100) {
        // Now the view_layout table has to have records for all column widths
        $record = (object) array('columns' => 1, 'widths' => '100');
        insert_record('view_layout', $record);
        $record = (object) array('columns' => 5, 'widths' => '20,20,20,20,20');
        insert_record('view_layout', $record);
    }
    if ($oldversion < 2009102200) {
        if (!count_records_select('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'))) {
            insert_record('activity_type', (object) array('name' => 'groupmessage', 'admin' => 0, 'delay' => 0));
        }
    }
    if ($oldversion < 2009102900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('sessionid');
        drop_field($table, $field);
    }
    if ($oldversion < 2009110500) {
        set_config('creategroups', 'all');
    }
    if ($oldversion < 2009110900) {
        // Fix export cronjob so it runs 12 hours apart
        execute_sql("UPDATE {cron} SET hour = '3,15' WHERE callfunction = 'export_cleanup_old_exports'");
        // Cron job to clean old imports
        $cron = new StdClass();
        $cron->callfunction = 'import_cleanup_old_imports';
        $cron->minute = '0';
        $cron->hour = '4,16';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009111200) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailssent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009111201) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailsbounced');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009120100) {
        // Fix for bug in 1.1 => 1.2 upgrade which may have inserted
        // a second groupmessage activity_type record
        $records = get_records_select_array('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'), 'id');
        if ($records && count($records) > 1) {
            for ($i = 1; $i < count($records); $i++) {
                delete_records('activity_queue', 'type', $records[$i]->id);
                delete_records('notification_internal_activity', 'type', $records[$i]->id);
                delete_records('notification_emaildigest_queue', 'type', $records[$i]->id);
                delete_records('usr_activity_preference', 'activity', $records[$i]->id);
                delete_records('activity_type', 'id', $records[$i]->id);
            }
        }
    }
    if ($oldversion < 2009120900) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010011300) {
        // Clean up the mess left behind by failing to delete blogposts in a transaction
        try {
            include_once get_config('docroot') . 'artefact/lib.php';
            if (function_exists('rebuild_artefact_parent_cache_dirty')) {
                rebuild_artefact_parent_cache_dirty();
            }
        } catch (Exception $e) {
            log_debug('Upgrade 2010011300: rebuild_artefact_parent_cache_dirty failed.');
        }
        execute_sql("\n            INSERT INTO {artefact_blog_blogpost} (blogpost)\n            SELECT id FROM {artefact} WHERE artefacttype = 'blogpost' AND id NOT IN (\n                SELECT blogpost FROM {artefact_blog_blogpost}\n            )");
    }
    if ($oldversion < 2010012701) {
        set_config('userscanchooseviewthemes', 1);
    }
    if ($oldversion < 2010021500) {
        if ($data = check_upgrades('blocktype.recentforumposts')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010031000) {
        // For existing sites, preserve current user search behaviour:
        // Users are only searchable by their display names.
        set_config('userscanhiderealnames', 1);
        execute_sql("\n            INSERT INTO {usr_account_preference} (usr, field, value)\n            SELECT u.id, 'hiderealname', 1\n            FROM {usr} u LEFT JOIN {usr_account_preference} p ON (u.id = p.usr AND p.field = 'hiderealname')\n            WHERE NOT u.preferredname IS NULL AND u.preferredname != '' AND p.field IS NULL\n        ");
    }
    if ($oldversion < 2010040700) {
        // Set antispam defaults
        set_config('formsecret', get_random_key());
        if (!function_exists('checkdnsrr')) {
            require_once get_config('docroot') . 'lib/antispam.php';
        }
        if (checkdnsrr('test.uribl.com.black.uribl.com', 'A')) {
            set_config('antispam', 'advanced');
        } else {
            set_config('antispam', 'simple');
        }
        set_config('spamhaus', 0);
        set_config('surbl', 0);
    }
    if ($oldversion < 2010040800) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010041200) {
        delete_records('config', 'field', 'captchaoncontactform');
        delete_records('config', 'field', 'captchaonregisterform');
    }
    if ($oldversion < 2010041201) {
        $sql = "\n            SELECT u.id\n            FROM {usr} u\n            LEFT JOIN {artefact} a\n                ON (a.owner = u.id AND a.artefacttype = 'blog')\n            WHERE u.id > 0\n            GROUP BY u.id\n            HAVING COUNT(a.id) != 1";
        $manyblogusers = get_records_sql_array($sql, array());
        if ($manyblogusers) {
            foreach ($manyblogusers as $u) {
                $where = (object) array('usr' => $u->id, 'field' => 'multipleblogs');
                $data = (object) array('usr' => $u->id, 'field' => 'multipleblogs', 'value' => 1);
                ensure_record_exists('usr_account_preference', $where, $data);
            }
        }
    }
    if ($oldversion < 2010041600 && table_exists(new XMLDBTable('view_feedback'))) {
        // Add author, authorname to artefact table
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('author');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        table_column('artefact', null, 'authorname', 'text', null, null, null, '');
        if (is_postgres()) {
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN authorname DROP DEFAULT");
            set_field('artefact', 'authorname', null);
            execute_sql('UPDATE {artefact} SET authorname = g.name FROM {group} g WHERE "group" = g.id');
            execute_sql("UPDATE {artefact} SET authorname = CASE WHEN institution = 'mahara' THEN ? ELSE i.displayname END FROM {institution} i WHERE institution = i.name", array(get_config('sitename')));
        } else {
            execute_sql("UPDATE {artefact} a, {group} g SET a.authorname = g.name WHERE a.group = g.id");
            execute_sql("UPDATE {artefact} a, {institution} i SET a.authorname = CASE WHEN a.institution = 'mahara' THEN ? ELSE i.displayname END WHERE a.institution = i.name", array(get_config('sitename')));
        }
        execute_sql('UPDATE {artefact} SET author = owner WHERE owner IS NOT NULL');
        execute_sql('ALTER TABLE {artefact} ADD CHECK (
            (author IS NOT NULL AND authorname IS NULL    ) OR
            (author IS NULL     AND authorname IS NOT NULL)
        )');
        // Move feedback activity type to artefact plugin
        execute_sql("\n            UPDATE {activity_type}\n            SET plugintype = 'artefact', pluginname = 'comment'\n            WHERE name = 'feedback'\n        ");
        // Install the comment artefact
        if ($data = check_upgrades('artefact.comment')) {
            upgrade_plugin($data);
        }
        // Flag all views & artefacts to enable/disable comments
        table_column('artefact', null, 'allowcomments', 'integer', 1);
        table_column('view', null, 'allowcomments', 'integer', 1, null, 1);
        // Initially allow comments on blogposts, images, files
        set_field_select('artefact', 'allowcomments', 1, 'artefacttype IN (?,?,?)', array('blogpost', 'image', 'file'));
        // Convert old feedback to comment artefacts
        if ($viewfeedback = get_records_sql_array('
            SELECT f.*, v.id AS viewid, v.owner, v.group, v.institution
            FROM {view_feedback} f JOIN {view} v ON f.view = v.id', array())) {
            foreach ($viewfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onview' => $f->viewid);
                insert_record('artefact_comment_comment', $comment);
                if (!empty($f->attachment)) {
                    insert_record('artefact_attachment', (object) array('artefact' => $aid, 'attachment' => $f->attachment));
                }
            }
        }
        // We are throwing away the view information from artefact_feedback.
        // From now on all artefact comments appear together and are not
        // tied to a particular view.
        if ($artefactfeedback = get_records_sql_array('
            SELECT f.*, a.id AS artefactid, a.owner, a.group, a.institution
            FROM {artefact_feedback} f JOIN {artefact} a ON f.artefact = a.id', array())) {
            foreach ($artefactfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onartefact' => $f->artefactid);
                insert_record('artefact_comment_comment', $comment);
            }
        }
        // Drop feedback tables
        $table = new XMLDBTable('view_feedback');
        drop_table($table);
        $table = new XMLDBTable('artefact_feedback');
        drop_table($table);
        // Add site setting for anonymous comments
        set_config('anonymouscomments', 1);
    }
    if ($oldversion < 2010041900 && !table_exists(new XMLDBTable('site_data'))) {
        // Upgrades for admin stats pages
        // Table for collection of historical stats
        $table = new XMLDBTable('site_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'type'));
        create_table($table);
        // Insert cron jobs to save site data
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
        // Put best guess at installation time into config table.
        set_config('installation_time', get_field_sql("SELECT MIN(ctime) FROM {site_content}"));
        // Save the current time so we know when we started collecting stats
        set_config('stats_installation_time', db_format_timestamp(time()));
        // Add ctime to usr table for daily count of users created
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // Add visits column to view table
        $table = new XMLDBTable('view');
        $field = new XMLDBField('visits');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Add table to store daily view visits
        $table = new XMLDBTable('view_visit');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addIndexInfo('ctimeix', XMLDB_INDEX_NOTUNIQUE, array('ctime'));
        create_table($table);
        // Insert a cron job to check for new versions of Mahara
        $cron = new StdClass();
        $cron->callfunction = 'cron_check_for_updates';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2010042600) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('parent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('parentfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('parent'), 'notification_internal_activity', array('id'));
        add_key($table, $key);
        $field = new XMLDBField('from');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('fromfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('from'), 'usr', array('id'));
        add_key($table, $key);
        // Set from column for old user messages
        $usermessages = get_records_array('notification_internal_activity', 'type', get_field('activity_type', 'id', 'name', 'usermessage'));
        if ($usermessages) {
            foreach ($usermessages as &$m) {
                if (preg_match('/sendmessage\\.php\\?id=(\\d+)/', $m->url, $match)) {
                    set_field('notification_internal_activity', 'from', $match[1], 'id', $m->id);
                }
            }
        }
    }
    if ($oldversion < 2010042602 && !get_record('view_type', 'type', 'dashboard')) {
        insert_record('view_type', (object) array('type' => 'dashboard'));
        if ($data = check_upgrades('blocktype.inbox')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.newviews')) {
            upgrade_plugin($data);
        }
        // Install system dashboard view
        require_once get_config('libroot') . 'view.php';
        $dbtime = db_format_timestamp(time());
        $viewdata = (object) array('type' => 'dashboard', 'owner' => 0, 'numcolumns' => 2, 'ownerformat' => FORMAT_NAME_PREFERREDNAME, 'title' => get_string('dashboardviewtitle', 'view'), 'template' => 1, 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'newviews', 'title' => get_string('title', 'blocktype.newviews'), 'column' => 1, 'config' => array('limit' => 5)), array('blocktype' => 'myviews', 'title' => get_string('title', 'blocktype.myviews'), 'column' => 1, 'config' => null), array('blocktype' => 'inbox', 'title' => get_string('inboxblocktitle'), 'column' => 2, 'config' => array('feedback' => true, 'groupmessage' => true, 'institutionmessage' => true, 'maharamessage' => true, 'usermessage' => true, 'viewaccess' => true, 'watchlist' => true, 'maxitems' => '5')), array('blocktype' => 'inbox', 'title' => get_string('topicsimfollowing'), 'column' => 2, 'config' => array('newpost' => true, 'maxitems' => '5')));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        $weights = array(1 => 0, 2 => 0);
        foreach ($blocktypes as $blocktype) {
            if (in_array($blocktype['blocktype'], $installed)) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010042603) {
        execute_sql('ALTER TABLE {usr} ADD COLUMN showhomeinfo SMALLINT NOT NULL DEFAULT 1');
        set_config('homepageinfo', 1);
    }
    if ($oldversion < 2010042604) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('urltext');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2010051000) {
        set_field('activity_type', 'delay', 1, 'name', 'groupmessage');
    }
    if ($oldversion < 2010052000) {
        $showusers = get_config('showonlineuserssideblock');
        set_config('showonlineuserssideblock', (int) (is_null($showusers) || $showusers));
    }
    if ($oldversion < 2010060300) {
        // Add table to associate users with php session ids
        $table = new XMLDBTable('usr_session');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('session', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('session'));
        $table->addIndexInfo('usrix', XMLDB_INDEX_NOTUNIQUE, array('usr'));
        create_table($table);
    }
    if ($oldversion < 2010061100) {
        set_config('registerterms', 1);
    }
    if ($oldversion < 2010061800) {
        insert_record('view_type', (object) array('type' => 'grouphomepage'));
        if ($data = check_upgrades('blocktype.groupmembers')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupinfo')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupviews')) {
            upgrade_plugin($data);
        }
        $dbtime = db_format_timestamp(time());
        // create a system template for group homepage views
        require_once get_config('libroot') . 'view.php';
        $viewdata = (object) array('type' => 'grouphomepage', 'owner' => 0, 'numcolumns' => 1, 'template' => 1, 'title' => get_string('grouphomepage', 'view'), 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'groupinfo', 'title' => '', 'column' => 1, 'config' => null), array('blocktype' => 'recentforumposts', 'title' => get_string('latestforumposts', 'interaction.forum'), 'column' => 1, 'config' => null), array('blocktype' => 'groupviews', 'title' => get_string('Views', 'view'), 'column' => 1, 'config' => null), array('blocktype' => 'groupmembers', 'title' => get_string('Members', 'group'), 'column' => 1, 'config' => null));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        foreach ($blocktypes as $k => $blocktype) {
            if (!in_array($blocktype['blocktype'], $installed)) {
                unset($blocktypes[$k]);
            }
        }
        $weights = array(1 => 0);
        foreach ($blocktypes as $blocktype) {
            $weights[$blocktype['column']]++;
            insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
        }
        // add a default group homepage view for all groups in the system
        unset($viewdata->owner);
        $viewdata->template = 0;
        if (!($groups = get_records_array('group', '', '', '', 'id,public'))) {
            $groups = array();
        }
        foreach ($groups as $group) {
            $viewdata->group = $group->id;
            $id = insert_record('view', $viewdata, 'id', true);
            insert_record('view_access', (object) array('view' => $id, 'accesstype' => $group->public ? 'public' : 'loggedin'));
            insert_record('view_access_group', (object) array('view' => $id, 'group' => $group->id));
            $weights = array(1 => 0);
            foreach ($blocktypes as $blocktype) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010062502) {
        //new feature feedback control on views
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('allowcomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Add comment approval to view/artefact (default 0)
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table = new XMLDBTable('view');
        add_field($table, $field);
        $table = new XMLDBTable('artefact');
        add_field($table, $field);
        // view_access_(group|usr|token) tables are getting wide with duplicated columns,
        // so just create all the necessary columns in view_access and move stuff there
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null);
        change_field_notnull($table, $field);
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('role');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $field = new XMLDBField('usr');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('token');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Copy data to view_access
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, "group", role, startdate, stopdate)
            SELECT view, NULL, "group", role, startdate, stopdate FROM {view_access_group}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, usr, startdate, stopdate)
            SELECT view, NULL, usr, startdate, stopdate FROM {view_access_usr}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, token, visible, startdate, stopdate)
            SELECT view, NULL, token, visible, startdate, stopdate FROM {view_access_token}');
        // Add foreign keys
        $key = new XMLDBKey('groupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('usrfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        add_key($table, $key);
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        add_index($table, $index);
        // Exactly one of accesstype, group, usr, token must be not null
        execute_sql('ALTER TABLE {view_access} ADD CHECK (
            (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL)
        )');
        // Drop old tables
        $table = new XMLDBTable('view_access_group');
        drop_table($table);
        $table = new XMLDBTable('view_access_usr');
        drop_table($table);
        $table = new XMLDBTable('view_access_token');
        drop_table($table);
        // Insert explicit tutor access records for submitted views
        if (!($submittedviews = get_records_sql_array('
            SELECT v.id, v.submittedgroup, g.grouptype
            FROM {view} v JOIN {group} g ON (v.submittedgroup = g.id AND g.deleted = 0)', array()))) {
            $submittedviews = array();
        }
        $roles = array();
        foreach ($submittedviews as $v) {
            if (!isset($roles[$v->grouptype])) {
                $rs = get_column('grouptype_roles', 'role', 'grouptype', $v->grouptype, 'see_submitted_views', 1);
                $roles[$v->grouptype] = empty($rs) ? array() : $rs;
            }
            foreach ($roles[$v->grouptype] as $role) {
                $accessrecord = (object) array('view' => $v->id, 'group' => $v->submittedgroup, 'role' => $role, 'visible' => 0, 'allowcomments' => 1, 'approvecomments' => 0);
                ensure_record_exists('view_access', $accessrecord, $accessrecord);
            }
        }
    }
    if ($oldversion < 2010070700) {
        $table = new XMLDBTable('group_category');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('category');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('categoryfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('category'), 'group_category', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2010071300) {
        set_config('searchusernames', 1);
    }
    if ($oldversion < 2010071500) {
        reload_html_filters();
    }
    if ($oldversion < 2010071600) {
        if (is_postgres()) {
            // change_field_enum should do this
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends', 'objectionable'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2010071900) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('viewnotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2010081000) {
        // new table collection
        $table = new XMLDBTable('collection');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('navigation', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // new table collection_view
        $table = new XMLDBTable('collection_view');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('view'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
        // Drop unique constraint on token column of view_access
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        drop_index($table, $index);
        $index = new XMLDBIndex('tokenix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('token'));
        add_index($table, $index);
    }
    if ($oldversion < 2010081001) {
        if ($data = check_upgrades('artefact.plans')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.plans/plans')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010081100) {
        if ($data = check_upgrades('blocktype.navigation')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010082000) {
        delete_records_select('config', "field IN ('usersrank', 'groupsrank', 'viewsrank')");
    }
    if ($oldversion < 2010091300) {
        // Cron job missing from installs post 2010041900
        if (!record_exists('cron', 'callfunction', 'cron_check_for_updates')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_check_for_updates';
            $cron->minute = rand(0, 59);
            $cron->hour = rand(0, 23);
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010091500) {
        // Previous version of 2010040800 upgrade created the submittedtime
        // column not null (see bug #638550)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        change_field_notnull($table, $field);
        // Our crappy db is full of redundant data (submittedtime depends on
        // submittedhost or submittedgroup) so it's easy to correct this.
        execute_sql("\n            UPDATE {view} SET submittedtime = NULL\n            WHERE submittedtime IS NOT NULL AND submittedgroup IS NULL AND submittedhost IS NULL");
    }
    if ($oldversion < 2010100702) {
        // Add general notification cleanup cron
        if (!record_exists('cron', 'callfunction', 'cron_clean_internal_activity_notifications')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_clean_internal_activity_notifications';
            $cron->minute = 45;
            $cron->hour = 22;
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010110800) {
        // Encrypt all passwords with no set salt values
        $sql = "SELECT * FROM {usr}\n                WHERE salt IS NULL OR salt = ''";
        if ($passwords = get_records_sql_array($sql, array())) {
            foreach ($passwords as $p) {
                $p->salt = substr(md5(rand(1000000, 9999999)), 2, 8);
                $p->password = sha1($p->salt . $p->password);
                update_record('usr', $p);
            }
        }
    }
    if ($oldversion < 2010122200) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('priority');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        set_field('institution', 'priority', 0, 'name', 'mahara');
    }
    if ($oldversion < 2010122201) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('accessconf');
        $field->setAttributes(XMLDB_TYPE_CHAR, 40, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010122700) {
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('accesstypeix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        add_index($table, $index);
    }
    if ($oldversion < 2011012800) {
        reload_html_filters();
    }
    if ($oldversion < 2011032500) {
        // Uninstall solr plugin; it's moving to contrib until it's fixed up.
        delete_records('search_cron', 'plugin', 'solr');
        delete_records('search_event_subscription', 'plugin', 'solr');
        delete_records('search_config', 'plugin', 'solr');
        delete_records('search_installed', 'name', 'solr');
        $searchplugin = get_config('searchplugin');
        if ($searchplugin == 'solr') {
            set_config('searchplugin', 'internal');
        }
    }
    if ($oldversion < 2011041800) {
        // Remove titles from system dashboard, group homepage blocks, so new users/groups
        // get blocks with automatically generated, translatable default titles.
        $systemdashboard = get_field('view', 'id', 'owner', 0, 'type', 'dashboard');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('newviews','myviews','inbox')", array($systemdashboard));
        $systemgrouphomepage = get_field('view', 'id', 'owner', 0, 'type', 'grouphomepage');
        set_field_select('block_instance', 'title', '', "view = ? AND blocktype IN ('recentforumposts','groupviews','groupmembers')", array($systemgrouphomepage));
    }
    if ($oldversion < 2011042000) {
        // Create empty variables in database for email configuration
        set_config('smtphosts', '');
        set_config('smtpport', '');
        set_config('smtpuser', '');
        set_config('smtppass', '');
        set_config('smtpsecure', '');
        $SESSION->add_info_msg('Email settings now can be configured via Site settings, however they may be overriden by those set in the config file. If you have no specific reason to use config file email configuration, please consider moving them to Site settings area.');
    }
    if ($oldversion < 2011050300) {
        if (get_config('httpswwwroot')) {
            // Notify users about httpswwwroot removal if it is still set
            $SESSION->add_info_msg('HTTPS logins have been deprecated, you need to remove the httpswwwroot variable from config file and switch your wwwroot to https so that the whole site is served over HTTPS.<br>See <a href="https://bugs.launchpad.net/mahara/+bug/646713">https://bugs.launchpad.net/mahara/+bug/646713</a> for more details.', 0);
        }
    }
    if ($oldversion < 2011050600) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('username');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        // This drops the unique index on the username column in postgres.
        // See upgrade 2011051800.
        change_field_precision($table, $field);
    }
    if ($oldversion < 2011051700) {
        // Create new "external" category
        insert_record('blocktype_category', (object) array('name' => 'external'));
        // Migrate existing blocktypes to the new category
        set_field('blocktype_installed_category', 'category', 'external', 'category', 'feeds');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'externalvideo');
        set_field('blocktype_installed_category', 'category', 'external', 'blocktype', 'googleapps');
        // Delete old "feeds" category
        delete_records('blocktype_category', 'name', 'feeds');
    }
    if ($oldversion < 2011051800) {
        // Restore index that may be missing due to upgrade 2011050600.
        $table = new XMLDBTable('usr');
        $index = new XMLDBIndex('usr_use_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
        if (!index_exists($table, $index)) {
            if (is_postgres()) {
                // For postgres, create the index on the lowercase username, the way it's
                // done in core_postinst().
                execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
            } else {
                $index = new XMLDBIndex('usernameuk');
                $index->setAttributes(XMLDB_INDEX_UNIQUE, array('username'));
                add_index($table, $index);
            }
        }
    }
    if ($oldversion < 2011052300) {
        if ($data = check_upgrades("blocktype.googleapps")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011061100) {
        // This block fixes an issue of upgrading from 1.4_STABLE to master
        // version number is date after 1.4_STABLE
        // 2011052400
        // add_field checks if field exists
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // 2011053100
        // add_field checks if field exists
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('defaultquota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        // 2011053101
        // add_field checks if field exists
        $table = new XMLDBTable('group');
        $field = new XMLDBField('quota');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('quotaused');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060700
        // add_field checks if field exists
        $table = new XMLDBTable('view');
        $field = new XMLDBField('retainview');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // 2011060701
        // site setting to limit online users count
        if (!get_config('onlineuserssideblockmaxusers')) {
            set_config('onlineuserssideblockmaxusers', 10);
        }
        // 2011060701
        // add_field checks if field exists
        // instiutional setting to limit online users type
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('showonlineusers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 2);
        add_field($table, $field);
    }
    if ($oldversion < 2011061300) {
        // Add more indexes to the usr table for user searches
        if (is_postgres()) {
            $table = new XMLDBTable('usr');
            $index = new XMLDBIndex('usr_fir_ix');
            $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('firstname', 'lastname', 'preferredname', 'studentid', 'email'));
            if (!index_exists($table, $index)) {
                execute_sql('CREATE INDEX {usr_fir_ix} ON {usr}(LOWER(firstname))');
                execute_sql('CREATE INDEX {usr_las_ix} ON {usr}(LOWER(lastname))');
                execute_sql('CREATE INDEX {usr_pre_ix} ON {usr}(LOWER(preferredname))');
                execute_sql('CREATE INDEX {usr_stu_ix} ON {usr}(LOWER(studentid))');
                execute_sql('CREATE INDEX {usr_ema_ix} ON {usr}(LOWER(email))');
            }
        }
    }
    if ($oldversion < 2011061400) {
        // Add institution to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add shortname to group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('shortnameuk');
        $index->setAttributes(XMLDB_KEY_UNIQUE, array('institution', 'shortname'));
        add_index($table, $index);
    }
    if ($oldversion < 2011061500) {
        // Add favourites
        $table = new XMLDBTable('favorite');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('ownershortuk', XMLDB_INDEX_UNIQUE, array('owner', 'shortname'));
        create_table($table);
        $table = new XMLDBTable('favorite_usr');
        $table->addFieldInfo('favorite', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('favorite,usr'));
        $table->addKeyInfo('favoritefk', XMLDB_KEY_FOREIGN, array('favorite'), 'favorite', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062100) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('allowinstitutionpublicviews');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2011062200) {
        $table = new XMLDBTable('usr_tag');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('usr', 'tag'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2011062300) {
        // Install a cron job to generate the sitemap
        if (!record_exists('cron', 'callfunction', 'cron_sitemap_daily')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_sitemap_daily';
            $cron->minute = '0';
            $cron->hour = '1';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2011062400) {
        // self-registration per institution confrimation setting
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerconfirm');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('pending');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('reason');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2011062700) {
        set_config('dropdownmenu', 0);
    }
    if ($oldversion < 2011070500) {
        // Add profileicon foreign key to artefact table, first clearing any bad profileicon
        // values out of usr.
        execute_sql("\n            UPDATE {usr} SET profileicon = NULL\n            WHERE NOT profileicon IN (SELECT id FROM {artefact} WHERE artefacttype = 'profileicon')");
        $table = new XMLDBTable('usr');
        $key = new XMLDBKey('profileiconfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('profileicon'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011070501) {
        // Add logo to institution table
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('logo');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('logofk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('logo'), 'artefact', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011072200) {
        if (is_postgres()) {
            execute_sql("\n                UPDATE {group}\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    quotaused = f.quotaused\n                FROM (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                WHERE {group}.id = f.id");
        } else {
            execute_sql("\n                UPDATE {group}, (\n                    SELECT g.id AS id, COALESCE(gf.quotaused, 0) AS quotaused\n                    FROM {group} g\n                        LEFT OUTER JOIN (\n                            SELECT a.group, SUM(aff.size) AS quotaused\n                            FROM {artefact} a JOIN {artefact_file_files} aff ON a.id = aff.artefact\n                            WHERE NOT a.group IS NULL\n                            GROUP BY a.group\n                        ) gf ON gf.group = g.id\n                    WHERE g.quota IS NULL AND g.quotaused = 0 AND g.deleted = 0\n                ) f\n                SET quota = CASE WHEN f.quotaused < 52428800 THEN 52428800 ELSE f.quotaused + 52428800 END,\n                    {group}.quotaused = f.quotaused\n                WHERE {group}.id = f.id");
        }
    }
    if ($oldversion < 2011072600) {
        // Add tables to store custom institution styles
        // Currently only institutions can use them, but merge this with skin tables later...
        $table = new XMLDBTable('style');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('css', XMLDB_TYPE_TEXT);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('style_property');
        $table->addFieldInfo('style', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('style', 'field'));
        $table->addKeyInfo('stylefk', XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        create_table($table);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('style');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('stylefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('style'), 'style', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2011082200) {
        // Doing a direct insert of the new artefact type instead of running upgrade_plugin(), in order to support the
        // transition from old profile fields to the new socialprofile artefact in Mahara 1.10
        if (!record_exists('artefact_installed_type', 'name', 'html', 'plugin', 'internal')) {
            insert_record('artefact_installed_type', (object) array('name' => 'html', 'plugin' => 'internal'));
        }
        // Move the textbox blocktype into artefact/internal
        set_field('blocktype_installed', 'artefactplugin', 'internal', 'name', 'textbox');
        if ($data = check_upgrades("blocktype.internal/textbox")) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2011082300) {
        // Add institution to view_access table
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
            // Add foreign key
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            if (is_postgres()) {
                // Update constraint checks
                execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {view_access_check}');
                execute_sql('ALTER TABLE {view_access} ADD CHECK (
                    (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL     AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL AND institution IS NULL    ) OR
                    (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NULL     AND institution IS NOT NULL))');
            } else {
                // MySQL doesn't support these types of constraints
            }
        }
    }
    if ($oldversion < 2011082400) {
        // Add cron entry for cache cleanup
        $cron = new StdClass();
        $cron->callfunction = 'file_cleanup_old_cached_files';
        $cron->minute = '0';
        $cron->hour = '1';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011082401) {
        // Set config value for logged-in profile view access
        set_config('loggedinprofileviewaccess', 1);
    }
    if ($oldversion < 2011083000) {
        // Jointype changes
        $table = new XMLDBTable('group');
        $field = new XMLDBField('request');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('group', 'request', 1, 'jointype', 'request');
        // Turn all request & invite groups into the 'approve' type
        $field = new XMLDBField('jointype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'request', 'invite', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        set_field('group', 'jointype', 'approve', 'jointype', 'request');
        set_field('group', 'jointype', 'approve', 'jointype', 'invite');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('open', 'controlled', 'approve'), 'open');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} DROP CONSTRAINT {grou_joi_ck}');
        }
        change_field_enum($table, $field);
        // Move view submission from grouptype to group
        $field = new XMLDBField('submittableto');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        execute_sql("UPDATE {group} SET submittableto = 1 WHERE grouptype IN (SELECT name FROM {grouptype} WHERE submittableto = 1)");
        $table = new XMLDBTable('grouptype');
        $field = new XMLDBField('submittableto');
        drop_field($table, $field);
        // Any group can potentially take submissions, so make sure someone can assess them
        set_field('grouptype_roles', 'see_submitted_views', 1, 'role', 'admin');
        // Move group view editing permission from grouptype_roles to the group table
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editroles');
        $field->setAttributes(XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('all', 'notmember', 'admin'), 'all');
        add_field($table, $field);
        execute_sql("\n            UPDATE {group} SET editroles = 'notmember' WHERE grouptype IN (\n                SELECT grouptype FROM {grouptype_roles} WHERE role = 'member' AND edit_views = 0\n            )");
        $table = new XMLDBTable('grouptype_roles');
        $field = new XMLDBField('edit_views');
        drop_field($table, $field);
    }
    if ($oldversion < 2011090900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('password');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        change_field_type($table, $field, true, true);
    }
    if ($oldversion < 2011091200) {
        // Locked group views (only editable by group admins)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('locked');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_field('view', 'locked', 1, 'type', 'grouphomepage');
        // Setting to hide groups from the "Find Groups" listing
        $table = new XMLDBTable('group');
        $field = new XMLDBField('hidden');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members
        $field = new XMLDBField('hidemembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Setting to hide group members from members
        $field = new XMLDBField('hidemembersfrommembers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to invite friends
        $field = new XMLDBField('invitefriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Allow group members to recommend the group to friends
        $field = new XMLDBField('suggestfriends');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2011091300) {
        $table = new XMLDBTable('blocktype_category');
        $field = new XMLDBField('sort');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('0', 'fileimagevideo'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('1', 'blog'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('2', 'general'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('3', 'internal'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('4', 'resume'));
        execute_sql("UPDATE {blocktype_category} SET sort = ? WHERE name = ?", array('5', 'external'));
        $index = new XMLDBIndex('sortuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('sort'));
        add_index($table, $index, false);
    }
    if ($oldversion < 2011092600) {
        // Move the taggedposts blocktype into artefact/blog/blocktype
        set_field('blocktype_installed', 'artefactplugin', 'blog', 'name', 'taggedposts');
    }
    if ($oldversion < 2011102700) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('logintries');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Every 5 minutes, reset everyone's login attempts to 0
        $cron = new StdClass();
        $cron->callfunction = 'user_login_tries_to_zero';
        $cron->minute = '*/5';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2011111500) {
        $table = new XMLDBTable('blocktype_installed_category');
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('blocktype'));
        add_key($table, $key);
    }
    if ($oldversion < 2011120200) {
        if ($data = check_upgrades('blocktype.blog/taggedposts')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.watchlist')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2012011300) {
        $table = new XMLDBTable('group_member');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
    }
    if ($oldversion < 2012021000) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('unread');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012021700) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012022100) {
        reload_html_filters();
    }
    if ($oldversion < 2012042600 && !table_exists(new XMLDBTable('iframe_source'))) {
        // Tables for configurable safe iframe sources
        $table = new XMLDBTable('iframe_source_icon');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('domain', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $iframedomains = array('YouTube' => 'www.youtube.com', 'Vimeo' => 'vimeo.com', 'SlideShare' => 'www.slideshare.net', 'Glogster' => 'www.glogster.com', 'WikiEducator' => 'wikieducator.org', 'Voki' => 'voki.com');
        foreach ($iframedomains as $name => $domain) {
            insert_record('iframe_source_icon', (object) array('name' => $name, 'domain' => $domain));
        }
        $table = new XMLDBTable('iframe_source');
        $table->addFieldInfo('prefix', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('prefix'));
        $table->addKeyInfo('namefk', XMLDB_KEY_FOREIGN, array('name'), 'iframe_source_icon', array('name'));
        create_table($table);
        $iframesources = array('www.youtube.com/embed/' => 'YouTube', 'player.vimeo.com/video/' => 'Vimeo', 'www.slideshare.net/slideshow/embed_code/' => 'SlideShare', 'www.glogster.com/glog/' => 'Glogster', 'www.glogster.com/glog.php' => 'Glogster', 'edu.glogster.com/glog/' => 'Glogster', 'edu.glogster.com/glog.php' => 'Glogster', 'wikieducator.org/index.php' => 'WikiEducator', 'voki.com/php/' => 'Voki');
        foreach ($iframesources as $prefix => $name) {
            insert_record('iframe_source', (object) array('prefix' => $prefix, 'name' => $name));
        }
        $iframeregexp = '%^https?://(' . str_replace('.', '\\.', implode('|', array_keys($iframesources))) . ')%';
        set_config('iframeregexp', $iframeregexp);
    }
    if ($oldversion < 2012042800) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('extra');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2012051500) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('authtype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 'internal');
        add_field($table, $field);
        $key = new XMLDBKey('authtype');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('authtype'), 'auth_installed', array('name'));
        add_key($table, $key);
    }
    if ($oldversion < 2012053100) {
        // Clean url fields for usr, group, and view tables.
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 30, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid'));
        add_index($table, $index);
        $table = new XMLDBTable('view');
        $field = new XMLDBField('urlid');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('urliduk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('urlid', 'owner', 'group', 'institution'));
        add_index($table, $index);
    }
    if ($oldversion < 2012060100) {
        // Collection submission
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedgroup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $key = new XMLDBKey('submittedgroupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedgroup'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('submittedhostfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('submittedhost'), 'host', array('wwwroot'));
        add_key($table, $key);
    }
    if ($oldversion < 2012062900) {
        // Add site registration data tables
        $table = new XMLDBTable('site_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('site_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'site_registration', array('id'));
        create_table($table);
    }
    if ($oldversion < 2012062901) {
        // Add institution registration data tables
        $table = new XMLDBTable('institution_registration');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        $table = new XMLDBTable('institution_registration_data');
        $table->addFieldInfo('registration_id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('registration_id', 'field'));
        $table->addKeyInfo('regdatafk', XMLDB_KEY_FOREIGN, array('registration_id'), 'institution_registration', array('id'));
        create_table($table);
        // Install a cron job to collection institution registration data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_registration_data';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = rand(0, 6);
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012062902) {
        // Add institution stats table
        $table = new XMLDBTable('institution_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'institution', 'type'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        create_table($table);
        // Insert cron jobs to save institution data
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_institution_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012070200) {
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        add_field($table, $field);
        $field = new XMLDBField('owner');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        change_field_notnull($table, $field);
        // For PostgresSQL, change_field_notnull of $field=owner with precision = 10 BIGINT(10)
        // will add a temporary column, move data from owner column, remove the column 'owner'
        // and then rename the temporary column to 'owner'. Therefore, all indexes and foreign keys
        // related to column 'owner' will be removed
        if (is_postgres()) {
            $key = new XMLDBKey('owner');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
            add_key($table, $key);
        }
        $key = new XMLDBKey('group');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('institution');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // Add constraints
        execute_sql('ALTER TABLE {collection} ADD CHECK (
            (owner IS NOT NULL AND "group" IS NULL     AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NOT NULL AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NULL     AND institution IS NOT NULL)
        )');
    }
    if ($oldversion < 2012070300) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('groupparticipationreports');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2012080200) {
        $sql = "\n            FROM {usr} u JOIN {auth_instance} ai ON (u.authinstance = ai.id)\n            WHERE u.deleted = 0 AND ai.authname = 'internal' AND u.password != '*' AND u.salt != '*'\n            AND u.password NOT LIKE '\$%'";
        $pwcount = count_records_sql("SELECT COUNT(*) " . $sql);
        $sql = "\n            SELECT u.id, u.password, u.salt" . $sql . " AND u.id > ?\n            ORDER BY u.id";
        $done = 0;
        $lastid = 0;
        $limit = 2000;
        while ($users = get_records_sql_array($sql, array($lastid), 0, $limit)) {
            foreach ($users as $user) {
                // Wrap the old hashed password inside a SHA512 hash ($6$ is the identifier for SHA512)
                $user->password = crypt($user->password, '$6$' . substr(md5(get_config('passwordsaltmain') . $user->salt), 0, 16));
                // Drop the salt from the password as it may contain secrets that are not stored in the db
                // for example, the passwordsaltmain value
                $user->password = substr($user->password, 0, 3) . substr($user->password, 3 + 16);
                set_field('usr', 'password', $user->password, 'id', $user->id);
                remove_user_sessions($user->id);
                $lastid = $user->id;
            }
            $done += count($users);
            log_debug("Upgrading stored passwords: {$done}/{$pwcount}");
            set_time_limit(30);
        }
    }
    if ($oldversion < 2012080300) {
        // For multi-tokens we need '|' aka pipe characters either side of their old single token
        execute_sql('UPDATE {usr_account_preference} SET value = \'|\' || value || \'|\'
                            WHERE field=\'mobileuploadtoken\' AND NOT value ' . db_ilike() . '\'|%|\'');
    }
    if ($oldversion < 2012080600) {
        // Every minute, poll an imap mailbox to see if there are new mail bounces
        $cron = new StdClass();
        $cron->callfunction = 'check_imap_for_bounces';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2012080601) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('editwindowstart');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
        $field = new XMLDBField('editwindowend');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $field);
    }
    if ($oldversion < 2013011700) {
        set_config('defaultregistrationexpirylifetime', 1209600);
    }
    if ($oldversion < 2013012100) {
        $event = (object) array('name' => 'loginas');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2013012101) {
        $table = new XMLDBTable('event_log');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('realusr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('data', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('realusrfk', XMLDB_KEY_FOREIGN, array('realusr'), 'usr', array('id'));
        create_table($table);
        $cron = new StdClass();
        $cron->callfunction = 'cron_event_log_expire';
        $cron->minute = 7;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2013020500) {
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('license');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensor');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensorurl');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('licensedefault');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255);
        add_field($table, $field);
        $field = new XMLDBField('licensemandatory');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $table = new XMLDBTable('artefact_license');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('icon', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
    }
    if ($oldversion < 2013020501) {
        require_once 'license.php';
        install_licenses_default();
    }
    if ($oldversion < 2013032202) {
        require_once get_config('libroot') . 'license.php';
        set_field('usr_account_preference', 'value', LICENSE_INSTITUTION_DEFAULT, 'field', 'licensedefault', 'value', '-');
    }
    if ($oldversion < 2013050700) {
        $table = new XMLDBTable('collection_tag');
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('tag', XMLDB_TYPE_CHAR, 128, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('collection', 'tag'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013062600) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('dropdownmenu');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2013081400) {
        // We've made a change to how update_safe_iframe_regex() generates the regex
        // Call this function to make sure the stored value reflects that change.
        update_safe_iframe_regex();
    }
    if ($oldversion < 2013082100) {
        log_debug('Update database for flexible page layouts feature');
        log_debug('1. Create table view_rows_columns');
        $table = new XMLDBTable('view_rows_columns');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        log_debug('2. Remake the table view_layout as view_layout_columns');
        $table = new XMLDBTable('view_layout_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('widths', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('columnwidthuk', XMLDB_KEY_UNIQUE, array('columns', 'widths'));
        create_table($table);
        log_debug('3. Alter table view_layout');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('rows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        $field = new XMLDBField('iscustom');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('layoutmenuorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug('4. Create table view_layout_rows_columns');
        $table = new XMLDBTable('view_layout_rows_columns');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('viewlayout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('row', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('columns', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('rowfk', XMLDB_KEY_FOREIGN, array('viewlayout'), 'view_layout', array('id'));
        $table->addKeyInfo('columnsfk', XMLDB_KEY_FOREIGN, array('columns'), 'view_layout_columns', array('id'));
        create_table($table);
        log_debug('5. Create table usr_custom_layout');
        $table = new XMLDBTable('usr_custom_layout');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('layout', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('layoutfk', XMLDB_KEY_FOREIGN, array('layout'), 'view_layout', array('id'));
        create_table($table);
        log_debug('6. Convert existing view_layout records into new-style view_layouts with just one row');
        $oldlayouts = get_records_array('view_layout', '', '', 'id', 'id, columns, widths');
        foreach ($oldlayouts as $layout) {
            // We don't actually need to populate the "rows", "iscustom" or "layoutmenuorder" columns,
            // because their defaults take care of that.
            // Check to see if there's a view_layout_columns record that matches its widths.
            $colsid = get_field('view_layout_columns', 'id', 'widths', $layout->widths);
            if (!$colsid) {
                $colsid = insert_record('view_layout_columns', (object) array('columns' => $layout->columns, 'widths' => $layout->widths), 'id', true);
            }
            // Now insert a record for it in view_layout_rows_columns, to represent its one row
            insert_record('view_layout_rows_columns', (object) array('viewlayout' => $layout->id, 'row' => 1, 'columns' => $colsid));
            // And also it needs a record in usr_custom_layout saying it belongs to the root user
            insert_record('usr_custom_layout', (object) array('usr' => 0, 'layout' => $layout->id));
        }
        log_debug('7. Drop the obsolete view_layout.columns and view_layout.widths fields');
        $table = new XMLDBTable('view_layout');
        $field = new XMLDBField('columns');
        drop_field($table, $field);
        $field = new XMLDBField('widths');
        drop_field($table, $field);
        log_debug('8. Update default values for tables view_layout, view_layout_columns and view_layout_rows_columns');
        install_view_layout_defaults();
        log_debug('9. Update the table "block_instance"');
        $table = new XMLDBTable('block_instance');
        $field = new XMLDBField('row');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        // This one tends to take a while...
        set_time_limit(30);
        add_field($table, $field);
        set_time_limit(30);
        // Refactor the block_instance.viewcolumnorderuk key so it includes row.
        $key = new XMLDBKey('viewcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'column', 'order'));
        // If this particular site has been around since before Mahara 1.2, this
        // will actually have been created as a unique index rather than a unique
        // key, so check for that first.
        $indexname = find_index_name($table, $key);
        if (preg_match('/uix$/', $indexname)) {
            $index = new XMLDBIndex($indexname);
            $index->setAttributes(XMLDB_INDEX_UNIQUE, array('view', 'column', 'order'));
            drop_index($table, $index);
        } else {
            drop_key($table, $key);
        }
        $key = new XMLDBKey('viewrowcolumnorderuk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('view', 'row', 'column', 'order'));
        add_key($table, $key);
        log_debug('10. Add a "numrows" column to the views table.');
        // The default value of "1" will be correct
        // for all existing views, because they're using the old one-row layout style
        $table = new XMLDBTable('view');
        $field = new XMLDBField('numrows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        log_debug('11. Update the table "view_rows_columns" for existing pages');
        execute_sql('INSERT INTO {view_rows_columns} ("view", "row", "columns") SELECT v.id, 1, v.numcolumns FROM {view} v');
    }
    if ($oldversion < 2013091900) {
        // Create skin table...
        $table = new XMLDBTable('skin');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 10, 'private', XMLDB_NOTNULL);
        $table->addFieldInfo('viewskin', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('bodybgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('viewbgimg', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('ownerfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // Create skin_favorites table...
        $table = new XMLDBTable('skin_favorites');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('user', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('favorites', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userfk', XMLDB_KEY_FOREIGN, array('user'), 'usr', array('id'));
        create_table($table);
        // Create skin_fonts table...
        $table = new XMLDBTable('skin_fonts');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('licence', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('notice', XMLDB_TYPE_TEXT);
        $table->addFieldInfo('previewfont', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('variants', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('fonttype', XMLDB_TYPE_CHAR, 10, 'site', XMLDB_NOTNULL);
        $table->addFieldInfo('onlyheading', XMLDB_TYPE_INTEGER, 1, 0, XMLDB_NOTNULL);
        $table->addFieldInfo('fontstack', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('genericfont', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('cursive', 'fantasy', 'monospace', 'sans-serif', 'serif'));
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('nameuk', XMLDB_KEY_UNIQUE, array('name'));
        create_table($table);
        // Set column 'skin' to 'view' table...
        $table = new XMLDBTable('view');
        $field = new XMLDBField('skin');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        require_once get_config('libroot') . 'skin.php';
        install_skins_default();
    }
    if ($oldversion < 2013091901) {
        // Add a "skins" table to institutions to record whether they've enabled skins or not
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('skins');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1, 'dropdownmenu');
        add_field($table, $field);
    }
    if ($oldversion < 2013092300) {
        $table = new XMLDBTable('import_entry_requests');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('importid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryid', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entryparent', XMLDB_TYPE_CHAR, 255, null, null);
        $table->addFieldInfo('strategy', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ownerid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytype', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrytitle', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('entrycontent', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('duplicateditemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('existingitemids', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('artefactmapping', XMLDB_TYPE_TEXT, null, null, null);
        $table->addFieldInfo('decision', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('owneridfk', XMLDB_KEY_FOREIGN, array('ownerid'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2013092600) {
        //  When uploading file as attachment and attaching it to an artefact, the artefact id
        //  (in artefact field) and uploaded file artefact id (in attachment filed) are stored.
        //  For Resume composite types (educationhistory, employmenthistory, books, etc.) this
        //  is not enough. So we have to add item field to differentiate between e.g. different
        //  employments in employmenhistory and to which employment the user actually whishes to
        //  attach certain attachment...
        $table = new XMLDBTable('artefact_attachment');
        $field = new XMLDBField('item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
    }
    if ($oldversion < 2013112100) {
        // Add a new column 'last_processed_userid' to the table 'activity_queue' in order to
        // split multiple user activity notifications into chunks
        $table = new XMLDBTable('activity_queue');
        $field = new XMLDBField('last_processed_userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('last_processed_useridfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('last_processed_userid'), 'usr', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2013112600) {
        // If a mahara site was upgraded from 1.0 then keys for the following tables
        // may be missing so we will check for them and if missing add them.
        // Normally when we create a foreign key, we create an index alongside it.
        // If these keys were created by the 1.1 upgrade script, they will be missing
        // those indexes. To get the index and the key in place, we have to re-create
        // the key.
        $table = new XMLDBTable('artefact_access_usr');
        $index = new XMLDBIndex('usrfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('usr'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.usr column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('usrfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.usr referencing usr.id (the column probably contains some nonexistent user id's");
            }
        }
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_usr.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_usr.artefact referencing artefact.id (the column probably contains some nonexistent artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('usr', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_usr across columns (usr, artefact). (Probably the table contains some non-unique values in those columns)");
            }
        }
        $table = new XMLDBTable('artefact_access_role');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('artefact');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change artefact_access_role.artefact column to NOT NULL (it probably contains some NULL values)");
            }
            $key = new XMLDBKey('artefactfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column artefact_access_role.artefact referencing artefact.id (the column probably contains some nonexistente artefact id's)");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('role', 'artefact'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table artefact_access_role across columns (role, artefact). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('artefact_attachment');
        $index = new XMLDBIndex('artefactfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        if (!index_exists($table, $index)) {
            try {
                add_index($table, $index);
            } catch (SQLException $e) {
                log_warn("Couldn't set a non-unique index on column artefact_attachment.artefact");
            }
        }
        $table = new XMLDBTable('group');
        $key = new XMLDBKey('grouptypefk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column group.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes)");
            }
        }
        $table = new XMLDBTable('grouptype_roles');
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column grouptype_roles.grouptype referencing grouptype.name (the column probably contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('grouptype', 'role'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table grouptype_roles across columns (grouptype, role). (Probably there are some non-unique values in those columns.)");
            }
        }
        $table = new XMLDBTable('view_autocreate_grouptype');
        $index = new XMLDBIndex('viewfk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('view'));
        if (!index_exists($table, $index)) {
            $field = new XMLDBField('view');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            try {
                change_field_type($table, $field, true, true);
            } catch (SQLException $e) {
                log_warn("Couldn't change column view_autocreate_grouptype.view to NOT NULL (probably the column contains some NULL values)");
            }
            $key = new XMLDBKey('viewfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.view referencing view.id (probably the column contains some nonexistent view IDs");
            }
        }
        $index = new XMLDBIndex('grouptypefk');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('grouptype'));
        if (!index_exists($table, $index)) {
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a foreign key on column view_autocreate_grouptype.grouptype referencing grouptype.name (probably the column contains some nonexistent grouptypes");
            }
        }
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('view', 'grouptype'));
        if (!db_key_exists($table, $key)) {
            try {
                add_key($table, $key);
            } catch (SQLException $e) {
                log_warn("Couldn't set a primary key on table view_autocreate_grouptype across columns (view, grouptype). (Probably those columns contain some non-unique values.)");
            }
        }
    }
    if ($oldversion < 2013121300) {
        // view_rows_columns can be missing the 'id' column if upgrading from version
        // earlier than v1.8 and because we are adding a sequential primary column after
        // the table is already made we need to
        // - check that the column doesn't exist then add it without key or sequence
        // - update the values for the new id column to be sequential
        // - then add the primary key and finally make the column sequential
        if ($records = get_records_sql_array('SELECT * FROM {view_rows_columns}', array())) {
            if (empty($records[0]->id)) {
                $table = new XMLDBTable('view_rows_columns');
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'view');
                add_field($table, $field);
                $x = 1;
                foreach ($records as $record) {
                    execute_sql('UPDATE {view_rows_columns} SET id = ? WHERE view = ? AND row = ? AND columns = ?', array($x, $record->view, $record->row, $record->columns));
                    $x++;
                }
                // we can't add a sequence on a field unless it has a primary key
                $key = new XMLDBKey('primary');
                $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                add_key($table, $key);
                $field = new XMLDBField('id');
                $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
                change_field_type($table, $field);
                // but when we change field type postgres drops the keys for the column so we need
                // to add the primary key back again - see line 2205 for more info
                if (is_postgres()) {
                    $key = new XMLDBKey('primary');
                    $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
                    add_key($table, $key);
                }
            }
        }
    }
    if ($oldversion < 2014010700) {
        // If the usr_custom_layout.group column exists, it indicates that we this patch has already
        // been run and we should skip it.
        $table = new XMLDBTable('usr_custom_layout');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
        if (!field_exists($table, $field)) {
            // Add a log output line here so that we can tell whether this patch ran or not.
            log_debug('Correcting custom layout table structures.');
            // fix issue where custom layouts saved in groups, site pages and institutions
            // were set to have usr = 0 because view owner was null
            $table = new XMLDBTable('usr_custom_layout');
            $field = new XMLDBField('usr');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
            change_field_notnull($table, $field);
            // For PostgresSQL, change_field_notnull creates a temporary column, moves data to new temp column
            // and then renames the temp column to 'usr'. Therefore, all indexes and foreign keys
            // related to column 'owner' will be removed
            if (is_postgres()) {
                $key = new XMLDBKey('usr');
                $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
                add_key($table, $key);
            }
            $field = new XMLDBField('group');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, 'usr');
            add_field($table, $field);
            $key = new XMLDBKey('groupfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
            add_key($table, $key);
            $field = new XMLDBField('institution');
            $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null, 'group');
            add_field($table, $field);
            $key = new XMLDBKey('institutionfk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
            add_key($table, $key);
            // update previous records
            // get custom layouts with usr = 0 which are not in default set
            $groupcustomlayouts = get_records_sql_array('SELECT ucl.layout FROM {usr_custom_layout} ucl
                                                         LEFT JOIN {view_layout} vl ON vl.id = ucl.layout
                                                         WHERE usr = 0 AND iscustom = 1
                                                         ORDER BY ucl.id', array());
            if ($groupcustomlayouts != false) {
                foreach ($groupcustomlayouts as $groupcustomlayout) {
                    // find views using this custom layout
                    $views = get_records_array('view', 'layout', $groupcustomlayout->layout, '', 'owner, "group", institution');
                    if ($views != false) {
                        foreach ($views as $view) {
                            if (isset($view->owner)) {
                                // view owned by individual
                                $recordexists = get_record('usr_custom_layout', 'usr', $view->owner, 'layout', $groupcustomlayout->layout);
                                if (!$recordexists) {
                                    // add new record into usr_custom_layout table
                                    $customlayout = new stdClass();
                                    $customlayout->usr = $view->owner;
                                    $customlayout->layout = $groupcustomlayout->layout;
                                    insert_record('usr_custom_layout', $customlayout, 'id');
                                }
                            } else {
                                if (isset($view->group)) {
                                    // view owned by group
                                    $recordexists = get_record('usr_custom_layout', 'group', $view->group, 'layout', $groupcustomlayout->layout);
                                    if (!$recordexists) {
                                        // add new record into usr_custom_layout table
                                        $customlayout = new stdClass();
                                        $customlayout->group = $view->group;
                                        $customlayout->layout = $groupcustomlayout->layout;
                                        insert_record('usr_custom_layout', $customlayout, 'id');
                                    }
                                } else {
                                    if (isset($view->institution)) {
                                        // view owned by group
                                        $recordexists = get_record('usr_custom_layout', 'institution', $view->institution, 'layout', $groupcustomlayout->layout);
                                        if (!$recordexists) {
                                            // add new record into usr_custom_layout table
                                            $customlayout = new stdClass();
                                            $customlayout->institution = $view->institution;
                                            $customlayout->layout = $groupcustomlayout->layout;
                                            insert_record('usr_custom_layout', $customlayout, 'id');
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // now remove this custom layout
                    $removedrecords = delete_records('usr_custom_layout', 'usr', '0', 'layout', $groupcustomlayout->layout);
                }
            }
        }
    }
    if ($oldversion < 2014010800) {
        $table = new XMLDBTable('institution_config');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('instfielduk', XMLDB_INDEX_UNIQUE, array('institution', 'field'));
        create_table($table);
    }
    if ($oldversion < 2014010801) {
        // adding institution column to allow for different site content for each institution
        $table = new XMLDBTable('site_content');
        $field = new XMLDBField('institution');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        // resetting the primary key and updating what is currently there to be
        // the 'mahara' institution's site pages
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name'));
        drop_key($table, $key);
        execute_sql("UPDATE {site_content} SET institution = ?", array('mahara'));
        $key = new XMLDBKey('primary');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('name', 'institution'));
        add_key($table, $key);
        $key = new XMLDBKey('institutionfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        add_key($table, $key);
        // now add the default general pages for each existing institution with the values of
        // the 'mahara' institution. These can them be altered via Administration -> Institutions -> General pages
        $sitecontentarray = array();
        $sitecontents = get_records_array('site_content', 'institution', 'mahara');
        foreach ($sitecontents as $sitecontent) {
            $sitecontentarray[$sitecontent->name] = $sitecontent->content;
        }
        $pages = site_content_pages();
        $now = db_format_timestamp(time());
        $institutions = get_records_array('institution');
        foreach ($institutions as $institution) {
            if ($institution->name != 'mahara') {
                foreach ($pages as $name) {
                    $page = new stdClass();
                    $page->name = $name;
                    $page->ctime = $now;
                    $page->mtime = $now;
                    $page->content = $sitecontentarray[$name];
                    $page->institution = $institution->name;
                    insert_record('site_content', $page);
                    $pageconfig = new stdClass();
                    $pageconfig->institution = $institution->name;
                    $pageconfig->field = 'sitepages_' . $name;
                    $pageconfig->value = 'mahara';
                    insert_record('institution_config', $pageconfig);
                }
            }
        }
    }
    if ($oldversion < 2014021100) {
        // Reset the view's skin value, if the skin does not exist
        execute_sql("UPDATE {view} v SET skin = NULL WHERE v.skin IS NOT NULL AND NOT EXISTS (SELECT id FROM {skin} s WHERE v.skin = s.id)");
    }
    if ($oldversion < 2014021200) {
        // Adding new Creative Commons 4.0 licenses.
        // CC4.0 will be added only if:
        // -- The CC4.0 URL doesn't already exist;
        // -- And CC3.0 hasn't been deleted earlier.
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebysa', 'install');
        $license->shortname = get_string('licenseshortnamebysa', 'install');
        $license->icon = 'license:by-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by/4.0/';
        $license->displayname = get_string('licensedisplaynameby', 'install');
        $license->shortname = get_string('licenseshortnameby', 'install');
        $license->icon = 'license:by.png';
        $version30 = 'http://creativecommons.org/licenses/by/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebynd', 'install');
        $license->shortname = get_string('licenseshortnamebynd', 'install');
        $license->icon = 'license:by-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-sa/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncsa', 'install');
        $license->shortname = get_string('licenseshortnamebyncsa', 'install');
        $license->icon = 'license:by-nc-sa.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-sa/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc/4.0/';
        $license->displayname = get_string('licensedisplaynamebync', 'install');
        $license->shortname = get_string('licenseshortnamebync', 'install');
        $license->icon = 'license:by-nc.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
        $license = new stdClass();
        $license->name = 'http://creativecommons.org/licenses/by-nc-nd/4.0/';
        $license->displayname = get_string('licensedisplaynamebyncnd', 'install');
        $license->shortname = get_string('licenseshortnamebyncnd', 'install');
        $license->icon = 'license:by-nc-nd.png';
        $version30 = 'http://creativecommons.org/licenses/by-nc-nd/3.0/';
        if (!record_exists('artefact_license', 'name', $license->name) && record_exists('artefact_license', 'name', $version30)) {
            insert_record('artefact_license', $license);
        }
    }
    if ($oldversion < 2014022400) {
        // Make sure artefacts are properly locked for submitted views.
        // Can be a problem for older sites
        $submitted = get_records_sql_array("SELECT v.owner FROM {view_artefact} va\n                        LEFT JOIN {view} v on v.id = va.view\n                        LEFT JOIN {artefact} a on a.id = va.artefact\n                        WHERE (v.submittedgroup IS NOT NULL OR v.submittedhost IS NOT NULL)", array());
        if ($submitted) {
            require_once get_config('docroot') . 'artefact/lib.php';
            foreach ($submitted as $record) {
                ArtefactType::update_locked($record->owner);
            }
        }
    }
    if ($oldversion < 2014022600) {
        $table = new XMLDBTable('host');
        $field = new XMLDBField('portno');
        drop_field($table, $field);
    }
    if ($oldversion < 2014032400) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('sendnow');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032500) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('probation');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2014032600) {
        set_config('watchlistnotification_delay', 20);
        if (!table_exists(new XMLDBTable('watchlist_queue'))) {
            $table = new XMLDBTable('watchlist_queue');
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('block', XMLDB_TYPE_INTEGER, 10, null, false);
            $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
            $table->addFieldInfo('changed_on', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
            $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
            $table->addKeyInfo('blockfk', XMLDB_KEY_FOREIGN, array('block'), 'block_instance', array('id'));
            $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            create_table($table);
        }
        // new event type: delete blockinstance
        $e = new stdClass();
        $e->name = 'deleteblockinstance';
        ensure_record_exists('event_type', $e, $e);
        // install the core event subscriptions
        $subs = array(array('event' => 'blockinstancecommit', 'callfunction' => 'watchlist_record_changes'), array('event' => 'deleteblockinstance', 'callfunction' => 'watchlist_block_deleted'), array('event' => 'saveartefact', 'callfunction' => 'watchlist_record_changes'), array('event' => 'saveview', 'callfunction' => 'watchlist_record_changes'));
        foreach ($subs as $sub) {
            ensure_record_exists('event_subscription', (object) $sub, (object) $sub);
        }
        // install the cronjobs...
        $cron = new stdClass();
        $cron->callfunction = 'watchlist_process_notifications';
        $cron->minute = '*';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014032700) {
        // Remove bad data created by the upload user via csv where users in no institution
        // have 'licensedefault' set causing an error
        execute_sql("DELETE FROM {usr_account_preference} WHERE FIELD = 'licensedefault' AND usr IN (\n                        SELECT u.id FROM {usr} u\n                        LEFT JOIN {usr_institution} ui ON ui.usr = u.id\n                        WHERE ui.institution = 'mahara' OR ui.institution is null\n                     )");
    }
    if ($oldversion < 2014040300) {
        // Figure out where the magicdb is, and stick with that.
        require_once get_config('libroot') . 'file.php';
        update_magicdb_path();
    }
    // Add id field and corresponding index to institution table.
    if ($oldversion < 2014040400) {
        $table = new XMLDBTable('institution');
        // Add id field.
        $field = new XMLDBField('id');
        if (!field_exists($table, $field)) {
            // Field.
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 1, 'name');
            add_field($table, $field);
            // Update ids.
            $institutions = get_records_array('institution');
            $x = 1;
            foreach ($institutions as $institution) {
                execute_sql('UPDATE {institution} SET id = ? WHERE name = ?', array($x, $institution->name));
                $x++;
            }
            $key = new XMLDBKey('inst_id_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
            add_key($table, $key);
            // Add sequence.
            $field = new XMLDBField('id');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
            change_field_type($table, $field);
            // In postgres, keys and indexes are removed when a field is changed ("Add sequence" above), so add the key back.
            if (is_postgres()) {
                $key = new XMLDBKey('inst_id_uk');
                $key->setAttributes(XMLDB_KEY_UNIQUE, array('id'));
                add_key($table, $key);
            }
        }
    }
    if ($oldversion < 2014041401) {
        $table = new XMLDBTable('institution');
        $field = new XMLDBField('registerallowed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, '0');
        change_field_default($table, $field);
    }
    if ($oldversion < 2014041600) {
        // Add allownonemethod and defaultmethod fields to activity_type table.
        $table = new XMLDBTable('activity_type');
        $field = new XMLDBField('allownonemethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL, null, null, null, 1, 'delay');
        add_field($table, $field);
        $field = new XMLDBField('defaultmethod');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, 'email', 'allownonemethod');
        add_field($table, $field);
        // Allow null method in usr_activity_preference.
        // Null indicates "none", no record indicates "not yet set" so use the default.
        $table = new XMLDBTable('usr_activity_preference');
        $field = new XMLDBField('method');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null, null, null, null, null);
        change_field_notnull($table, $field);
    }
    // Add about me block to existing profile template.
    if ($oldversion < 2014043000) {
        $systemprofileviewid = get_field('view', 'id', 'owner', 0, 'type', 'profile');
        // Find out how many blocks already exist.
        $maxorder = get_field_sql('select max("order") from {block_instance} where "view"=? and "row"=? and "column"=?', array($systemprofileviewid, 1, 1));
        // Create the block at the end of the cell.
        require_once get_config('docroot') . 'blocktype/lib.php';
        $aboutme = new BlockInstance(0, array('blocktype' => 'profileinfo', 'title' => get_string('aboutme', 'blocktype.internal/profileinfo'), 'view' => $systemprofileviewid, 'row' => 1, 'column' => 1, 'order' => $maxorder + 1));
        $aboutme->commit();
        // Move the block to the start of the cell.
        require_once get_config('libroot') . 'view.php';
        $view = new View($systemprofileviewid);
        $view->moveblockinstance(array('id' => $aboutme->get('id'), 'row' => 1, 'column' => 1, 'order' => 1));
    }
    if ($oldversion < 2014050901) {
        require_once get_config('docroot') . 'artefact/lib.php';
        // First drop artefact_parent_cache table.
        $table = new XMLDBTable('artefact_parent_cache');
        drop_table($table, true);
        // Remove cron jobs from DB.
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_dirty');
        delete_records('cron', 'callfunction', 'rebuild_artefact_parent_cache_complete');
        // Add path field to artefact table.
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '1024', null, null, null, null, null);
        add_field($table, $field);
        // Fill the new field with path data.
        // Set all artefacts to the path they'd have if they have no parent.
        log_debug('Filling in parent artefact paths');
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug('Dropping elasticsearch artefact triggers');
            require_once get_config('docroot') . 'search/elasticsearch/lib.php';
            ElasticsearchIndexing::drop_triggers('artefact');
        }
        $count = 0;
        $limit = 1000;
        $limitsmall = 200;
        $total = count_records_select('artefact', 'path IS NULL AND parent IS NULL');
        for ($i = 0; $i <= $total; $i += $limitsmall) {
            if (is_mysql()) {
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall);
            } else {
                // Postgres can only handle limit in subquery
                execute_sql("UPDATE {artefact} SET path = CONCAT('/', id) WHERE id IN (SELECT id FROM {artefact} WHERE path IS NULL AND parent IS NULL LIMIT " . $limitsmall . ")");
            }
            $count += $limitsmall;
            if ($count % $limit == 0 || $count >= $total) {
                if ($count > $total) {
                    $count = $total;
                }
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
        $newcount = count_records_select('artefact', 'path IS NULL');
        if ($newcount) {
            $childlevel = 0;
            do {
                $childlevel++;
                $lastcount = $newcount;
                log_debug("Filling in level-{$childlevel} child artefact paths");
                if (is_postgres()) {
                    execute_sql("\n                        UPDATE {artefact}\n                        SET path = p.path || '/' || {artefact}.id\n                        FROM {artefact} p\n                        WHERE\n                            {artefact}.parent=p.id\n                            AND {artefact}.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                } else {
                    execute_sql("\n                        UPDATE\n                            {artefact} a\n                            INNER JOIN {artefact} p\n                            ON a.parent = p.id\n                        SET a.path=p.path || '/' || a.id\n                        WHERE\n                            a.path IS NULL\n                            AND p.path IS NOT NULL\n                    ");
                }
                $newcount = count_records_select('artefact', 'path IS NULL');
                // There may be some bad records whose paths can't be filled in,
                // so stop looping if the count stops going down.
            } while ($newcount > 0 && $newcount < $lastcount);
            log_debug("Done filling in child artefact paths");
        }
        if (get_config('searchplugin') == 'elasticsearch') {
            log_debug("Add triggers back in");
            ElasticsearchIndexing::create_triggers('artefact');
        }
    }
    // Make objectionable independent of view_access page.
    if ($oldversion < 2014060300) {
        log_debug("Create 'objectionable' table.");
        $table = new XMLDBTable('objectionable');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('objecttype', XMLDB_TYPE_CHAR, 20, null, XMLDB_NOTNULL);
        $table->addFieldInfo('objectid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedby', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('report', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addFieldInfo('reportedtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('resolvedby', XMLDB_TYPE_INTEGER, 10, null, null);
        $table->addFieldInfo('resolvedtime', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('reporterfk', XMLDB_KEY_FOREIGN, array('reportedby'), 'usr', array('id'));
        $table->addKeyInfo('resolverfk', XMLDB_KEY_FOREIGN, array('resolvedby'), 'usr', array('id'));
        $table->addIndexInfo('objectix', XMLDB_INDEX_NOTUNIQUE, array('objectid', 'objecttype'));
        create_table($table);
        // Migrate data to a new format.
        // Since we don't have report or name of the user, use root ID.
        // Table 'notification_internal_activity' contains data that is
        // not possible to extract in any reasonable way.
        $objectionable = get_records_array('view_access', 'accesstype', 'objectionable');
        db_begin();
        log_debug('Migrating objectionable records to new format');
        if (!empty($objectionable)) {
            $count = 0;
            $limit = 1000;
            $total = count($objectionable);
            foreach ($objectionable as $record) {
                $todb = new stdClass();
                $todb->objecttype = 'view';
                $todb->objectid = $record->view;
                $todb->reportedby = 0;
                $todb->report = '';
                $todb->reportedtime = $record->ctime ? $record->ctime : format_date(time());
                if (!empty($record->stopdate)) {
                    // Since we can't get an ID of a user who resolved an issue, use root ID.
                    $todb->resolvedby = 0;
                    $todb->resolvedtime = $record->stopdate;
                }
                insert_record('objectionable', $todb);
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        // Delete data from 'view_access' table as we don't need it any more.
        delete_records('view_access', 'accesstype', 'objectionable');
        db_commit();
        log_debug("Drop constraint on 'view_access'");
        // Need to run this to avoid contraints problems on Postgres.
        if (is_postgres()) {
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        log_debug("Update 'view_access' accesstype");
        // Update accesstype in 'view_access' not to use 'objectionable'.
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2014060500) {
        log_debug("Add 'artefact_access' table.");
        $table = new XMLDBTable('artefact_access');
        $table->addFieldInfo('artefact', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('accesstype', XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends'));
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('institution', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('artefactfk', XMLDB_KEY_FOREIGN, array('artefact'), 'artefact', array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('institutionfk', XMLDB_KEY_FOREIGN, array('institution'), 'institution', array('name'));
        $table->addIndexInfo('accesstypeix', XMLDB_INDEX_NOTUNIQUE, array('accesstype'));
        create_table($table);
    }
    if ($oldversion < 2014061100) {
        log_debug('Add module related tables');
        $table = new XMLDBTable('module_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('module_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('module_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'module_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2014062000) {
        log_debug('Fix up auth_clean_expired_password_requests cron');
        $where = array('callfunction' => 'auth_clean_expired_password_requests');
        $data = array('callfunction' => 'auth_clean_expired_password_requests', 'minute' => '5', 'hour' => '0', 'day' => '*', 'month' => '*', 'dayofweek' => '*');
        ensure_record_exists('cron', (object) $where, (object) $data);
    }
    if ($oldversion < 2014062500) {
        log_debug("Add 'feedbacknotify' option to 'group' table");
        require_once get_config('libroot') . 'group.php';
        $table = new XMLDBTable('group');
        $field = new XMLDBField('feedbacknotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, GROUP_ROLES_ALL);
        if (!field_exists($table, $field)) {
            add_field($table, $field);
        }
    }
    if ($oldversion < 2014073100) {
        log_debug('Delete leftover data which are not associated to any institution');
        // Institution collections
        $collectionids = get_column_sql('
            SELECT id
            FROM {collection} c
            WHERE c.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = c.institution)');
        if ($collectionids) {
            require_once get_config('libroot') . 'collection.php';
            $count = 0;
            $limit = 200;
            $total = count($collectionids);
            foreach ($collectionids as $collectionid) {
                $collection = new Collection($collectionid);
                $collection->delete();
                $count++;
                if ($count % $limit == 0) {
                    log_debug("Deleting leftover collections: {$count}/{$total}");
                    set_time_limit(30);
                }
            }
            log_debug("Deleting leftover collections: {$count}/{$total}");
        }
        log_debug('Delete leftover custom layouts / usr registration');
        // Institution custom layouts and registration
        delete_records_sql('
            DELETE FROM {usr_custom_layout}
            WHERE {usr_custom_layout}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_custom_layout}.institution)');
        delete_records_sql('
            DELETE FROM {usr_registration}
            WHERE {usr_registration}.institution IS NOT NULL
                AND NOT EXISTS (SELECT 1 FROM {institution} i WHERE i.name = {usr_registration}.institution)');
    }
    if ($oldversion < 2014081900) {
        log_debug("Check blocktype 'text' is installed");
        if ($data = check_upgrades('blocktype.text')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014091600) {
        log_debug('Allow anonymous pages');
        $table = new XMLDBTable('view');
        $field = new XMLDBField('anonymise');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_config('allowanonymouspages', 0);
    }
    if ($oldversion < 2014091800) {
        log_debug("Add 'allowarchives' column to the 'group' table");
        $table = new XMLDBTable('group');
        $field = new XMLDBField('allowarchives');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        log_debug("Add 'submittedstatus' column to 'view' table");
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug("Need to update the submitted status for any existing views that are submitted");
        execute_sql('UPDATE {view} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug("Add 'submittedstatus' column to 'collection' table");
        $table = new XMLDBTable('collection');
        $field = new XMLDBField('submittedstatus');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0, 'submittedtime');
        add_field($table, $field);
        log_debug('Need to update the submitted status for any existing collections that are submitted');
        execute_sql('UPDATE {collection} SET submittedstatus = 1 WHERE submittedgroup IS NOT NULL
                    AND submittedtime IS NOT NULL');
        log_debug('Adding the export queue / submission tables');
        // Add export queue table - each export is one row.
        $table = new XMLDBTable('export_queue');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('exporttype', XMLDB_TYPE_CHAR, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('starttime', XMLDB_TYPE_DATETIME);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addFieldInfo('submitter', XMLDB_TYPE_INTEGER, 10);
        // for when the submitter is not the owner
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('submitterfk', XMLDB_KEY_FOREIGN, array('submitter'), 'usr', array('id'));
        create_table($table);
        // Add export queue items table which maps what views/collections/artefacts relate to the queue item.
        $table = new XMLDBTable('export_queue_items');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('exportqueueid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('exportqueuefk', XMLDB_KEY_FOREIGN, array('exportqueueid'), 'export_queue', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        create_table($table);
        // Add export archive table to hold info that will allow one to download the zip file
        $table = new XMLDBTable('export_archive');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filename', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filetitle', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('filepath', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('submission', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Add archived submissions table to hold submission info
        $table = new XMLDBTable('archived_submissions');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('archiveid', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('group', XMLDB_TYPE_INTEGER, 10);
        $table->addFieldInfo('externalhost', XMLDB_TYPE_CHAR, 50);
        $table->addFieldInfo('externalid', XMLDB_TYPE_CHAR, 255);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('groupfk', XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        $table->addKeyInfo('archivefk', XMLDB_KEY_FOREIGN, array('archiveid'), 'export_archive', array('id'));
        create_table($table);
        // install the cronjob to process export queue
        $cron = new StdClass();
        $cron->callfunction = 'export_process_queue';
        $cron->minute = '*/6';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
        // install the cronjob to clean up deleted archived submissions items
        $cron = new StdClass();
        $cron->callfunction = 'submissions_delete_removed_archive';
        $cron->minute = '15';
        $cron->hour = '1';
        $cron->day = '1';
        $cron->month = '*';
        $cron->dayofweek = '*';
        ensure_record_exists('cron', $cron, $cron);
    }
    if ($oldversion < 2014092300) {
        log_debug('Add the socialprofile artefacttype');
        // Need to insert directly into the table instead of running upgrade_plugin(), so that we can transition
        // all the old social network artefact types into the new unified socialprofile type before deleting
        // the old types from artefact_installed_type
        insert_record('artefact_installed_type', (object) array('name' => 'socialprofile', 'plugin' => 'internal'));
        // Convert existing messaging types to socialprofile types.
        $oldmessagingfieldsarray = array('icqnumber', 'msnnumber', 'aimscreenname', 'yahoochat', 'skypeusername', 'jabberusername');
        $oldmessagingfields = implode(',', array_map('db_quote', $oldmessagingfieldsarray));
        $sql = "SELECT * FROM {artefact}\n                WHERE artefacttype IN (" . $oldmessagingfields . ")";
        if ($results = get_records_sql_assoc($sql, array())) {
            $count = 0;
            $limit = 1000;
            $total = count($results);
            safe_require('artefact', 'internal');
            foreach ($results as $result) {
                $i = new ArtefactTypeSocialprofile($result->id, (array) $result);
                $i->set('artefacttype', 'socialprofile');
                switch ($result->artefacttype) {
                    case 'aimscreenname':
                        $i->set('note', 'aim');
                        $i->set('description', get_string('aim', 'artefact.internal'));
                        break;
                    case 'icqnumber':
                        $i->set('note', 'icq');
                        $i->set('description', get_string('icq', 'artefact.internal'));
                        break;
                    case 'jabberusername':
                        $i->set('note', 'jabber');
                        $i->set('description', get_string('jabber', 'artefact.internal'));
                        break;
                    case 'msnnumber':
                    case 'skypeusername':
                        // MSN no longer exists and has been replaced by Skype.
                        $i->set('note', 'skype');
                        $i->set('description', get_string('skype', 'artefact.internal'));
                        break;
                    case 'yahoochat':
                        $i->set('note', 'yahoo');
                        $i->set('description', get_string('yahoo', 'artefact.internal'));
                        break;
                }
                $i->set('title', $result->title);
                $i->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
        $sql = "SELECT value FROM {search_config} WHERE plugin='elasticsearch' AND field='artefacttypesmap'";
        if ($result = get_field_sql($sql, array())) {
            log_debug('Clean up elasticsearch fields for the old messaging fields');
            $artefacttypesmap_array = explode("\n", $result);
            $elasticsearchartefacttypesmap = array();
            foreach ($artefacttypesmap_array as $key => $value) {
                $tmpkey = explode("|", $value);
                if (count($tmpkey) == 3) {
                    if (!in_array($tmpkey[0], $oldmessagingfieldsarray)) {
                        // we're going to keep this one.
                        $elasticsearchartefacttypesmap[] = $value;
                    }
                }
            }
            // add socialprofile field.
            $elasticsearchartefacttypesmap[] = "socialprofile|Profile|Text";
            // now save the data excluding the old messaging fields.
            set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', implode("\n", $elasticsearchartefacttypesmap));
        }
        log_debug('Delete unused, but still installed artefact types');
        delete_records_select("artefact_installed_type", "name IN (" . $oldmessagingfields . ")");
        log_debug('Install the social profile blocktype so users can see their migrated data');
        if ($data = check_upgrades('blocktype.internal/socialprofile')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014092300) {
        log_debug("Install 'multirecipientnotification' plugin");
        if ($data = check_upgrades('module.multirecipientnotification')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2014101300) {
        log_debug("Make sure default notifications are not set to 'none'");
        // Make sure the 'system messages' and 'messages from other users' have a notification method set
        // It was possible after earlier upgrades to set method to 'none'.
        // Also make sure old defaultmethod is respected.
        $activitytypes = get_records_assoc('activity_type');
        foreach ($activitytypes as $type) {
            $type->defaultmethod = get_config('defaultnotificationmethod') ? get_config('defaultnotificationmethod') : 'email';
            if ($type->name == 'maharamessage' || $type->name == 'usermessage') {
                $type->allownonemethod = 0;
            }
            update_record('activity_type', $type);
        }
        // Make sure users have their 'system messages' and 'messages from other users' notification method set
        if ($useractivities = get_records_sql_assoc("SELECT * FROM {activity_type} at, {usr_activity_preference} uap\n                                                     WHERE at.id = uap.activity\n                                                     AND at.name IN ('maharamessage', 'usermessage')\n                                                     AND (method IS NULL OR method = '')", array())) {
            foreach ($useractivities as $activity) {
                $userprefs = new stdClass();
                $userprefs->method = $activity->defaultmethod;
                update_record('usr_activity_preference', $userprefs, array('usr' => $activity->usr, 'activity' => $activity->activity));
            }
        }
    }
    if ($oldversion < 2014101500) {
        log_debug('Place skin fonts in their correct directories');
        if ($fonts = get_records_assoc('skin_fonts', 'fonttype', 'google')) {
            $fontpath = get_config('dataroot') . 'skins/fonts/';
            foreach ($fonts as $font) {
                // if google font is not already in subdir
                if (!is_dir($fontpath . $font->name)) {
                    if (file_exists($fontpath . $font->previewfont)) {
                        // we need to create the subdir and move the file into it
                        $newfontpath = $fontpath . $font->name . '/';
                        check_dir_exists($newfontpath, true, true);
                        rename($fontpath . $font->previewfont, $newfontpath . $font->previewfont);
                        // and move the license file if it exists also
                        if (file_exists($fontpath . $font->licence)) {
                            rename($fontpath . $font->licence, $newfontpath . $font->licence);
                        }
                    } else {
                        // the file is not there for some reason so we might as well delete the font from the db
                        $result = delete_records('skin_fonts', 'name', $font->name);
                        if ($result !== false) {
                            // Check to see if the font is being used in a skin. If it is remove it from
                            // the skin's viewskin data
                            $skins = get_records_array('skin');
                            if (is_array($skins)) {
                                foreach ($skins as $skin) {
                                    $options = unserialize($skin->viewskin);
                                    foreach ($options as $key => $option) {
                                        if (preg_match('/font_family/', $key) && $option == $font->name) {
                                            require_once get_config('docroot') . 'lib/skin.php';
                                            $skinobj = new Skin($skin->id);
                                            $viewskin = $skinobj->get('viewskin');
                                            $viewskin[$key] = false;
                                            $skinobj->set('viewskin', $viewskin);
                                            $skinobj->commit();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($oldversion < 2014101501) {
        log_debug('Unlock root user grouphomepage template in case it is locked');
        set_field('view', 'locked', 0, 'type', 'grouphomepage', 'owner', 0);
    }
    if ($oldversion < 2014110500) {
        log_debug('Add cacheversion and assign random string');
        // Adding cacheversion, as an arbitrary number appended to the end of JS & CSS files in order
        // to tell cacheing software when they've been updated. (Without having to use the Mahara
        // minor version for that purpose.)
        // Set this to a random starting number to make minor version slightly harder to detect
        if (!get_config('cacheversion')) {
            set_config('cacheversion', rand(1000, 9999));
        }
    }
    if ($oldversion < 2014110700) {
        log_debug("Add in 'shortcut' category to 'blocktype_category'");
        // Increment all the existing sorts by 1 to make room...
        $cats = get_records_array('blocktype_category', '', '', 'sort desc');
        foreach ($cats as $cat) {
            $cat->sort = $cat->sort + 1;
            update_record('blocktype_category', $cat, 'name');
        }
        $todb = new stdClass();
        $todb->name = 'shortcut';
        $todb->sort = '0';
        insert_record('blocktype_category', $todb);
    }
    if ($oldversion < 2014112700) {
        log_debug("Fix up group homepages so that no duplicate 'groupview' blocks are present");
        // Need to find the group homepages that have more than one groupview on them
        // and merge their data into one groupview as we shouldn't allow more than one groupview block
        // as it breaks pagination
        // First get any pages that have more than one groupview on them
        // and find the status of the groupview blocks
        if ($records = get_records_sql_array("SELECT v.id AS view, bi.id AS block FROM {view} v\n            INNER JOIN {block_instance} bi ON v.id = bi.view\n            WHERE v.id IN (\n                SELECT v.id FROM {view} v\n                 INNER JOIN {block_instance} bi ON v.id = bi.view\n                 WHERE bi.blocktype = 'groupviews'\n                  AND v.type = 'grouphomepage'\n                 GROUP BY v.id\n                 HAVING COUNT(v.id) > 1\n            )\n            AND bi.blocktype='groupviews'\n            ORDER BY v.id, bi.id", array())) {
            require_once get_config('docroot') . 'blocktype/lib.php';
            $lastview = 0;
            // set default
            $info = array();
            $x = -1;
            foreach ($records as $record) {
                if ($lastview != $record->view) {
                    $x++;
                    $info[$x]['in']['showgroupviews'] = 0;
                    $info[$x]['in']['showsharedviews'] = 0;
                    $info[$x]['in']['view'] = $record->view;
                    $info[$x]['in']['block'] = $record->block;
                    $lastview = $record->view;
                } else {
                    $info[$x]['out'][] = $record->block;
                }
                $bi = new BlockInstance($record->block);
                $configdata = $bi->get('configdata');
                if (!empty($configdata['showgroupviews'])) {
                    $info[$x]['in']['showgroupviews'] = 1;
                }
                if (!empty($configdata['showsharedviews'])) {
                    $info[$x]['in']['showsharedviews'] = 1;
                }
            }
            // now that we have info on the state of play we need to save one of the blocks
            // with correct data and delete the not needed blocks
            $count = 0;
            $limit = 1000;
            $total = count($info);
            foreach ($info as $item) {
                $bi = new BlockInstance($item['in']['block']);
                $configdata = $bi->get('configdata');
                $configdata['showgroupviews'] = $item['in']['showgroupviews'];
                $configdata['showsharedviews'] = $item['in']['showsharedviews'];
                $bi->set('configdata', $configdata);
                $bi->commit();
                foreach ($item['out'] as $old) {
                    $bi = new BlockInstance($old);
                    $bi->delete();
                }
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2014121200) {
        log_debug('Remove layout preview thumbs directory');
        require_once 'file.php';
        $layoutdir = get_config('dataroot') . 'images/layoutpreviewthumbs';
        if (file_exists($layoutdir)) {
            rmdirr($layoutdir);
        }
    }
    if ($oldversion < 2015013000) {
        log_debug("Add a 'sortorder' column to 'blocktype_installed_category'");
        // Add a sortorder column to blocktype_installed_category
        $table = new XMLDBTable('blocktype_installed_category');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 100000, 'category');
        add_field($table, $field);
    }
    if ($oldversion < 2015021000) {
        log_debug('Need to update any dashboard pages to not have skins');
        // and seen as we are updating and selecting from the same table
        // we need to use a temptable for it to work in mysql
        execute_Sql("UPDATE {view} SET skin = NULL WHERE id IN ( SELECT vid FROM (SELECT id AS vid FROM {view} WHERE type = 'dashboard' AND skin IS NOT NULL) AS temptable)");
    }
    if ($oldversion < 2015021900) {
        log_debug('Remove bbcode formatting from existing wall posts');
        require_once get_config('docroot') . '/lib/stringparser_bbcode/lib.php';
        if ($records = get_records_sql_array("SELECT id, text FROM {blocktype_wall_post} WHERE text LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                $r->text = parse_bbcode($r->text);
                update_record('blocktype_wall_post', $r);
            }
        }
    }
    if ($oldversion < 2015030400) {
        log_debug("Update search config settings");
        if (get_config('searchusernames') === 1) {
            set_config('nousernames', 0);
        } else {
            set_config('nousernames', 1);
        }
        delete_records('config', 'field', 'searchusernames');
    }
    if ($oldversion < 2015032600) {
        log_debug("Update block categories for plugins");
        if ($blocktypes = plugins_installed('blocktype', true)) {
            foreach ($blocktypes as $bt) {
                install_blocktype_categories_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
            }
        }
    }
    if ($oldversion < 2015033000) {
        log_debug("Updating TinyMCE emoticon locations in mahara database");
        // Seeing as tinymce has moved the location of the emoticons
        // we need to fix up a few places where users could have added emoticons.
        // $replacements is key = table, value = column
        $replacements = array('view' => 'description', 'artefact' => 'title', 'artefact' => 'description', 'group' => 'description', 'interaction_forum_post' => 'body', 'notification_internal_activity' => 'message', 'blocktype_wall_post' => 'text', 'site_content' => 'content');
        foreach ($replacements as $key => $value) {
            execute_sql("UPDATE {" . $key . "} SET " . $value . " = REPLACE(" . $value . ", '/emotions/img', '/emoticons/img') WHERE " . $value . " LIKE '%/emotions/img%'");
        }
        // we need to handle block_instance configdata in a special way
        if ($results = get_records_sql_array("SELECT id FROM {block_instance} WHERE configdata LIKE '%/emotions/img%'", array())) {
            log_debug("Updating 'block_instance' data for TinyMCE");
            require_once get_config('docroot') . 'blocktype/lib.php';
            $count = 0;
            $limit = 1000;
            $total = count($results);
            foreach ($results as $result) {
                $bi = new BlockInstance($result->id);
                $configdata = $bi->get('configdata');
                foreach ($configdata as $key => $value) {
                    $configdata[$key] = preg_replace('/\\/emotions\\/img/', '/emotions/img', $value);
                }
                $bi->set('configdata', $configdata);
                $bi->commit();
                $count++;
                if ($count % $limit == 0 || $count == $total) {
                    log_debug("{$count}/{$total}");
                    set_time_limit(30);
                }
            }
        }
    }
    if ($oldversion < 2015041400) {
        log_debug('Force install of annotation and webservices plugins');
        if ($data = check_upgrades('artefact.annotation')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('auth.webservice')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2015042800) {
        log_debug('Clear Dwoo cache of unescaped institution names');
        require_once 'dwoo/dwoo/dwooAutoload.php';
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/view/accesslistrow.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
        @unlink(get_config('dataroot') . 'dwoo/compile/default' . get_config('docroot') . 'theme/raw/' . 'templates/admin/users/accesslistitem.tpl.d' . Dwoo_Core::RELEASE_TAG . '.php');
    }
    if ($oldversion < 2015071500) {
        log_debug('Expanding the size of the import_entry_requests.entrycontent column');
        $table = new XMLDBTable('import_entry_requests');
        $field = new XMLDBField('entrycontent');
        $field->setType(XMLDB_TYPE_TEXT);
        $field->setLength('big');
        change_field_precision($table, $field);
    }
    if ($oldversion < 2015072000) {
        // If we are upgrading from a site built before 2014092300 straight to 15.10
        // then the plugin won't exist as an artefact.
        if (table_exists(new XMLDBTable('artefact_multirecipient_userrelation'))) {
            log_debug('Change installation of artefact plugin multirecipentNotification to plugin module.');
            // first, drop the old triggers
            db_drop_trigger('update_unread_insert2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_update2', 'artefact_multirecipient_userrelation');
            db_drop_trigger('update_unread_delete2', 'artefact_multirecipient_userrelation');
            // rename tables artefact_multirecipientnotifiaction_notification and
            // Table: artefact_multirecipient_userrelation to module-prefix
            execute_sql("ALTER TABLE {artefact_multirecipient_notification} RENAME TO {module_multirecipient_notification}");
            execute_sql("ALTER TABLE {artefact_multirecipient_userrelation} RENAME TO {module_multirecipient_userrelation}");
            if (is_postgres()) {
                // Rename seq artefact_multirecipientnotifiaction_notification_id_seq and
                // artefact_multirecipient_userrelation_id_seq
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_notification_id_seq} RENAME TO {module_multirecipient_notification_id_seq}");
                execute_sql("ALTER SEQUENCE {artefact_multirecipient_userrelation_id_seq} RENAME TO {module_multirecipient_userrelation_id_seq}");
            }
            //move event_subscrition entries for artefact plugin
            //multirecipientnotification to table module_event_subscription
            $subscriptions = get_records_array('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_event_subscription', 'plugin', 'multirecipientnotification');
            delete_records('artefact_installed_type', 'plugin', 'multirecipientnotification');
            $installrecord = get_record('artefact_installed', 'name', 'multirecipientnotification');
            if (is_object($installrecord)) {
                insert_record('module_installed', $installrecord);
                delete_records('artefact_installed', 'name', 'multirecipientnotification');
            }
            if (is_array($subscriptions)) {
                foreach ($subscriptions as $subscription) {
                    insert_record('module_event_subscription', $subscription, 'id');
                }
            }
            // recreate trigger
            safe_require('module', 'multirecipientnotification');
            PluginModuleMultirecipientnotification::postinst(0);
        }
    }
    if ($oldversion < 2015081000) {
        log_debug('Add user_login_data table to record when a user logs in');
        $table = new XMLDBTable('usr_login_data');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrloginfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
        // Insert info about current users's logins
        $results = get_records_sql_array("SELECT id,lastlogin FROM {usr} WHERE deleted = 0 AND lastlogin IS NOT NULL");
        $count = 0;
        $limit = 1000;
        $total = count($results);
        foreach ($results as $result) {
            insert_record('usr_login_data', (object) array('usr' => $result->id, 'ctime' => $result->lastlogin));
            $count++;
            if ($count % $limit == 0 || $count == $total) {
                log_debug("{$count}/{$total}");
                set_time_limit(30);
            }
        }
    }
    if ($oldversion < 2015081700) {
        // In 15.10, we changed the registration site policy.
        // We need to remind the site admins to register the site again with the new policy.
        log_debug('Remind the site admins to register the site again with the new policy');
        if (get_config('new_registration_policy') != -1) {
            set_config('new_registration_policy', true);
        }
        if (get_config('registration_sendweeklyupdates')) {
            set_config('registration_sendweeklyupdates', false);
        }
    }
    if ($oldversion < 2015082500) {
        // Add a site default portfolio page template
        log_debug('Add a site default portfolio page template');
        require_once 'view.php';
        install_system_portfolio_view();
    }
    if ($oldversion < 2015091700) {
        log_debug('Update cached customizable theme CSS');
        $styles = get_records_array('institution', 'theme', 'custom', 'id', 'displayname, style');
        if ($styles) {
            foreach ($styles as $newinstitution) {
                $styleid = $newinstitution->style;
                $properties = array();
                $record = (object) array('style' => $styleid);
                $proprecs = get_records_array('style_property', 'style', $styleid, 'field', 'field, value');
                foreach ($proprecs as $p) {
                    $properties[$p->field] = $p->value;
                }
                // Update the css
                $smarty = smarty_core();
                $smarty->assign('data', $properties);
                set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);
            }
        }
    }
    return $status;
}
コード例 #7
0
ファイル: db.php プロジェクト: nagyistoce/moodle-Teach-Pilot
/**
 * This function sets the data in the database to the good format. This function
 * have this properties:
 * 1 - does not depend on the previous version: it has to discover which changes to apply
 * 2 - (a corolary of 1) is idempotent, i.e, f(f(x)) = f(x)
 * **/
function wrsqz_update_database()
{
    //update shortanswer wirisCASForComputations field
    $updates = 0;
    $shortanswertable = new XMLDBTable('question_shortanswerwiris');
    if (table_exists($shortanswertable)) {
        $eqoptionfield = new XMLDBField('eqoption');
        if (field_exists($shortanswertable, $eqoptionfield)) {
            $saq = get_records('question_shortanswerwiris');
            foreach ($saq as $question) {
                if (trim($question->eqoption) != '') {
                    $decodedEqoption = array();
                    mb_parse_str($question->eqoption, $decodedEqoption);
                    if (isset($decodedEqoption['wirisCASForComputations'])) {
                        $wirisCASForComputations = $decodedEqoption['wirisCASForComputations'];
                        unset($decodedEqoption['wirisCASForComputations']);
                        $question->eqoption = http_build_query($decodedEqoption, null, '&');
                        if (!empty($question->options)) {
                            $options = unserialize($question->options);
                        } else {
                            $options = array();
                        }
                        $options['wirisCASForComputations'] = $wirisCASForComputations;
                        $question->options = serialize($options);
                        update_record('question_shortanswerwiris', $question);
                        $updates++;
                    }
                }
            }
        }
    }
    if ($updates) {
        echo utf8_htmlentities(translate('Updated shortanswer wirisCASForComputations field: ')) . $updates . utf8_htmlentities(translate(' records')) . '<br />';
    }
}
コード例 #8
0
function xmldb_lightboxgallery_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2007111400) {
        // Insert perpage and comments fields into lightboxgallery
        $table = new XMLDBTable('lightboxgallery');
        $field = new XMLDBField('perpage');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'description');
            $result = $result && add_field($table, $field);
        }
        $field = new XMLDBField('comments');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'perpage');
            $result = $result && add_field($table, $field);
        }
        // Create new lightboxgallery_comments table
        $table = new XMLDBTable('lightboxgallery_comments');
        if (!table_exists($table)) {
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
            $table->addFieldInfo('gallery', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
            $table->addFieldInfo('user', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
            $table->addFieldInfo('comment', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
            $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addIndexInfo('gallery', XMLDB_INDEX_NOTUNIQUE, array('gallery'));
            $result = $result && create_table($table);
        }
        // Insert add_to_log entry to log_display table
        if (!record_exists('log_display', 'module', 'lightboxgallery', 'action', 'comment')) {
            $record = new object();
            $record->module = 'lightboxgallery';
            $record->action = 'comment';
            $record->mtable = 'lightboxgallery';
            $record->field = 'name';
            $result = $result && insert_record('log_display', $record);
        }
    }
    if ($result && $oldversion < 2007121700) {
        // Insert extinfo field into lightboxgallery
        $table = new XMLDBTable('lightboxgallery');
        $field = new XMLDBField('extinfo');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'comments');
            $result = $result && add_field($table, $field);
        }
        // Create lightboxgallery_captions table
        $table = new XMLDBTable('lightboxgallery_captions');
        if (!table_exists($table)) {
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
            $table->addFieldInfo('gallery', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
            $table->addFieldInfo('image', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
            $table->addFieldInfo('caption', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addIndexInfo('gallery', XMLDB_INDEX_NOTUNIQUE, array('gallery'));
            $result = $result && create_table($table);
        }
    }
    if ($result && $oldversion < 2008110600) {
        // Insert public, rss, autoresize, resize fields into lightboxgallery
        $table = new XMLDBTable('lightboxgallery');
        $newfields = array('public', 'rss', 'autoresize', 'resize');
        $previousfield = 'comments';
        foreach ($newfields as $newfield) {
            $field = new XMLDBField($newfield);
            if (!field_exists($table, $field)) {
                $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $previousfield);
                $result = $result && add_field($table, $field);
                $previousfield = $newfield;
            }
        }
        // Rename user field to userid in lightboxgallery_comments (for postgres)
        $table = new XMLDBTable('lightboxgallery_comments');
        $field = new XMLDBField('user');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
            $result = $result && rename_field($table, $field, 'userid');
        }
        // Rename caption field to description and insert metatype field in lightboxgallery_captions
        $table = new XMLDBTable('lightboxgallery_captions');
        $field = new XMLDBField('caption');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null, 'image');
            $result = $result && rename_field($table, $field, 'description');
        }
        $field = new XMLDBField('metatype');
        if (table_exists($table) && !field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('caption', 'tag'), 'caption', 'image');
            $result = $result && add_field($table, $field);
        }
        // Rename table lightboxgallery_captions to lightboxgallery_image_meta
        $result = $result && rename_table($table, 'lightboxgallery_image_meta');
    }
    if ($result && $oldversion < 2009051200) {
        // Rename public field to ispublic in lightboxgallery (for mssql)
        $table = new XMLDBTable('lightboxgallery');
        $field = new XMLDBField('public');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'comments');
            $result = $result && rename_field($table, $field, 'ispublic');
        }
    }
    return $result;
}
コード例 #9
0
function xmldb_scorm_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2006103100) {
        /// Create the new sco optionals data table
        /// Define table scorm_scoes_data to be created
        $table = new XMLDBTable('scorm_scoes_data');
        /// Adding fields to table scorm_scoes_data
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scorm_scoes_data
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table scorm_scoes_data
        $table->addIndexInfo('scoid', XMLDB_INDEX_NOTUNIQUE, array('scoid'));
        /// Launch create table for scorm_scoes_data
        $result = $result && create_table($table);
        /// The old fields used in scorm_scoes
        $fields = array('parameters' => '', 'prerequisites' => '', 'maxtimeallowed' => '', 'timelimitaction' => '', 'datafromlms' => '', 'masteryscore' => '', 'next' => '0', 'previous' => '0');
        /// Retrieve old datas
        if ($scorms = get_records('scorm')) {
            foreach ($scorms as $scorm) {
                if ($olddatas = get_records('scorm_scoes', 'scorm', $scorm->id)) {
                    foreach ($olddatas as $olddata) {
                        $newdata = new stdClass();
                        $newdata->scoid = $olddata->id;
                        foreach ($fields as $field => $value) {
                            if ($olddata->{$field} != $value) {
                                $newdata->name = addslashes($field);
                                $newdata->value = addslashes($olddata->{$field});
                                $id = insert_record('scorm_scoes_data', $newdata);
                                $result = $result && $id != 0;
                            }
                        }
                    }
                }
            }
        }
        /// Remove no more used fields
        $table = new XMLDBTable('scorm_scoes');
        foreach ($fields as $field => $value) {
            $field = new XMLDBField($field);
            $result = $result && drop_field($table, $field);
        }
    }
    if ($result && $oldversion < 2006120900) {
        /// Define table scorm_seq_objective to be created
        $table = new XMLDBTable('scorm_seq_objective');
        /// Adding fields to table scorm_seq_objective
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('primaryobj', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('objectiveid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('satisfiedbymeasure', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('minnormalizedmeasure', XMLDB_TYPE_FLOAT, '11, 4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0.0000');
        /// Adding keys to table scorm_seq_objective
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_objective_uniq', XMLDB_KEY_UNIQUE, array('scoid', 'id'));
        $table->addKeyInfo('scorm_objective_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        /// Launch create table for scorm_seq_objective
        $result = $result && create_table($table);
        /// Define table scorm_seq_mapinfo to be created
        $table = new XMLDBTable('scorm_seq_mapinfo');
        /// Adding fields to table scorm_seq_mapinfo
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('objectiveid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('targetobjectiveid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('readsatisfiedstatus', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('readnormalizedmeasure', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('writesatisfiedstatus', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('writenormalizedmeasure', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table scorm_seq_mapinfo
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_mapinfo_uniq', XMLDB_KEY_UNIQUE, array('scoid', 'id', 'objectiveid'));
        $table->addKeyInfo('scorm_mapinfo_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        $table->addKeyInfo('scorm_mapinfo_objectiveid', XMLDB_KEY_FOREIGN, array('objectiveid'), 'scorm_seq_objective', array('id'));
        /// Launch create table for scorm_seq_mapinfo
        $result = $result && create_table($table);
        /// Define table scorm_seq_ruleconds to be created
        $table = new XMLDBTable('scorm_seq_ruleconds');
        /// Adding fields to table scorm_seq_ruleconds
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('conditioncombination', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, null, null, null, 'all');
        $table->addFieldInfo('ruletype', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scorm_seq_ruleconds
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_ruleconds_un', XMLDB_KEY_UNIQUE, array('scoid', 'id'));
        $table->addKeyInfo('scorm_ruleconds_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        /// Launch create table for scorm_seq_ruleconds
        $result = $result && create_table($table);
        /// Define table scorm_seq_rulecond to be created
        $table = new XMLDBTable('scorm_seq_rulecond');
        /// Adding fields to table scorm_seq_rulecond
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('ruleconditionsid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('refrencedobjective', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('measurethreshold', XMLDB_TYPE_FLOAT, '11, 4', null, XMLDB_NOTNULL, null, null, null, '0.0000');
        $table->addFieldInfo('operator', XMLDB_TYPE_CHAR, '5', null, XMLDB_NOTNULL, null, null, null, 'noOp');
        $table->addFieldInfo('cond', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'always');
        /// Adding keys to table scorm_seq_rulecond
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_rulecond_uniq', XMLDB_KEY_UNIQUE, array('id', 'scoid', 'ruleconditionsid'));
        $table->addKeyInfo('scorm_rulecond_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        $table->addKeyInfo('scorm_rulecond_ruleconditionsid', XMLDB_KEY_FOREIGN, array('ruleconditionsid'), 'scorm_seq_ruleconds', array('id'));
        /// Launch create table for scorm_seq_rulecond
        $result = $result && create_table($table);
        /// Define table scorm_seq_rolluprule to be created
        $table = new XMLDBTable('scorm_seq_rolluprule');
        /// Adding fields to table scorm_seq_rolluprule
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('childactivityset', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('minimumcount', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('minimumpercent', XMLDB_TYPE_FLOAT, '11, 4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0.0000');
        $table->addFieldInfo('conditioncombination', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, null, null, null, 'all');
        $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scorm_seq_rolluprule
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_rolluprule_uniq', XMLDB_KEY_UNIQUE, array('scoid', 'id'));
        $table->addKeyInfo('scorm_rolluprule_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        /// Launch create table for scorm_seq_rolluprule
        $result = $result && create_table($table);
        /// Define table scorm_seq_rolluprulecond to be created
        $table = new XMLDBTable('scorm_seq_rolluprulecond');
        /// Adding fields to table scorm_seq_rolluprulecond
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('scoid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rollupruleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('operator', XMLDB_TYPE_CHAR, '5', null, XMLDB_NOTNULL, null, null, null, 'noOp');
        $table->addFieldInfo('cond', XMLDB_TYPE_CHAR, '25', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scorm_seq_rolluprulecond
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('scorm_rulluprulecond_uniq', XMLDB_KEY_UNIQUE, array('scoid', 'rollupruleid', 'id'));
        $table->addKeyInfo('scorm_rolluprulecond_scoid', XMLDB_KEY_FOREIGN, array('scoid'), 'scorm_scoes', array('id'));
        $table->addKeyInfo('scorm_rolluprulecond_rolluprule', XMLDB_KEY_FOREIGN, array('rollupruleid'), 'scorm_seq_rolluprule', array('id'));
        /// Launch create table for scorm_seq_rolluprulecond
        $result = $result && create_table($table);
    }
    //Adding new field to table scorm
    if ($result && $oldversion < 2007011800) {
        /// Define field format to be added to data_comments
        $table = new XMLDBTable('scorm');
        $field = new XMLDBField('md5_result');
        $field->setAttributes(XMLDB_TYPE_CHAR, '32', null, null, null, null, null, null, null);
        /// Launch add field format
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('external');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007012400) {
        /// Rename field external on table scorm to updatefreq
        $table = new XMLDBTable('scorm');
        $field = new XMLDBField('external');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'maxattempt');
            /// Launch rename field updatefreq
            $result = $result && rename_field($table, $field, 'updatefreq');
        } else {
            $field = new XMLDBField('updatefreq');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'maxattempt');
            $result = $result && add_field($table, $field);
        }
        /// Rename field md5_result on table scorm to md5hash
        $field = new XMLDBField('md5_result');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, null, null, 'updatefreq');
            /// Launch rename field md5hash
            $result = $result && rename_field($table, $field, 'md5hash');
        } else {
            $field = new XMLDBField('md5hash');
            $field->setAttributes(XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, null, '', 'updatefreq');
            $result = $result && add_field($table, $field);
        }
    }
    if ($result && $oldversion < 2007031300) {
        if ($scorms = get_records('scorm')) {
            foreach ($scorms as $scorm) {
                if ($scoes = get_records('scorm_scoes', 'scorm', $scorm->id)) {
                    foreach ($scoes as $sco) {
                        if ($tracks = get_records('scorm_scoes_track', 'scoid', $sco->id)) {
                            foreach ($tracks as $track) {
                                $element = preg_replace('/\\.N(\\d+)\\./', ".\$1.", $track->element);
                                if ($track->element != $element) {
                                    $track->element = $element;
                                    update_record('scorm_scoes_track', $track);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if ($result && $oldversion < 2007081001) {
        require_once $CFG->dirroot . '/mod/scorm/lib.php';
        // too much debug output
        $db->debug = false;
        scorm_update_grades();
        $db->debug = true;
    }
    return $result;
}
コード例 #10
0
ファイル: upgrade.php プロジェクト: nadavkav/MoodleTAO
function xmldb_local_upgrade($oldversion)
{
    global $CFG, $db;
    $result = true;
    $reassigncaps = false;
    $resetcustomroles = false;
    $resetstickyblocks = false;
    // learning path approval status changes
    if ($result && $oldversion < 2008091803) {
        // fields added to the course table
        $table = new XMLDBTable('course');
        $field = new XMLDBField('approval_status_id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, null);
        //function setAttributes($type, $precision=null, $unsigned=null, $notnull=null, $sequence=null, $enum=null, $enumvalues=null, $default=null, $previous=null) {
        if (!field_exists($table, $field)) {
            /// Launch add field shortname
            $result = $result && add_field($table, $field);
        }
    }
    if ($oldversion < 2008092100) {
        // create the roles we need
        $roles = array('superadmin' => array('name' => 'Super Admin', 'description' => 'The highest level site administrator', 'legacy' => 'admin'), 'headteacher' => array('name' => 'Head Teacher', 'description' => 'Oversees the professional development of the teachers at his/her school and other schools that s/he has been assigned to cover.'), 'headeditor' => array('name' => 'Head Editor', 'description' => 'Approves Learning Plans'), 'seniorteacher' => array('name' => 'Senior Teacher', 'description' => 'Has already achieved Participating Teacher and Master Teacher certification and is now pursuing Senior Teacher certification.'), 'masterteacher' => array('name' => 'Master Teacher', 'description' => 'Has already achieved Participating Teacher certification and is now pursuing Master Teacher certification. Is assigned to an Senior Teacher.'), 'participatingteacher' => array('name' => 'Participating Teacher', 'description' => 'Pursuing Participating Teacher certification. Is assigned to an Master Teacher.'), 'translator' => array('name' => 'Translator', 'description' => 'Localizes User Interface'));
        foreach ($roles as $shortname => $roledata) {
            if (!array_key_exists('legacy', $roledata)) {
                $roledata['legacy'] = '';
            }
            $roles[$shortname]['id'] = create_role($roledata['name'], $shortname, $roledata['description'], $roledata['legacy']);
        }
        // boostrap superadmin to the same as admin
        $admin = get_record('role', 'shortname', 'admin');
        role_cap_duplicate($admin, $roles['superadmin']['id']);
    }
    // try to start over!!!
    if ($result && $oldversion < 2008092400) {
        $table = new XMLDBTable('course_status_history');
        if (table_exists($table)) {
            drop_table($table);
        }
        // fields added to the course table
        $table = new XMLDBTable('course');
        $field = new XMLDBField('approval_status_id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null, null, null, null, null, null);
        /// Launch add field approval_status_id
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// Define table mdl_course_approval_status_history to be created
        $table = new XMLDBTable('course_status_history');
        /// Adding fields to table mdl_course_approval_status
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timestamp', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('approval_status_id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('reason', XMLDB_TYPE_TEXT, '1000', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2008092401) {
        $roles = get_records_select('role', "shortname IN ('headteacher', 'headeditor', 'seniorteacher', 'masterteacher', 'participatingteacher', 'translator')");
        set_config('messageenabledroles', implode(',', array_keys($roles)));
    }
    if ($oldversion < 2008092500) {
        // add course classification stuff
        $table = new XMLDBTable('classification_type');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL, false, true, array('filter', 'topcategory', 'secondcategory'), 'filter');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
        $table = new XMLDBTable('classification_value');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
        $table = new XMLDBTable('course_classification');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2008092501) {
        // bootstrap out classification system based on the TAO website.
        $types = array(array('name' => 'Teaching strategies', 'type' => 'filter', 'values' => array('Connected Model', 'Constructivist Model', 'Integrated Model', 'Nested Model', 'Networked/Extended Model', 'Sequenced Model', 'Shared Model')), array('name' => 'Teaching methods', 'type' => 'filter', 'values' => array('Action-Oriented Learning', 'Active video work', 'Ball Bearings', 'Case Study', 'Creative writing', 'Discovery of learning', 'Excursion', 'Experiment', 'Free work', 'Group Puzzle', 'Learning Circle', 'Learning through teaching', 'Letter method', 'Mind mapping', 'Portfolio', 'Project Work', 'SOL method', 'Station Work', 'Traffic Lights', 'Using Tools and Resources', 'Web quest', 'Weekly Plan', 'Workshop', 'Other')), array('name' => 'Learning styles', 'type' => 'filter', 'values' => array('Visual/spatial', 'Verbal/linguistic', 'Logical/mathematical', 'Musical/rhythmic', 'Bodily/kinaesthetic', 'Interpersonal/social', 'Intrapersonal/introspective', 'Communication', 'Information', 'Simulation', 'Presentation', 'Production', 'Visualisation')), array('name' => 'Key Stages', 'type' => 'topcategory', 'values' => array('1 and 2', '3 and 4')), array('name' => 'Subject', 'type' => 'secondcategory', 'values' => array('English', 'Mathematics', 'Science', 'Design and Technology', 'ICT', 'History', 'Geography', 'Art and Design', 'Music', 'Physical Education')));
        foreach ($types as $t) {
            $values = $t['values'];
            $newid = insert_record('classification_type', (object) $t);
            foreach ($values as $v) {
                insert_record('classification_value', (object) array('type' => $newid, 'value' => $v));
            }
        }
    }
    if ($result && $oldversion < 2008100703) {
        // change course status values - seemingly have to drop and recreate the table to reset the serial with xmldb
        $table = new XMLDBTable('course_approval_status');
        if (table_exists($table)) {
            drop_table($table);
        }
        /// Define table mdl_course_approval_status to be created
        $table = new XMLDBTable('course_approval_status');
        /// Adding fields to table mdl_course_approval_status
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_TEXT, 15, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('displayname', XMLDB_TYPE_TEXT, '50', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, '100', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table mdl_course_approval_status
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for mdl_course_approval_status
        $result = $result && create_table($table);
        // insert status records
        $record = new object();
        $record->id = 1;
        $record->shortname = 'notsubmitted';
        $record->displayname = 'Not Submitted';
        $record->description = 'Not submitted';
        insert_record('course_approval_status', $record);
        $record->id = 2;
        $record->shortname = 'submitted';
        $record->displayname = 'Submitted';
        $record->description = 'Submitted for approval';
        insert_record('course_approval_status', $record);
        $record->id = 3;
        $record->shortname = 'needschange';
        $record->displayname = 'Needs Changes';
        $record->description = 'Reviewed and needs changes';
        insert_record('course_approval_status', $record);
        $record->id = 4;
        $record->shortname = 'resubmitted';
        $record->displayname = 'Resubmitted';
        $record->description = 'Resubmitted for approval';
        insert_record('course_approval_status', $record);
        $record->id = 5;
        $record->shortname = 'approved';
        $record->displayname = 'Approved';
        $record->description = 'Reviewed and approved';
        insert_record('course_approval_status', $record);
        $record->id = 6;
        $record->shortname = 'published';
        $record->displayname = 'Published';
        $record->description = 'Published';
        insert_record('course_approval_status', $record);
        $record->id = 7;
        $record->shortname = 'suspendeddate';
        $record->displayname = 'Suspended - Out-Dated';
        $record->description = 'Suspended - out-dated';
        insert_record('course_approval_status', $record);
        $record->id = 8;
        $record->shortname = 'suspendedauthor';
        $record->displayname = 'Suspended - By Author ';
        $record->description = 'Suspended - by author request';
        insert_record('course_approval_status', $record);
    }
    if ($oldversion < 2008101300) {
        $table = new XMLDBTable('header_image');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('image', XMLDB_TYPE_TEXT, 'medium', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('url', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2008101400) {
        set_config('defaultcustomheader', 'welcome.jpg');
    }
    // Upgrade of Learning Path Author roles
    if ($oldversion < 2008103000) {
        // add new roles
        //TODO: hardcoded Lang strings need to be put into lang!
        $roles = array('lpcreator' => array('name' => 'LP Creator', 'description' => 'Learning Path Creators can create new learning paths.', 'legacy' => 'coursecreator'), 'lpauthor' => array('name' => 'Learning Path Author', 'description' => 'Develops new Learning Plans.'), 'lpeditor' => array('name' => 'Learning Path Editor', 'description' => 'Allowed editing rights on a learning path'));
        foreach ($roles as $shortname => $roledata) {
            if (!array_key_exists('legacy', $roledata)) {
                $roledata['legacy'] = '';
            }
            $roles[$shortname]['id'] = create_role($roledata['name'], $shortname, $roledata['description'], $roledata['legacy']);
        }
        // set default capabilities to each role
        $syscontext = get_context_instance(CONTEXT_SYSTEM);
        $lpc = get_record('role', 'shortname', 'lpcreator');
        $lpa = get_record('role', 'shortname', 'lpauthor');
        $lpe = get_record('role', 'shortname', 'lpeditor');
        // creator
        $allowedcaps = array('moodle/local:islpcreator', 'moodle/course:create');
        foreach ($allowedcaps as $cap) {
            assign_capability($cap, CAP_ALLOW, $lpc->id, $syscontext->id, true);
        }
        // editor
        $allowedcaps = array('moodle/local:islpeditor', 'moodle/local:classifylearningpath', 'moodle/role:assign', 'format/page:addpages', 'format/page:editpages', 'format/page:managepages', 'format/page:viewpagesettings', 'moodle/site:manageblocks', 'moodle/course:manageactivities');
        foreach ($allowedcaps as $cap) {
            assign_capability($cap, CAP_ALLOW, $lpe->id, $syscontext->id, true);
        }
        // author
        $allowedcaps = array('moodle/local:islpauthor');
        foreach ($allowedcaps as $cap) {
            assign_capability($cap, CAP_ALLOW, $lpa->id, $syscontext->id, true);
        }
    }
    // assign new capability
    if ($oldversion < 2008110100) {
        $syscontext = get_context_instance(CONTEXT_SYSTEM);
        $role = get_record('role', 'shortname', 'lpauthor');
        assign_capability('moodle/local:viewunpublishedlearningpath', CAP_ALLOW, $role->id, $syscontext->id, true);
        $role = get_record('role', 'shortname', 'headeditor');
        assign_capability('moodle/local:viewunpublishedlearningpath', CAP_ALLOW, $role->id, $syscontext->id, true);
    }
    if ($oldversion < 2008110300) {
        set_config('lpautomatedcategorisation', 1);
    }
    if ($oldversion < 2008111300) {
        create_role('Certified Participating Teacher', 'certifiedpt', 'Role for a Participating Teacher once they have become certified', '');
    }
    if ($oldversion < 2008111800) {
        // make sure ST doesn't get can message own alumni now that we've split 9 & 10
        delete_records('role_capabilities', 'capability', 'moodle/local:canmessageownalumni', 'roleid', get_field('role', 'id', 'shortname', ROLE_ST));
    }
    if ($oldversion < 2008112100 && get_site()) {
        $b = (object) array('blockid' => get_field('block', 'id', 'name', 'tao_nav'), 'pageid' => SITEID, 'pagetype' => 'course-view', 'position' => 'l', 'weight' => 1, 'visible' => 1, 'configdata' => '');
        insert_record('block_instance', $b);
    }
    if ($oldversion < 2008112101) {
        insert_record('header_image', (object) array('image' => 'header_login.jpg', 'url' => '/login/index.php', 'sortorder' => 1));
    }
    if ($oldversion < 2008112102) {
        //first delete old custom user profile fields
        if ($custid = get_field('user_info_category', 'id', 'name', 'certification')) {
            delete_records('user_info_field', 'categoryid', $custid);
            delete_records('user_info_category', 'name', 'certification');
        }
    }
    if ($oldversion < 2008113000) {
        $table = new XMLDBTable('format_page_user_view');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('format_page_id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2008120801) {
        // field added to the course_modules table
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('trackprogress');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0, null);
        /// Launch add field shortname
        $result = $result && add_field($table, $field);
    }
    if ($oldversion < 2009022103) {
        // new group invites table
        $table = new XMLDBTable('group_invites');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fromuserid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('groupid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009022104) {
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('groupleader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        $result = $result && add_field($table, $field);
    }
    if ($oldversion < 2009023800) {
        $table = new XMLDBTable('user_friend');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('friendid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($oldversion < 2009031105) {
        $table = new XMLDBTable('certification_status');
        if (table_exists($table)) {
            drop_table($table);
        }
    }
    if ($oldversion < 2009031107) {
        $headerimages = array();
        $headerimages[1]->image = 'header_login.jpg';
        $headerimages[1]->url = '/login/logout.php';
        $headerimages[1]->description = 'logout page';
        $headerimages[1]->sortorder = 1;
        $headerimages[2]->image = 'mycollaboration.jpg';
        $headerimages[2]->url = '/local/my/collaboration.php';
        $headerimages[2]->description = 'My Collaboration';
        $headerimages[2]->sortorder = 1;
        $headerimages[3]->image = 'mylearning.jpg';
        $headerimages[3]->url = '/local/lp/list.php';
        $headerimages[3]->description = 'Learning Paths';
        $headerimages[3]->sortorder = 1;
        $headerimages[4]->image = 'mylearning.jpg';
        $headerimages[4]->url = '/local/my/learning.php';
        $headerimages[4]->description = 'My Learning';
        $headerimages[4]->sortorder = 1;
        $headerimages[5]->image = 'mywork.jpg';
        $headerimages[5]->url = '/local/my/work.php';
        $headerimages[5]->description = 'My Work';
        $headerimages[5]->sortorder = 1;
        $headerimages[6]->image = 'header_login.jpg';
        $headerimages[6]->url = '/index.php';
        $headerimages[6]->description = 'homepage';
        $headerimages[6]->sortorder = 1;
        $headerimages[7]->image = 'header_login.jpg';
        $headerimages[7]->url = '/';
        $headerimages[7]->description = 'homepage';
        $headerimages[7]->sortorder = 1;
        foreach ($headerimages as $himg) {
            //first check to make sure this record doesn't already exist
            if (!record_exists('header_image', 'image', $himg->image, 'url', $himg->url)) {
                insert_record('header_image', $himg);
            }
        }
    }
    if ($oldversion < 2009031108) {
        set_config('defaultblocks_topics', 'tao_nav:course_list');
        set_config('defaultblocks_weeks', 'tao_nav:course_list');
        set_config('defaultblocks_social', 'tao_nav:course_list');
    }
    if ($oldversion < 2009031109) {
        //add courseid to header_image table
        $table = new XMLDBTable('header_image');
        $field = new XMLDBField('courseid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    if ($oldversion < 2009031110) {
        //modify url to allow nulls
        $table = new XMLDBTable('header_image');
        $field = new XMLDBField('url');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, null, null, null, null, null);
        $result = $result && change_field_notnull($table, $field);
    }
    if ($oldversion < 2009052201) {
        // add 'custom' flag to roles table
        $table = new XMLDBTable('role');
        $field = new XMLDBField('custom');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        // make the assumption that everything with an id over 7 (the standard Moodle installed roles) at this stage is a custom role
        execute_sql("UPDATE {$CFG->prefix}role SET custom = 1 WHERE id > 7");
    }
    if ($oldversion < 2009052501) {
        $table = new XMLDBTable('user_friend');
        $field = new XMLDBField('approved');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    if ($oldversion < 2009062401) {
        $hostid = get_field('mnet_host', 'id', 'name', 'localmahara');
        $host2service = new stdClass();
        $host2service->serviceid = get_field('mnet_service', 'id', 'name', 'local_mahara');
        if (!empty($host2service->serviceid)) {
            $host2service->publish = 0;
            $host2service->subscribe = 1;
            if ($hostrec = get_record('mnet_host2service', 'hostid', $hostid, 'serviceid', $host2service->serviceid)) {
                $host2service->id = $hostrec->id;
                update_record('mnet_host2service', $host2service);
            } else {
                insert_record('mnet_host2service', $host2service);
            }
        }
    }
    if ($oldversion < 2009062800) {
        $table = new XMLDBTable('learning_path_mode');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_TEXT, 'big', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
        $lpmodes = array();
        $lpmodes[0]->shortname = 'standard';
        $lpmodes[0]->name = 'Standard';
        $lpmodes[1]->shortname = 'rafl';
        $lpmodes[1]->name = 'RAFL';
        foreach ($lpmodes as $mode) {
            insert_record('learning_path_mode', $mode);
        }
    }
    if ($oldversion < 2009062800) {
        $table = new XMLDBTable('course');
        $field = new XMLDBField('learning_path_mode');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    if ($oldversion < 2009062903) {
        $ptroleid = get_field('role', 'id', 'shortname', ROLE_PT);
        $lparoleid = get_field('role', 'id', 'shortname', ROLE_LPAUTHOR);
        set_config('defaultcourseroleid', $ptroleid);
        set_config('creatornewroleid', $lparoleid);
    }
    if ($oldversion < 2009070200) {
        // force setup of rafl item fields
        $table = new XMLDBTable('format_page');
        $field = new XMLDBField('rafl_item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('format_page_items');
        $field = new XMLDBField('rafl_item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, null, null, null, null, null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    if ($result && $oldversion < 2009071803) {
        //delete old tao_certification table and insert it's rows into the new table
        $table = new XMLDBTable('tao_certification_status');
        if (table_exists($table)) {
            $certrecords = get_records('tao_certification_status');
            if (!empty($certrecords)) {
                foreach ($certrecords as $cert) {
                    $cert->id = null;
                    insert_record('tao_user_certification_status', $cert);
                }
            }
            drop_table($table);
        }
        //now remove old blocks.
        $oldblocknames = array('authored_learning_paths', 'certification_path', 'course_status', 'learning_path_summary', 'lp_brief', 'lp_qa', 'team_groups');
        foreach ($oldblocknames as $oldblockname) {
            if ($oldblockid = get_field('block', 'id', 'name', $oldblockname)) {
                //first get new blocks id
                $newblockid = get_field('block', 'id', 'name', 'tao_' . $oldblockname);
                //now update block instance table replacing oldid with new one
                $oldblocks = get_records('block_instance', 'blockid', $oldblockid);
                if (!empty($oldblocks)) {
                    foreach ($oldblocks as $oldblock) {
                        $oldblock->blockid = $newblockid;
                        update_record('block_instance', $oldblock);
                    }
                }
                //now delete old record from block table.
                delete_records('block', 'name', $oldblockname);
            }
        }
    }
    if ($result && $oldversion < 2009072700) {
        //set up custom scale - in postinst so that the $USER is set.
        $scale = new stdclass();
        $scale->courseid = 0;
        $scale->userid = 0;
        $scale->name = 'TAO: Stars';
        $scale->scale = '★☆☆☆☆, ★★☆☆☆, ★★★☆☆, ★★★★☆, ★★★★★';
        $scale->description = '';
        $scale->timemodified = time();
        insert_record('scale', $scale);
    }
    if ($result && $oldversion < 2009072701) {
        //create new table for storing TAOview ratings
        $table = new XMLDBTable('taoview_ratings');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('artefactid', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('time', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rating', XMLDB_TYPE_INTEGER, 4, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2009072706) {
        //published course category is being moved.
        $cat = get_field('course_categories', 'id', 'name', get_string('taocatlp', 'local'));
        $pubcat = get_field('course_categories', 'id', 'name', 'Published');
        if (!empty($cat) && !empty($pubcat)) {
            //set default publish category to the main one.
            set_config('lppublishedcategory', $cat);
            //now find all the courses in the old published category and put them in the new one.
            $publishedcourses = get_records('course', 'category', $pubcat);
            if (!empty($publishedcourses)) {
                foreach ($publishedcourses as $pc) {
                    $pc->category = $cat;
                    update_record('course', $pc);
                }
            }
            //now remove old course category
            delete_records('course_categories', 'id', $pubcat);
        }
    }
    if ($result && $oldversion < 2009072708) {
        //now prevent the admin user from having the switchrole cap in learning path category
        $lpid = get_field('course_categories', 'id', 'name', get_string('taocatlp', 'local'));
        if (!empty($lpid)) {
            //this will only trigger on upgrades - not for fresh installs as the above category isn't created untill post_inst
            $catcontext = get_context_instance(CONTEXT_COURSECAT, $lpid);
            foreach (get_admin_roles() as $adminrole) {
                assign_capability('moodle/role:switchroles', CAP_PREVENT, $adminrole->id, $catcontext->id);
            }
        }
    }
    if ($result && $oldversion < 2009080300) {
        $reassigncaps = true;
        $resetcustomroles = true;
        $resetstickyblocks = true;
    }
    if ($result && $oldversion < 2009080301) {
        set_config('allowvisiblecoursesinhiddencategories', '1');
    }
    if ($result && $oldversion < 2009080302) {
        //delete old header image records
        delete_records('header_image', 'url', '/local/mahara/taoview.php?view=teaching');
        delete_records('header_image', 'url', '/local/mahara/taoview.php?view=tools');
        $headerimg = new stdclass();
        $headerimg->image = 'myteaching.jpg';
        $headerimg->url = '/local/mahara/taoviewtaoresources.php';
        $headerimg->description = get_string('myteaching', 'local');
        $headerimg->sortorder = 1;
        if (!record_exists('header_image', 'image', $headerimg->image, 'url', $headerimg->url)) {
            insert_record('header_image', $headerimg);
        }
        $headerimg->image = 'mytools.jpg';
        $headerimg->url = '/local/mahara/taoviewtaotools.php';
        $headerimg->description = get_string('mytools', 'local');
        if (!record_exists('header_image', 'image', $headerimg->image, 'url', $headerimg->url)) {
            insert_record('header_image', $headerimg);
        }
    }
    if ($result && $oldversion < 2009080303) {
        set_config('defaulthtmleditor', 'tinymce');
    }
    if ($result && $oldversion < 2009080309) {
        require_once $CFG->dirroot . '/mod/rafl/locallib.php';
        if (!check_rafl_table_encoding()) {
            notify("WARNING: The smartassess rafl tables are not utf8 based tables - they must be manually converted.");
            $result = false;
        }
    }
    if ($result && $oldversion < 2009101407) {
        $table = new XMLDBTable('rafl_webcells');
        if (table_exists($table)) {
            $webcelltext = 'How will the learning path be evaluated and developed?';
            $sql = "UPDATE {$CFG->prefix}rafl_webcells SET webcell_title = '" . $webcelltext . "' WHERE webcell_id =368657";
            if (!execute_sql($sql)) {
                notify('rafl_webcells UPDATE failed');
                $result = false;
            }
            //now update format page
            $fpitems = get_records('format_page', 'nameone', 'How will the learning path be evaluated and develo');
            foreach ($fpitems as $fpi) {
                $fpi->nameone = $webcelltext;
                $fpi->nametwo = $webcelltext;
                update_record('format_page', $fpi);
            }
        }
    }
    if ($result && $oldversion < 2009101410) {
        $reassigncaps = true;
        $resetcustomroles = true;
    }
    if ($result && $oldversion < 2009101413) {
        //MNET change update.
        //first create array of mappings
        $mnetfields = array();
        $mnetfields['address'] = 'address';
        $mnetfields['aim'] = 'aimscreenname';
        $mnetfields['city'] = 'town';
        $mnetfields['country'] = 'country';
        $mnetfields['deleted'] = 'deleted';
        $mnetfields['description'] = 'introduction';
        $mnetfields['firstname'] = 'firstname';
        $mnetfields['htmleditor'] = 'wysiwyg';
        $mnetfields['icq'] = 'icqnumber';
        $mnetfields['idnumber'] = 'studentid';
        $mnetfields['lang'] = 'lang';
        $mnetfields['lastname'] = 'lastname';
        $mnetfields['mns'] = 'mnsnumber';
        $mnetfields['phone1'] = 'businessnumber';
        $mnetfields['phone2'] = 'homenumber';
        $mnetfields['skype'] = 'skypeusername';
        $mnetfields['url'] = 'officialwebsite';
        $mnetfields['yahoo'] = 'yahoochat';
        //first find any active mnet entries.
        $hosts = get_records_select('mnet_host', 'deleted=0 AND applicationid=2');
        if (!empty($hosts)) {
            foreach ($hosts as $host) {
                foreach ($mnetfields as $name => $value) {
                    set_config($name, $value, 'mnet_userprofile_' . $host->id);
                }
            }
        }
        //now add mapping fields to db.
    }
    // check whether we've been asked to reset anything
    if (!empty($reassigncaps)) {
        tao_reassign_capabilities();
    }
    if (!empty($resetcustomroles)) {
        if (empty($CFG->taomode)) {
            // only perform this in 'core' taomode
            tao_reset_custom_roles();
        }
    }
    if (!empty($resetstickyblocks)) {
        if (empty($CFG->taomode)) {
            // only perform this in 'core' taomode
            tao_reset_stickyblocks(true);
        }
    }
    return $result;
}
コード例 #11
0
function xmldb_data_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    /// if ($result && $oldversion < YYYYMMDD00) { //New version in version.php
    ///     $result = result of "/lib/ddllib.php" function calls
    /// }
    if ($result && $oldversion < 2006121300) {
        /// Define field format to be added to data_comments
        $table = new XMLDBTable('data_comments');
        $field = new XMLDBField('format');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'content');
        /// Launch add field format
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007022600) {
        /// Define field asearchtemplate to be added to data
        $table = new XMLDBTable('data');
        $field = new XMLDBField('asearchtemplate');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'jstemplate');
        /// Launch add field asearchtemplate
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007072200) {
        require_once $CFG->dirroot . '/mod/data/lib.php';
        // too much debug output
        $db->debug = false;
        data_update_grades();
        $db->debug = true;
    }
    if ($result && $oldversion < 2007081400) {
        /// Define field notification to be added to data
        $table = new XMLDBTable('data');
        $field = new XMLDBField('notification');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null, 'editany');
        /// Launch add field notification
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007081402) {
        /// Define index type-dataid (not unique) to be added to data_fields
        $table = new XMLDBTable('data_fields');
        $index = new XMLDBIndex('type-dataid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('type', 'dataid'));
        /// Launch add index type-dataid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Define index course (not unique) to be added to data
        $table = new XMLDBTable('data');
        $index = new XMLDBIndex('course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course'));
        /// Launch add index course
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
    }
    //===== 1.9.0 upgrade line ======//
    if ($result && $oldversion < 2007101512) {
        /// Launch add field asearchtemplate again if does not exists yet - reported on several sites
        $table = new XMLDBTable('data');
        $field = new XMLDBField('asearchtemplate');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'jstemplate');
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    ///Display a warning message about "Required Entries" fix from MDL-16999
    if ($result && $oldversion < 2007101514) {
        if (!get_config('data', 'requiredentriesfixflag')) {
            set_config('requiredentriesfixflag', true, 'data');
            // remove old flag
            $databases = get_records_sql("SELECT d.*, c.fullname\n                                              FROM {$CFG->prefix}data d, {$CFG->prefix}course c\n                                              WHERE d.course = c.id\n                                              AND (d.requiredentries > 0 OR d.requiredentriestoview > 0)\n                                              ORDER BY c.fullname, d.name");
            if (!empty($databases)) {
                $a = new object();
                $a->text = '';
                foreach ($databases as $database) {
                    $a->text .= "<p>" . $database->fullname . " - " . $database->name . " (course id: " . $database->course . " - database id: " . $database->id . ")</p>";
                }
                notify(get_string('requiredentrieschanged', 'data', $a));
            }
        }
    }
    if ($result && $oldversion < 2007101515) {
        // Upgrade all the data->notification currently being
        // NULL to 0
        $sql = "UPDATE {$CFG->prefix}data SET notification=0 WHERE notification IS NULL";
        $result = execute_sql($sql);
        $table = new XMLDBTable('data');
        $field = new XMLDBField('notification');
        // First step, Set NOT NULL
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'editany');
        $result = $result && change_field_notnull($table, $field);
        // Second step, Set default to 0
        $result = $result && change_field_default($table, $field);
    }
    return $result;
}
コード例 #12
0
function xmldb_wiki_upgrade($oldversion = 0)
{
    global $CFG, $db;
    $result = true;
    // Checks if the current version installed in the system is old wiki (ewiki) or is new wiki (nwiki)
    // We can distinguish ewiki from nwiki checking wiki_synonymous table existence.
    //Initialy we asume we aren't upgrading from old wiki
    $fromoldwiki = false;
    $table = new XMLDBTable('wiki_synonymous');
    if (!table_exists($table)) {
        //New wiki isn't installed yet
        $fromoldwiki = true;
        //We are upgrading from old wiki.
        // Upgrading ewiki to last version using XMLDB functions.
        require_once $CFG->dirroot . '/mod/wiki/wikimigrate/ewiki_upgrade.php';
        $result = xmldb_ewiki_upgrade($oldversion);
        // We have an upgraded ewiki at this point of process.
        // Migration can start.
        require_once $CFG->dirroot . '/mod/wiki/wikimigrate/ewiki_migrate.php';
        wiki_migrate_ewiki();
        $oldversion = 0;
    }
    if ($result && $oldversion < 2006042900) {
        //Delete previous log_display records for wiki for safety
        delete_records('log_display', 'module', 'wiki');
        //Add new log_display_records
        $record->module = 'wiki';
        $record->action = 'add';
        $record->mtable = 'wiki';
        $record->field = 'name';
        $result = insert_record('log_display', $record);
        $record->action = 'update';
        $result = $result && insert_record('log_display', $record);
        $record->action = 'view';
        $result = $result && insert_record('log_display', $record);
        $record->action = 'view all';
        $result = $result && insert_record('log_display', $record);
        $record->mtable = 'wiki_pages';
        $record->field = 'pagename';
        $record->action = 'view page';
        $result = $result && insert_record('log_display', $record);
        $record->action = 'edit page';
        $result = $result && insert_record('log_display', $record);
        $record->action = 'save page';
        $result = $result && insert_record('log_display', $record);
        $record->action = 'info page';
        $result = $result && insert_record('log_display', $record);
        // OLD SENTENCES
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'add', 'wiki', 'name') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'update', 'wiki', 'name') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'view', 'wiki', 'name') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'view all', 'wiki', 'name') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'view page', 'wiki_pages', 'pagename') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'edit page', 'wiki_pages', 'pagename') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'save page', 'wiki_pages', 'pagename') ");
        //        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('wiki', 'info page', 'wiki_pages', 'pagename') ");
    }
    if ($result && $oldversion < 2006050301) {
        $result = table_column('wiki_synonymous', '', 'userid', 'int', '10', 'unsigned', '0', 'not null', 'groupid');
        if (empty($fromoldwiki)) {
            //Only if we aren't migrating from old wiki, because it creates these columns and fills them!
            $result = $result && table_column('wiki', '', 'intro', 'text', '', '', '', 'not null', 'name');
            $result = $result && table_column('wiki', '', 'introformat', 'tinyint', '2', 'unsigned', '0', 'not null', 'intro');
            //add colums
            $result = $result && table_column('wiki_pages', '', 'userid', 'int', '10', 'unsigned', '0', 'not null', 'author');
            $result = $result && table_column('wiki_synonymous', '', 'userid', 'int', '10', 'unsigned', '0', 'not null', 'groupid');
            //set userid  via author values
            $authors = get_records_select('wiki_pages', null, null, 'distinct author');
            // OLD SENTENCE
            //            $authors = get_records_sql('SELECT DISTINCT author, author FROM '.$CFG->prefix.'wiki_pages');
            foreach ($authors as $author) {
                if ($user = get_record('user', 'username', $author->author)) {
                    $result = $result && set_field('wiki_pages', 'userid', $user->id, 'author', $author->author);
                }
            }
        }
    }
    if ($result && $oldversion < 2006050500) {
        //droping and regenerating some indexes to normalize everything
        //(some of them could not exist, but for safety...)
        $table = new XMLDBTable('wiki');
        $index = new XMLDBIndex('course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course'));
        $result = drop_index($table, $index);
        $index = new XMLDBIndex('course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course'));
        $result = $result && add_index($table, $index);
        $table = new XMLDBTable('wiki_pages');
        $key = new XMLDBKey('dfwiki_pages_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid'));
        $result = $result && drop_key($table, $key);
        $key = new XMLDBKey('wiki_pages_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid'));
        $result = $result && drop_key($table, $key);
        $key = new XMLDBKey('wiki_pages_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid', 'ownerid'));
        $result = $result && add_key($table, $key);
        $table = new XMLDBTable('wiki_synonymous');
        $key = new XMLDBKey('dfwiki_synonymous_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'userid'));
        $result = drop_key($table, $key);
        $key = new XMLDBKey('wiki_synonymous_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'userid'));
        $result = drop_key($table, $key);
        $key = new XMLDBKey('wiki_synonymous_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'userid'));
        $result = $result && add_key($table, $key);
        // OLD SENTENCES
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki DROP KEY course;",false);
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki ADD KEY course (course);",false);
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages DROP KEY dfwiki_pages_uk;",false);
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages DROP KEY wiki_pages_uk;",false);
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages ADD UNIQUE KEY wiki_pages_uk (pagename, version, dfwiki, groupid, userid);",false);
        //-        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous DROP KEY dfwiki_synonymous_uk;",false);
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous DROP KEY wiki_synonymous_uk;",false);
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous ADD UNIQUE KEY wiki_synonymous_uk (syn,dfwiki,groupid, userid);",false);
    }
    if ($result && $oldversion < 2006051800) {
        $table = new XMLDBTable('wiki_pages');
        $field = new XMLDBField('highlight');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'editable');
        $result = add_field($table, $field);
        // OLD SENTECE
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` ADD `highlight` tinyint(1) NOT NULL default 0 AFTER `editable`');
    }
    if ($result && $oldversion < 2006053000) {
        if (empty($fromoldwiki)) {
            //Only if we aren't migrating from old wiki, because it creates this column!
            $table = new XMLDBTable('wiki_pages');
            $field = new XMLDBField('votes');
            $field->setAttributes(XMLDB_TYPE_INTEGER, null, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'hits');
            $result = add_field($table, $field);
            // OLD SENTENCE
            //    execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` ADD `votes` INTEGER UNSIGNED NOT NULL default 0 AFTER `hits`');
        }
    }
    if ($result && $oldversion < 2006060701) {
        if (empty($fromoldwiki)) {
            $table = new XMLDBTable('wiki');
            $field = new XMLDBField('studentmode');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = add_field($table, $field);
            $field = new XMLDBField('teacherdiscussion');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            $field = new XMLDBField('studentdiscussion');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            $field = new XMLDBField('editanothergroup');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            $field = new XMLDBField('editanotherstudent');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            $table = new XMLDBTable('wiki_pages');
            $field = new XMLDBField('evaluation');
            $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, '', 'groupid');
            $result = add_field($table, $field);
            // OLD SENTENCES
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `studentmode` tinyint(1) NOT NULL default 0');
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `teacherdiscussion` int(1) NOT NULL default 0');
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `studentdiscussion` int(1) NOT NULL default 0');
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `editanothergroup` tinyint(1) not null default 0');
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `editanotherstudent` tinyint(1) not null default 0');
            //
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` ADD `evaluation` MEDIUMTEXT default NULL AFTER `groupid`');
        } else {
            $table = new XMLDBTable('wiki_pages');
            $field = new XMLDBField('evaluation');
            $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, '', 'ownerid');
            $result = add_field($table, $field);
            // OLD SENTENCE
            //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` ADD `evaluation` MEDIUMTEXT default NULL AFTER `ownerid`');
        }
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('evaluation');
        $field->setAttributes(XMLDB_TYPE_CHAR, '40', null, null, null, null, null, 'noeval', 'studentdiscussion');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('notetype');
        $field->setAttributes(XMLDB_TYPE_CHAR, '40', null, null, null, null, null, 'quant', 'evaluation');
        $result = $result && add_field($table, $field);
        // OLD SENTECES
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `evaluation` varchar(40) default "noeval" AFTER `studentdiscussion`');
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `notetype` varchar(40) default "quant" AFTER `evaluation`');
    }
    if ($result && $oldversion < 2006060702 && empty($fromoldwiki)) {
        //make sure we don't have ownerid in the DB (backward compatibility)
        $table = new XMLDBTable('wiki_pages');
        $field = $table->findFieldInArray('ownerid');
        if (empty($field)) {
            $field = new XMLDBField('ownerid');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'groupid');
            $result = add_field($table, $field);
            $key = new XMLDBKey('wiki_pages_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid'));
            $result = $result && drop_key($table, $key);
            $key = new XMLDBKey('wiki_pages_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid', 'ownerid'));
            $result = $result && add_key($table, $key);
            $table = new XMLDBTable('wiki_synonymous');
            $field = new XMLDBField('userid');
            $result = $result && drop_field($table, $field);
            $field = new XMLDBField('ownerid');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            $key = new XMLDBKey('wiki_synonymous_uk');
            $result = $result && drop_key($table, $key);
            $key = new XMLDBKey('wiki_synonymous_uk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'ownerid'));
            $result = $result && add_key($table, $key);
            // OLD SENTENCES
            //        //make sure we don't have ownerid in the DB (backward compatibility)
            //       if(!get_records_sql('SELECT ownerid FROM '.$CFG->prefix.'wiki_pages LIMIT 0 , 30')){
            //            //adding new ownerid replacing userid
            //-            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` ADD `ownerid` int(10) unsigned not null default 0 AFTER `groupid`');
            //-            execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous DROP userid;",false);
            //-            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_synonymous` ADD `ownerid` int(10) unsigned not null default 0');
            //
            //-            execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages DROP KEY wiki_pages_uk;",false);
            //-            execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages ADD UNIQUE KEY wiki_pages_uk (pagename, version, dfwiki, groupid, userid, ownerid);",false);
            //
            //-            execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous DROP KEY wiki_synonymous_uk;",false);
            //-            execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous ADD UNIQUE KEY wiki_synonymous_uk (syn,dfwiki,groupid,ownerid);",false);
            //
            //now ownerid is the old userid, and userid is the author's id
            $quer = 'UPDATE ' . $CFG->prefix . 'wiki_pages SET ownerid = userid';
            $result = $result && execute_sql($quer);
            // It can't be translated to XMLDB functions
            $authors = get_records_select('wiki_pages', null, null, 'distinct author');
            foreach ($authors as $author) {
                if ($user = get_record('user', 'username', $author->author)) {
                    //set userid corrrectly
                    set_field('wiki_pages', 'userid', $user->id, 'author', $author->author);
                }
                // OLD SENTENCES
                //            //now ownerid is the old userid, and userid is the author's id
                //            $quer = 'UPDATE '.$CFG->prefix.'wiki_pages
                //            SET ownerid = userid';
                //            execute_sql($quer);
                //
                //            //set userid  via author values
                //            $authors = get_records_sql('SELECT DISTINCT author, author FROM '.$CFG->prefix.'wiki_pages');
                //            foreach($authors as $author) {
                //                if ($user = get_record('user', 'username', $author->author)) {
                //                        //set userid corrrectly
                //                        set_field ('wiki_pages', 'userid', $user->id, 'author', $author->author);
                //                }
                //            }
            }
        }
    }
    if ($result && $oldversion < 2006060702 && $fromoldwiki) {
        $table = new XMLDBTable('wiki_pages');
        $field = new XMLDBField('destacar');
        $result = drop_field($table, $field);
        $key = new XMLDBKey('wiki_pages_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid'));
        $result = $result && drop_key($table, $key);
        $key = new XMLDBKey('wiki_pages_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('pagename', 'version', 'dfwiki', 'groupid', 'userid', 'ownerid'));
        $result = $result && add_key($table, $key);
        $table = new XMLDBTable('wiki_synonymous');
        $field = new XMLDBField('userid');
        $result = $result && drop_field($table, $field);
        $key = new XMLDBKey('wiki_synonymous_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'userid', 'ownerid'));
        $result = $result && drop_key($table, $key);
        $key = new XMLDBKey('wiki_synonymous_uk');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('syn', 'dfwiki', 'groupid', 'ownerid'));
        $result = $result && add_key($table, $key);
        // OLD SENTENCES
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` DROP `destacar`');
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_synonymous` DROP `userid`');
        //
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages DROP KEY wiki_pages_uk;",false);
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_pages ADD UNIQUE KEY wiki_pages_uk (pagename, version, dfwiki, groupid, userid, ownerid);",false);
        //
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous DROP KEY wiki_synonymous_uk;",false);
        //        execute_sql(" ALTER TABLE {$CFG->prefix}wiki_synonymous ADD UNIQUE KEY wiki_synonymous_uk (syn,dfwiki,groupid,ownerid);",false);
        $authors = get_records_select('wiki_pages', null, null, 'author');
        if (!empty($authors)) {
            foreach ($authors as $author) {
                if ($user = get_record('user', 'username', $author->author)) {
                    //set userid corrrectly
                    set_field('wiki_pages', 'userid', $user->id, 'author', $author->author);
                }
            }
        }
        //OLD SENTENCES
        //        //set userid  via author values
        //        $authors = get_records_sql('SELECT DISTINCT author, author FROM '.$CFG->prefix.'wiki_pages');
        //        foreach($authors as $author) {
        //            if ($user = get_record('user', 'username', $author->author)) {
        //                //set userid corrrectly
        //                set_field ('wiki_pages', 'userid', $user->id, 'author', $author->author);
        //            }
        //        }
    }
    //Actualizamos la newwiki independientemenre de si hemos utilizado
    //una dfwiki instalada y actualizada o una dfwiki temporal
    if ($result && $oldversion < 2006070700) {
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('votemode');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = add_field($table, $field);
        // OLD SENTENCE
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `votemode` tinyint(1) NOT NULL default 0');
    }
    if ($result && $oldversion < 2006070703) {
        $table = new XMLDBTable('wiki_votes');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('pagename', XMLDB_TYPE_CHAR, '160', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, '0', null);
        $table->addFieldInfo('dfwiki', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, '0', null);
        $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $result = create_table($table);
        // OLD SENTENCE
        //        execute_sql('CREATE TABLE `'.$CFG->prefix.'wiki_votes` (`id` int(10) unsigned NOT NULL auto_increment,
        //                          `pagename` varchar(160) NOT NULL,
        //                          `version` int(10) unsigned NOT NULL default 0,
        //                          `dfwiki` int(10) unsigned NOT NULL,
        //                          `username` varchar(100) NOT NULL,
        //                          PRIMARY KEY  (`id`))');
    }
    if ($result && $oldversion < 2006071402) {
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('listofteachers');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = add_field($table, $field);
        // OLD SENTENCE
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `listofteachers` tinyint(1) NOT NULL default 0');
    }
    if ($result && $oldversion < 2006072401) {
        $table = new XMLDBTable('wiki_pages');
        $field = new XMLDBField('votes');
        $result = drop_field($table, $field);
        // OLD VERSION
        //        execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_pages` DROP `votes`');
    }
    // correct version error
    if ($result && $oldversion == 2006271001) {
        $oldversion = 2006102701;
        $result = set_field('modules', 'version', '2006102701', 'name', 'wiki');
        // OLD SENTENCE
        //        execute_sql('UPDATE `'.$CFG->prefix.'modules` SET `version`= 2006102701 WHERE `name` = wiki');
    }
    if ($result && $oldversion < 2006112101) {
        $table = new XMLDBTable('wiki');
        $field = $table->findFieldInArray('editorrows');
        if (empty($field)) {
            $field = new XMLDBField('editorrows');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, '40', null);
            $result = add_field($table, $field);
        }
        $field = $table->findFieldInArray('editorcols');
        if (empty($field)) {
            $field = new XMLDBField('editorcols');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, '60', null);
            $result = $result && add_field($table, $field);
        }
        // OLD SENTENCES
        //        if (!get_records_sql('SHOW COLUMNS FROM '.$CFG->prefix.'wiki WHERE Field=\'editorrows\'')){
        //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `editorrows` integer NOT NULL DEFAULT 40');
        //        }
        //
        //        if (!get_records_sql('SHOW COLUMNS FROM '.$CFG->prefix.'wiki WHERE Field=\'editorcols\'')){
        //            execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `editorcols` integer NOT NULL DEFAULT 60');
        //        }
    }
    if ($result && $oldversion < 2006112502) {
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('wikicourse');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = add_field($table, $field);
        // OLD SENTENCE
        //      execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `wikicourse` int(10) unsigned NOT NULL DEFAULT 0');
        if ($wikicourses = get_records('course', 'format', 'wiki')) {
            $wikimod = get_record('modules', 'name', 'wiki');
            foreach ($wikicourses as $wikicourse) {
                $min = get_record_select('course_module', 'course = ' . $wikicourse->id . ' AND module = ' . $wikimod->id, 'min(id) as minim');
                // OLD SENTENCE
                //              $min = get_record_sql('SELECT MIN(`id`) AS minim FROM '.$CFG->prefix.'course_modules WHERE `course`=\''.$wikicourse->id.'\' AND `module`=\''.$wikimod->id.'\'');
                $cm = get_record('course_modules', 'id', $min->minim);
                $result = $result && set_field('wiki', 'wikicourse', $wikicourse->id, 'id', $cm->instance);
            }
        }
    }
    if ($result && $oldversion < 2007022707) {
        // Moving archives to the new directory (from dfwikiX to wikiX)
        require_once $CFG->dirroot . '/lib/uploadlib.php';
        require_once $CFG->dirroot . '/backup/lib.php';
        $wikimod = get_record("modules", "name", "wiki");
        $wikis = get_records("wiki");
        if (!empty($wikis)) {
            foreach ($wikis as $wiki) {
                $cm = get_record("course_modules", "course", $wiki->course, "instance", $wiki->id, "module", $wikimod->id);
                if (check_dir_exists($CFG->dataroot . "/" . $wiki->course . "/moddata/dfwiki" . $cm->id)) {
                    check_dir_exists($CFG->dataroot . "/" . $wiki->course . "/moddata/wiki" . $cm->id, true, true);
                    $flist = list_directories_and_files($CFG->dataroot . "/" . $wiki->course . "/moddata/dfwiki" . $cm->id);
                    foreach ($flist as $file) {
                        $result = $result && copy($CFG->dataroot . "/" . $wiki->course . "/moddata/dfwiki" . $cm->id . "/" . $file, $CFG->dataroot . "/" . $wiki->course . "/moddata/wiki" . $cm->id . "/" . $file);
                    }
                    $result = $result && remove_dir($CFG->dataroot . "/" . $wiki->course . "/moddata/dfwiki" . $cm->id);
                }
            }
        }
    }
    if ($result && $oldversion < 2007030301) {
        // Adding filetemplate file to database
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('filetemplate');
        $field->setAttributes(XMLDB_TYPE_CHAR, '60', null, null, null, null, null, null, null);
        $result = add_field($table, $field);
        // OLD SENTENCE
        //      execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `filetemplate` VARCHAR(60) NULL DEFAULT NULL');
    }
    if ($result && $oldversion < 2007060701) {
        $table = new XMLDBTable('wiki_locks');
        if (!table_exists($table)) {
            // Adding wiki_locks table to admin wiki pages lock system
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
            $table->addFieldInfo('wikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
            $table->addFieldInfo('pagename', XMLDB_TYPE_CHAR, '160', null, XMLDB_NOTNULL, null, null, '', null);
            $table->addFieldInfo('lockedby', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 0, null);
            $table->addFieldInfo('lockedsince', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, '0', null);
            $table->addFieldInfo('lockedseen', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, '0', null);
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addKeyInfo('wiki_locks_uk', XMLDB_KEY_UNIQUE, array('wikiid', 'pagename'));
            $table->addIndexInfo('wiki_locks_ix', XMLDB_INDEX_NOTUNIQUE, array('lockedseen'));
            $result = $result && create_table($table);
        }
        // OLD SENTENCE
        //		modify_database("","
        //			CREATE TABLE prefix_wiki_locks
        //			(
        //			  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
        //			  wikiid INT(10) UNSIGNED NOT NULL,
        //			  pagename VARCHAR(160) NOT NULL DEFAULT '',
        //			  lockedby INT(10) NOT NULL DEFAULT 0,
        //			  lockedsince INT(10) NOT NULL DEFAULT 0,
        //			  lockedseen INT(10) NOT NULL DEFAULT 0,
        //			  PRIMARY KEY(id),
        //			  UNIQUE INDEX wiki_locks_uk(wikiid,pagename),
        //			  INDEX wiki_locks_ix(lockedseen)
        //			);");
    }
    if ($result && $oldversion < 2007072301) {
        ////////////////////////////
        // Fixing some old errors //
        ////////////////////////////
        // Old mysql.php created this field as intergers: int(11)
        // They must be smallint(3)
        //
        // I'm going to change defaults too.
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('editorrows');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, null, null, '30', null);
        $result = change_field_precision($table, $field);
        $result = $result && change_field_default($table, $field);
        $field = new XMLDBField('editorcols');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, null, null, '120', null);
        $result = $result && change_field_precision($table, $field);
        $result = $result && change_field_default($table, $field);
        // Changing wikicourse to bigint
        $field = new XMLDBField('wikicourse');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_precision($table, $field);
        }
        // Renaming key 'course'
        $key = new XMLDBIndex('course');
        $key->setAttributes(XMLDB_INDEX_UNIQUE, array('course'));
        $result = $result && drop_index($table, $key);
        $key = new XMLDBIndex('wiki_cou_ix');
        $key->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course'));
        $result = $result && add_index($table, $key);
        /*	
        	// Changing some field in wiki_pages
        	$table = new XMLDBTable('wiki_pages');
        	$field = new XMLDBField('evaluation');
        	$field->setAttributes(XMLDB_TYPE_TEXT,'medium' , null, XMLDB_NOTNULL, null, null, null, "", 'ownerid');
        	$result = $result && change_field_default($table, $field);
        	$result = $result && change_field_notnull($table, $field);
        */
    }
    // Add groupid and ownerid fields to the wiki_locks table
    if ($result && $oldversion < 2007121701) {
        $table = new XMLDBTable('wiki_locks');
        $field = new XMLDBField('groupid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, 0, null);
        $result = add_field($table, $field);
        $field = new XMLDBField('ownerid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0, null);
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008013105) {
        // To create a new tables: wiki_evaluation and wiki_evaluation_edition
        /////////// WIKI_EVALUATION ////////////////////////////////
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('evaluation');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'studentdiscussion');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('notetype');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'evaluation');
        $result = $result && add_field($table, $field);
        /// Define field id to be added to wiki_evaluation
        $table = new XMLDBTable('wiki_evaluation');
        if (!table_exists($table)) {
            // Adding wiki_evaluation table
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null, null);
            $table->addFieldInfo('pagename', XMLDB_TYPE_CHAR, '160', null, XMLDB_NOTNULL, null, null, null, null, 'id');
            $table->addFieldInfo('wikiid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'pagename');
            $table->addFieldInfo('groupid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'wikiid');
            $table->addFieldInfo('ownerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'groupid');
            $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'ownerid');
            $table->addFieldInfo('wikigrade', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'userid');
            $table->addFieldInfo('wikigrade_initial', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'wikigrade');
            $table->addFieldInfo('comment', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'wikigrade_initial');
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addKeyInfo('key_uinique', XMLDB_KEY_UNIQUE, array('pagename', 'wikiid', 'groupid', 'ownerid', 'userid'));
            $table->addKeyInfo('foreign_key_user', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
            $result = $result && create_table($table);
        }
        /////////// WIKI_EVALUATION_EDITION ////////////////////////////////
        /// Define field id to be added to wiki_evaluation_edition
        $table = new XMLDBTable('wiki_evaluation_edition');
        if (!table_exists($table)) {
            // Adding wiki_evaluation table
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null, null);
            $table->addFieldInfo('wiki_pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
            $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'wiki_pageid');
            $table->addFieldInfo('valoration', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, null, 'userid');
            $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'valoration');
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addKeyInfo('key_unique_edition', XMLDB_KEY_UNIQUE, array('wiki_pageid', 'userid'));
            $table->addKeyInfo('foreign_key_user', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
            $table->addKeyInfo('foreign_key_wikipage', XMLDB_KEY_FOREIGN, array('wiki_pageid'), 'wiki_pages', array('id'));
            /// Create the table wiki_evaluation_edition
            $result = $result && create_table($table);
        }
    }
    if ($result && $oldversion < 2008080401) {
        $table = new XMLDBTable('wiki');
        $field = new XMLDBField('evaluation');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'studentdiscussion');
        $result = $result && change_field_type($table, $field);
        $field = new XMLDBField('notetype');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'evaluation');
        $result = $result && change_field_type($table, $field);
    }
    return $result;
}
コード例 #13
0
ファイル: upgrade.php プロジェクト: kai707/ITSA-backup
function xmldb_feedback_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2007012310) {
        //create a new table feedback_completedtmp and the field-definition
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, true, null, null, null, null);
        $table->addField($field);
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('guestid');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, false, null, null, '', null);
        $table->addField($field);
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $key = new XMLDBKey('PRIMARY');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
        $table->addKey($key);
        $key = new XMLDBKey('feedback');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('feedback'), 'feedback', 'id');
        $table->addKey($key);
        $result = $result && create_table($table);
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        //create a new table feedback_valuetmp and the field-definition
        $table = new XMLDBTable('feedback_valuetmp');
        $field = new XMLDBField('id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, true, null, null, null, null);
        $table->addField($field);
        $field = new XMLDBField('course_id');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('item');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('completed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('tmp_completed');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        $table->addField($field);
        $field = new XMLDBField('value');
        $field->setAttributes(XMLDB_TYPE_TEXT, null, null, null, false, null, null, '', null);
        $table->addField($field);
        $key = new XMLDBKey('PRIMARY');
        $key->setAttributes(XMLDB_KEY_PRIMARY, array('id'));
        $table->addKey($key);
        $key = new XMLDBKey('feedback');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('item'), 'feedback_item', 'id');
        $table->addKey($key);
        $result = $result && create_table($table);
        ////////////////////////////////////////////////////////////
    }
    if ($result && $oldversion < 2007050504) {
        /// Define field random_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completed');
        $field = new XMLDBField('random_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        /// Launch add field1
        $result = $result && add_field($table, $field);
        /// Define field anonymous_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completed');
        $field = new XMLDBField('anonymous_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '1', null);
        /// Launch add field2
        $result = $result && add_field($table, $field);
        /// Define field random_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('random_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '0', null);
        /// Launch add field1
        $result = $result && add_field($table, $field);
        /// Define field anonymous_response to be added to feedback_completed
        $table = new XMLDBTable('feedback_completedtmp');
        $field = new XMLDBField('anonymous_response');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, false, null, null, '1', null);
        /// Launch add field2
        $result = $result && add_field($table, $field);
        ////////////////////////////////////////////////////////////
    }
    if ($result && $oldversion < 2007102600) {
        // public is a reserved word on Oracle
        $table = new XMLDBTable('feedback_template');
        $field = new XMLDBField('ispublic');
        if (!field_exists($table, $field)) {
            $result = $result && table_column('feedback_template', 'public', 'ispublic', 'integer', 1);
        }
    }
    if ($result && $oldversion < 2008042400) {
        //New version in version.php
        if ($all_nonanonymous_feedbacks = get_records('feedback', 'anonymous', 2)) {
            $update_sql = 'UPDATE ' . $CFG->prefix . 'feedback_completed SET anonymous_response = 2 WHERE feedback = ';
            foreach ($all_nonanonymous_feedbacks as $fb) {
                $result = $result && execute_sql($update_sql . $fb->id);
            }
        }
    }
    if ($result && $oldversion < 2008042401) {
        //New version in version.php
        if ($result) {
            $concat_radio = sql_concat("'r>>>>>'", 'presentation');
            $concat_check = sql_concat("'c>>>>>'", 'presentation');
            $concat_dropdown = sql_concat("'d>>>>>'", 'presentation');
            $update_sql1 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_radio . " WHERE typ IN('radio','radiorated')";
            $update_sql2 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_dropdown . " WHERE typ IN('dropdown','dropdownrated')";
            $update_sql3 = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = " . $concat_check . " WHERE typ = 'check'";
            $result = $result && execute_sql($update_sql1);
            $result = $result && execute_sql($update_sql2);
            $result = $result && execute_sql($update_sql3);
        }
        if ($result) {
            $update_sql1 = "UPDATE " . $CFG->prefix . "feedback_item SET typ = 'multichoice' WHERE typ IN('radio','check','dropdown')";
            $update_sql2 = "UPDATE " . $CFG->prefix . "feedback_item SET typ = 'multichoicerated' WHERE typ IN('radiorated','dropdownrated')";
            $result = $result && execute_sql($update_sql1);
            $result = $result && execute_sql($update_sql2);
        }
    }
    if ($result && $oldversion < 2008042801) {
        $new_log_display = new object();
        $new_log_display->module = 'feedback';
        $new_log_display->action = 'startcomplete';
        $new_log_display->mtable = 'feedback';
        $new_log_display->field = 'name';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'submit';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'delete';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'view';
        $result = $result && insert_record('log_display', $new_log_display);
        $new_log_display = clone $new_log_display;
        $new_log_display->action = 'view all';
        $new_log_display->mtable = 'course';
        $new_log_display->field = 'shortname';
        $result = $result && insert_record('log_display', $new_log_display);
    }
    if ($result && $oldversion < 2008042900) {
        /// Define field autonumbering to be added to feedback
        $table = new XMLDBTable('feedback');
        $field = new XMLDBField('autonumbering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'multiple_submit');
        /// Launch add field2
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008050104) {
        /// Define field site_after_submit to be added to feedback
        $table = new XMLDBTable('feedback');
        $field = new XMLDBField('site_after_submit');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, false, null, null, '', 'autonumbering');
        /// Launch add field2
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008050112) {
        $update_sql = "UPDATE " . $CFG->prefix . "feedback_item SET presentation = '-|-' WHERE presentation = '0|0' AND typ = 'numeric'";
        $result = $result && execute_sql($update_sql);
    }
    return $result;
}
コード例 #14
0
ファイル: install.php プロジェクト: sabdev1/ljcdevsab
 private function upgrade_to_1_8_9_4($version)
 {
     global $wpdb;
     // Try to enable the expired ads, bug in 1.0.6.17:
     if ($version == '1.0.6.17') {
         $query = "UPDATE " . AWPCP_TABLE_ADS . " SET DISABLED=0 WHERE ad_enddate >= NOW()";
         $wpdb->query($query);
     }
     if (version_compare($version, '1.8.7.1', "<")) {
         // Fix the problem with disabled_date not being nullable from 1.8.7
         $query = "ALTER TABLE " . AWPCP_TABLE_ADS . " MODIFY disabled_date DATETIME";
         $wpdb->query($query);
     }
     // Upgrade featured ad columns for module
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'is_featured_ad')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `is_featured_ad` TINYINT(1) DEFAULT NULL");
     }
     // Upgrade for tracking poster's IP address
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'posterip')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `posterip` VARCHAR(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL");
     }
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'flagged')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `flagged` TINYINT(1) DEFAULT NULL");
     }
     // Upgrade for deleting ads that are marked as disabled or deleted
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'disabled_date')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `disabled_date` DATETIME DEFAULT NULL");
     }
     if (!awpcp_column_exists(AWPCP_TABLE_ADFEES, 'is_featured_ad_pricing')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADFEES . "  ADD `is_featured_ad_pricing` TINYINT(1) DEFAULT NULL");
     }
     if (!awpcp_column_exists(AWPCP_TABLE_ADFEES, 'categories')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADFEES . "  ADD `categories` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci");
     }
     if (!awpcp_column_exists(AWPCP_TABLE_CATEGORIES, 'category_order')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_CATEGORIES . "  ADD `category_order` INT(10) NULL DEFAULT 0 AFTER category_name");
         $wpdb->query("UPDATE " . AWPCP_TABLE_CATEGORIES . " SET category_order=0");
     }
     // Fix the shortcode issue if present in installed version
     $sql = "UPDATE " . $wpdb->posts . " SET post_content='[AWPCPCLASSIFIEDSUI]' ";
     $sql .= "WHERE post_content='[[AWPCPCLASSIFIEDSUI]]'";
     $wpdb->query($sql);
     $settings_table_exists = checkfortable(AWPCP_TABLE_ADSETTINGS);
     if ($settings_table_exists && !field_exists('tos')) {
         // add terms of service field
         $sql = 'INSERT INTO ' . AWPCP_TABLE_ADSETTINGS . '(`config_option`,`config_value`,`config_diz`,`config_group_id`,`option_type`)
             VALUES ("tos","Terms of service go here...","Terms of Service for posting an ad - modify this to fit your needs:","1","0")';
         $wpdb->query($sql);
         $sql = 'INSERT INTO ' . AWPCP_TABLE_ADSETTINGS . '(`config_option`,`config_value`,`config_diz`,`config_group_id`,`option_type`)
             VALUES ("requiredtos", "Display and require Terms of Service","Display and require Terms of Service","1","0")';
         $wpdb->query($sql);
     }
     if ($settings_table_exists && !field_exists('notifyofadexpired')) {
         //add notify of an expired ad field
         $sql = 'insert into ' . AWPCP_TABLE_ADSETTINGS . '(`config_option`,`config_value`,`config_diz`,`config_group_id`,`option_type`)
             values ("notifyofadexpired","Notify admin of expired ads.","Notify admin of expired ads.","1","0")';
         $wpdb->query($sql);
     }
     if ($settings_table_exists && field_exists('notifyofadexpired')) {
         //Fix bug from 1.8.6.4:
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET option_type =0 where config_option='notifyofadexpired'");
     }
     // Update ad_settings table to ad field config groud ID if field does not exist in installed version
     $cgid_column_name_exists = $wpdb->get_var("SELECT config_group_id FROM " . AWPCP_TABLE_ADSETTINGS);
     if ($settings_table_exists && ($cgid_column_name_exists === false || is_null($cgid_column_name_exists))) {
         $query = "ALTER TABLE " . AWPCP_TABLE_ADSETTINGS . "  ADD `config_group_id` TINYINT(1) UNSIGNED NOT NULL DEFAULT 1 AFTER config_diz";
         $wpdb->query($query);
         $myconfig_group_ops_1 = array('showlatestawpcpnews', 'uiwelcome', 'main_page_display', 'useakismet', 'contactformcheckhuman', 'contactformcheckhumanhighnumval', 'awpcptitleseparator', 'showcityinpagetitle', 'showstateinpagetitle', 'showcountryinpagetitle', 'showcategoryinpagetitle', 'showcountyvillageinpagetitle', 'awpcppagefilterswitch', 'activatelanguages', 'sidebarwidgetbeforecontent', 'sidebarwidgetaftercontent', 'sidebarwidgetbeforetitle', 'sidebarwidgetaftertitle', 'usesenderemailinsteadofadmin', 'awpcpadminaccesslevel', 'awpcpadminemail', 'useakismet');
         $myconfig_group_ops_2 = array('addurationfreemode', 'autoexpiredisabledelete', 'maxcharactersallowed', 'notifyofadexpiring', 'notifyofadposted', 'adapprove', 'disablependingads', 'showadcount', 'displayadviews', 'onlyadmincanplaceads', 'allowhtmlinadtext', 'hyperlinkurlsinadtext', 'notice_awaiting_approval_ad', 'buildsearchdropdownlists', 'visitwebsitelinknofollow', 'groupbrowseadsby', 'groupsearchresultsby', 'displayadthumbwidth', 'adresultsperpage', 'displayadlayoutcode', 'awpcpshowtheadlayout');
         $myconfig_group_ops_3 = array('freepay', 'paylivetestmode', 'paypalemail', 'paypalcurrencycode', 'displaycurrencycode', '2checkout', 'activatepaypal', 'activate2checkout', 'twocheckoutpaymentsrecurring', 'paypalpaymentsrecurring');
         $myconfig_group_ops_4 = array('imagesallowdisallow', 'awpcp_thickbox_disabled', 'imagesapprove', 'imagesallowedfree', 'uploadfoldername', 'maximagesize', 'minimagesize', 'imgthumbwidth', 'imgmaxheight', 'imgmaxwidth');
         $myconfig_group_ops_5 = array('useadsense', 'adsense', 'adsenseposition');
         $myconfig_group_ops_6 = array('displayphonefield', 'displayphonefieldreqop', 'displaycityfield', 'displaycityfieldreqop', 'displaystatefield', 'displaystatefieldreqop', 'displaycountryfield', 'displaycountryfieldreqop', 'displaycountyvillagefield', 'displaycountyvillagefieldreqop', 'displaypricefield', 'displaypricefieldreqop', 'displaywebsitefield', 'displaywebsitefieldreqop', 'displaypostedbyfield');
         $myconfig_group_ops_7 = array('requireuserregistration', 'postloginformto', 'registrationurl');
         $myconfig_group_ops_8 = array('contactformsubjectline', 'contactformbodymessage', 'listingaddedsubject', 'listingaddedbody', 'resendakeyformsubjectline', 'resendakeyformbodymessage', 'paymentabortedsubjectline', 'paymentabortedbodymessage', 'adexpiredsubjectline', 'adexpiredbodymessage');
         $myconfig_group_ops_9 = array('usesmtp', 'smtphost', 'smtpport', 'smtpusername', 'smtppassword');
         $myconfig_group_ops_10 = array('userpagename', 'showadspagename', 'placeadpagename', 'page-name-renew-ad', 'browseadspagename', 'browsecatspagename', 'editadpagename', 'paymentthankyoupagename', 'paymentcancelpagename', 'replytoadpagename', 'searchadspagename', 'categoriesviewpagename');
         $myconfig_group_ops_11 = array('seofriendlyurls', 'pathvaluecontact', 'pathvalueshowad', 'pathvaluebrowsecategory', 'pathvalueviewcategories', 'pathvaluecancelpayment', 'pathvaluepaymentthankyou');
         // assign a group value to each setting
         foreach ($myconfig_group_ops_1 as $myconfig_group_op_1) {
             add_config_group_id($cvalue = 1, $myconfig_group_op_1);
         }
         foreach ($myconfig_group_ops_2 as $myconfig_group_op_2) {
             add_config_group_id($cvalue = '2', $myconfig_group_op_2);
         }
         foreach ($myconfig_group_ops_3 as $myconfig_group_op_3) {
             add_config_group_id($cvalue = '3', $myconfig_group_op_3);
         }
         foreach ($myconfig_group_ops_4 as $myconfig_group_op_4) {
             add_config_group_id($cvalue = '4', $myconfig_group_op_4);
         }
         foreach ($myconfig_group_ops_5 as $myconfig_group_op_5) {
             add_config_group_id($cvalue = '5', $myconfig_group_op_5);
         }
         foreach ($myconfig_group_ops_6 as $myconfig_group_op_6) {
             add_config_group_id($cvalue = '6', $myconfig_group_op_6);
         }
         foreach ($myconfig_group_ops_7 as $myconfig_group_op_7) {
             add_config_group_id($cvalue = '7', $myconfig_group_op_7);
         }
         foreach ($myconfig_group_ops_8 as $myconfig_group_op_8) {
             add_config_group_id($cvalue = '8', $myconfig_group_op_8);
         }
         foreach ($myconfig_group_ops_9 as $myconfig_group_op_9) {
             add_config_group_id($cvalue = '9', $myconfig_group_op_9);
         }
         foreach ($myconfig_group_ops_10 as $myconfig_group_op_10) {
             add_config_group_id($cvalue = '10', $myconfig_group_op_10);
         }
         foreach ($myconfig_group_ops_11 as $myconfig_group_op_11) {
             add_config_group_id($cvalue = '11', $myconfig_group_op_11);
         }
     }
     if ($settings_table_exists && get_awpcp_option_group_id('seofriendlyurls') == 1) {
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET `config_group_id` = '11' WHERE `config_option` = 'seofriendlyurls'");
     }
     if ($settings_table_exists && get_awpcp_option_type('main_page_display') == 1) {
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET `config_value` = 0, `option_type` = 0, `config_diz` = 'Main page layout [ check for ad listings ] [ Uncheck for categories ]',config_group_id=1 WHERE `config_option` = 'main_page_display'");
     }
     if ($settings_table_exists && get_awpcp_option_config_diz('paylivetestmode') != "Put payment gateways in test mode") {
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET `config_value` = 0, `option_type` = 0, `config_diz` = 'Put payment gateways in test mode' WHERE `config_option` = 'paylivetestmode'");
     }
     if ($settings_table_exists && get_awpcp_option_config_diz('adresultsperpage') != "Default number of ads per page") {
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET `config_value` = '10', `option_type` = 1, `config_diz` = 'Default number of ads per page' WHERE `config_option` = 'adresultsperpage'");
     }
     if ($settings_table_exists && get_awpcp_option_config_diz('awpcpshowtheadlayout') != "<div id=\"showawpcpadpage\"><div class=\"adtitle\">{$ad_title}</div><br/><div class=\"showawpcpadpage\">{$featureimg}<label>Contact Information</label><br/><a href=\"{$quers}/{$codecontact}\">Contact {$adcontact_name}</a>{$adcontactphone} {$location} {$awpcpvisitwebsite}</div>{$aditemprice} {$awpcpextrafields} <div class=\"fixfloat\"></div> {$showadsense1}<div class=\"showawpcpadpage\"><label>More Information</label><br/>{$addetails}</div>{$showadsense2} <div class=\"fixfloat\"></div><div id=\"displayimagethumbswrapper\"><div id=\"displayimagethumbs\"><ul>{$awpcpshowadotherimages}</ul></div></div><span class=\"fixfloat\">{$tweetbtn} {$sharebtn} {$flagad}</span>{$awpcpadviews} {$showadsense3}</div>") {
         $wpdb->query("UPDATE " . AWPCP_TABLE_ADSETTINGS . " SET `config_value` = '2', `option_type` = '2', `config_diz` = 'Modify as needed to control layout of single ad view page. Maintain code formatted as \$somecodetitle. Changing the code keys will prevent the elements they represent from displaying.', `config_value` = '<div id=\"showawpcpadpage\"><div class=\"adtitle\">\$ad_title</div><br/><div class=\"showawpcpadpage\">\$featureimg<label>Contact Information</label><br/><a href=\"\$quers/\$codecontact\">Contact \$adcontact_name</a>\$adcontactphone \$location \$awpcpvisitwebsite</div>\$aditemprice \$awpcpextrafields <div class=\"fixfloat\"></div> \$showadsense1<div class=\"showawpcpadpage\"><label>More Information</label><br/>\$addetails</div>\$showadsense2 <div class=\"fixfloat\"></div><div id=\"displayimagethumbswrapper\"><div id=\"displayimagethumbs\"><ul>\$awpcpshowadotherimages</ul></div></div><span class=\"fixfloat\">\$tweetbtn \$sharebtn \$flagad</span>\$awpcpadviews \$showadsense3</div>' WHERE `config_option` = 'awpcpshowtheadlayout'");
     }
     ////
     // Match up the ad settings fields of current versions and upgrading versions
     ////
     if ($settings_table_exists) {
         if (!field_exists($field = 'userpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('userpagename', 'AWPCP', 'Name for classifieds page. [CAUTION: Make sure page does not already exist]','10',1);");
         }
         if (!field_exists($field = 'showadspagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showadspagename', 'Show Ad', 'Name for show ads page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'placeadpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('placeadpagename', 'Place Ad', 'Name for place ads page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'browseadspagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('browseadspagename', 'Browse Ads', 'Name browse ads apge. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'searchadspagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES        ('searchadspagename', 'Search Ads', 'Name for search ads page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'paymentthankyoupagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paymentthankyoupagename', 'Payment Thank You', 'Name for payment thank you page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'paymentcancelpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paymentcancelpagename', 'Cancel Payment', 'Name for payment cancel page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'replytoadpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('replytoadpagename', 'Reply To Ad', 'Name for reply to ad page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'browsecatspagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('browsecatspagename', 'Browse Categories', 'Name for browse categories page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'editadpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('editadpagename', 'Edit Ad', 'Name for edit ad page. [CAUTION: existing page will be overwritten]','10',1);");
         }
         if (!field_exists($field = 'categoriesviewpagename')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES        ('categoriesviewpagename', 'View Categories', 'Name for categories view page. [ Dynamic Page]','10',1);");
         }
         if (!field_exists($field = 'freepay')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('freepay', 0, 'Charge Listing Fee?','3',0);");
         }
         if (!field_exists($field = 'requireuserregistration')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('requireuserregistration', 0, 'Require user registration?','7',0);");
         }
         if (!field_exists($field = 'postloginformto')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('postloginformto', '', 'Post login form to [Value should be the full URL to the wordpress login script. Example http://www.awpcp.com/wp-login.php **Only needed if registration is required and your login url is mod-rewritten ] ','7',1);");
         }
         if (!field_exists($field = 'registrationurl')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('registrationurl', '', 'Location of registraiton page [Value should be the full URL to the wordpress registration page. Example http://www.awpcp.com/wp-login.php?action=register **Only needed if registration is required and your login url is mod-rewritten ] ','7',1);");
         }
         if (!field_exists($field = 'main_page_display')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('main_page_display', 0, 'Main page layout [ check for ad listings | Uncheck for categories ]',1,0);");
         }
         if (!field_exists($field = 'activatelanguages')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('activatelanguages', 0, 'Activate Language Capability',1,0);");
         }
         if (!field_exists($field = 'awpcpadminaccesslevel')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcpadminaccesslevel', 'admin', 'Set wordpress role of users who can have admin access to classifieds. Choices [admin,editor]. Currently no other roles will be granted access.',1,1);");
         }
         if (!field_exists($field = 'sidebarwidgetaftertitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('sidebarwidgetaftertitle', '</h3>', 'Code to appear after widget title',1,1);");
         }
         if (!field_exists($field = 'sidebarwidgetbeforetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('sidebarwidgetbeforetitle', '<h3 class=\"widgettitle\">', 'Code to appear before widget title',1,1);");
         }
         if (!field_exists($field = 'sidebarwidgetaftercontent')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('sidebarwidgetaftercontent', '</div>', 'Code to appear after widget content',1,1);");
         }
         if (!field_exists($field = 'sidebarwidgetbeforecontent')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('sidebarwidgetbeforecontent', '<div class=\"widget\">', 'Code to appear before widget content',1,1);");
         }
         if (!field_exists($field = 'usesenderemailinsteadofadmin')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('usesenderemailinsteadofadmin', 0, 'Check this to use the name and email of the sender in the FROM field when someone replies to an ad. When unchecked the messages go out with the website name and WP admin email address in the from field. Some servers will not process outgoing emails that have an email address from gmail, yahoo, hotmail and other free email services in the FROM field. Some servers will also not process emails that have an email address that is different from the email address associated with your hosting account in the FROM field. If you are with such a webhost you need to leave this option unchecked and make sure your WordPress admin email address is tied to your hosting account.',1,0);");
         }
         if (!field_exists($field = 'awpcpadminemail')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcpadminemail', '', 'Emails go out using your WordPress admin email. If you prefer to use a different email enter it here.',1,1);");
         }
         if (!field_exists($field = 'awpcptitleseparator')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcptitleseparator', '-', 'The character to use to separate ad details used in browser page title [Example: | / - ]',1,1);");
         }
         if (!field_exists($field = 'showcityinpagetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showcityinpagetitle', 1, 'Show city in browser page title when viewing individual ad',1,0);");
         }
         if (!field_exists($field = 'showstateinpagetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showstateinpagetitle', 1, 'Show state in browser page title when viewing individual ad',1,0);");
         }
         if (!field_exists($field = 'showcountryinpagetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showcountryinpagetitle', 1, 'Show country in browser page title when viewing individual ad',1,0);");
         }
         if (!field_exists($field = 'showcountyvillageinpagetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES        ('showcountyvillageinpagetitle', 1, 'Show county/village/other setting in browser page title when viewing individual ad',1,0);");
         }
         if (!field_exists($field = 'showcategoryinpagetitle')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showcategoryinpagetitle', 1, 'Show category in browser page title when viewing individual ad',1,0);");
         }
         if (!field_exists($field = 'awpcppagefilterswitch')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcppagefilterswitch', 1, 'Uncheck this if you need to turn off the awpcp page filter that prevents awpcp classifieds children pages from showing up in your wp pages menu [you might need to do this if for example the awpcp page filter is messing up your page menu. It means you will have to manually exclude the awpcp children pages from showing in your page list. Some of the pages really should not be visible to your users by default]',1,0);");
         }
         if (!field_exists($field = 'paylivetestmode')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paylivetestmode', 0, 'Put Paypal and 2Checkout in test mode.','3',0);");
         }
         if (!field_exists($field = 'useadsense')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('useadsense', 1, 'Activate adsense','5',0);");
         }
         if (!field_exists($field = 'adsense')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adsense', 'Adsense code', 'Your adsense code [ Best if 468 by 60 text or banner. ]','5','2');");
         }
         if (!field_exists($field = 'adsenseposition')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adsenseposition', '2', 'Adsense position. [ 1 - above ad text body ] [ 2 - under ad text body ] [ 3 - below ad images. ]','5',1);");
         }
         if (!field_exists($field = 'addurationfreemode')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('addurationfreemode', 0, 'Expire free ads after how many days? [0 for no expiry].','2',1);");
         }
         if (!field_exists($field = 'autoexpiredisabledelete')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('autoexpiredisabledelete', 0, 'Disable expired ads instead of deleting them?','2',0);");
         }
         if (!field_exists($field = 'imagesallowdisallow')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imagesallowdisallow', 1, 'Allow images in ads? [Affects both free and paid]','4',0);");
         }
         if (!field_exists($field = 'awpcp_thickbox_disabled')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcp_thickbox_disabled', 0, 'Turn off the thickbox/lightbox if it conflicts with other elements of your site','4',0);");
         }
         if (!field_exists($field = 'imagesallowedfree')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imagesallowedfree', '4', ' Free mode number of images allowed?','4',1);");
         }
         if (!field_exists($field = 'uploadfoldername')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('uploadfoldername', 'uploads', 'Upload folder name. [ Folder must exist and be located in your wp-content directory ]','4',1);");
         }
         if (!field_exists($field = 'maximagesize')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('maximagesize', '150000', 'Maximum size per image user can upload to system.','4',1);");
         }
         if (!field_exists($field = 'minimagesize')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('minimagesize', '300', 'Minimum size per image user can upload to system','4',1);");
         }
         if (!field_exists($field = 'imgthumbwidth')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imgthumbwidth', '125', 'Minimum height/width for uploaded images (used for both).','4',1);");
         }
         if (!field_exists($field = 'maxcharactersallowed')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('maxcharactersallowed', '750', 'What is the maximum number of characters the text of an ad can contain?','2',1);");
         }
         if (!field_exists($field = 'imgmaxheight')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,`config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imgmaxheight', '480', 'Max image height. Images taller than this are automatically resized upon upload.','4',1);");
         }
         if (!field_exists($field = 'imgmaxwidth')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imgmaxwidth', '640', 'Max image width. Images wider than this are automatically resized upon upload.','4',1);");
         }
         if (!field_exists($field = 'paypalemail')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paypalemail', '*****@*****.**', 'Email address for paypal payments [if running in paymode and if paypal is activated]','3',1);");
         }
         if (!field_exists($field = 'paypalcurrencycode')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paypalcurrencycode', 'USD', 'The currency in which you would like to receive your paypal payments','3',1);");
         }
         if (!field_exists($field = 'displaycurrencycode')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycurrencycode', 'USD', 'The currency to show on your payment pages','3',1);");
         }
         if (!field_exists($field = '2checkout')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('2checkout', 'xxxxxxx', 'Account for 2Checkout payments [if running in pay mode and if 2Checkout is activated]','3',1);");
         }
         if (!field_exists($field = 'activatepaypal')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('activatepaypal', 1, 'Activate PayPal','3',0);");
         }
         if (!field_exists($field = 'activate2checkout')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('activate2checkout', 1, 'Activate 2Checkout ','3',0);");
         }
         if (!field_exists($field = 'paypalpaymentsrecurring')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paypalpaymentsrecurring', 0, 'Use recurring payments paypal [ this feature is not fully automated or fully integrated. For more reliable results do not use recurring ','3',0);");
         }
         if (!field_exists($field = 'twocheckoutpaymentsrecurring')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('twocheckoutpaymentsrecurring', 0, 'Use recurring payments 2checkout [ this feature is not fully automated or fully integrated. For more reliable results do not use recurring ','3',0);");
         }
         if (!field_exists($field = 'notifyofadexpiring')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('notifyofadexpiring', 1, 'Notify ad poster that their ad has expired?','2',0);");
         }
         if (!field_exists($field = 'notifyofadposted')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('notifyofadposted', 1, 'Notify admin of new ad.','2',0);");
         }
         if (!field_exists($field = 'listingaddedsubject')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('listingaddedsubject', 'Your classified ad listing has been submitted', 'Subject line for email sent out when someone posts an ad','8',1);");
         }
         if (!field_exists($field = 'listingaddedbody')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('listingaddedbody', 'Thank you for submitting your classified ad. The details of your ad are shown below.', 'Message body text for email sent out when someone posts an ad','8','2');");
         }
         if (!field_exists($field = 'imagesapprove')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('imagesapprove', 0, 'Hide images until admin approves them','4',0);");
         }
         if (!field_exists($field = 'adapprove')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adapprove', 0, 'Disable ad until admin approves','2',0);");
         }
         if (!field_exists($field = 'displayadthumbwidth')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displayadthumbwidth', '80', 'Width for thumbnails in ad listings view [Only numerical value]','2',1);");
         }
         if (!field_exists($field = 'disablependingads')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('disablependingads', 1, 'Enable paid ads that are pending payment.','2',0);");
         }
         if (!field_exists($field = 'groupbrowseadsby')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('groupbrowseadsby', 1, 'Group ad listings by','2','3');");
         }
         if (!field_exists($field = 'groupsearchresultsby')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('groupsearchresultsby', 1, 'Group ad listings in search results by','2','3');");
         }
         if (!field_exists($field = 'showadcount')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showadcount', 1, 'Show how many ads a category contains.','2',0);");
         }
         if (!field_exists($field = 'adresultsperpage')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adresultsperpage', '10', 'Default number of ads per page','2',1);");
         }
         if (!field_exists($field = 'noadsinparentcat')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('noadsinparentcat', 0, 'Prevent ads from being posted to top level categories?.','2',0);");
         }
         if (!field_exists($field = 'displayadviews')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displayadviews', 1, 'Show ad views','2',0);");
         }
         if (!field_exists($field = 'displayadlayoutcode')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displayadlayoutcode', '<div class=\"\$awpcpdisplayaditems\"><div style=\"width:\$imgblockwidth;padding:5px;float:left;margin-right:20px;\">\$awpcp_image_name_srccode</div><div style=\"width:50%;padding:5px;float:left;\"><h4>\$ad_title</h4> \$addetailssummary...</div><div style=\"padding:5px;float:left;\"> \$awpcpadpostdate \$awpcp_city_display \$awpcp_state_display \$awpcp_display_adviews \$awpcp_display_price </div><div class=\"fixfloat\"></div></div><div class=\"fixfloat\"></div>', 'Modify as needed to control layout of ad listings page. Maintain code formatted as \$somecodetitle. Changing the code keys will prevent the elements they represent from displaying.','2','2');");
         }
         if (!field_exists($field = 'awpcpshowtheadlayout')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('awpcpshowtheadlayout', '<div id=\"showawpcpadpage\"><div class=\"adtitle\">\$ad_title</div><br/><div class=\"showawpcpadpage\">\$featureimg<label>Contact Information</label><br/><a href=\"\$quers/\$codecontact\">Contact \$adcontact_name</a>\$adcontactphone \$location \$awpcpvisitwebsite</div>\$aditemprice \$awpcpextrafields <div class=\"fixfloat\"></div> \$showadsense1<div class=\"showawpcpadpage\"><label>More Information</label><br/>\$addetails</div>\$showadsense2 <div class=\"fixfloat\"></div><div id=\"displayimagethumbswrapper\"><div id=\"displayimagethumbs\"><ul>\$awpcpshowadotherimages</ul></div></div><span class=\"fixfloat\">\$tweetbtn \$sharebtn \$flagad</span>\$awpcpadviews \$showadsense3</div>', 'Modify as needed to control layout of single ad view page. Maintain code formatted as \$somecodetitle. Changing the code keys will prevent the elements they represent from displaying.','2','2');");
         }
         if (!field_exists($field = 'usesmtp')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('usesmtp', 0, 'Enable external SMTP server [ if emails not processing normally]', 9 ,0);");
         }
         if (!field_exists($field = 'smtphost')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('smtphost', 'mail.example.com', 'SMTP host [ if emails not processing normally]', 9 ,1);");
         }
         if (!field_exists($field = 'smtpport')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('smtpport', '25', 'SMTP port [ if emails not processing normally]', 9 ,1);");
         }
         if (!field_exists($field = 'smtpusername')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('smtpusername', 'smtp_username', 'SMTP username [ if emails not processing normally]', 9,1);");
         }
         if (!field_exists($field = 'smtppassword')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('smtppassword', '', 'SMTP password [ if emails not processing normally]', 9,1);");
         }
         if (!field_exists($field = 'onlyadmincanplaceads')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('onlyadmincanplaceads', 0, 'Only admin can post ads', '2',0);");
         }
         if (!field_exists($field = 'contactformcheckhuman')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('contactformcheckhuman', 1, 'Activate Math ad post and contact form validation', 1,0);");
         }
         if (!field_exists($field = 'useakismet')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('useakismet', 0, 'Use Akismet for Posting Ads/Contact Responses (strong anti-spam)', 1,0);");
         }
         if (!field_exists($field = 'contactformcheckhumanhighnumval')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('contactformcheckhumanhighnumval', '10', 'Math validation highest number', 1,1);");
         }
         if (!field_exists($field = 'contactformsubjectline')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('contactformsubjectline', 'Response to your AWPCP Demo Ad', 'Subject line for email sent out when someone replies to ad','8', 1);");
         }
         if (!field_exists($field = 'contactformbodymessage')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('contactformbodymessage', 'Someone has responded to your AWPCP Demo Ad', 'Message body text for email sent out when someone replies to ad', '8','2');");
         }
         if (!field_exists($field = 'resendakeyformsubjectline')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('resendakeyformsubjectline', 'The classified ad access key you requested', 'Subject line for email sent out when someone requests their ad access key resent','8', 1);");
         }
         if (!field_exists($field = 'resendakeyformbodymessage')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('resendakeyformbodymessage', 'You asked to have your classified ad ad access key resent. Below are all the ad access keys in the system that are tied to the email address you provided', 'Message body text for email sent out when someone requests their ad access key resent', '8','2');");
         }
         if (!field_exists($field = 'paymentabortedsubjectline')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paymentabortedsubjectline', 'There was a problem processing your classified ads listing payment', 'Subject line for email sent out when the payment processing does not complete','8', 1);");
         }
         if (!field_exists($field = 'paymentabortedbodymessage')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('paymentabortedbodymessage', 'There was a problem encountered during your attempt to submit payment for your classified ad listing. If funds were removed from the account you tried to use to make a payment please contact the website admin or the payment website customer service for assistance.', 'Message body text for email sent out when the payment processing does not complete','8','2');");
         }
         if (!field_exists($field = 'adexpiredsubjectline')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adexpiredsubjectline', 'Your classifieds listing ad has expired', 'Subject line for email sent out when an ad has auto-expired','8', 1);");
         }
         if (!field_exists($field = 'adexpiredbodymessage')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('adexpiredbodymessage', 'This is an automated notification that your classified ad has expired.','Message body text for email sent out when an ad has auto-expired', '8','2');");
         }
         if (!field_exists($field = 'seofriendlyurls')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('seofriendlyurls', 0, 'Search Engine Friendly URLs? [ Does not work in some instances ]', '11',0);");
         }
         if (!field_exists($field = 'pathvaluecontact')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvaluecontact', '3', 'If contact page link not working in seo mode change value until correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'pathvalueshowad')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvalueshowad', '3', 'If show ad links not working in seo mode change value until correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'pathvaluebrowsecats')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvaluebrowsecats', '2', 'If browse categories links not working in seo mode change value until correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'pathvalueviewcategories')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvalueviewcategories', '2', 'If the view categories link is not working in seo mode change value until correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'pathvaluecancelpayment')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvaluecancelpayment', '2', 'If the cancel payment buttons are not working in seo mode it means the path the plugin is using is not correct. Change the until the correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'pathvaluepaymentthankyou')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('pathvaluepaymentthankyou', '2', 'If the payment thank you page is not working in seo mode it means the path the plugin is using is not correct. Change the until the correct path is found. Start at 1', '11',1);");
         }
         if (!field_exists($field = 'allowhtmlinadtext')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('allowhtmlinadtext', 0, 'Allow HTML in ad text [ Not recommended ]', '2',0);");
         }
         if (!field_exists($field = 'htmlstatustext')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('htmlstatustext', 'No HTML Allowed', 'Display this text above ad detail text input box on ad post page', '2','2');");
         }
         if (!field_exists($field = 'hyperlinkurlsinadtext')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('hyperlinkurlsinadtext', 0, 'Make URLs in ad text clickable', '2',0);");
         }
         if (!field_exists($field = 'visitwebsitelinknofollow')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('visitwebsitelinknofollow', 1, 'Add no follow to links in ads', '2',0);");
         }
         if (!field_exists($field = 'notice_awaiting_approval_ad')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('notice_awaiting_approval_ad', 'All ads must first be approved by the administrator before they are activated in the system. As soon as an admin has approved your ad it will become visible in the system. Thank you for your business.','Text for message to notify user that ad is awaiting approval','2','2');");
         }
         if (!field_exists($field = 'displayphonefield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displayphonefield', 1, 'Show phone field','6',0);");
         }
         if (!field_exists($field = 'displayphonefieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displayphonefieldreqop', 0, 'Require phone','6',0);");
         }
         if (!field_exists($field = 'displaycityfield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycityfield', 1, 'Show city field.','6',0);");
         }
         if (!field_exists($field = 'displaycityfieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycityfieldreqop', 0, 'Require city','6',0);");
         }
         if (!field_exists($field = 'displaystatefield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaystatefield', 1, 'Show state field.','6',0);");
         }
         if (!field_exists($field = 'displaystatefieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaystatefieldreqop', 0, 'Require state','6',0);");
         }
         if (!field_exists($field = 'displaycountryfield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycountryfield', 1, 'Show country field.','6',0);");
         }
         if (!field_exists($field = 'displaycountryfieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycountryfieldreqop', 0, 'Require country','6',0);");
         }
         if (!field_exists($field = 'displaycountyvillagefield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycountyvillagefield', 0, 'Show County/village/other.','6',0);");
         }
         if (!field_exists($field = 'displaycountyvillagefieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaycountyvillagefieldreqop', 0, 'Require county/village/other.','6',0);");
         }
         if (!field_exists($field = 'displaypricefield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaypricefield', 1, 'Show price field.','6',0);");
         }
         if (!field_exists($field = 'displaypricefieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,  `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaypricefieldreqop', 0, 'Require price.','6',0);");
         }
         if (!field_exists($field = 'displaywebsitefield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaywebsitefield', 1, 'Show website field','6',0);");
         }
         if (!field_exists($field = 'displaywebsitefieldreqop')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaywebsitefieldreqop', 0, 'Require website','6',0);");
         }
         if (!field_exists($field = 'displaypostedbyfield')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('displaypostedbyfield', 1, 'Show Posted By field?','6',0);");
         }
         if (!field_exists($field = 'buildsearchdropdownlists')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,    `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('buildsearchdropdownlists', 0, 'The search form can attempt to build drop down country, state, city and county lists if data is available in the system. Limits search to available locations. Note that with the regions module installed the value for this option is overridden.','2',0);");
         }
         if (!field_exists($field = 'uiwelcome')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` ,   `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('uiwelcome', 'Looking for a job? Trying to find a date? Looking for an apartment? Browse our classifieds. Have a job to advertise? An apartment to rent? Post a classified ad.', 'The welcome text for your classified page on the user side',1,'2');");
         }
         if (!field_exists($field = 'showlatestawpcpnews')) {
             $wpdb->query("INSERT  INTO " . AWPCP_TABLE_ADSETTINGS . " (`config_option` , `config_value` , `config_diz` , `config_group_id`, `option_type`    ) VALUES('showlatestawpcpnews', 1, 'Allow AWPCP RSS.',1,0);");
         }
     }
     // create or restore AWPCP pages
     // awpcp_create_pages();
     // Add new field websiteurl to awpcp_ads
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'websiteurl')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `websiteurl` VARCHAR( 500 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `ad_contact_email`");
     }
     $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  DROP INDEX `titdes`");
     $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD FULLTEXT KEY `titdes` (`ad_title`,`ad_details`)");
     // Add new field ad_fee_paid for sorting ads by paid listings first
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'ad_fee_paid')) {
         $query = "ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `ad_fee_paid` FLOAT(7,2) NOT NULL AFTER `adterm_id`";
         $wpdb->query($query);
     }
     // Increase the length value for the ad_item_price field
     $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . " CHANGE `ad_item_price` `ad_item_price` INT( 25 ) NOT NULL");
     // Ad new field add_county_village to awpcp_ads
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'ad_county_village')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `ad_county_village` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `ad_country`");
     }
     // Add field ad_views to table awpcp_ads to track ad views
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'ad_views')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `ad_views` INT(10) NOT NULL DEFAULT 0 AFTER `ad_item_price`");
     }
     // Insert new field ad_item_price into awpcp_ads table
     if (!awpcp_column_exists(AWPCP_TABLE_ADS, 'ad_item_price')) {
         $wpdb->query("ALTER TABLE " . AWPCP_TABLE_ADS . "  ADD `ad_item_price` INT( 10 ) NOT NULL AFTER `ad_country`");
     }
 }
コード例 #15
0
ファイル: upgrade.php プロジェクト: henriquecrang/e-UNI
function xmldb_block_email_list_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $DB;
    $result = true;
    // If is set upgrade_blocks_savepoint function
    $existfunction = false;
    if (!function_exists('upgrade_blocks_savepoint')) {
        $existfunction = true;
    }
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    if ($result && $oldversion < 2007062205) {
        $fields = array('mod/email:viewmail', 'mod/email:addmail', 'mod/email:reply', 'mod/email:replyall', 'mod/email:forward', 'mod/email:addsubfolder', 'mod/email:updatesubfolder', 'mod/email:removesubfolder');
        /// Remove no more used fields
        $table = new XMLDBTable('capabilities');
        foreach ($fields as $name) {
            $field = new XMLDBField($name);
            $result = $result && drop_field($table, $field);
        }
        // Active cron block of email_list
        if ($result) {
            if ($email_list = get_record('block', 'name', 'email_list')) {
                $email_list->cron = 1;
                update_record('block', $email_list);
            }
        }
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2007062205, 'email_list');
        }
    }
    // force
    $result = true;
    if ($result && $oldversion < 2007072003) {
        // Add marriedfolder2courses flag on email_preferences
        $table = new XMLDBTable('email_preference');
        $field = new XMLDBField('marriedfolders2courses');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
        // Add course ID on email_folder
        $table = new XMLDBTable('email_folder');
        $field = new XMLDBField('course');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
        // Add index
        $key = new XMLDBKey('course');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));
        $result = $result && add_key($table, $key);
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2007072003, 'email_list');
        }
    }
    if ($result && $oldversion < 2008061400) {
        // Add reply and forwarded info field on email_mail.
        $table = new XMLDBTable('email_send');
        $field = new XMLDBField('answered');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2008061400, 'email_list');
        }
    }
    // Solve old problems
    if ($result && $oldversion < 2008061600) {
        $table = new XMLDBTable('email_preference');
        $field = new XMLDBField('marriedfolders2courses');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('email_folder');
        $field = new XMLDBField('course');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            // Add index
            $key = new XMLDBKey('course');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));
            $result = $result && add_key($table, $key);
        }
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2008061600, 'email_list');
        }
    }
    // Add new index
    if ($result and $oldversion < 2008081602) {
        // Add combine key on foldermail
        $table = new XMLDBTable('email_foldermail');
        $index = new XMLDBIndex('folderid-mailid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('folderid', 'mailid'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2008081602, 'email_list');
        }
    }
    // Upgrading to Moodle 2.0
    if ($result and $oldversion < 2009040200) {
        // Portable SQL staments to Oracle, MySQL and PostgreSQL NOT APPLYCABLE to MSSQL
        if ($CFG->dbname != 'mssql') {
            // Moodle 1.9 or prior
            if ($CFG->version < '2009011541') {
                // Filter
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_filter RENAME TO {$CFG->prefix}block_email_list_filter");
                // Folder
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_folder RENAME TO {$CFG->prefix}block_email_list_folder") && $result;
                // Foldermail
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_foldermail RENAME TO {$CFG->prefix}block_email_list_foldermail") && $result;
                // Mail
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_mail RENAME TO {$CFG->prefix}block_email_list_mail") && $result;
                // Preference
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_preference RENAME TO {$CFG->prefix}block_email_list_preference") && $result;
                // Send
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_send RENAME TO {$CFG->prefix}block_email_list_send") && $result;
                // Subfolder
                $result = execute_sql("ALTER TABLE {$CFG->prefix}email_subfolder RENAME TO {$CFG->prefix}block_email_list_subfolder") && $result;
            } else {
                // Filter
                $DB->execute("ALTER TABLE {$CFG->prefix}email_filter RENAME TO {$CFG->prefix}block_email_list_filter");
                // Folder
                $DB->execute("ALTER TABLE {$CFG->prefix}email_folder RENAME TO {$CFG->prefix}block_email_list_folder");
                // Foldermail
                $DB->execute("ALTER TABLE {$CFG->prefix}email_foldermail RENAME TO {$CFG->prefix}block_email_list_foldermail");
                // Mail
                $DB->execute("ALTER TABLE {$CFG->prefix}email_mail RENAME TO {$CFG->prefix}block_email_list_mail");
                // Preference
                $DB->execute("ALTER TABLE {$CFG->prefix}email_preference RENAME TO {$CFG->prefix}block_email_list_preference");
                // Send
                $DB->execute("ALTER TABLE {$CFG->prefix}email_send RENAME TO {$CFG->prefix}block_email_list_send");
                // Subfolder
                $DB->execute("ALTER TABLE {$CFG->prefix}email_subfolder RENAME TO {$CFG->prefix}block_email_list_subfolder");
            }
        }
        // Change module name to Standard eMail name.
        if ($logs = get_records('log_display', 'module', 'email')) {
            foreach ($logs as $log) {
                set_field('log_display', 'module', 'email_list', 'id', $log->id);
            }
        }
        // Only compatible with 1.9 or prior versions
        if ($existfunction) {
            /// Block savepoint reached
            upgrade_blocks_savepoint($result, 2009040200, 'email_list');
        }
    }
    return $result;
}
コード例 #16
0
ファイル: setting.php プロジェクト: sany217/WeiXin
        set_sys_para(array("WEIXINQY_OAURL" => "{$WEIXINQY_OAURL}"));
    }
    if ($_POST['WEIXINQY_SECRET'] != "" && $_POST['WEIXINQY_CORPID'] != "") {
        $WEIXINQY_CORPID = htmlspecialchars($_POST['WEIXINQY_CORPID']);
        $WEIXINQY_SECRET = htmlspecialchars($_POST['WEIXINQY_SECRET']);
        set_sys_para(array("WEIXINQY_SECRET" => "{$WEIXINQY_SECRET}", "WEIXINQY_CORPID" => "{$WEIXINQY_CORPID}"));
        include_once "inc/utility_cache.php";
        $WEIXINQY_TOKENS = TD::get_cache("WEIXINQY_TOKENS");
        if ($WEIXINQY_TOKENS !== FALSE) {
            TD::set_cache("WEIXINQY_TOKENS", NULL);
        }
    }
}
include_once "inc/conn.php";
include_once "inc/utility_update.php";
if (!field_exists("DEPARTMENT", "WEIXIN_DEPT_ID")) {
    $query = "ALTER TABLE `department` ADD COLUMN `WEIXIN_DEPT_ID`  int(11) NOT NULL DEFAULT 0 AFTER `DEPT_EMAIL_AUDITS_IDS`";
    exequery(TD::conn(), $query, TRUE);
    add_sys_para(array("WEIXINQY_SECRET" => "", "WEIXINQY_CORPID" => "", "WEIXINQY_OAURL" => "", "WEIXINQY_APP_SMS" => ""));
    cache_sys_para();
}
$PARA_ARRAY = get_sys_para("WEIXINQY_CORPID,WEIXINQY_SECRET,WEIXINQY_OAURL");
$WEIXINQY_CORPID = $PARA_ARRAY['WEIXINQY_CORPID'];
$WEIXINQY_SECRET = $PARA_ARRAY['WEIXINQY_SECRET'];
$WEIXINQY_OAURL = $PARA_ARRAY['WEIXINQY_OAURL'];
echo "<body>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"";
echo MYOA_JS_SERVER;
echo "/static/js/bootstrap/css/bootstrap.css\">\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"";
echo MYOA_JS_SERVER;
echo "/static/modules/weixinqy/style.css\">\r\n<script type=\"text/javascript\" src=\"";
echo MYOA_JS_SERVER;
コード例 #17
0
ファイル: upgrade.php プロジェクト: nadavkav/MoodleTAO
function xmldb_certificate_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2007102806) {
        /// Add new fields to certificate table
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('printoutcome');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'gradefmt');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007102800) {
        /// Add new fields to certificate table
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('reportcert');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'savecert');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('certificate_issues');
        $field = new XMLDBField('reportgrade');
        $field->setAttributes(XMLDB_TYPE_CHAR, '10', null, null, null, null, null, null, 'certdate');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2007061300) {
        /// Add new fields to certificate table
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('emailothers');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'emailteachers');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('printhours');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'gradefmt');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('lockgrade');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'printhours');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('requiredgrade');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'lockgrade');
        $result = $result && add_field($table, $field);
        /// Rename field save to savecert
        $field = new XMLDBField('save');
        if (field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'emailothers');
            /// Launch rename field savecert
            $result = $result && rename_field($table, $field, 'savecert');
        } else {
            $field = new XMLDBField('savecert');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'emailothers');
            $result = $result && add_field($table, $field);
        }
    }
    if ($result && $oldversion < 2007061301) {
        $table = new XMLDBTable('certificate_linked_modules');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null, null);
        $table->addFieldInfo('certificate_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        $table->addFieldInfo('linkid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'certificate_id');
        $table->addFieldInfo('linkgrade', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'linkid');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'linkgrade');
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('certificate_id', XMLDB_INDEX_NOTUNIQUE, array('certificate_id'));
        $table->addIndexInfo('linkid', XMLDB_INDEX_NOTUNIQUE, array('linkid'));
        $result = create_table($table);
        if ($result) {
            require_once $CFG->dirroot . '/mod/certificate/lib.php';
            $result = certificate_upgrade_grading_info();
        }
    }
    if ($result && $oldversion < 2007061302) {
        $table = new XMLDBTable('certificate_linked_modules');
        $field = new XMLDBField('linkid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'certificate_id');
        $result = change_field_unsigned($table, $field);
    }
    if ($result && $oldversion < 2008080902) {
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('requiredcertification');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'printhours');
        $result = add_field($table, $field);
    }
    if ($result && $oldversion < 2008080903) {
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('setcertification');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'printhours');
        $result = add_field($table, $field);
    }
    if ($result && $oldversion < 2008080904) {
        /// Add new fields to certificate table if they dont already exist
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('intro');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'name');
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
    }
    if ($result && $oldversion < 2008080905) {
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('setcertification');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null, 'printhours');
        $result = change_field_type($table, $field);
    }
    if ($result && $oldversion < 2008080906) {
        $table = new XMLDBTable('certificate');
        $field = new XMLDBField('requiredcertification');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null, 'printhours');
        $result = change_field_type($table, $field);
    }
    return $result;
}
コード例 #18
0
ファイル: sql_backup.php プロジェクト: kpabijanskas/fusionpbx
 $sql = "select * from {$table_name}";
 if (strlen($sql) > 0) {
     $prep_statement_2 = $db->prepare(check_sql($sql));
     if ($prep_statement_2) {
         $prep_statement_2->execute();
         $result2 = $prep_statement_2->fetchAll(PDO::FETCH_ASSOC);
     } else {
         echo "<b>" . $text['label-error'] . ":</b>\n";
         echo "<pre>\n";
         print_r($db->errorInfo());
         echo "</pre>\n";
     }
     $x = 0;
     foreach ($result2[0] as $key => $value) {
         if ($row[$column] != "db") {
             if (field_exists($apps, $table_name, $key)) {
                 $column_array[$x] = $key;
             }
             $x++;
         }
     }
     $column_array_count = count($column_array);
     foreach ($result2 as &$row) {
         $sql = "INSERT INTO {$table_name} (";
         $x = 1;
         foreach ($column_array as $column) {
             if ($x < $column_array_count) {
                 if (strlen($row[$column]) > 0) {
                     $sql .= '' . $column . ',';
                 }
             } else {
コード例 #19
0
function xmldb_interaction_forum_upgrade($oldversion = 0)
{
    if ($oldversion < 2009062300) {
        foreach (array('topic', 'forum') as $type) {
            log_debug("Subscription upgrade for {$type}s");
            // Add missing primary key to the subscription tables
            // Step 1: remove duplicates
            if ($dupes = get_records_sql_array('
                SELECT "user", ' . $type . ', COUNT(*)
                FROM {interaction_forum_subscription_' . $type . '}
                GROUP BY "user", ' . $type . '
                HAVING COUNT(*) > 1', array())) {
                // We found duplicate subscriptions to a topic/forum
                foreach ($dupes as $dupe) {
                    log_debug("interaction.forum: Removing duplicate {$type} subscription for {$dupe->user}");
                    delete_records('interaction_forum_subscription_' . $type, 'user', $dupe->user, $type, $dupe->{$type});
                    insert_record('interaction_forum_subscription_' . $type, (object) array('user' => $dupe->user, $type => $dupe->{$type}));
                }
            }
            // Step 2: add the actual key
            $table = new XMLDBTable('interaction_forum_subscription_' . $type);
            $key = new XMLDBKey('primary');
            $key->setAttributes(XMLDB_KEY_PRIMARY, array('user', $type));
            add_key($table, $key);
            // Add a 'key' column, used for unsubscriptions
            $field = new XMLDBField('key');
            $field->setAttributes(XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, null);
            add_field($table, $field);
            $key = new XMLDBKey('keyuk');
            $key->setAttributes(XMLDB_KEY_UNIQUE, array('key'));
            add_key($table, $key);
            // Populate the key column
            if ($records = get_records_array('interaction_forum_subscription_' . $type, '', '', '', '"user", ' . $type)) {
                foreach ($records as $where) {
                    $new = (object) array('user' => $where->user, $type => $where->{$type}, 'key' => dechex(mt_rand()));
                    update_record('interaction_forum_subscription_' . $type, $new, $where);
                }
            }
            // Now make the key column not null
            $field->setAttributes(XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            change_field_notnull($table, $field);
        }
    }
    if ($oldversion < 2009081700) {
        if (!get_record('interaction_config', 'plugin', 'forum', 'field', 'postdelay')) {
            insert_record('interaction_config', (object) array('plugin' => 'forum', 'field' => 'postdelay', 'value' => 30));
        }
    }
    if ($oldversion < 2009081800) {
        $subscription = (object) array('plugin' => 'forum', 'event' => 'creategroup', 'callfunction' => 'create_default_forum');
        ensure_record_exists('interaction_event_subscription', $subscription, $subscription);
    }
    if ($oldversion < 2012071100) {
        // Add new column 'path' to table interaction_forum_post used for diplaying posts by threads
        $table = new XMLDBTable('interaction_forum_post');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, 2048, null, null);
        add_field($table, $field);
        $index = new XMLDBIndex('pathix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('path'));
        add_index($table, $index);
        // Update the column 'path' for all posts in the old database
        $done = 0;
        $lastid = 0;
        $pwcount = count_records('interaction_forum_post');
        if (is_mysql()) {
            $mp = mysql_get_variable('max_allowed_packet');
            $limit = $mp && is_numeric($mp) && $mp > 1048576 ? $mp / 8192 : 100;
        } else {
            $limit = 2000;
        }
        while ($posts = get_records_select_array('interaction_forum_post', 'id > ?', array($lastid), 'id', 'id, parent', 0, $limit)) {
            foreach ($posts as $post) {
                // Update the column 'path'
                $path = sprintf('%010d', $post->id);
                $parentid = $post->parent;
                while (!empty($parentid)) {
                    if ($p = get_record_select('interaction_forum_post', 'id = ?', array($parentid), 'parent, path')) {
                        if (!empty($p->path)) {
                            $path = $p->path . '/' . $path;
                            break;
                        }
                        $path = sprintf('%010d', $parentid) . '/' . $path;
                        $parentid = $p->parent;
                    } else {
                        throw new SQLException("Can't find the post with id = '{$parentid}'");
                    }
                }
                $post->path = $path;
                update_record('interaction_forum_post', $post);
                $lastid = $post->id;
            }
            $done += count($posts);
            log_debug("Updating posts' path: {$done}/{$pwcount}");
            set_time_limit(50);
        }
    }
    if ($oldversion < 2014050800) {
        // Subscribe admins to new activity.
        $adminusers = get_column('usr', 'id', 'admin', 1, 'deleted', 0);
        activity_add_admin_defaults($adminusers);
    }
    if ($oldversion < 2014060500) {
        // Drop unused fields.
        $table = new XMLDBTable('interaction_forum_post');
        $field = new XMLDBField('reported');
        if (field_exists($table, $field)) {
            drop_field($table, $field, true);
        }
        $field = new XMLDBField('reportedreason');
        if (field_exists($table, $field)) {
            drop_field($table, $field, true);
        }
    }
    return true;
}
コード例 #20
0
function xmldb_core_upgrade($oldversion = 0)
{
    ini_set('max_execution_time', 120);
    // Let's be safe
    raise_memory_limit('256M');
    $INNODB = is_mysql() ? ' TYPE=innodb' : '';
    $status = true;
    // We discovered that username case insensitivity was not being enforced at
    // most of the entry points to the system at which users can be created.
    // This problem manifested itself as users who had the same LOWER(username)
    // as another not being able to log in. The fix is to implement the checks,
    // rename the "duplicate" users and add a constraint on the database so it
    // can't happen again
    if ($oldversion < 2008040202) {
        $renamed = $newusernames = $oldusernames = array();
        $allusers = get_records_array('usr', '', '', 'id', 'id, username');
        $usernamemapping = array();
        foreach ($allusers as $user) {
            $oldusernames[] = $user->username;
            $usernamemapping[strtolower($user->username)][] = array('id' => $user->id, 'username' => $user->username);
        }
        foreach ($usernamemapping as $lcname => $users) {
            if (count($users) == 1) {
                continue;
            }
            // Uhohes. Rename the user(s) who were created last
            $skippedfirst = false;
            foreach ($users as $user) {
                if (!$skippedfirst) {
                    $skippedfirst = true;
                    continue;
                }
                $userobj = new User();
                $userobj->find_by_id($user['id']);
                // Append digits keeping total length <= 30
                $i = 1;
                $newname = substr($user['username'], 0, 29) . $i;
                while (isset($newusernames[$newname]) || isset($oldusernames[$newname])) {
                    $i++;
                    $newname = substr($user['username'], 0, 30 - floor(log10($i) + 1)) . $i;
                }
                set_field('usr', 'username', $newname, 'id', $user['id']);
                $newusernames[$newname] = true;
                $renamed[$newname] = $userobj;
                log_debug(" * Renamed {$user['username']} to {$newname}");
            }
        }
        if (!empty($renamed)) {
            // Notify changed usernames to administrator
            $report = '# Each line in this file is in the form "old_username new_username"' . "\n";
            $message = "Mahara now requires usernames to be unique, case insensitively.\n";
            $message .= "Some usernames on your site were changed during the upgrade:\n\n";
            foreach ($renamed as $newname => $olduser) {
                $report .= "{$olduser->username} {$newname}\n";
                $message .= "Old username: {$olduser->username}\n" . "New username: {$newname}\n\n";
            }
            $sitename = get_config('sitename');
            $file = get_config('dataroot') . 'user_migration_report_2.txt';
            if (file_put_contents($file, $report)) {
                $message .= "\n" . 'A copy of this list has been saved to the file ' . $file;
            }
            global $USER;
            email_user($USER, null, $sitename . ': User migration', $message);
            // Notify changed usernames to users
            $usermessagestart = "Your username at {$sitename} has been changed:\n\n";
            $usermessageend = "\n\nNext time you visit the site, please login using your new username.";
            foreach ($renamed as $newname => $olduser) {
                if ($olduser->email == '') {
                    continue;
                }
                log_debug("Attempting to notify {$newname} ({$olduser->email}) of their new username...");
                email_user($olduser, null, $sitename . ': User name changed', $usermessagestart . "Old username: {$olduser->username}\nNew username: {$newname}" . $usermessageend);
            }
        }
        // Now we know all usernames are unique over their lowercase values, we
        // can put an index in so data doesn't get all inconsistent next time
        if (is_postgres()) {
            execute_sql('DROP INDEX {usr_use_uix}');
            execute_sql('CREATE UNIQUE INDEX {usr_use_uix} ON {usr}(LOWER(username))');
        } else {
            // MySQL cannot create indexes over functions of columns. Too bad
            // for it. We won't drop the existing index because that offers a
            // large degree of protection, but when MySQL finally supports this
            // we will be able to add it
        }
        // Install a cron job to delete old session files
        $cron = new StdClass();
        $cron->callfunction = 'auth_remove_old_session_files';
        $cron->minute = '30';
        $cron->hour = '20';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2008040203) {
        // Install a cron job to recalculate user quotas
        $cron = new StdClass();
        $cron->callfunction = 'recalculate_quota';
        $cron->minute = '15';
        $cron->hour = '2';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2008040204) {
        if (field_exists(new XMLDBTable('usr_friend_request'), new XMLDBField('reason'))) {
            if (is_postgres()) {
                execute_sql('ALTER TABLE {usr_friend_request} RENAME COLUMN reason TO message');
            } else {
                if (is_mysql()) {
                    execute_sql('ALTER TABLE {usr_friend_request} CHANGE reason message TEXT');
                }
            }
        }
    }
    if ($oldversion < 2008080400) {
        // Group type refactor
        log_debug('GROUP TYPE REFACTOR');
        execute_sql('ALTER TABLE {group} ADD grouptype CHARACTER VARYING(20)');
        execute_sql('ALTER TABLE {group_member} ADD role CHARACTER VARYING(255)');
        $groups = get_records_array('group');
        if ($groups) {
            require_once get_config('docroot') . 'grouptype/lib.php';
            require_once get_config('docroot') . 'grouptype/standard/lib.php';
            require_once get_config('docroot') . 'grouptype/course/lib.php';
            foreach ($groups as $group) {
                log_debug("Migrating group {$group->name} ({$group->id})");
                // Establish the new group type
                if ($group->jointype == 'controlled') {
                    $group->grouptype = 'course';
                } else {
                    $group->grouptype = 'standard';
                }
                execute_sql('UPDATE {group} SET grouptype = ? WHERE id = ?', array($group->grouptype, $group->id));
                log_debug(' * new group type is ' . $group->grouptype);
                // Convert group membership information to roles
                foreach (call_static_method('GroupType' . $group->grouptype, 'get_roles') as $role) {
                    if ($role == 'admin') {
                        // It would be nice to use ensure_record_exists here,
                        // but because ctime is not null we have to provide it
                        // as data, which means the ctime would be updated if
                        // the record _did_ exist
                        if (get_record('group_member', 'group', $group->id, 'member', $group->owner)) {
                            execute_sql("UPDATE {group_member}\n                                SET role = 'admin'\n                                WHERE \"group\" = ?\n                                AND member = ?", array($group->id, $group->owner));
                        } else {
                            // In old versions of Mahara, there did not need to
                            // be a record in the group_member table for the
                            // owner
                            $data = (object) array('group' => $group->id, 'member' => $group->owner, 'ctime' => db_format_timestamp(time()), 'role' => 'admin');
                            insert_record('group_member', $data);
                        }
                        log_debug(" * marked user {$group->owner} as having the admin role");
                    } else {
                        // Setting role instances for tutors and members
                        $tutorflag = $role == 'tutor' ? 1 : 0;
                        execute_sql('UPDATE {group_member}
                            SET role = ?
                            WHERE "group" = ?
                            AND member != ?
                            AND tutor = ?', array($role, $group->id, $group->owner, $tutorflag));
                        log_debug(" * marked appropriate users as being {$role}s");
                    }
                }
            }
        }
        if (is_postgres()) {
            execute_sql('ALTER TABLE {group} ALTER grouptype SET NOT NULL');
            execute_sql('ALTER TABLE {group_member} ALTER role SET NOT NULL');
        } else {
            if (is_mysql()) {
                execute_sql('ALTER TABLE {group} MODIFY grouptype CHARACTER VARYING(20) NOT NULL');
                execute_sql('ALTER TABLE {group_member} MODIFY role CHARACTER VARYING(255) NOT NULL');
            }
        }
        if (is_mysql()) {
            execute_sql('ALTER TABLE {group} DROP FOREIGN KEY {grou_own_fk}');
        }
        execute_sql('ALTER TABLE {group} DROP owner');
        execute_sql('ALTER TABLE {group_member} DROP tutor');
        // Adminfiles become "institution-owned artefacts"
        execute_sql("ALTER TABLE {artefact} ADD COLUMN institution CHARACTER VARYING(255);");
        if (is_postgres()) {
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN owner DROP NOT NULL;");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {artefact} MODIFY owner BIGINT(10) NULL;");
            }
        }
        execute_sql("ALTER TABLE {artefact} ADD CONSTRAINT {arte_ins_fk} FOREIGN KEY (institution) REFERENCES {institution}(name);");
        execute_sql("UPDATE {artefact} SET institution = 'mahara', owner = NULL WHERE id IN (SELECT artefact FROM {artefact_file_files} WHERE adminfiles = 1)");
        execute_sql("ALTER TABLE {artefact_file_files} DROP COLUMN adminfiles");
        execute_sql('ALTER TABLE {artefact} ADD COLUMN "group" BIGINT');
        execute_sql('ALTER TABLE {artefact} ADD CONSTRAINT {arte_gro_fk} FOREIGN KEY ("group") REFERENCES {group}(id)');
        // New artefact permissions for use with group-owned artefacts
        execute_sql('CREATE TABLE {artefact_access_role} (
            role VARCHAR(255) NOT NULL,
            artefact INTEGER NOT NULL REFERENCES {artefact}(id),
            can_view SMALLINT NOT NULL,
            can_edit SMALLINT NOT NULL,
            can_republish SMALLINT NOT NULL
        )' . $INNODB);
        execute_sql('CREATE TABLE {artefact_access_usr} (
            usr INTEGER NOT NULL REFERENCES {usr}(id),
            artefact INTEGER NOT NULL REFERENCES {artefact}(id),
            can_republish SMALLINT
        )' . $INNODB);
        // grouptype tables
        execute_sql("CREATE TABLE {grouptype} (\n            name VARCHAR(20) PRIMARY KEY,\n            submittableto SMALLINT NOT NULL,\n            defaultrole VARCHAR(255) NOT NULL DEFAULT 'member'\n        )" . $INNODB);
        execute_sql("INSERT INTO {grouptype} (name,submittableto) VALUES ('standard',0)");
        execute_sql("INSERT INTO {grouptype} (name,submittableto) VALUES ('course',1)");
        execute_sql('CREATE TABLE {grouptype_roles} (
            grouptype VARCHAR(20) NOT NULL REFERENCES {grouptype}(name),
            edit_views SMALLINT NOT NULL DEFAULT 1,
            see_submitted_views SMALLINT NOT NULL DEFAULT 0,
            role VARCHAR(255) NOT NULL
        )' . $INNODB);
        execute_sql("INSERT INTO {grouptype_roles} (grouptype,edit_views,see_submitted_views,role) VALUES ('standard',1,0,'admin')");
        execute_sql("INSERT INTO {grouptype_roles} (grouptype,edit_views,see_submitted_views,role) VALUES ('standard',1,0,'member')");
        execute_sql("INSERT INTO {grouptype_roles} (grouptype,edit_views,see_submitted_views,role) VALUES ('course',1,0,'admin')");
        execute_sql("INSERT INTO {grouptype_roles} (grouptype,edit_views,see_submitted_views,role) VALUES ('course',1,1,'tutor')");
        execute_sql("INSERT INTO {grouptype_roles} (grouptype,edit_views,see_submitted_views,role) VALUES ('course',0,0,'member')");
        if (is_postgres()) {
            $table = new XMLDBTable('group');
            $key = new XMLDBKey('grouptypefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('grouptype'), 'grouptype', array('name'));
            add_key($table, $key);
        } else {
            if (is_mysql()) {
                // Seems to refuse to create foreign key, not sure why yet
                execute_sql("ALTER TABLE {group} ADD INDEX {grou_gro_ix} (grouptype);");
                // execute_sql("ALTER TABLE {group} ADD CONSTRAINT {grou_gro_fk} FOREIGN KEY (grouptype) REFERENCES {grouptype} (name);");
            }
        }
        // Group views
        execute_sql('ALTER TABLE {view} ADD COLUMN "group" BIGINT');
        execute_sql('ALTER TABLE {view} ADD CONSTRAINT {view_gro_fk} FOREIGN KEY ("group") REFERENCES {group}(id)');
        if (is_postgres()) {
            execute_sql('ALTER TABLE {view} ALTER COLUMN owner DROP NOT NULL');
            execute_sql('ALTER TABLE {view} ALTER COLUMN ownerformat DROP NOT NULL');
        } else {
            if (is_mysql()) {
                execute_sql('ALTER TABLE {view} MODIFY owner BIGINT(10) NULL');
                execute_sql('ALTER TABLE {view} MODIFY ownerformat TEXT NULL');
            }
        }
        execute_sql('ALTER TABLE {view_access_group} ADD COLUMN role VARCHAR(255)');
        execute_sql("UPDATE {view_access_group} SET role = 'tutor' WHERE tutoronly = 1");
        execute_sql('ALTER TABLE {view_access_group} DROP COLUMN tutoronly');
        // grouptype plugin tables
        $table = new XMLDBTable('grouptype_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('grouptype_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, null, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, null, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, null, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, null, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, null, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'grouptype_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('grouptype_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'grouptype_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('grouptype_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, null, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'grouptype_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
        if ($data = check_upgrades('grouptype.standard')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('grouptype.course')) {
            upgrade_plugin($data);
        }
        // Group invitations take a role
        execute_sql('ALTER TABLE {group_member_invite} ADD COLUMN role VARCHAR(255)');
    }
    if ($oldversion < 2008081101) {
        execute_sql("ALTER TABLE {view} ADD COLUMN institution CHARACTER VARYING(255);");
        execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_ins_fk} FOREIGN KEY (institution) REFERENCES {institution}(name);");
        execute_sql("ALTER TABLE {view} ADD COLUMN template SMALLINT NOT NULL DEFAULT 0;");
    }
    if ($oldversion < 2008081102) {
        execute_sql("ALTER TABLE {view} ADD COLUMN copynewuser SMALLINT NOT NULL DEFAULT 0;");
        execute_sql('CREATE TABLE {view_autocreate_grouptype} (
            view INTEGER NOT NULL REFERENCES {view}(id),
            grouptype VARCHAR(20) NOT NULL REFERENCES {grouptype}(name)
        )' . $INNODB);
    }
    if ($oldversion < 2008090100) {
        $table = new XMLDBTable('import_queue');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('host', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('queue', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('ready', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('expirytime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('format', XMLDB_TYPE_CHAR, 50, null, null);
        $table->addFieldInfo('data', XMLDB_TYPE_TEXT, 'large', null, null);
        $table->addFieldInfo('token', XMLDB_TYPE_CHAR, 40, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        $table->addKeyInfo('hostfk', XMLDB_KEY_FOREIGN, array('host'), 'host', array('wwwroot'));
        create_table($table);
        // Install a cron job to process the queue
        $cron = new StdClass();
        $cron->callfunction = 'import_process_queue';
        $cron->minute = '*/5';
        $cron->hour = '*';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2008090800) {
        $table = new XMLDBTable('artefact_log');
        $table->addFieldInfo('artefact', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, null, null);
        $table->addFieldInfo('time', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('title', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, 10, null, null);
        $table->addFieldInfo('created', XMLDB_TYPE_INTEGER, 1, null, null);
        $table->addFieldInfo('deleted', XMLDB_TYPE_INTEGER, 1, null, null);
        $table->addFieldInfo('edited', XMLDB_TYPE_INTEGER, 1, null, null);
        $table->addIndexInfo('artefactix', XMLDB_INDEX_NOTUNIQUE, array('artefact'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        create_table($table);
    }
    if ($oldversion < 2008091500) {
        // NOTE: Yes, this number is bigger than the number for the next upgrade
        // The next upgrade got committed first. It deletes all users properly,
        // but the usr table has a 30 character limit on username, which can be
        // violated when people with long usernames are deleted
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('username');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, XMLDB_NOTNULL);
        change_field_precision($table, $field);
    }
    if ($oldversion < 2008091200) {
        // Some cleanups for deleted users, based on the new model of handling them
        if ($userids = get_column('usr', 'id', 'deleted', 1)) {
            foreach ($userids as $userid) {
                // We want to append 'deleted.timestamp' to some unique fields in the usr
                // table, so they can be reused by new accounts
                $fieldstomunge = array('username', 'email');
                $datasuffix = '.deleted.' . time();
                $user = get_record('usr', 'id', $userid, null, null, null, null, implode(', ', $fieldstomunge));
                $deleterec = new StdClass();
                $deleterec->id = $userid;
                $deleterec->deleted = 1;
                foreach ($fieldstomunge as $field) {
                    if (!preg_match('/\\.deleted\\.\\d+$/', $user->{$field})) {
                        $deleterec->{$field} = $user->{$field} . $datasuffix;
                    }
                }
                // Set authinstance to default internal, otherwise the old authinstance can be blocked from deletion
                // by deleted users.
                $authinst = get_field('auth_instance', 'id', 'institution', 'mahara', 'instancename', 'internal');
                if ($authinst) {
                    $deleterec->authinstance = $deleterec->lastauthinstance = $authinst;
                }
                update_record('usr', $deleterec);
                // Because the user is being deleted, but their email address may be wanted
                // for a new user, we change their email addresses to add
                // 'deleted.[timestamp]'
                execute_sql("UPDATE {artefact_internal_profile_email}\n                             SET email = email || ?\n                             WHERE owner = ? AND NOT email LIKE '%.deleted.%'", array($datasuffix, $userid));
                // Remove remote user records
                delete_records('auth_remote_user', 'localusr', $userid);
            }
        }
    }
    if ($oldversion < 2008091601) {
        $table = new XMLDBTable('event_subscription');
        if (!table_exists($table)) {
            $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
            $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
            $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
            $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('event', 'callfunction'));
            create_table($table);
            insert_record('event_subscription', (object) array('event' => 'createuser', 'callfunction' => 'activity_set_defaults'));
            $table = new XMLDBTable('view_type');
            $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('type'));
            create_table($table);
            $viewtypes = array('portfolio', 'profile');
            foreach ($viewtypes as $vt) {
                insert_record('view_type', (object) array('type' => $vt));
            }
            $table = new XMLDBTable('blocktype_installed_viewtype');
            $table->addFieldInfo('blocktype', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->addFieldInfo('viewtype', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('blocktype', 'viewtype'));
            $table->addKeyInfo('blocktypefk', XMLDB_KEY_FOREIGN, array('blocktype'), 'blocktype_installed', array('name'));
            $table->addKeyInfo('viewtypefk', XMLDB_KEY_FOREIGN, array('viewtype'), 'view_type', array('type'));
            create_table($table);
            $table = new XMLDBTable('view');
            $field = new XMLDBField('type');
            $field->setAttributes(XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, null);
            add_field($table, $field);
            $key = new XMLDBKey('typefk');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('type'), 'view_type', array('type'));
            add_key($table, $key);
            set_field('view', 'type', 'portfolio');
            $field->setAttributes(XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
            change_field_notnull($table, $field);
            if ($blocktypes = plugins_installed('blocktype', true)) {
                foreach ($blocktypes as $bt) {
                    install_blocktype_viewtypes_for_plugin(blocktype_single_to_namespaced($bt->name, $bt->artefactplugin));
                }
            }
        }
    }
    if ($oldversion < 2008091603) {
        foreach (array('myviews', 'mygroups', 'myfriends', 'wall') as $blocktype) {
            $data = check_upgrades("blocktype.{$blocktype}");
            if ($data) {
                upgrade_plugin($data);
            }
        }
        if (!get_record('view', 'owner', 0, 'type', 'profile')) {
            // First ensure system user has id = 0; In older MySQL installations it may be > 0
            $sysuser = get_record('usr', 'username', 'root');
            if ($sysuser && $sysuser->id > 0 && !count_records('usr', 'id', 0)) {
                set_field('usr', 'id', 0, 'id', $sysuser->id);
            }
            // Install system profile view
            require_once get_config('libroot') . 'view.php';
            $dbtime = db_format_timestamp(time());
            $viewdata = (object) array('type' => 'profile', 'owner' => 0, 'numcolumns' => 2, 'ownerformat' => FORMAT_NAME_PREFERREDNAME, 'title' => get_string('profileviewtitle', 'view'), 'description' => '', 'template' => 1, 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
            $id = insert_record('view', $viewdata, 'id', true);
            $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
            insert_record('view_access', $accessdata);
            $blocktypes = array('myviews' => 1, 'mygroups' => 1, 'myfriends' => 2, 'wall' => 2);
            // column ids
            $installed = get_column_sql('SELECT name FROM {blocktype_installed} WHERE name IN (' . join(',', array_map('db_quote', array_keys($blocktypes))) . ')');
            $weights = array(1 => 0, 2 => 0);
            foreach (array_keys($blocktypes) as $blocktype) {
                if (in_array($blocktype, $installed)) {
                    $weights[$blocktypes[$blocktype]]++;
                    insert_record('block_instance', (object) array('blocktype' => $blocktype, 'title' => get_string('title', 'blocktype.' . $blocktype), 'view' => $id, 'column' => $blocktypes[$blocktype], 'order' => $weights[$blocktypes[$blocktype]]));
                }
            }
        }
    }
    if ($oldversion < 2008091604) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastlastlogin');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    if ($oldversion < 2008092000) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastaccess');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    // The previous upgrade forces the user to be logged out.  The
    // next upgrade should probably set disablelogin = false and
    // minupgradefrom = 2008092000 in version.php.
    if ($oldversion < 2008101500) {
        // Remove event subscription for new user accounts to have a default
        // profile view created, they're now created on demand
        execute_sql("DELETE FROM {event_subscription} WHERE event = 'createuser' AND callfunction = 'install_default_profile_view';");
    }
    if ($oldversion < 2008101602) {
        $artefactdata = get_config('dataroot') . 'artefact/';
        if (is_dir($artefactdata . 'file/profileicons')) {
            throw new SystemException("Upgrade 2008101602: {$artefactdata}/file/profileicons already exists!");
        }
        // Move artefact/internal/profileicons directory to artefact/file
        set_field('artefact_installed_type', 'plugin', 'file', 'name', 'profileicon');
        set_field('artefact_config', 'plugin', 'file', 'field', 'profileiconwidth');
        set_field('artefact_config', 'plugin', 'file', 'field', 'profileiconheight');
        if (is_dir($artefactdata . 'internal/profileicons')) {
            if (!is_dir($artefactdata . 'file')) {
                mkdir($artefactdata . 'file');
            }
            if (!rename($artefactdata . 'internal/profileicons', $artefactdata . 'file/profileicons')) {
                throw new SystemException("Failed moving {$artefactdata}/internal/profileicons to {$artefactdata}/file/profileicons");
            }
            // Insert artefact_file_files records for all profileicons
            $profileicons = get_column('artefact', 'id', 'artefacttype', 'profileicon');
            if ($profileicons) {
                foreach ($profileicons as $a) {
                    $filename = $artefactdata . 'file/profileicons/originals/' . $a % 256 . '/' . $a;
                    if (file_exists($filename)) {
                        $filesize = filesize($filename);
                        $imagesize = getimagesize($artefactdata . 'file/profileicons/originals/' . $a % 256 . '/' . $a);
                        insert_record('artefact_file_files', (object) array('artefact' => $a, 'fileid' => $a, 'size' => $filesize));
                        insert_record('artefact_file_image', (object) array('artefact' => $a, 'width' => $imagesize[0], 'height' => $imagesize[1]));
                    } else {
                        log_debug("Profile icon artefact {$a} has no file on disk at {$filename}");
                    }
                }
            }
        }
    }
    if ($oldversion < 2008102200) {
        $table = new XMLDBTable('view_access_token');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('token', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('startdate', XMLDB_TYPE_DATETIME, null, null);
        $table->addFieldInfo('stopdate', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('token'));
        create_table($table);
    }
    if ($oldversion < 2008102400) {
        // Feedback can be left by anon users with a view token, so feedback author must be nullable
        $table = new XMLDBTable('view_feedback');
        if (is_mysql()) {
            execute_sql("ALTER TABLE {view_feedback} DROP FOREIGN KEY {viewfeed_aut_fk}");
            execute_sql('ALTER TABLE {view_feedback} MODIFY author BIGINT(10) NULL');
        } else {
            $field = new XMLDBField('author');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED);
            change_field_notnull($table, $field);
        }
        $key = new XMLDBKEY('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        $table = new XMLDBTable('artefact_feedback');
        if (is_mysql()) {
            execute_sql("ALTER TABLE {artefact_feedback} DROP FOREIGN KEY {artefeed_aut_fk}");
            execute_sql('ALTER TABLE {artefact_feedback} MODIFY author BIGINT(10) NULL');
        } else {
            $field = new XMLDBField('author');
            $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED);
            change_field_notnull($table, $field);
        }
        $key = new XMLDBKEY('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        table_column('view_feedback', null, 'authorname', 'text', null, null, null, '');
        table_column('artefact_feedback', null, 'authorname', 'text', null, null, null, '');
    }
    if ($oldversion < 2008110700) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('public');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        set_config('createpublicgroups', 'admins');
    }
    if ($oldversion < 2008111102) {
        set_field('grouptype_roles', 'see_submitted_views', 1, 'grouptype', 'course', 'role', 'admin');
    }
    if ($oldversion < 2008111200) {
        // Event subscription for auto adding users to groups
        insert_record('event_subscription', (object) array('event' => 'createuser', 'callfunction' => 'add_user_to_autoadd_groups'));
        $table = new XMLDBTable('group');
        $field = new XMLDBField('usersautoadded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2008111201) {
        $event = (object) array('name' => 'userjoinsgroup');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2008110400) {
        // Correct capitalisation of internal authinstance for 'no institution', only if it hasn't changed previously
        execute_sql("UPDATE {auth_instance} SET instancename = 'Internal' WHERE institution = 'mahara' AND authname = 'internal' AND instancename = 'internal'");
    }
    if ($oldversion < 2008121500) {
        // Make sure the system profile view is marked as a template and is
        // allowed to be copied by everyone
        require_once 'view.php';
        execute_sql("UPDATE {view} SET template = 1 WHERE owner = 0 AND type = 'profile'");
        $viewid = get_field('view', 'id', 'owner', 0, 'type', 'profile');
        delete_records('view_access', 'view', $viewid);
        insert_record('view_access', (object) array('view' => $viewid, 'accesstype' => 'loggedin'));
    }
    if ($oldversion < 2008122300) {
        // Delete all activity_queue entries older than 2 weeks. Designed to
        // prevent total spammage caused by the activity queue processing bug
        delete_records_select('activity_queue', 'ctime < ?', array(db_format_timestamp(time() - 86400 * 14)));
    }
    if ($oldversion < 2009011500) {
        // Make the "port" column larger so it can handle any port number
        $table = new XMLDBTable('host');
        $field = new XMLDBField('portno');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, null, null, null, 80);
        change_field_precision($table, $field);
    }
    if ($oldversion < 2009021600) {
        // Add constraints on view and artefact tables to make sure that of the
        // owner/group/institution fields, only one is set at any given time
        // First, we make blind assumptions in order to tweak the data into
        // being valid. In theory, there shouldn't be much danger because most
        // people will upgrade from 1.0 to 1.1, and thus never have invalid
        // data in their tables.
        execute_sql('UPDATE {artefact} SET owner = NULL WHERE institution IS NOT NULL');
        execute_sql('UPDATE {artefact} SET "group" = NULL WHERE institution IS NOT NULL');
        execute_sql('UPDATE {artefact} SET owner = NULL WHERE "group" IS NOT NULL');
        execute_sql('UPDATE {view} SET owner = NULL WHERE institution IS NOT NULL');
        execute_sql('UPDATE {view} SET "group" = NULL WHERE institution IS NOT NULL');
        execute_sql('UPDATE {view} SET owner = NULL WHERE "group" IS NOT NULL');
        // Now add the constraints. MySQL parses check constraints but doesn't
        // actually apply them. So these protections will only apply if you use
        // Postgres. You did read the installation instruction's
        // recommendations that you use postgres, didn't you?
        execute_sql('ALTER TABLE {artefact} ADD CHECK (
            (owner IS NOT NULL AND "group" IS NULL     AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NOT NULL AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NULL     AND institution IS NOT NULL)
        )');
        execute_sql('ALTER TABLE {view} ADD CHECK (
            (owner IS NOT NULL AND "group" IS NULL     AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NOT NULL AND institution IS NULL) OR
            (owner IS NULL     AND "group" IS NULL     AND institution IS NOT NULL)
        )');
    }
    if ($oldversion < 2009021700) {
        try {
            include_once 'xmlize.php';
            $newlist = xmlize(file_get_contents(get_config('libroot') . 'htmlpurifiercustom/filters.xml'));
            $filters = $newlist['filters']['#']['filter'];
            foreach ($filters as &$f) {
                $f = (object) array('site' => $f['#']['site'][0]['#'], 'file' => $f['#']['filename'][0]['#']);
            }
            $filters[] = (object) array('site' => 'http://www.youtube.com', 'file' => 'YouTube');
            set_config('filters', serialize($filters));
        } catch (Exception $e) {
            log_debug('Upgrade 2009021700: failed to load html filters');
        }
    }
    if ($oldversion < 2009021701) {
        // Make sure that all views that can be copied have loggedin access
        // This upgrade just fixes potentially corrupt data caused by running a
        // beta version then upgrading it
        if ($views = get_column('view', 'id', 'copynewuser', '1')) {
            $views[] = 1;
            foreach ($views as $viewid) {
                if (!record_exists('view_access', 'view', $viewid, 'accesstype', 'loggedin')) {
                    // We're not checking that access dates are null (aka
                    // it can always be accessed), but the chance of people
                    // needing this upgrade are slim anyway
                    insert_record('view_access', (object) array('view' => $viewid, 'accesstype' => 'loggedin', 'startdate' => null, 'stopdate' => null));
                }
            }
        }
    }
    if ($oldversion < 2009021900) {
        // Generate a unique installation key
        set_config('installation_key', get_random_key());
    }
    if ($oldversion < 2009021901) {
        // Insert a cron job to send registration data to mahara.org
        $cron = new StdClass();
        $cron->callfunction = 'cron_send_registration_data';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = rand(0, 6);
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009022700) {
        // Get rid of all blocks with position 0 caused by 'about me' block on profile views
        if (count_records('block_instance', 'order', 0) && !count_records_select('block_instance', '"order" < 0')) {
            if (is_mysql()) {
                $ids = get_column_sql('
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column)');
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (' . join(',', $ids) . ')');
            } else {
                execute_sql('UPDATE {block_instance} SET "order" =  -1 * "order" WHERE id IN (
                    SELECT i.id FROM {block_instance} i
                    INNER JOIN (SELECT view, "column" FROM {block_instance} WHERE "order" = 0) z
                        ON (z.view = i.view AND z.column = i.column))');
            }
            execute_sql('UPDATE {block_instance} SET "order" = 1 WHERE "order" = 0');
            execute_sql('UPDATE {block_instance} SET "order" = -1 * ("order" - 1) WHERE "order" < 0');
        }
    }
    if ($oldversion < 2009031000) {
        reload_html_filters();
    }
    if ($oldversion < 2009031300) {
        $table = new XMLDBTable('institution');
        $expiry = new XMLDBField('expiry');
        $expiry->setAttributes(XMLDB_TYPE_DATETIME);
        add_field($table, $expiry);
        $expirymailsent = new XMLDBField('expirymailsent');
        $expirymailsent->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $expirymailsent);
        $suspended = new XMLDBField('suspended');
        $suspended->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $suspended);
        // Insert a cron job to check for soon expiring and expired institutions
        if (!record_exists('cron', 'callfunction', 'auth_handle_institution_expiries')) {
            $cron = new StdClass();
            $cron->callfunction = 'auth_handle_institution_expiries';
            $cron->minute = '5';
            $cron->hour = '9';
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2009031800) {
        // Files can only attach blogpost artefacts, but we would like to be able to attach them
        // to other stuff.  Rename the existing attachment table artefact_blog_blogpost_file to
        // artefact_file_attachment so we don't end up with many tables doing the same thing.
        execute_sql("ALTER TABLE {artefact_blog_blogpost_file} RENAME TO {artefact_attachment}");
        if (is_postgres()) {
            // Ensure all of the indexes and constraints are renamed
            execute_sql("\n            ALTER TABLE {artefact_attachment} RENAME blogpost TO artefact;\n            ALTER TABLE {artefact_attachment} RENAME file TO attachment;\n\n            ALTER INDEX {arteblogblogfile_blofil_pk} RENAME TO {arteatta_artatt_pk};\n            ALTER INDEX {arteblogblogfile_blo_ix} RENAME TO {arteatta_art_ix};\n            ALTER INDEX {arteblogblogfile_fil_ix} RENAME TO {arteatta_att_ix};\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_blo_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY (artefact) REFERENCES {artefact}(id);\n\n            ALTER TABLE {artefact_attachment} DROP CONSTRAINT {arteblogblogfile_fil_fk};\n            ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY (attachment) REFERENCES {artefact}(id);\n            ");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_blo_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_blo_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE blogpost artefact BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_art_fk} FOREIGN KEY {arteatta_art_ix} (artefact) REFERENCES {artefact}(id)");
                execute_sql("ALTER TABLE {artefact_attachment} DROP FOREIGN KEY {arteblogblogfile_fil_fk}");
                execute_sql("ALTER TABLE {artefact_attachment} DROP INDEX {arteblogblogfile_fil_ix}");
                execute_sql("ALTER TABLE {artefact_attachment} CHANGE file attachment BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {artefact_attachment} ADD CONSTRAINT {arteatta_att_fk} FOREIGN KEY {arteatta_att_ix} (attachment) REFERENCES {artefact}(id)");
            }
        }
        // Drop the _pending table. From now on files uploaded as attachments will become artefacts
        // straight away.  Hopefully changes to the upload/file browser form will make it clear to
        // the user that these attachments sit in his/her files area as soon as they are uploaded.
        $table = new XMLDBTable('artefact_blog_blogpost_file_pending');
        drop_table($table);
    }
    if ($oldversion < 2009040900) {
        // The view access page has been putting the string 'null' in as a group role in IE.
        set_field('view_access_group', 'role', null, 'role', 'null');
    }
    if ($oldversion < 2009040901) {
        $table = new XMLDBTable('import_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('import_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('import_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'import_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
        $table = new XMLDBTable('export_installed');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('version', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('release', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('active', XMLDB_TYPE_INTEGER, 1, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('name'));
        create_table($table);
        $table = new XMLDBTable('export_cron');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('minute', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('hour', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('day', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('dayofweek', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('month', XMLDB_TYPE_CHAR, 25, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '*');
        $table->addFieldInfo('nextrun', XMLDB_TYPE_DATETIME, null, null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'callfunction'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_config');
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('field', XMLDB_TYPE_CHAR, 100, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('plugin', 'field'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        create_table($table);
        $table = new XMLDBTable('export_event_subscription');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('plugin', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('event', XMLDB_TYPE_CHAR, 50, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('callfunction', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('pluginfk', XMLDB_KEY_FOREIGN, array('plugin'), 'export_installed', array('name'));
        $table->addKeyInfo('eventfk', XMLDB_KEY_FOREIGN, array('event'), 'event_type', array('name'));
        $table->addKeyInfo('subscruk', XMLDB_KEY_UNIQUE, array('plugin', 'event', 'callfunction'));
        create_table($table);
    }
    if ($oldversion < 2009050700) {
        if ($data = check_upgrades('export.html')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('export.leap')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('import.leap')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009051200) {
        // Rename submittedto column to submittedgroup
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} RENAME submittedto TO submittedgroup");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} DROP FOREIGN KEY {view_sub_fk}");
                execute_sql("ALTER TABLE {view} DROP INDEX {view_sub_ix}");
                execute_sql("ALTER TABLE {view} CHANGE submittedto submittedgroup BIGINT(10) DEFAULT NULL");
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_sub_fk} FOREIGN KEY {view_sub_ix} (submittedgroup) REFERENCES {group}(id)");
            }
        }
        // Add submittedhost column for views submitted to remote moodle hosts
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedhost');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
        // Do this manually because xmldb tries to create a key with the same name (view_sub_vk) as an existing one, and fails.
        if (is_postgres()) {
            execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY (submittedhost) REFERENCES {host}(wwwroot)");
            execute_sql("CREATE INDEX {view_subh_ix} ON {view} (submittedhost)");
        } else {
            if (is_mysql()) {
                execute_sql("ALTER TABLE {view} ADD CONSTRAINT {view_subh_fk} FOREIGN KEY {view_subh_ix} (submittedhost) REFERENCES {host}(wwwroot)");
            }
        }
    }
    if ($oldversion < 2009051201) {
        // Invisible view access keys for roaming moodle teachers
        $table = new XMLDBTable('view_access_token');
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2009052700) {
        // Install a cron job to clean out old exports
        $cron = new StdClass();
        $cron->callfunction = 'export_cleanup_old_exports';
        $cron->minute = '0';
        $cron->hour = '3,13';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009070600) {
        // This was forgotten as part of the 1.0 -> 1.1 upgrade
        if ($data = check_upgrades('blocktype.file/html')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009070700) {
        foreach (array('addfriend', 'removefriend', 'addfriendrequest', 'removefriendrequest') as $eventtype) {
            $event = (object) array('name' => $eventtype);
            ensure_record_exists('event_type', $event, $event);
        }
    }
    if ($oldversion < 2009070900) {
        if (is_mysql()) {
            execute_sql("ALTER TABLE {usr} DROP FOREIGN KEY {usr_las_fk}");
            execute_sql("ALTER TABLE {usr} DROP INDEX {usr_las_ix}");
        }
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('lastauthinstance');
        drop_field($table, $field);
    }
    if ($oldversion < 2009080600) {
        $table = new XMLDBTable('view');
        $index = new XMLDBIndex('view_own_type_uix');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('owner'));
        if (!index_exists($table, $index)) {
            // Delete duplicate profile views if there are any, then add an index
            // that will prevent it happening again - but only on postgres, as it's
            // the only db that supports partial indexes
            if ($viewdata = get_records_sql_array("\n                SELECT owner, id\n                FROM {view}\n                WHERE owner IN (\n                    SELECT owner\n                    FROM {view}\n                    WHERE type = 'profile'\n                    GROUP BY owner\n                    HAVING COUNT(*) > 1\n                )\n                AND type = 'profile'\n                ORDER BY owner, id", array())) {
                require_once 'view.php';
                $seen = array();
                foreach ($viewdata as $record) {
                    $seen[$record->owner][] = $record->id;
                }
                foreach ($seen as $owner => $views) {
                    // Remove the first one, which is their real profile view
                    array_shift($views);
                    foreach ($views as $viewid) {
                        delete_records('artefact_feedback', 'view', $viewid);
                        delete_records('view_feedback', 'view', $viewid);
                        delete_records('view_access', 'view', $viewid);
                        delete_records('view_access_group', 'view', $viewid);
                        delete_records('view_access_usr', 'view', $viewid);
                        delete_records('view_access_token', 'view', $viewid);
                        delete_records('view_autocreate_grouptype', 'view', $viewid);
                        delete_records('view_tag', 'view', $viewid);
                        delete_records('usr_watchlist_view', 'view', $viewid);
                        if ($blockinstanceids = get_column('block_instance', 'id', 'view', $viewid)) {
                            foreach ($blockinstanceids as $id) {
                                if (table_exists('blocktype_wall_post')) {
                                    delete_records('blocktype_wall_post', 'instance', $id);
                                }
                                delete_records('view_artefact', 'block', $id);
                                delete_records('block_instance', 'id', $id);
                            }
                        }
                        delete_records('view', 'id', $viewid);
                    }
                }
            }
            if (is_postgres()) {
                execute_sql("CREATE UNIQUE INDEX {view_own_type_uix} ON {view}(owner) WHERE type = 'profile'");
            }
        }
    }
    if ($oldversion < 2009080601) {
        execute_sql("DELETE FROM {group_member_invite} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'invite')");
        execute_sql("DELETE FROM {group_member_request} WHERE \"group\" NOT IN (SELECT id FROM {group} WHERE jointype = 'request')");
    }
    if ($oldversion < 2009081800) {
        $event = (object) array('name' => 'creategroup');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009082400) {
        $table = new XMLDBTable('usr_registration');
        $field = new XMLDBField('username');
        drop_field($table, $field);
        $field = new XMLDBField('salt');
        drop_field($table, $field);
        $field = new XMLDBField('password');
        drop_field($table, $field);
    }
    if ($oldversion < 2009082600) {
        $captcha = get_config('captcha_on_contact_form');
        set_config('captchaoncontactform', (int) (is_null($captcha) || $captcha));
        $captcha = get_config('captcha_on_register_form');
        set_config('captchaonregisterform', (int) (is_null($captcha) || $captcha));
    }
    if ($oldversion < 2009090700) {
        set_config('showselfsearchsideblock', 1);
        set_config('showtagssideblock', 1);
        set_config('tagssideblockmaxtags', 20);
    }
    if ($oldversion < 2009092100) {
        if ($data = check_upgrades('import.file')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.creativecommons')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2009092900) {
        $event = (object) array('name' => 'deleteartefacts');
        ensure_record_exists('event_type', $event, $event);
    }
    if ($oldversion < 2009101600) {
        // Remove bbcode formatting from existing feedback
        if ($records = get_records_sql_array("SELECT * FROM {view_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('view_feedback', $r);
            }
        }
        if ($records = get_records_sql_array("SELECT * FROM {artefact_feedback} WHERE message LIKE '%[%'", array())) {
            foreach ($records as &$r) {
                if (function_exists('parse_bbcode')) {
                    $r->message = parse_bbcode($r->message);
                }
                update_record('artefact_feedback', $r);
            }
        }
    }
    if ($oldversion < 2009102100) {
        // Now the view_layout table has to have records for all column widths
        $record = (object) array('columns' => 1, 'widths' => '100');
        insert_record('view_layout', $record);
        $record = (object) array('columns' => 5, 'widths' => '20,20,20,20,20');
        insert_record('view_layout', $record);
    }
    if ($oldversion < 2009102200) {
        if (!count_records_select('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'))) {
            insert_record('activity_type', (object) array('name' => 'groupmessage', 'admin' => 0, 'delay' => 0));
        }
    }
    if ($oldversion < 2009102900) {
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('sessionid');
        drop_field($table, $field);
    }
    if ($oldversion < 2009110500) {
        set_config('creategroups', 'all');
    }
    if ($oldversion < 2009110900) {
        // Fix export cronjob so it runs 12 hours apart
        execute_sql("UPDATE {cron} SET hour = '3,15' WHERE callfunction = 'export_cleanup_old_exports'");
        // Cron job to clean old imports
        $cron = new StdClass();
        $cron->callfunction = 'import_cleanup_old_imports';
        $cron->minute = '0';
        $cron->hour = '4,16';
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2009111200) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailssent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009111201) {
        $table = new XMLDBTable('artefact_internal_profile_email');
        $field = new XMLDBField('mailsbounced');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 2, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
    }
    if ($oldversion < 2009120100) {
        // Fix for bug in 1.1 => 1.2 upgrade which may have inserted
        // a second groupmessage activity_type record
        $records = get_records_select_array('activity_type', 'name = ? AND plugintype IS NULL AND pluginname IS NULL', array('groupmessage'), 'id');
        if ($records && count($records) > 1) {
            for ($i = 1; $i < count($records); $i++) {
                delete_records('activity_queue', 'type', $records[$i]->id);
                delete_records('notification_internal_activity', 'type', $records[$i]->id);
                delete_records('notification_emaildigest_queue', 'type', $records[$i]->id);
                delete_records('usr_activity_preference', 'activity', $records[$i]->id);
                delete_records('activity_type', 'id', $records[$i]->id);
            }
        }
    }
    if ($oldversion < 2009120900) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010011300) {
        // Clean up the mess left behind by failing to delete blogposts in a transaction
        try {
            include_once get_config('docroot') . 'artefact/lib.php';
            if (function_exists('rebuild_artefact_parent_cache_dirty')) {
                rebuild_artefact_parent_cache_dirty();
            }
        } catch (Exception $e) {
            log_debug('Upgrade 2010011300: rebuild_artefact_parent_cache_dirty failed.');
        }
        execute_sql("\n            INSERT INTO {artefact_blog_blogpost} (blogpost)\n            SELECT id FROM {artefact} WHERE artefacttype = 'blogpost' AND id NOT IN (\n                SELECT blogpost FROM {artefact_blog_blogpost}\n            )");
    }
    if ($oldversion < 2010012700) {
        set_config('viewmicroheaders', 1);
    }
    if ($oldversion < 2010012701) {
        set_config('userscanchooseviewthemes', 1);
    }
    if ($oldversion < 2010021500) {
        if ($data = check_upgrades('blocktype.recentforumposts')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010021600) {
        // Set remoteavatars defaults
        // Check if the site is using https
        $urlprotocol = substr(get_config('wwwroot'), 0, 5);
        if (strtolower($urlprotocol) == 'https') {
            // Avoid mix of secure and insecure contents
            set_config('remoteavatars', 0);
        } else {
            // Check to see if we can reach gravatar.com
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_FAILONERROR, true);
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_VERBOSE, false);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            // timeout in seconds
            curl_setopt($ch, CURLOPT_COOKIE, '');
            curl_setopt($ch, CURLOPT_REFERER, '');
            // for privacy
            curl_setopt($ch, CURLOPT_URL, 'http://www.gravatar.com/');
            if (curl_exec($ch)) {
                // By default, turn it on
                set_config('remoteavatars', 1);
            } else {
                // Can't reach gravatar.com in a timely fashion
                set_config('remoteavatars', 0);
            }
            curl_close($ch);
        }
    }
    if ($oldversion < 2010031000) {
        // For existing sites, preserve current user search behaviour:
        // Users are only searchable by their display names.
        set_config('userscanhiderealnames', 1);
        execute_sql("\n            INSERT INTO {usr_account_preference} (usr, field, value)\n            SELECT u.id, 'hiderealname', 1\n            FROM {usr} u LEFT JOIN {usr_account_preference} p ON (u.id = p.usr AND p.field = 'hiderealname')\n            WHERE NOT u.preferredname IS NULL AND u.preferredname != '' AND p.field IS NULL\n        ");
    }
    if ($oldversion < 2010040700) {
        // Set antispam defaults
        set_config('formsecret', get_random_key());
        if (!function_exists('checkdnsrr')) {
            require_once get_config('docroot') . 'lib/antispam.php';
        }
        if (checkdnsrr('test.uribl.com.black.uribl.com', 'A')) {
            set_config('antispam', 'advanced');
        } else {
            set_config('antispam', 'simple');
        }
        set_config('spamhaus', 0);
        set_config('surbl', 0);
    }
    if ($oldversion < 2010040800) {
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
    }
    if ($oldversion < 2010041200) {
        delete_records('config', 'field', 'captchaoncontactform');
        delete_records('config', 'field', 'captchaonregisterform');
    }
    if ($oldversion < 2010041201) {
        $sql = "\n            SELECT u.id\n            FROM {usr} u\n            LEFT JOIN {artefact} a\n                ON (a.owner = u.id AND a.artefacttype = 'blog')\n            WHERE u.id > 0\n            GROUP BY u.id\n            HAVING COUNT(a.id) != 1";
        $manyblogusers = get_records_sql_array($sql, null);
        if ($manyblogusers) {
            foreach ($manyblogusers as $u) {
                $where = (object) array('usr' => $u->id, 'field' => 'multipleblogs');
                $data = (object) array('usr' => $u->id, 'field' => 'multipleblogs', 'value' => 1);
                ensure_record_exists('usr_account_preference', $where, $data);
            }
        }
    }
    if ($oldversion < 2010041600 && table_exists(new XMLDBTable('view_feedback'))) {
        // Add author, authorname to artefact table
        $table = new XMLDBTable('artefact');
        $field = new XMLDBField('author');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('authorfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('author'), 'usr', array('id'));
        add_key($table, $key);
        table_column('artefact', null, 'authorname', 'text', null, null, null, '');
        if (is_postgres()) {
            execute_sql("ALTER TABLE {artefact} ALTER COLUMN authorname DROP DEFAULT");
            set_field('artefact', 'authorname', null);
            execute_sql('UPDATE {artefact} SET authorname = g.name FROM {group} g WHERE "group" = g.id');
            execute_sql("UPDATE {artefact} SET authorname = CASE WHEN institution = 'mahara' THEN ? ELSE i.displayname END FROM {institution} i WHERE institution = i.name", array(get_config('sitename')));
        } else {
            execute_sql("UPDATE {artefact} a, {group} g SET a.authorname = g.name WHERE a.group = g.id");
            execute_sql("UPDATE {artefact} a, {institution} i SET a.authorname = CASE WHEN a.institution = 'mahara' THEN ? ELSE i.displayname END WHERE a.institution = i.name", array(get_config('sitename')));
        }
        execute_sql('UPDATE {artefact} SET author = owner WHERE owner IS NOT NULL');
        execute_sql('ALTER TABLE {artefact} ADD CHECK (
            (author IS NOT NULL AND authorname IS NULL    ) OR
            (author IS NULL     AND authorname IS NOT NULL)
        )');
        // Move feedback activity type to artefact plugin
        execute_sql("\n            UPDATE {activity_type}\n            SET plugintype = 'artefact', pluginname = 'comment'\n            WHERE name = 'feedback'\n        ");
        // Install the comment artefact
        if ($data = check_upgrades('artefact.comment')) {
            upgrade_plugin($data);
        }
        // Flag all views & artefacts to enable/disable comments
        table_column('artefact', null, 'allowcomments', 'integer', 1);
        table_column('view', null, 'allowcomments', 'integer', 1, null, 1);
        // Initially allow comments on blogposts, images, files
        set_field_select('artefact', 'allowcomments', 1, 'artefacttype IN (?,?,?)', array('blogpost', 'image', 'file'));
        // Convert old feedback to comment artefacts
        if ($viewfeedback = get_records_sql_array('
            SELECT f.*, v.id AS viewid, v.owner, v.group, v.institution
            FROM {view_feedback} f JOIN {view} v ON f.view = v.id', array())) {
            foreach ($viewfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onview' => $f->viewid);
                insert_record('artefact_comment_comment', $comment);
                if (!empty($f->attachment)) {
                    insert_record('artefact_attachment', (object) array('artefact' => $aid, 'attachment' => $f->attachment));
                }
            }
        }
        // We are throwing away the view information from artefact_feedback.
        // From now on all artefact comments appear together and are not
        // tied to a particular view.
        if ($artefactfeedback = get_records_sql_array('
            SELECT f.*, a.id AS artefactid, a.owner, a.group, a.institution
            FROM {artefact_feedback} f JOIN {artefact} a ON f.artefact = a.id', array())) {
            foreach ($artefactfeedback as &$f) {
                if ($f->author > 0) {
                    $f->authorname = null;
                } else {
                    $f->author = null;
                    if (empty($f->authorname)) {
                        $f->authorname = '?';
                    }
                }
                $artefact = (object) array('artefacttype' => 'comment', 'owner' => $f->owner, 'group' => $f->group, 'institution' => $f->institution, 'author' => $f->author, 'authorname' => $f->authorname, 'title' => get_string('Comment', 'artefact.comment'), 'description' => $f->message, 'ctime' => $f->ctime, 'atime' => $f->ctime, 'mtime' => $f->ctime);
                $aid = insert_record('artefact', $artefact, 'id', true);
                $comment = (object) array('artefact' => $aid, 'private' => 1 - $f->public, 'onartefact' => $f->artefactid);
                insert_record('artefact_comment_comment', $comment);
            }
        }
        // Drop feedback tables
        $table = new XMLDBTable('view_feedback');
        drop_table($table);
        $table = new XMLDBTable('artefact_feedback');
        drop_table($table);
        // Add site setting for anonymous comments
        set_config('anonymouscomments', 1);
    }
    if ($oldversion < 2010041900 && !table_exists(new XMLDBTable('site_data'))) {
        // Upgrades for admin stats pages
        // Table for collection of historical stats
        $table = new XMLDBTable('site_data');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, XMLDB_NOTNULL);
        $table->addFieldInfo('type', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('ctime', 'type'));
        create_table($table);
        // Insert cron jobs to save site data
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_weekly';
        $cron->minute = 55;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = 6;
        insert_record('cron', $cron);
        $cron = new StdClass();
        $cron->callfunction = 'cron_site_data_daily';
        $cron->minute = 51;
        $cron->hour = 23;
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
        // Put best guess at installation time into config table.
        set_config('installation_time', get_field_sql("SELECT MIN(ctime) FROM {site_content}"));
        // Save the current time so we know when we started collecting stats
        set_config('stats_installation_time', db_format_timestamp(time()));
        // Add ctime to usr table for daily count of users created
        $table = new XMLDBTable('usr');
        $field = new XMLDBField('ctime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        add_field($table, $field);
        // Add visits column to view table
        $table = new XMLDBTable('view');
        $field = new XMLDBField('visits');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        // Add table to store daily view visits
        $table = new XMLDBTable('view_visit');
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addIndexInfo('ctimeix', XMLDB_INDEX_NOTUNIQUE, array('ctime'));
        create_table($table);
        // Insert a cron job to check for new versions of Mahara
        $cron = new StdClass();
        $cron->callfunction = 'cron_check_for_updates';
        $cron->minute = rand(0, 59);
        $cron->hour = rand(0, 23);
        $cron->day = '*';
        $cron->month = '*';
        $cron->dayofweek = '*';
        insert_record('cron', $cron);
    }
    if ($oldversion < 2010042600) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('parent');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('parentfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('parent'), 'notification_internal_activity', array('id'));
        add_key($table, $key);
        $field = new XMLDBField('from');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10');
        add_field($table, $field);
        $key = new XMLDBKey('fromfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('from'), 'usr', array('id'));
        add_key($table, $key);
        // Set from column for old user messages
        $usermessages = get_records_array('notification_internal_activity', 'type', get_field('activity_type', 'id', 'name', 'usermessage'));
        if ($usermessages) {
            foreach ($usermessages as &$m) {
                if (preg_match('/sendmessage\\.php\\?id=(\\d+)/', $m->url, $match)) {
                    set_field('notification_internal_activity', 'from', $match[1], 'id', $m->id);
                }
            }
        }
    }
    if ($oldversion < 2010042602 && !get_record('view_type', 'type', 'dashboard')) {
        insert_record('view_type', (object) array('type' => 'dashboard'));
        if ($data = check_upgrades('blocktype.inbox')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.newviews')) {
            upgrade_plugin($data);
        }
        // Install system dashboard view
        require_once get_config('libroot') . 'view.php';
        $dbtime = db_format_timestamp(time());
        $viewdata = (object) array('type' => 'dashboard', 'owner' => 0, 'numcolumns' => 2, 'ownerformat' => FORMAT_NAME_PREFERREDNAME, 'title' => get_string('dashboardviewtitle', 'view'), 'template' => 1, 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'newviews', 'title' => get_string('title', 'blocktype.newviews'), 'column' => 1, 'config' => array('limit' => 5)), array('blocktype' => 'myviews', 'title' => get_string('title', 'blocktype.myviews'), 'column' => 1, 'config' => null), array('blocktype' => 'inbox', 'title' => get_string('recentactivity'), 'column' => 2, 'config' => array('feedback' => true, 'groupmessage' => true, 'institutionmessage' => true, 'maharamessage' => true, 'usermessage' => true, 'viewaccess' => true, 'watchlist' => true, 'maxitems' => '5')), array('blocktype' => 'inbox', 'title' => get_string('topicsimfollowing'), 'column' => 2, 'config' => array('newpost' => true, 'maxitems' => '5')));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        $weights = array(1 => 0, 2 => 0);
        foreach ($blocktypes as $blocktype) {
            if (in_array($blocktype['blocktype'], $installed)) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010042603) {
        execute_sql('ALTER TABLE {usr} ADD COLUMN showhomeinfo SMALLINT NOT NULL DEFAULT 1');
        set_config('homepageinfo', 1);
    }
    if ($oldversion < 2010042604) {
        // @todo: Move to notification/internal
        $table = new XMLDBTable('notification_internal_activity');
        $field = new XMLDBField('urltext');
        $field->setAttributes(XMLDB_TYPE_TEXT);
        add_field($table, $field);
    }
    if ($oldversion < 2010051000) {
        set_field('activity_type', 'delay', 1, 'name', 'groupmessage');
    }
    if ($oldversion < 2010052000) {
        $showusers = get_config('showonlineuserssideblock');
        set_config('showonlineuserssideblock', (int) (is_null($showusers) || $showusers));
    }
    if ($oldversion < 2010060300) {
        // Add table to associate users with php session ids
        $table = new XMLDBTable('usr_session');
        $table->addFieldInfo('usr', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('session', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('session'));
        $table->addIndexInfo('usrix', XMLDB_INDEX_NOTUNIQUE, array('usr'));
        create_table($table);
    }
    if ($oldversion < 2010061100) {
        set_config('registerterms', 1);
    }
    if ($oldversion < 2010061800) {
        insert_record('view_type', (object) array('type' => 'grouphomepage'));
        if ($data = check_upgrades('blocktype.groupmembers')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupinfo')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.groupviews')) {
            upgrade_plugin($data);
        }
        $dbtime = db_format_timestamp(time());
        // create a system template for group homepage views
        require_once get_config('libroot') . 'view.php';
        $viewdata = (object) array('type' => 'grouphomepage', 'owner' => 0, 'numcolumns' => 1, 'template' => 1, 'title' => get_string('grouphomepage', 'view'), 'ctime' => $dbtime, 'atime' => $dbtime, 'mtime' => $dbtime);
        $id = insert_record('view', $viewdata, 'id', true);
        $accessdata = (object) array('view' => $id, 'accesstype' => 'loggedin');
        insert_record('view_access', $accessdata);
        $blocktypes = array(array('blocktype' => 'groupinfo', 'title' => '', 'column' => 1, 'config' => null), array('blocktype' => 'recentforumposts', 'title' => get_string('latestforumposts', 'interaction.forum'), 'column' => 1, 'config' => null), array('blocktype' => 'groupviews', 'title' => get_string('Views', 'view'), 'column' => 1, 'config' => null), array('blocktype' => 'groupmembers', 'title' => get_string('Members', 'group'), 'column' => 1, 'config' => null));
        $installed = get_column_sql('SELECT name FROM {blocktype_installed}');
        foreach ($blocktypes as $k => $blocktype) {
            if (!in_array($blocktype['blocktype'], $installed)) {
                unset($blocktypes[$k]);
            }
        }
        $weights = array(1 => 0);
        foreach ($blocktypes as $blocktype) {
            $weights[$blocktype['column']]++;
            insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
        }
        // add a default group homepage view for all groups in the system
        unset($viewdata->owner);
        $viewdata->template = 0;
        if (!($groups = get_records_array('group', '', '', '', 'id,public'))) {
            $groups = array();
        }
        foreach ($groups as $group) {
            $viewdata->group = $group->id;
            $id = insert_record('view', $viewdata, 'id', true);
            insert_record('view_access', (object) array('view' => $id, 'accesstype' => $group->public ? 'public' : 'loggedin'));
            insert_record('view_access_group', (object) array('view' => $id, 'group' => $group->id));
            $weights = array(1 => 0);
            foreach ($blocktypes as $blocktype) {
                $weights[$blocktype['column']]++;
                insert_record('block_instance', (object) array('blocktype' => $blocktype['blocktype'], 'title' => $blocktype['title'], 'view' => $id, 'column' => $blocktype['column'], 'order' => $weights[$blocktype['column']], 'configdata' => serialize($blocktype['config'])));
            }
        }
    }
    if ($oldversion < 2010062502) {
        //new feature feedback control on views
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('allowcomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        add_field($table, $field);
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Add comment approval to view/artefact (default 0)
        $field = new XMLDBField('approvecomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 0);
        $table = new XMLDBTable('view');
        add_field($table, $field);
        $table = new XMLDBTable('artefact');
        add_field($table, $field);
        // view_access_(group|usr|token) tables are getting wide with duplicated columns,
        // so just create all the necessary columns in view_access and move stuff there
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null);
        change_field_notnull($table, $field);
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('role');
        $field->setAttributes(XMLDB_TYPE_CHAR, 255, null, null);
        add_field($table, $field);
        $field = new XMLDBField('usr');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10, null, null);
        add_field($table, $field);
        $field = new XMLDBField('token');
        $field->setAttributes(XMLDB_TYPE_CHAR, 100, null, null);
        add_field($table, $field);
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
        // Copy data to view_access
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, "group", role, startdate, stopdate)
            SELECT view, NULL, "group", role, startdate, stopdate FROM {view_access_group}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, usr, startdate, stopdate)
            SELECT view, NULL, usr, startdate, stopdate FROM {view_access_usr}');
        execute_sql('
            INSERT INTO {view_access} (view, accesstype, token, visible, startdate, stopdate)
            SELECT view, NULL, token, visible, startdate, stopdate FROM {view_access_token}');
        // Add foreign keys
        $key = new XMLDBKey('groupfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('group'), 'group', array('id'));
        add_key($table, $key);
        $key = new XMLDBKey('usrfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usr'), 'usr', array('id'));
        add_key($table, $key);
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        add_index($table, $index);
        // Exactly one of accesstype, group, usr, token must be not null
        execute_sql('ALTER TABLE {view_access} ADD CHECK (
            (accesstype IS NOT NULL AND "group" IS NULL     AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NOT NULL AND usr IS NULL     AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NOT NULL AND token IS NULL) OR
            (accesstype IS NULL     AND "group" IS NULL     AND usr IS NULL     AND token IS NOT NULL)
        )');
        // Drop old tables
        $table = new XMLDBTable('view_access_group');
        drop_table($table);
        $table = new XMLDBTable('view_access_usr');
        drop_table($table);
        $table = new XMLDBTable('view_access_token');
        drop_table($table);
        // Insert explicit tutor access records for submitted views
        if (!($submittedviews = get_records_sql_array('
            SELECT v.id, v.submittedgroup, g.grouptype
            FROM {view} v JOIN {group} g ON (v.submittedgroup = g.id AND g.deleted = 0)', array()))) {
            $submittedviews = array();
        }
        $roles = array();
        foreach ($submittedviews as $v) {
            if (!isset($roles[$v->grouptype])) {
                $rs = get_column('grouptype_roles', 'role', 'grouptype', $v->grouptype, 'see_submitted_views', 1);
                $roles[$v->grouptype] = empty($rs) ? array() : $rs;
            }
            foreach ($roles[$v->grouptype] as $role) {
                $accessrecord = (object) array('view' => $v->id, 'group' => $v->submittedgroup, 'role' => $role, 'visible' => 0, 'allowcomments' => 1, 'approvecomments' => 0);
                ensure_record_exists('view_access', $accessrecord, $accessrecord);
            }
        }
    }
    if ($oldversion < 2010070700) {
        $table = new XMLDBTable('group_category');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, 255, null, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        create_table($table);
        $table = new XMLDBTable('group');
        $field = new XMLDBField('category');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 10);
        add_field($table, $field);
        $key = new XMLDBKey('categoryfk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('category'), 'group_category', array('id'));
        add_key($table, $key);
    }
    if ($oldversion < 2010071300) {
        set_config('searchusernames', 1);
    }
    if ($oldversion < 2010071500) {
        reload_html_filters();
    }
    if ($oldversion < 2010071600) {
        if (is_postgres()) {
            // change_field_enum should do this
            execute_sql('ALTER TABLE {view_access} DROP CONSTRAINT {viewacce_acc_ck}');
        }
        $table = new XMLDBTable('view_access');
        $field = new XMLDBField('accesstype');
        $field->setAttributes(XMLDB_TYPE_CHAR, 16, null, null, null, XMLDB_ENUM, array('public', 'loggedin', 'friends', 'objectionable'));
        change_field_enum($table, $field);
    }
    if ($oldversion < 2010071900) {
        $table = new XMLDBTable('group');
        $field = new XMLDBField('viewnotify');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        add_field($table, $field);
    }
    if ($oldversion < 2010081000) {
        // new table collection
        $table = new XMLDBTable('collection');
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, 255, XMLDB_UNSIGNED, XMLDB_NOTNULL);
        $table->addFieldInfo('owner', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addFieldInfo('ctime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('mtime', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, null);
        $table->addFieldInfo('navigation', XMLDB_TYPE_INTEGER, 1, null, XMLDB_NOTNULL, null, null, null, 1);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('usrfk', XMLDB_KEY_FOREIGN, array('owner'), 'usr', array('id'));
        create_table($table);
        // new table collection_view
        $table = new XMLDBTable('collection_view');
        $table->addFieldInfo('view', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('collection', XMLDB_TYPE_INTEGER, 10, false, XMLDB_NOTNULL);
        $table->addFieldInfo('displayorder', XMLDB_TYPE_INTEGER, 10, null, XMLDB_NOTNULL);
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('view'));
        $table->addKeyInfo('viewfk', XMLDB_KEY_FOREIGN, array('view'), 'view', array('id'));
        $table->addKeyInfo('collectionfk', XMLDB_KEY_FOREIGN, array('collection'), 'collection', array('id'));
        create_table($table);
        // Drop unique constraint on token column of view_access
        $table = new XMLDBTable('view_access');
        $index = new XMLDBIndex('tokenuk');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('token'));
        drop_index($table, $index);
        $index = new XMLDBIndex('tokenix');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('token'));
        add_index($table, $index);
    }
    if ($oldversion < 2010081001) {
        if ($data = check_upgrades('artefact.plans')) {
            upgrade_plugin($data);
        }
        if ($data = check_upgrades('blocktype.plans/plans')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010081100) {
        if ($data = check_upgrades('blocktype.navigation')) {
            upgrade_plugin($data);
        }
    }
    if ($oldversion < 2010082000) {
        delete_records_select('config', "field IN ('usersrank', 'groupsrank', 'viewsrank')");
    }
    if ($oldversion < 2010091300) {
        // Cron job missing from installs post 2010041900
        if (!record_exists('cron', 'callfunction', 'cron_check_for_updates')) {
            $cron = new StdClass();
            $cron->callfunction = 'cron_check_for_updates';
            $cron->minute = rand(0, 59);
            $cron->hour = rand(0, 23);
            $cron->day = '*';
            $cron->month = '*';
            $cron->dayofweek = '*';
            insert_record('cron', $cron);
        }
    }
    if ($oldversion < 2010091500) {
        // Previous version of 2010040800 upgrade created the submittedtime
        // column not null (see bug #638550)
        $table = new XMLDBTable('view');
        $field = new XMLDBField('submittedtime');
        $field->setAttributes(XMLDB_TYPE_DATETIME, null, null);
        change_field_notnull($table, $field);
        // Our crappy db is full of redundant data (submittedtime depends on
        // submittedhost or submittedgroup) so it's easy to correct this.
        execute_sql("\n            UPDATE {view} SET submittedtime = NULL\n            WHERE submittedtime IS NOT NULL AND submittedgroup IS NULL AND submittedhost IS NULL");
    }
    return $status;
}
コード例 #21
0
/**
 * This function will rename the field in the table passed as arguments
 * Before renaming the field, the function will check it exists
 *
 * @uses $CFG, $db
 * @param XMLDBTable table object (just the name is mandatory)
 * @param XMLDBField index object (full specs are required)
 * @param string new name of the field
 * @param boolean continue to specify if must continue on error (true) or stop (false)
 * @param boolean feedback to specify to show status info (true) or not (false)
 * @return boolean true on success, false on error
 */
function rename_field($table, $field, $newname, $continue = true, $feedback = true)
{
    global $CFG, $db;
    $status = true;
    if (strtolower(get_class($table)) != 'xmldbtable') {
        return false;
    }
    if (strtolower(get_class($field)) != 'xmldbfield') {
        return false;
    }
    /// Check we have included full field specs
    if (!$field->getType()) {
        debugging('Field ' . $table->getName() . '->' . $field->getName() . ' must contain full specs. Rename skipped', DEBUG_DEVELOPER);
        return false;
    }
    /// Check field isn't id. Renaming over that field is not allowed
    if ($field->getName() == 'id') {
        debugging('Field ' . $table->getName() . '->' . $field->getName() . ' cannot be renamed. Rename skipped', DEBUG_DEVELOPER);
        return true;
        //Field is "id", nothing to do
    }
    /// Check field exists
    if (!field_exists($table, $field)) {
        debugging('Field ' . $table->getName() . '->' . $field->getName() . ' does not exist. Rename skipped', DEBUG_DEVELOPER);
        return true;
        //Field doesn't exist, nothing to do
    }
    /// Check newname isn't empty
    if (!$newname) {
        debugging('New name for field ' . $table->getName() . '->' . $field->getName() . ' is empty! Rename skipped', DEBUG_DEVELOPER);
        return true;
        //Field doesn't exist, nothing to do
    }
    if (!($sqlarr = $table->getRenameFieldSQL($CFG->dbtype, $CFG->prefix, $field, $newname, false))) {
        return true;
        //Empty array = nothing to do = no error
    }
    return execute_sql_arr($sqlarr, $continue, $feedback);
}
コード例 #22
0
ファイル: upgrade.php プロジェクト: laiello/poodll
function xmldb_poodllflashcard_upgrade($oldversion = 0)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    $result = true;
    // this should patch the question_match anyway
    $table = new XMLDBTable('question_match');
    $field = new XMLDBField('numquestions');
    $field->setAttributes(XMLDB_TYPE_INTEGER, '10', 'true', 'true', null, null, null, '0');
    if (!field_exists($table, $field)) {
        add_field($table, $field, true, true);
    }
    if ($oldversion < 2008050400) {
        /// Define field starttime to be added to poodllflashcard
        $table = new XMLDBTable('poodllflashcard');
        /// Launch add field starttime
        $field = new XMLDBField('starttime');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, null, 'timemodified');
        $result = $result && add_field($table, $field);
        /// Launch add field endtime
        $field = new XMLDBField('endtime');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, null, 'starttime');
        $result = $result && add_field($table, $field);
        /// Launch add field autodowngrade
        $field = new XMLDBField('autodowngrade');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 1, 'questionid');
        $result = $result && add_field($table, $field);
        /// Launch add field deck2_release
        $field = new XMLDBField('deck2_release');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 96, 'autodowngrade');
        $result = $result && add_field($table, $field);
        /// Launch add field deck3_release
        $field = new XMLDBField('deck3_release');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 96, 'deck2_release');
        $result = $result && add_field($table, $field);
        /// Launch add field deck1_delay
        $field = new XMLDBField('deck1_delay');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 48, 'deck3_release');
        $result = $result && add_field($table, $field);
        /// Launch add field deck2_delay
        $field = new XMLDBField('deck2_delay');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 96, 'deck1_delay');
        $result = $result && add_field($table, $field);
        /// Launch add field deck3_delay
        $field = new XMLDBField('deck3_delay');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 168, 'deck2_delay');
        $result = $result && add_field($table, $field);
        /// Define table poodllflashcard_card to be created
        $table = new XMLDBTable('poodllflashcard_card');
        /// Adding fields to table poodllflashcard_card
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flashcardid', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('entryid', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('deck', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('lastaccessed', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0');
        /// Adding keys to table poodllflashcard_card
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for poodllflashcard_card
        $result = $result && create_table($table);
    }
    if ($oldversion < 2008050500) {
        /// Define field starttime to be added to poodllflashcard
        $table = new XMLDBTable('poodllflashcard');
        /// Launch add field deck4_release
        $field = new XMLDBField('deck4_release');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 96, 'deck3_release');
        $result = $result && add_field($table, $field);
        /// Launch add field deck4_delay
        $field = new XMLDBField('deck4_delay');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 336, 'deck3_delay');
        $result = $result && add_field($table, $field);
        /// Launch add field questionsasimages
        $field = new XMLDBField('questionsasimages');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'deck4_delay');
        $result = $result && add_field($table, $field);
        /// Launch add field answersasimages
        $field = new XMLDBField('answersasimages');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'questionsasimages');
        $result = $result && add_field($table, $field);
    }
    if ($oldversion < 2008050501) {
        /// Define field starttime to be added to poodllflashcard
        $table = new XMLDBTable('poodllflashcard');
        /// Launch add field decks
        $field = new XMLDBField('decks');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '3', 'autodowngrade');
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008050800) {
        /// Define table poodllflashcard_deckdata to be created
        $table = new XMLDBTable('poodllflashcard_deckdata');
        /// Adding fields to table poodllflashcard_deckdata
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flashcardid', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('questiontext', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('answertext', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table poodllflashcard_deckdata
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for poodllflashcard_deckdata
        $result = $result && create_table($table);
    }
    if ($result && $oldversion < 2008050900) {
        /// Define field accesscount to be added to poodllflashcard_card
        $table = new XMLDBTable('poodllflashcard_card');
        $field = new XMLDBField('accesscount');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'lastaccessed');
        /// Launch add field accesscount
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008051100) {
        /// Rename field questionsasimages on table poodllflashcard to questionsmediatype
        $table = new XMLDBTable('poodllflashcard');
        $field = new XMLDBField('questionsasimages');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'deck4_delay');
        /// Launch rename field questionsmediatype
        $result = $result && rename_field($table, $field, 'questionsmediatype');
        /// Rename field answersasimages on table poodllflashcard to answersmediatype
        $table = new XMLDBTable('poodllflashcard');
        $field = new XMLDBField('answersasimages');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'deck4_delay');
        /// Launch rename field questionsmediatype
        $result = $result && rename_field($table, $field, 'answersmediatype');
        /// Define field flipdeck to be added to poodllflashcard
        $table = new XMLDBTable('poodllflashcard');
        $field = new XMLDBField('flipdeck');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, '0', 'answersmediatype');
        $result = $result && add_field($table, $field);
    }
    return $result;
}
コード例 #23
0
ファイル: upgrade.php プロジェクト: nadavkav/MoodleTAO
function xmldb_main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $USER, $SITE, $db;
    $result = true;
    if ($result && $oldversion < 2006100401) {
        /// Only for those tracking Moodle 1.7 dev, others will have these dropped in moodle_install_roles()
        if (!empty($CFG->rolesactive)) {
            drop_table(new XMLDBTable('user_students'));
            drop_table(new XMLDBTable('user_teachers'));
            drop_table(new XMLDBTable('user_coursecreators'));
            drop_table(new XMLDBTable('user_admins'));
        }
        upgrade_main_savepoint($result, 2006100401);
    }
    if ($result && $oldversion < 2006100601) {
        /// Disable the exercise module because it's unmaintained
        if ($module = get_record('modules', 'name', 'exercise')) {
            if ($module->visible) {
                // Hide/disable the module entry
                set_field('modules', 'visible', '0', 'id', $module->id);
                // Save existing visible state for all activities
                set_field('course_modules', 'visibleold', '1', 'visible', '1', 'module', $module->id);
                set_field('course_modules', 'visibleold', '0', 'visible', '0', 'module', $module->id);
                // Hide all activities
                set_field('course_modules', 'visible', '0', 'module', $module->id);
                //require_once($CFG->dirroot.'/course/lib.php');
                //rebuild_course_cache();  // Rebuld cache for all modules because they might have changed
            }
        }
        upgrade_main_savepoint($result, 2006100601);
    }
    if ($result && $oldversion < 2006101001) {
        /// Disable the LAMS module by default (if it is installed)
        if (count_records('modules', 'name', 'lams') && !count_records('lams')) {
            set_field('modules', 'visible', 0, 'name', 'lams');
            // Disable it by default
        }
        upgrade_main_savepoint($result, 2006101001);
    }
    if ($result && $oldversion < 2006102600) {
        /// Define fields to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('description');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'categoryid');
        $field1 = new XMLDBField('param1');
        $field1->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'defaultdata');
        $field2 = new XMLDBField('param2');
        $field2->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param1');
        $field3 = new XMLDBField('param3');
        $field3->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param2');
        $field4 = new XMLDBField('param4');
        $field4->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param3');
        $field5 = new XMLDBField('param5');
        $field5->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param4');
        /// Launch add fields
        $result = $result && add_field($table, $field);
        $result = $result && add_field($table, $field1);
        $result = $result && add_field($table, $field2);
        $result = $result && add_field($table, $field3);
        $result = $result && add_field($table, $field4);
        $result = $result && add_field($table, $field5);
        upgrade_main_savepoint($result, 2006102600);
    }
    if ($result && $oldversion < 2006112000) {
        /// Define field attachment to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('attachment');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'format');
        /// Launch add field attachment
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112000);
    }
    if ($result && $oldversion < 2006112200) {
        /// Define field imagealt to be added to user
        $table = new XMLDBTable('user');
        $field = new XMLDBField('imagealt');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'trustbitmask');
        /// Launch add field imagealt
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('user');
        $field = new XMLDBField('screenreader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'imagealt');
        /// Launch add field screenreader
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112200);
    }
    if ($result && $oldversion < 2006120300) {
        /// Delete guest course section settings
        // following code can be executed repeatedly, such as when upgrading from 1.7.x - it is ok
        if ($guest = get_record('user', 'username', 'guest')) {
            execute_sql("DELETE FROM {$CFG->prefix}course_display where userid={$guest->id}", true);
        }
        upgrade_main_savepoint($result, 2006120300);
    }
    if ($result && $oldversion < 2006120400) {
        /// Remove secureforms config setting
        execute_sql("DELETE FROM {$CFG->prefix}config where name='secureforms'", true);
        upgrade_main_savepoint($result, 2006120400);
    }
    if (!empty($CFG->rolesactive) && $oldversion < 2006120700) {
        // add moodle/user:viewdetails to all roles!
        // note: use of assign_capability() is discouraged in upgrade script!
        if ($roles = get_records('role')) {
            $context = get_context_instance(CONTEXT_SYSTEM);
            foreach ($roles as $roleid => $role) {
                assign_capability('moodle/user:viewdetails', CAP_ALLOW, $roleid, $context->id);
            }
        }
        upgrade_main_savepoint($result, 2006120700);
    }
    // Move the auth plugin settings into the config_plugin table
    if ($result && $oldversion < 2007010300) {
        if ($CFG->auth == 'email') {
            set_config('registerauth', 'email');
        } else {
            set_config('registerauth', '');
        }
        $authplugins = get_list_of_plugins('auth');
        foreach ($CFG as $k => $v) {
            if (strpos($k, 'ldap_') === 0) {
                //upgrade nonstandard ldap settings
                $setting = substr($k, 5);
                if (set_config($setting, $v, "auth/ldap")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                continue;
            }
            if (strpos($k, 'auth_') !== 0) {
                continue;
            }
            $authsetting = substr($k, 5);
            foreach ($authplugins as $auth) {
                if (strpos($authsetting, $auth) !== 0) {
                    continue;
                }
                $setting = substr($authsetting, strlen($auth));
                if (set_config($setting, $v, "auth/{$auth}")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                break;
                // don't check the rest of the auth plugin names
            }
        }
        upgrade_main_savepoint($result, 2007010300);
    }
    if ($result && $oldversion < 2007010301) {
        //
        // Core MNET tables
        //
        $table = new XMLDBTable('mnet_host');
        $table->comment = 'Information about the local and remote hosts for RPC';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f->comment = 'Unique Host ID';
        $f = $table->addFieldInfo('deleted', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('wwwroot', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('ip_address', XMLDB_TYPE_CHAR, '39', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key_expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('transport', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('portno', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_connect_time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_log_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_host2service');
        $table->comment = 'Information about the services for a given host';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('publish', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('subscribe', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_serviceid', XMLDB_INDEX_UNIQUE, array('hostid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_log');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('ip', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('coursename', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('module', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('host_user_course', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'userid', 'course'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_rpc');
        $table->comment = 'Functions or methods that we may publish or subscribe to';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('function_name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_path', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent_type', XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enabled', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('help', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('profile', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('enabled_xpath', XMLDB_INDEX_NOTUNIQUE, array('enabled', 'xmlrpc_path'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service');
        $table->comment = 'A service is a group of functions';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('description', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('apiversion', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('offer', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service2rpc');
        $table->comment = 'Group functions or methods under a service';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rpcid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('unique', XMLDB_INDEX_UNIQUE, array('rpcid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        //
        // Prime MNET configuration entries -- will be needed later by auth/mnet
        //
        include_once $CFG->dirroot . '/mnet/lib.php';
        $env = new mnet_environment();
        $env->init();
        unset($env);
        // add mnethostid to user-
        $table = new XMLDBTable('user');
        $field = new XMLDBField('mnethostid');
        $field->setType(XMLDB_TYPE_INTEGER);
        $field->setLength(10);
        $field->setNotNull(true);
        $field->setSequence(null);
        $field->setEnum(null);
        $field->setDefault('0');
        $field->setPrevious("deleted");
        $field->setNext("username");
        $result = $result && add_field($table, $field);
        // The default mnethostid is zero... we need to update this for all
        // users of the local IdP service.
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'mnethostid', '0');
        $index = new XMLDBIndex('username');
        $index->setUnique(true);
        $index->setFields(array('username'));
        drop_index($table, $index);
        $index->setFields(array('mnethostid', 'username'));
        if (!add_index($table, $index)) {
            notify(get_string('duplicate_usernames', 'mnet', 'http://docs.moodle.org/en/DuplicateUsernames'));
        }
        unset($table, $field, $index);
        /**
         ** auth/mnet tables
         **/
        $table = new XMLDBTable('mnet_session');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('useragent', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('confirm_timeout', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('session_id', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('token', XMLDB_INDEX_UNIQUE, array('token'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_sso_access_control');
        $table->comment = 'Users by host permitted (or not) to login from a remote provider';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnet_host_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('access', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, 'allow');
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('mnethostid_username', XMLDB_INDEX_UNIQUE, array('mnet_host_id', 'username'));
        // Create the table
        $result = $result && create_table($table);
        if (empty($USER->mnet_host_id)) {
            $USER->mnet_host_id = $CFG->mnet_localhost_id;
            // Something for the current user to prevent warnings
        }
        /**
         ** enrol/mnet tables
         **/
        $table = new XMLDBTable('mnet_enrol_course');
        $table->comment = 'Information about courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cat_description', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '254', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('summary', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('startdate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cost', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('currency', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('defaultroleid', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('defaultrolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_remoteid', XMLDB_INDEX_UNIQUE, array('hostid', 'remoteid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_enrol_assignments');
        $table->comment = 'Information about enrolments on courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enroltime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('enroltype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_courseid', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'courseid'));
        $table->addIndexInfo('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Create the table
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007010301);
    }
    if ($result && $oldversion < 2007010404) {
        /// Define field shortname to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, 'shortname', 'id');
        /// Launch add field shortname
        $result = $result && add_field($table, $field);
        /// Changing type of field name on table user_info_field to text
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null, 'shortname');
        /// Launch change of type for field name
        $result = $result && change_field_type($table, $field);
        /// For existing fields use 'name' as the 'shortname' entry
        if ($fields = get_records_select('user_info_field', '', '', 'id, name')) {
            foreach ($fields as $field) {
                $field->shortname = clean_param($field->name, PARAM_ALPHANUM);
                $result && update_record('user_info_field', $field);
            }
        }
        upgrade_main_savepoint($result, 2007010404);
    }
    if ($result && $oldversion < 2007011501) {
        if (!empty($CFG->enablerecordcache) && empty($CFG->rcache) && empty($CFG->cachetype) && empty($CFG->intcachemax)) {
            set_config('cachetype', 'internal');
            set_config('rcache', true);
            set_config('intcachemax', $CFG->enablerecordcache);
            unset_config('enablerecordcache');
            unset($CFG->enablerecordcache);
        }
        upgrade_main_savepoint($result, 2007011501);
    }
    if ($result && $oldversion < 2007012100) {
        /// Some old PG servers have user->firstname & user->lastname with 30cc. They must be 100cc.
        /// Fixing that conditionally. MDL-7110
        if ($CFG->dbfamily == 'postgres') {
            /// Get Metadata from user table
            $cols = array_change_key_case($db->MetaColumns($CFG->prefix . 'user'), CASE_LOWER);
            /// Process user->firstname if needed
            if ($col = $cols['firstname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field firstname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('firstname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'idnumber');
                    /// Launch change of precision for field firstname
                    $result = $result && change_field_precision($table, $field);
                }
            }
            /// Process user->lastname if needed
            if ($col = $cols['lastname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field lastname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('lastname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'firstname');
                    /// Launch change of precision for field lastname
                    $result = $result && change_field_precision($table, $field);
                }
            }
        }
        upgrade_main_savepoint($result, 2007012100);
    }
    if ($result && $oldversion < 2007012101) {
        /// Changing precision of field lang on table course to (30)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null, 'groupmodeforce');
        /// Launch change of precision for field course->lang
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field lang on table user to (30)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en', 'country');
        /// Launch change of precision for field user->lang
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007012101);
    }
    if ($result && $oldversion < 2007012400) {
        /// Rename field access on table mnet_sso_access_control to accessctrl
        $table = new XMLDBTable('mnet_sso_access_control');
        $field = new XMLDBField('access');
        $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'allow', 'mnet_host_id');
        /// Launch rename field accessctrl
        $result = $result && rename_field($table, $field, 'accessctrl');
        upgrade_main_savepoint($result, 2007012400);
    }
    if ($result && $oldversion < 2007012500) {
        execute_sql("DELETE FROM {$CFG->prefix}user WHERE username='******'", true);
        upgrade_main_savepoint($result, 2007012500);
    }
    if ($result && $oldversion < 2007020400) {
        /// Only for MySQL and PG, declare the user->ajax field as not null. MDL-8421.
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            /// Changing nullability of field ajax on table user to not null
            $table = new XMLDBTable('user');
            $field = new XMLDBField('ajax');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'htmleditor');
            /// Launch change of nullability for field ajax
            $result = $result && change_field_notnull($table, $field);
        }
        upgrade_main_savepoint($result, 2007020400);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007021401) {
        /// create default logged in user role if not present - upgrade rom 1.7.x
        if (empty($CFG->defaultuserroleid) or empty($CFG->guestroleid) or $CFG->defaultuserroleid == $CFG->guestroleid) {
            if (!get_records('role', 'shortname', 'user')) {
                $userroleid = create_role(addslashes(get_string('authenticateduser')), 'user', addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
                if ($userroleid) {
                    reset_role_capabilities($userroleid);
                    set_config('defaultuserroleid', $userroleid);
                }
            }
        }
        upgrade_main_savepoint($result, 2007021401);
    }
    if ($result && $oldversion < 2007021501) {
        /// delete removed setting from config
        unset_config('tabselectedtofront');
        upgrade_main_savepoint($result, 2007021501);
    }
    if ($result && $oldversion < 2007032200) {
        /// Define table role_sortorder to be created
        $table = new XMLDBTable('role_sortorder');
        /// Adding fields to table role_sortorder
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortoder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table role_sortorder
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        $table->addKeyInfo('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table role_sortorder
        $table->addIndexInfo('userid-roleid-contextid', XMLDB_INDEX_UNIQUE, array('userid', 'roleid', 'contextid'));
        /// Launch create table for role_sortorder
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007032200);
    }
    /// code to change lenghen tag field to 255, MDL-9095
    if ($result && $oldversion < 2007040400) {
        /// Define index text (not unique) to be dropped form tags
        $table = new XMLDBTable('tags');
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch drop index text
        $result = $result && drop_index($table, $index);
        $field = new XMLDBField('text');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'userid');
        /// Launch change of type for field text
        $result = $result && change_field_type($table, $field);
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch add index text
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007040400);
    }
    if ($result && $oldversion < 2007041100) {
        /// Define field idnumber to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'section');
        /// Launch add field idnumber
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007041100);
    }
    /* Changes to the custom profile menu type - store values rather than indices.
       We could do all this with one tricky SQL statement but it's a one-off so no
       harm in using PHP loops */
    if ($result && $oldversion < 2007041600) {
        /// Get the menu fields
        if ($fields = get_records('user_info_field', 'datatype', 'menu')) {
            foreach ($fields as $field) {
                /// Get user data for the menu field
                if ($data = get_records('user_info_data', 'fieldid', $field->id)) {
                    /// Get the menu options
                    $options = explode("\n", $field->param1);
                    foreach ($data as $d) {
                        $key = array_search($d->data, $options);
                        /// If the data is an integer and is not one of the options,
                        /// set the respective option value
                        if (is_int($d->data) and ($key === NULL or $key === false) and isset($options[$d->data])) {
                            $d->data = $options[$d->data];
                            $result = $result && update_record('user_info_data', $d);
                        }
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007041600);
    }
    /// adding new gradebook tables
    if ($result && $oldversion < 2007041800) {
        /// Define table events_handlers to be created
        $table = new XMLDBTable('events_handlers');
        /// Adding fields to table events_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventname', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlermodule', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfunction', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        /// Adding keys to table events_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table events_handlers
        $table->addIndexInfo('eventname-handlermodule', XMLDB_INDEX_UNIQUE, array('eventname', 'handlermodule'));
        /// Launch create table for events_handlers
        $result = $result && create_table($table);
        /// Define table events_queue to be created
        $table = new XMLDBTable('events_queue');
        /// Adding fields to table events_queue
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventdata', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('schedule', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('stackdump', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch create table for events_queue
        $result = $result && create_table($table);
        /// Define table events_queue_handlers to be created
        $table = new XMLDBTable('events_queue_handlers');
        /// Adding fields to table events_queue_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('queuedeventid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('status', XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null);
        $table->addFieldInfo('errormessage', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('queuedeventid', XMLDB_KEY_FOREIGN, array('queuedeventid'), 'events_queue', array('id'));
        $table->addKeyInfo('handlerid', XMLDB_KEY_FOREIGN, array('handlerid'), 'events_handlers', array('id'));
        /// Launch create table for events_queue_handlers
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007041800);
    }
    if ($result && $oldversion < 2007043001) {
        /// Define field schedule to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('schedule');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'handlerfunction');
        /// Launch add field schedule
        $result = $result && add_field($table, $field);
        /// Define field status to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('status');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'schedule');
        /// Launch add field status
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007043001);
    }
    if ($result && $oldversion < 2007050201) {
        /// Define field theme to be added to course_categories
        $table = new XMLDBTable('course_categories');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'path');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007050201);
    }
    if ($result && $oldversion < 2007051100) {
        /// Define field forceunique to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('forceunique');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'visible');
        /// Launch add field forceunique
        $result = $result && add_field($table, $field);
        /// Define field signup to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('signup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'forceunique');
        /// Launch add field signup
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007051100);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007051801) {
        // Get the role id of the "Auth. User" role and check if the default role id is different
        // note: use of assign_capability() is discouraged in upgrade script!
        $userrole = get_record('role', 'shortname', 'user');
        $defaultroleid = $CFG->defaultuserroleid;
        if ($defaultroleid != $userrole->id) {
            //  Add in the new moodle/my:manageblocks capibility to the default user role
            $context = get_context_instance(CONTEXT_SYSTEM);
            assign_capability('moodle/my:manageblocks', CAP_ALLOW, $defaultroleid, $context->id);
        }
        upgrade_main_savepoint($result, 2007051801);
    }
    if ($result && $oldversion < 2007052200) {
        /// Define field schedule to be dropped from events_queue
        $table = new XMLDBTable('events_queue');
        $field = new XMLDBField('schedule');
        /// Launch drop field stackdump
        $result = $result && drop_field($table, $field);
        upgrade_main_savepoint($result, 2007052200);
    }
    if ($result && $oldversion < 2007052300) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype();
        upgrade_main_savepoint($result, 2007052300);
    }
    if ($result && $oldversion < 2007060500) {
        /// Define field usermodified to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('usermodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'created');
        /// Launch add field usermodified
        $result = $result && add_field($table, $field);
        /// Define key usermodified (foreign) to be added to post
        $table = new XMLDBTable('post');
        $key = new XMLDBKey('usermodified');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch add key usermodified
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007060500);
    }
    if ($result && $oldversion < 2007070603) {
        // Small update of guest user to be 100% sure it has the correct mnethostid (MDL-10375)
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'username', 'guest');
        upgrade_main_savepoint($result, 2007070603);
    }
    if ($result && $oldversion < 2007071400) {
        /**
         ** mnet application table
         **/
        $table = new XMLDBTable('mnet_application');
        $table->comment = 'Information about applications on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('display_name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_server_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sso_land_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        // Insert initial applications (moodle and mahara)
        $application = new stdClass();
        $application->name = 'moodle';
        $application->display_name = 'Moodle';
        $application->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
        $application->sso_land_url = '/auth/mnet/land.php';
        if ($result) {
            $newid = insert_record('mnet_application', $application, false);
        }
        $application = new stdClass();
        $application->name = 'mahara';
        $application->display_name = 'Mahara';
        $application->xmlrpc_server_url = '/api/xmlrpc/server.php';
        $application->sso_land_url = '/auth/xmlrpc/land.php';
        $result = $result && insert_record('mnet_application', $application, false);
        // New mnet_host->applicationid field
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, $newid, 'last_log_id');
        $result = $result && add_field($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007071400);
    }
    if ($result && $oldversion < 2007071607) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype_config_string();
        upgrade_main_savepoint($result, 2007071607);
    }
    if ($result && $oldversion < 2007072200) {
        /// Remove all grade tables used in development phases - we need new empty tables for final gradebook upgrade
        $tables = array('grade_categories', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses', 'grade_history', 'grade_import_newitem', 'grade_import_values');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        $tables = array('grade_categories_history', 'grade_items_history', 'grade_grades_history', 'grade_grades_text_history', 'grade_scale_history', 'grade_outcomes_history');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define table grade_outcomes to be created
        $table = new XMLDBTable('grade_outcomes');
        /// Adding fields to table grade_outcomes
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_outcomes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch create table for grade_outcomes
        $result = $result && create_table($table);
        /// Define table grade_categories to be created
        $table = new XMLDBTable('grade_categories');
        /// Adding fields to table grade_categories
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_categories
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        /// Launch create table for grade_categories
        $result = $result && create_table($table);
        /// Define table grade_items to be created
        $table = new XMLDBTable('grade_items');
        /// Adding fields to table grade_items
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_items
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        $table->addIndexInfo('itemtype-needsupdate', XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        $table->addIndexInfo('gradetype', XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        /// Launch create table for grade_items
        $result = $result && create_table($table);
        /// Define table grade_grades to be created
        $table = new XMLDBTable('grade_grades');
        /// Adding fields to table grade_grades
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_grades
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        /// Launch create table for grade_grades
        $result = $result && create_table($table);
        /// Define table grade_outcomes_history to be created
        $table = new XMLDBTable('grade_outcomes_history');
        /// Adding fields to table grade_outcomes_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_outcomes_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_outcomes_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_outcomes_history
        $result = $result && create_table($table);
        /// Define table grade_categories_history to be created
        $table = new XMLDBTable('grade_categories_history');
        /// Adding fields to table grade_categories_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_categories_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_categories', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_categories_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_categories_history
        $result = $result && create_table($table);
        /// Define table grade_items_history to be created
        $table = new XMLDBTable('grade_items_history');
        /// Adding fields to table grade_items_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_items_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_items', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_items_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_items_history
        $result = $result && create_table($table);
        /// Define table grade_grades_history to be created
        $table = new XMLDBTable('grade_grades_history');
        /// Adding fields to table grade_grades_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_grades_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_grades', array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_grades_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_grades_history
        $result = $result && create_table($table);
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for scale_history
        $result = $result && create_table($table);
        /// upgrade the old 1.8 gradebook - migrade data into new grade tables
        if ($result) {
            if ($rs = get_recordset('course')) {
                while ($course = rs_fetch_next_record($rs)) {
                    // this function uses SQL only, it must not be changed after 1.9 goes stable!!
                    if (!upgrade_18_gradebook($course->id)) {
                        $result = false;
                        break;
                    }
                }
                rs_close($rs);
            }
        }
        upgrade_main_savepoint($result, 2007072200);
    }
    if ($result && $oldversion < 2007072400) {
        /// Dropping one DEFAULT in a TEXT column. It's was only one remaining
        /// since Moodle 1.7, so new servers won't have those anymore.
        /// Changing the default of field sessdata on table sessions2 to drop it
        $table = new XMLDBTable('sessions2');
        $field = new XMLDBField('sessdata');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'modified');
        /// Launch change of default for field sessdata
        $result = $result && change_field_default($table, $field);
        upgrade_main_savepoint($result, 2007072400);
    }
    if ($result && $oldversion < 2007073100) {
        /// Define table grade_outcomes_courses to be created
        $table = new XMLDBTable('grade_outcomes_courses');
        /// Adding fields to table grade_outcomes_courses
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_outcomes_courses
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid-outcomeid', XMLDB_KEY_UNIQUE, array('courseid', 'outcomeid'));
        /// Launch create table for grade_outcomes_courses
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073100);
    }
    if ($result && $oldversion < 2007073101) {
        // Add new tag tables
        /// Define table tag to be created
        $table = new XMLDBTable('tag');
        /// Adding fields to table tag
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('tagtype', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('flag', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table tag
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag
        $table->addIndexInfo('name', XMLDB_INDEX_UNIQUE, array('name'));
        /// Launch create table for tag
        $result = $result && create_table($table);
        /// Define table tag_correlation to be created
        $table = new XMLDBTable('tag_correlation');
        /// Adding fields to table tag_correlation
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('correlatedtags', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_correlation
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_correlation
        $table->addIndexInfo('tagid', XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch create table for tag_correlation
        $result = $result && create_table($table);
        /// Define table tag_instance to be created
        $table = new XMLDBTable('tag_instance');
        /// Adding fields to table tag_instance
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_instance
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_instance
        $table->addIndexInfo('tagiditem', XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch create table for tag_instance
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073101);
    }
    if ($result && $oldversion < 2007073103) {
        /// Define field rawname to be added to tag
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('rawname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'name');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007073103);
    }
    if ($result && $oldversion < 2007073105) {
        /// Define field description to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_outcomes_history');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007073105);
    }
    // adding unique contraint on (courseid,shortname) of an outcome
    if ($result && $oldversion < 2007080100) {
        /// Define key courseid-shortname (unique) to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $key = new XMLDBKey('courseid-shortname');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('courseid', 'shortname'));
        /// Launch add key courseid-shortname
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007080100);
    }
    /// originally there was supportname and supportemail upgrade code - this is handled in upgradesettings.php instead
    if ($result && $oldversion < 2007080202) {
        /// Define index tagiditem (not unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        drop_index($table, $index);
        /// Define index tagiditem (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch add index tagiditem
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007080202);
    }
    if ($result && $oldversion < 2007080300) {
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007080300);
    }
    if ($result && $oldversion < 2007080800) {
        /// Normalize course->shortname MDL-10026
        /// Changing precision of field shortname on table course to (100)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'fullname');
        /// Launch change of precision for field shortname
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007080800);
    }
    if ($result && $oldversion < 2007080900) {
        /// Add context.path & index
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('context');
        $index = new XMLDBIndex('path');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('path'));
        $result = $result && add_index($table, $index);
        /// Add context.depth
        $table = new XMLDBTable('context');
        $field = new XMLDBField('depth');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'path');
        $result = $result && add_field($table, $field);
        /// make sure the system context has proper data
        get_system_context(false);
        upgrade_main_savepoint($result, 2007080900);
    }
    if ($result && $oldversion < 2007080903) {
        /// Define index
        $table = new XMLDBTable('grade_grades');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index itemtype-needsupdate (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('itemtype-needsupdate');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        if (!index_exists($table, $index)) {
            /// Launch add index itemtype-needsupdate
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('gradetype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007080903);
    }
    if ($result && $oldversion < 2007081000) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_upgrade_context_etc();
        upgrade_main_savepoint($result, 2007081000);
    }
    if ($result && $oldversion < 2007081302) {
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('password');
        if (field_exists($table, $field)) {
            /// 1.7.*/1.6.*/1.5.* - create 'groupings' and 'groupings_groups' + rename password to enrolmentkey
            /// or second run after fixing structure broken from 1.8.x
            $result = $result && upgrade_17_groups();
        } else {
            if (table_exists(new XMLDBTable('groups_groupings'))) {
                /// ELSE 'groups_groupings' table exists, this is 1.8.* properly upgraded
                $result = $result && upgrade_18_groups();
            } else {
                /// broken groups, failed 1.8.x upgrade
                upgrade_18_broken_groups();
                notify('Warning: failed groups upgrade detected! Unfortunately this problem ' . 'can not be fixed automatically. Mapping of groups to courses was lost, ' . 'you can either revert to backup from 1.7.x and run ugprade again or ' . 'continue and fill in the missing course ids into groups table manually.');
                $result = false;
            }
        }
        upgrade_main_savepoint($result, 2007081302);
    }
    if ($result && $oldversion < 2007081303) {
        /// Common groups upgrade for 1.8.* and 1.7.*/1.6.*..
        // delete not used fields
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('theme');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('lang');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        /// Add groupingid field/f.key to 'course' table.
        $table = new XMLDBTable('course');
        $field = new XMLDBField('defaultgroupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmodeforce');
        $result = $result && add_field($table, $field);
        /// Add grouping ID, grouponly field/f.key to 'course_modules' table.
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmode');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupmembersonly');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupingid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $key = new XMLDBKey('groupingid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007081303);
    }
    if ($result && $oldversion < 2007082300) {
        /// Define field ordering to be added to tag_instance table
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'itemid');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082300);
    }
    if ($result && $oldversion < 2007082700) {
        /// Define field timemodified to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'ordering');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082700);
    }
    /// migrate all tags table to tag - this code MUST use SQL only,
    /// because if the db structure changes the library functions will fail in future
    if ($result && $oldversion < 2007082701) {
        $tagrefs = array();
        // $tagrefs[$oldtagid] = $newtagid
        if ($rs = get_recordset('tags')) {
            $db->debug = false;
            while ($oldtag = rs_fetch_next_record($rs)) {
                $raw_normalized = clean_param($oldtag->text, PARAM_TAG);
                $normalized = moodle_strtolower($raw_normalized);
                // if this tag does not exist in tag table yet
                if (!($newtag = get_record('tag', 'name', addslashes($normalized), '', '', '', '', 'id'))) {
                    $itag = new object();
                    $itag->name = $normalized;
                    $itag->rawname = $raw_normalized;
                    $itag->userid = $oldtag->userid;
                    $itag->timemodified = time();
                    $itag->descriptionformat = 0;
                    // default format
                    if ($oldtag->type == 'official') {
                        $itag->tagtype = 'official';
                    } else {
                        $itag->tagtype = 'default';
                    }
                    if ($idx = insert_record('tag', addslashes_recursive($itag))) {
                        $tagrefs[$oldtag->id] = $idx;
                    }
                    // if this tag is already used by tag table
                } else {
                    $tagrefs[$oldtag->id] = $newtag->id;
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        // fetch all the tag instances and migrate them as well
        if ($rs = get_recordset('blog_tag_instance')) {
            $db->debug = false;
            while ($blogtag = rs_fetch_next_record($rs)) {
                if (array_key_exists($blogtag->tagid, $tagrefs)) {
                    $tag_instance = new object();
                    $tag_instance->tagid = $tagrefs[$blogtag->tagid];
                    $tag_instance->itemtype = 'blog';
                    $tag_instance->itemid = $blogtag->entryid;
                    $tag_instance->ordering = 1;
                    // does not matter much, because originally there was no ordering in blogs
                    $tag_instance->timemodified = time();
                    insert_record('tag_instance', $tag_instance);
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        unset($tagrefs);
        // release memory
        $table = new XMLDBTable('tags');
        drop_table($table);
        $table = new XMLDBTable('blog_tag_instance');
        drop_table($table);
        upgrade_main_savepoint($result, 2007082701);
    }
    /// MDL-11015, MDL-11016
    if ($result && $oldversion < 2007082800) {
        /// Changing type of field userid on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field userid
        $result = $result && change_field_type($table, $field);
        /// Changing type of field descriptionformat on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('descriptionformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'description');
        /// Launch change of type for field descriptionformat
        $result = $result && change_field_type($table, $field);
        /// Define key userid (foreign) to be added to tag
        $table = new XMLDBTable('tag');
        $key = new XMLDBKey('userid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch add key userid
        $result = $result && add_key($table, $key);
        /// Define index tagiditem (unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_instance to int
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        /// Changing sign of field itemid on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('itemid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'itemtype');
        /// Launch change of sign for field itemid
        $result = $result && change_field_unsigned($table, $field);
        /// Changing sign of field ordering on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'itemid');
        /// Launch change of sign for field ordering
        $result = $result && change_field_unsigned($table, $field);
        /// Define index itemtype-itemid-tagid (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('itemtype-itemid-tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid'));
        /// Launch add index itemtype-itemid-tagid
        $result = $result && add_index($table, $index);
        /// Define index tagid (unique) to be dropped form tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $index = new XMLDBIndex('tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch drop index tagid
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_correlation to int
        $table = new XMLDBTable('tag_correlation');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082800);
    }
    if ($result && $oldversion < 2007082801) {
        /// Define table user_private_key to be created
        $table = new XMLDBTable('user_private_key');
        /// Adding fields to table user_private_key
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('script', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iprestriction', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('validuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table user_private_key
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table user_private_key
        $table->addIndexInfo('script-value', XMLDB_INDEX_NOTUNIQUE, array('script', 'value'));
        /// Launch create table for user_private_key
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007082801);
    }
    /// Going to modify the applicationid from int(1) to int(10). Dropping and
    /// re-creating the associated keys/indexes is mandatory to be cross-db. MDL-11042
    if ($result && $oldversion < 2007082803) {
        /// Define key applicationid (foreign) to be dropped form mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch drop key applicationid
        $result = $result && drop_key($table, $key);
        /// Changing type of field applicationid on table mnet_host to int
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'last_log_id');
        /// Launch change of type for field applicationid
        $result = $result && change_field_type($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082803);
    }
    if ($result && $oldversion < 2007090503) {
        /// Define field aggregatesubcats to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregatesubcats to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// upgrade path in grade_categrories table - now using slash on both ends
        $concat = sql_concat('path', "'/'");
        $sql = "UPDATE {$CFG->prefix}grade_categories SET path = {$concat} WHERE path NOT LIKE '/%/'";
        execute_sql($sql, true);
        /// convert old aggregation constants if needed
        /*for ($i=0; $i<=12; $i=$i+2) {
              $j = $i+1;
              $sql = "UPDATE {$CFG->prefix}grade_categories SET aggregation = $i, aggregateonlygraded = 1 WHERE aggregation = $j";
              execute_sql($sql, true);
          }*/
        // not needed anymore - breaks upgrade now
        upgrade_main_savepoint($result, 2007090503);
    }
    /// To have UNIQUE indexes over NULLable columns isn't cross-db at all
    /// so we create a non unique index and programatically enforce uniqueness
    if ($result && $oldversion < 2007090600) {
        /// Define index idnumber (unique) to be dropped form course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        $result = $result && drop_index($table, $index);
        /// Define index idnumber-course (not unique) to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'course'));
        /// Launch add index idnumber-course
        $result = $result && add_index($table, $index);
        /// Define index idnumber-courseid (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('idnumber-courseid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'courseid'));
        /// Launch add index idnumber-courseid
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007090600);
    }
    /// Create the permanent context_temp table to be used by build_context_path()
    if ($result && $oldversion < 2007092001) {
        /// Define table context_temp to be created
        $table = new XMLDBTable('context_temp');
        /// Adding fields to table context_temp
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table context_temp
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for context_temp
        $result = $result && create_table($table);
        /// make sure category depths, parents and paths are ok, categories from 1.5 may not be properly initialized (MDL-12585)
        upgrade_fix_category_depths();
        /// Recalculate depths, paths and so on
        if (!empty($CFG->rolesactive)) {
            cleanup_contexts();
            // make sure all course, category and user contexts exist - we need it for grade letter upgrade, etc.
            create_contexts(CONTEXT_COURSE, false, true);
            create_contexts(CONTEXT_USER, false, true);
            // we need all contexts path/depths filled properly
            build_context_path(true, true);
            load_all_capabilities();
        } else {
            // upgrade from 1.6 - build all contexts
            create_contexts(null, true, true);
        }
        upgrade_main_savepoint($result, 2007092001);
    }
    /**
     * Merging of grade_grades_text back into grade_grades
     */
    if ($result && $oldversion < 2007092002) {
        /// Define field feedback to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        /// Define field feedback to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_grades_text');
        if ($result and table_exists($table)) {
            //migrade existing data into grade_grades table - this is slow but works for all dbs,
            //it will be executed on development sites only
            $fields = array('feedback', 'information');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = (\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id)";
                $result = execute_sql($sql) && $result;
            }
            $fields = array('feedbackformat', 'informationformat');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = COALESCE((\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id), 0)";
                $result = execute_sql($sql) && $result;
            }
            if ($result) {
                $tables = array('grade_grades_text', 'grade_grades_text_history');
                foreach ($tables as $table) {
                    $table = new XMLDBTable($table);
                    if (table_exists($table)) {
                        drop_table($table);
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007092002);
    }
    if ($result && $oldversion < 2007092803) {
        /// Remove obsoleted unit tests tables - they will be recreated automatically
        $tables = array('grade_categories', 'scale', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses');
        foreach ($tables as $tablename) {
            $table = new XMLDBTable('unittest_' . $tablename);
            if (table_exists($table)) {
                drop_table($table);
            }
            $table = new XMLDBTable('unittest_' . $tablename . '_history');
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define field display to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
        }
        /// Define field display to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// Define field decimals to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
            $result = $result && change_field_notnull($table, $field);
        }
        /// Define field decimals to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// fix incorrect -1 default for grade_item->display
        execute_sql("UPDATE {$CFG->prefix}grade_items SET display=0 WHERE display=-1");
        upgrade_main_savepoint($result, 2007092803);
    }
    /// migrade grade letters - we can not do this in normal grades upgrade becuase we need all course contexts
    if ($result && $oldversion < 2007092806) {
        $result = upgrade_18_letters();
        /// Define index contextidlowerboundary (not unique) to be added to grade_letters
        $table = new XMLDBTable('grade_letters');
        $index = new XMLDBIndex('contextid-lowerboundary');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
        /// Launch add index contextidlowerboundary
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007092806);
    }
    if ($result && $oldversion < 2007100100) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        /// Adding fields to table cache_flags
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flagtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table cache_flags
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /*
         * Note: mysql can not create indexes on text fields larger than 333 chars! 
         */
        /// Adding indexes to table cache_flags
        $table->addIndexInfo('flagtype', XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        $table->addIndexInfo('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        /// Launch create table for cache_flags
        if (!table_exists($table)) {
            $result = $result && create_table($table);
        }
        upgrade_main_savepoint($result, 2007100100);
    }
    if ($result && $oldversion < 2007100300) {
        /// MNET stuff for roaming theme
        /// Define field force_theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('force_theme');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'last_log_id');
        /// Launch add field force_theme
        $result = $result && add_field($table, $field);
        /// Define field theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'force_theme');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007100300);
    }
    if ($result && $oldversion < 2007100301) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('typename');
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('flagtype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('name');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007100301);
    }
    if ($result && $oldversion < 2007100303) {
        /// Changing nullability of field summary on table course to null
        $table = new XMLDBTable('course');
        $field = new XMLDBField('summary');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'idnumber');
        /// Launch change of nullability for field summary
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100303);
    }
    if ($result && $oldversion < 2007100500) {
        /// for dev sites - it is ok to do this repeatedly
        /// Changing nullability of field path on table context to null
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        /// Launch change of nullability for field path
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100500);
    }
    if ($result && $oldversion < 2007100700) {
        /// first drop existing tables - we do not need any data from there
        $table = new XMLDBTable('grade_import_values');
        if (table_exists($table)) {
            drop_table($table);
        }
        $table = new XMLDBTable('grade_import_newitem');
        if (table_exists($table)) {
            drop_table($table);
        }
        /// Define table grade_import_newitem to be created
        $table = new XMLDBTable('grade_import_newitem');
        /// Adding fields to table grade_import_newitem
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_import_newitem
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_newitem
        $result = $result && create_table($table);
        /// Define table grade_import_values to be created
        $table = new XMLDBTable('grade_import_values');
        /// Adding fields to table grade_import_values
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('newgradeitem', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_import_values
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('newgradeitem', XMLDB_KEY_FOREIGN, array('newgradeitem'), 'grade_import_newitem', array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_values
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100700);
    }
    /// dropping context_rel table - not used anymore
    if ($result && $oldversion < 2007100800) {
        /// Define table context_rel to be dropped
        $table = new XMLDBTable('context_rel');
        /// Launch drop table for context_rel
        if (table_exists($table)) {
            drop_table($table);
        }
        upgrade_main_savepoint($result, 2007100800);
    }
    /// Truncate the text_cahe table and add new index
    if ($result && $oldversion < 2007100802) {
        /// Truncate the cache_text table
        execute_sql("TRUNCATE TABLE {$CFG->prefix}cache_text", true);
        /// Define index timemodified (not unique) to be added to cache_text
        $table = new XMLDBTable('cache_text');
        $index = new XMLDBIndex('timemodified');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch add index timemodified
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007100802);
    }
    /// newtable for gradebook settings per course
    if ($result && $oldversion < 2007100803) {
        /// Define table grade_settings to be created
        $table = new XMLDBTable('grade_settings');
        /// Adding fields to table grade_settings
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_settings
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        /// Adding indexes to table grade_settings
        $table->addIndexInfo('courseid-name', XMLDB_INDEX_UNIQUE, array('courseid', 'name'));
        /// Launch create table for grade_settings
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100803);
    }
    /// cleanup in user_lastaccess
    if ($result && $oldversion < 2007100902) {
        $sql = "DELETE\n                  FROM {$CFG->prefix}user_lastaccess\n                 WHERE NOT EXISTS (SELECT 'x'\n                                    FROM {$CFG->prefix}course c\n                                   WHERE c.id = {$CFG->prefix}user_lastaccess.courseid)";
        execute_sql($sql);
        upgrade_main_savepoint($result, 2007100902);
    }
    /// drop old gradebook tables
    if ($result && $oldversion < 2007100903) {
        $tables = array('grade_category', 'grade_item', 'grade_letter', 'grade_preferences', 'grade_exceptions');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        upgrade_main_savepoint($result, 2007100903);
    }
    if ($result && $oldversion < 2007101500 && !file_exists($CFG->dataroot . '/user')) {
        // Get list of users by browsing moodledata/user
        $oldusersdir = $CFG->dataroot . '/users';
        $folders = get_directory_list($oldusersdir, '', false, true, false);
        foreach ($folders as $userid) {
            $olddir = $oldusersdir . '/' . $userid;
            $files = get_directory_list($olddir);
            if (empty($files)) {
                continue;
            }
            // Create new user directory
            if (!($newdir = make_user_directory($userid))) {
                // some weird directory - do not stop the upgrade, just ignore it
                continue;
            }
            // Move contents of old directory to new one
            if (file_exists($olddir) && file_exists($newdir)) {
                foreach ($files as $file) {
                    copy($olddir . '/' . $file, $newdir . '/' . $file);
                }
            } else {
                notify("Could not move the contents of {$olddir} into {$newdir}!");
                $result = false;
                break;
            }
        }
        // Leave a README in old users directory
        $readmefilename = $oldusersdir . '/README.txt';
        if ($handle = fopen($readmefilename, 'w+b')) {
            if (!fwrite($handle, get_string('olduserdirectory'))) {
                // Could not write to the readme file. No cause for huge concern
                notify("Could not write to the README.txt file in {$readmefilename}.");
            }
            fclose($handle);
        } else {
            // Could not create the readme file. No cause for huge concern
            notify("Could not create the README.txt file in {$readmefilename}.");
        }
    }
    if ($result && $oldversion < 2007101502) {
        /// try to remove duplicate entries
        $SQL = "SELECT userid, itemid, COUNT(*)\n               FROM {$CFG->prefix}grade_grades\n               GROUP BY userid, itemid\n               HAVING COUNT( * ) >1";
        // duplicates found
        if ($rs = get_recordset_sql($SQL)) {
            if ($rs && $rs->RecordCount() > 0) {
                while ($dup = rs_fetch_next_record($rs)) {
                    if ($thisdups = get_records_sql("SELECT id FROM {$CFG->prefix}grade_grades \n                                                    WHERE itemid = {$dup->itemid} AND userid = {$dup->userid}\n                                                    ORDER BY timemodified DESC")) {
                        $processed = 0;
                        // keep the first one
                        foreach ($thisdups as $thisdup) {
                            if ($processed) {
                                // remove the duplicates
                                delete_records('grade_grades', 'id', $thisdup->id);
                            }
                            $processed++;
                        }
                    }
                }
                rs_close($rs);
            }
        }
        /// Define key userid-itemid (unique) to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $key = new XMLDBKey('userid-itemid');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('userid', 'itemid'));
        /// Launch add key userid-itemid
        $result = $result && add_key($table, $key);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101502);
    }
    if ($result && $oldversion < 2007101505) {
        /// Changing precision of field dst_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('dst_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'dst_skipweeks');
        /// Launch change of precision for field dst_time
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field std_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('std_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'std_skipweeks');
        /// Launch change of precision for field std_time
        $result = $result && change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101505);
    }
    if ($result && $oldversion < 2007101506) {
        /// CONTEXT_PERSONAL was never implemented - removing
        $sql = "DELETE\n                  FROM {$CFG->prefix}context\n                 WHERE contextlevel=20";
        execute_sql($sql);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101506);
    }
    if ($result && $oldversion < 2007101507) {
        $db->debug = false;
        require_once $CFG->dirroot . '/course/lib.php';
        notify('Started rebuilding of course cache...', 'notifysuccess');
        rebuild_course_cache();
        // Rebuild course cache - new group related fields there
        notify('...finished rebuilding of course cache.', 'notifysuccess');
        $db->debug = true;
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101507);
    }
    if ($result && $oldversion < 2007101508) {
        $db->debug = false;
        notify('Updating country list according to recent official ISO listing...', 'notifysuccess');
        // re-assign users to valid countries
        set_field('user', 'country', 'CD', 'country', 'ZR');
        // Zaire is now Congo Democratique
        set_field('user', 'country', 'TL', 'country', 'TP');
        // Timor has changed
        set_field('user', 'country', 'FR', 'country', 'FX');
        // France metropolitaine doesn't exist
        set_field('user', 'country', 'RS', 'country', 'KO');
        // Kosovo is part of Serbia, "under the auspices of the United Nations, pursuant to UN Security Council Resolution 1244 of 10 June 1999."
        set_field('user', 'country', 'GB', 'country', 'WA');
        // Wales is part of UK (ie Great Britain)
        set_field('user', 'country', 'RS', 'country', 'CS');
        // Re-assign Serbia-Montenegro to Serbia.  This is arbitrary, but there is no way to make an automatic decision on this.
        notify('...update complete. Remember to update the language pack to get the most recent country names defitions and codes.  This is specialy important for sites with users from Congo (now CD), Timor (now TL), Kosovo (now RS), Wales (now GB), Serbia (RS) and Montenegro (ME).  Users based in Montenegro (ME) will need to manually update their profile.', 'notifysuccess');
        $db->debug = true;
        upgrade_main_savepoint($result, 2007101508);
    }
    if ($result && $oldversion < 2007101508.01) {
        // add forgotten table
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        if ($result and !table_exists($table)) {
            /// Launch create table for scale_history
            $result = $result && create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.01);
    }
    if ($result && $oldversion < 2007101508.02) {
        // upgade totals, no big deal if it fails
        require_once $CFG->libdir . '/statslib.php';
        stats_upgrade_totals();
        if (isset($CFG->loglifetime) and $CFG->loglifetime == 30) {
            set_config('loglifetime', 35);
            // we need more than 31 days for monthly stats!
        }
        notify('Upgrading log table indexes, this may take a long time, please be patient.', 'notifysuccess');
        /// Define index time-course-module-action (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time-course-module-action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time', 'course', 'module', 'action'));
        /// Launch drop index time-course-module-action
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        /// Launch drop index userid
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index info (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('info');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('info'));
        /// Launch drop index info
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index time (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time'));
        /// Launch add index time
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Define index action (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch add index action
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.02);
    }
    if ($result && $oldversion < 2007101508.03) {
        /// Define index course-userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('course-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'userid'));
        /// Launch drop index course-userid
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Define index userid-course (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid', 'course'));
        /// Launch add index userid-course
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.03);
    }
    if ($result && $oldversion < 2007101508.04) {
        set_field('tag_instance', 'itemtype', 'post', 'itemtype', 'blog');
        upgrade_main_savepoint($result, 2007101508.04);
    }
    if ($result && $oldversion < 2007101508.05) {
        /// Define index cmid (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('cmid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('cmid'));
        /// Launch add index cmid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.05);
    }
    if ($result && $oldversion < 2007101508.06) {
        /// Define index groupid-courseid-visible-userid (not unique) to be added to event
        $table = new XMLDBTable('event');
        $index = new XMLDBIndex('groupid-courseid-visible-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('groupid', 'courseid', 'visible', 'userid'));
        /// Launch add index groupid-courseid-visible-userid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.06);
    }
    if ($result && $oldversion < 2007101508.07) {
        /// Define table webdav_locks to be created
        $table = new XMLDBTable('webdav_locks');
        /// Adding fields to table webdav_locks
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('recursive', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exclusivelock', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('created', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('modified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('owner', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        /// Adding keys to table webdav_locks
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('token', XMLDB_KEY_UNIQUE, array('token'));
        /// Adding indexes to table webdav_locks
        $table->addIndexInfo('path', XMLDB_INDEX_NOTUNIQUE, array('path'));
        $table->addIndexInfo('expiry', XMLDB_INDEX_NOTUNIQUE, array('expiry'));
        /// Launch create table for webdav_locks
        $result = $result && create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.07);
    }
    if ($result && $oldversion < 2007101508.08) {
        // MDL-13676
        /// Define field name to be added to role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'text');
        /// Launch add field name
        $result = $result && add_field($table, $field);
        /// Copy data from old field to new field
        $result = $result && execute_sql('UPDATE ' . $CFG->prefix . 'role_names SET name = text');
        /// Define field text to be dropped from role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('text');
        /// Launch drop field text
        $result = $result && drop_field($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.08);
    }
    if ($result && $oldversion < 2007101509) {
        // force full regrading
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101510) {
        /// Fix minor problem caused by MDL-5482.
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_fix_random_question_parents();
        upgrade_main_savepoint($result, 2007101510);
    }
    if ($result && $oldversion < 2007101511) {
        // if guest role used as default user role unset it and force admin to choose new setting
        if (!empty($CFG->defaultuserroleid)) {
            if ($role = get_record('role', 'id', $CFG->defaultuserroleid)) {
                if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
                    if (isset($guestroles[$role->id])) {
                        set_config('defaultuserroleid', null);
                        notify('Guest role removed from "Default role for all users" setting, please select another role.', 'notifysuccess');
                    }
                }
            } else {
                set_config('defaultuserroleid', null);
            }
        }
    }
    if ($result && $oldversion < 2007101512) {
        notify('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
        /// Under MySQL and Postgres... detect old NULL contents and change them by correct empty string. MDL-14859
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            execute_sql("UPDATE {$CFG->prefix}user SET idnumber = '' WHERE idnumber IS NULL", true);
        }
        /// Define index idnumber (not unique) to be dropped form user
        $table = new XMLDBTable('user');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Changing precision of field idnumber on table user to (255)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'password');
        /// Launch change of precision for field idnumber
        $result = $result && change_field_precision($table, $field);
        /// Launch add index idnumber again
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        $result = $result && add_index($table, $index);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101512);
    }
    if ($result && $oldversion < 2007101513) {
        $log_action = new stdClass();
        $log_action->module = 'course';
        $log_action->action = 'unenrol';
        $log_action->mtable = 'course';
        $log_action->field = 'fullname';
        if (!record_exists("log_display", "action", "unenrol", "module", "course")) {
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101513);
    }
    if ($result && $oldversion < 2007101514) {
        $table = new XMLDBTable('mnet_enrol_course');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', true, true, null, false, false, 0);
        $result = change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007101514);
    }
    if ($result && $oldversion < 2007101515) {
        $result = delete_records_select('role_names', sql_isempty('role_names', 'name', false, false));
        upgrade_main_savepoint($result, 2007101515);
    }
    if ($result && $oldversion < 2007101517) {
        if (isset($CFG->defaultuserroleid) and isset($CFG->guestroleid) and $CFG->defaultuserroleid == $CFG->guestroleid) {
            // guest can not be selected in defaultuserroleid!
            unset_config('defaultuserroleid');
        }
        upgrade_main_savepoint($result, 2007101517);
    }
    if ($result && $oldversion < 2007101526) {
        /// Changing the default of field lang on table user to en_utf8
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en_utf8', 'country');
        /// Launch change of default for field lang
        $result = $result && change_field_default($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101526);
    }
    if ($result && $oldversion < 2007101527) {
        if (!get_config(NULL, 'statsruntimedays')) {
            set_config('statsruntimedays', '31');
        }
    }
    /// For MDL-17501. Ensure that any role that has moodle/course:update also
    /// has moodle/course:visibility.
    if ($result && $oldversion < 2007101532.1) {
        if (!empty($CFG->rolesactive)) {
            // In case we are upgrading from Moodle 1.6.
            /// Get the roles with 'moodle/course:update'.
            $systemcontext = get_context_instance(CONTEXT_SYSTEM);
            $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
            /// Give those roles 'moodle/course:visibility'.
            foreach ($roles as $role) {
                assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
            }
            /// Force all sessions to refresh access data.
            mark_context_dirty($systemcontext->path);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101532.1);
    }
    if ($result && $oldversion < 2007101542) {
        if (empty($CFG->hiddenuserfields)) {
            set_config('hiddenuserfields', 'firstaccess');
        } else {
            if (strpos($CFG->hiddenuserfields, 'firstaccess') === false) {
                //firstaccess should not already be listed but just in case
                set_config('hiddenuserfields', $CFG->hiddenuserfields . ',firstaccess');
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101542);
    }
    if ($result && $oldversion < 2007101545.01) {
        require_once "{$CFG->dirroot}/filter/tex/lib.php";
        filter_tex_updatedcallback(null);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101545.01);
    }
    if ($result && $oldversion < 2007101546.02) {
        if (empty($CFG->gradebook_latest195_upgrade)) {
            require_once $CFG->libdir . '/gradelib.php';
            // we need constants only
            // reset current coef for simple mean items - it may contain some rubbish ;-)
            $sql = "UPDATE {$CFG->prefix}grade_items\n                       SET aggregationcoef = 0\n                     WHERE categoryid IN (SELECT gc.id\n                                            FROM {$CFG->prefix}grade_categories gc\n                                           WHERE gc.aggregation = " . GRADE_AGGREGATE_WEIGHTED_MEAN2 . ")";
            $result = execute_sql($sql);
        } else {
            // direct upgrade from 1.8.x - no need to reset coef, because it is already ok
            unset_config('gradebook_latest195_upgrade');
        }
        upgrade_main_savepoint($result, 2007101546.02);
    }
    if ($result && $oldversion < 2007101546.03) {
        /// Deleting orphaned messages from deleted users.
        require_once $CFG->dirroot . '/message/lib.php';
        /// Detect deleted users with messages sent(useridfrom) and not read
        if ($deletedusers = get_records_sql("SELECT DISTINCT u.id\n                                           FROM {$CFG->prefix}user u\n                                           JOIN {$CFG->prefix}message m ON m.useridfrom = u.id\n                                          WHERE u.deleted = 1")) {
            foreach ($deletedusers as $deleteduser) {
                message_move_userfrom_unread2read($deleteduser->id);
                // move messages
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101546.03);
    }
    if ($result && $oldversion < 2007101546.05) {
        // force full regrading - the max grade for sum aggregation was not correct when scales involved,
        //                        extra credit grade is not dropped anymore in aggregations if drop low or keep high specified
        //                        sum aggragetion respects drop low and keep high when calculation max value
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101546.06) {
        unset_config('grade_report_showgroups');
        upgrade_main_savepoint($result, 2007101546.06);
    }
    if ($result && $oldversion < 2007101547) {
        // Let's check the status of mandatory mnet_host records, fixing them
        // and moving "orphan" users to default localhost record. MDL-16879
        notify('Fixing mnet records, this may take a while...', 'notifysuccess');
        $db->debug = false;
        // Can output too much. Disabling
        upgrade_fix_incorrect_mnethostids();
        $db->debug = true;
        // Restoring debug level
        upgrade_main_savepoint($result, 2007101547);
    }
    if ($result && $oldversion < 2007101551) {
        //insert new record for log_display table
        //used to record tag update.
        if (!record_exists("log_display", "action", "update", "module", "tag")) {
            $log_action = new stdClass();
            $log_action->module = 'tag';
            $log_action->action = 'update';
            $log_action->mtable = 'tag';
            $log_action->field = 'name';
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101551);
    }
    if ($result && $oldversion < 2007101561.01) {
        // As part of security changes password policy will now be enabled by default.
        // If it has not already been enabled then we will enable it... Admins will still
        // be able to switch it off after this upgrade
        if (record_exists('config', 'name', 'passwordpolicy', 'value', 0)) {
            unset_config('passwordpolicy');
        }
        $message = get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        notify($message, 'notifysuccess');
        unset($message);
        upgrade_main_savepoint($result, 2007101561.01);
    }
    if ($result && $oldversion < 2007101561.02) {
        $messagesubject = s($SITE->shortname) . ': ' . get_string('upgrade197noticesubject', 'admin');
        $message = '<p>' . s($SITE->fullname) . ' (' . s($CFG->wwwroot) . '):</p>' . get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        // Force administrators to change password on next login
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password, u.mailformat\n              FROM {$CFG->prefix}role_capabilities rc\n              JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n              JOIN {$CFG->prefix}user u ON u.id = ra.userid\n             WHERE rc.capability = 'moodle/site:doanything'\n                   AND rc.permission = " . CAP_ALLOW . "\n                   AND u.deleted = 0\n                   AND rc.contextid = " . $systemcontext->id . " AND (u.auth='manual' OR u.auth='email')";
        $adminusers = get_records_sql($sql);
        foreach ($adminusers as $adminuser) {
            if ($preference = get_record('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange')) {
                if ($preference->value == '1') {
                    continue;
                }
                set_field('user_preferences', 'value', '1', 'id', $preference->id);
            } else {
                $preference = new stdClass();
                $preference->userid = $adminuser->id;
                $preference->name = 'auth_forcepasswordchange';
                $preference->value = '1';
                insert_record('user_preferences', $preference);
            }
            $adminuser->maildisplay = 0;
            // do not use return email to self, it might actually help emails to get through and prevents notices
            // Message them with the notice about upgrading
            email_to_user($adminuser, $adminuser, $messagesubject, html_to_text($message), $message);
        }
        unset($adminusers);
        unset($preference);
        unset($message);
        unset($messagesubject);
        upgrade_main_savepoint($result, 2007101561.02);
    }
    if ($result && $oldversion < 2007101563.02) {
        // this block tries to undo incorrect forcing of new passwords for admins that have no
        // way to change passwords MDL-20933
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password\n                  FROM {$CFG->prefix}role_capabilities rc\n                  JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n                  JOIN {$CFG->prefix}user u ON u.id = ra.userid\n                 WHERE rc.capability = 'moodle/site:doanything'\n                       AND rc.permission = " . CAP_ALLOW . "\n                       AND u.deleted = 0\n                       AND rc.contextid = " . $systemcontext->id . " AND u.auth<>'manual' AND u.auth<>'email'";
        if ($adminusers = get_records_sql($sql)) {
            foreach ($adminusers as $adminuser) {
                delete_records('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange');
            }
        }
        unset($adminusers);
        upgrade_main_savepoint($result, 2007101563.02);
    }
    if ($result && $oldversion < 2007101563.03) {
        // NOTE: this is quite hacky, but anyway it should work fine in 1.9,
        //       in 2.0 we should always use plugin upgrade code for things like this
        $authsavailable = get_list_of_plugins('auth');
        foreach ($authsavailable as $authname) {
            if (!($auth = get_auth_plugin($authname))) {
                continue;
            }
            if ($auth->prevent_local_passwords()) {
                execute_sql("UPDATE {$CFG->prefix}user SET password='******' WHERE auth='{$authname}'");
            }
        }
        upgrade_main_savepoint($result, 2007101563.03);
    }
    return $result;
}
コード例 #24
0
ファイル: setup.php プロジェクト: jan-munneke/emoncms3
 if (table_exists($table)) {
     $out .= "<tr><td>TABLE " . $table . "</td><td>ok</td></tr>";
     //-----------------------------------------------------
     // Check table fields from schema
     //-----------------------------------------------------
     while ($field = key($schema[$table])) {
         $type = $schema[$table][$field]['type'];
         $null = $schema[$table][$field]['Null'];
         if (!$null) {
             $null = "YES";
         }
         $key = $schema[$table][$field]['Key'];
         $default = $schema[$table][$field]['default'];
         $extra = $schema[$table][$field]['Extra'];
         $out .= "<tr>";
         if (field_exists($table, $field)) {
             $out .= "<td>.." . $field . "</td><td>ok</td>";
         } else {
             $query = "ALTER TABLE `{$table}` ADD `{$field}` {$type}";
             echo $query;
             $out .= "<tr><td>.." . $field . "</td><td>added</td></tr>";
             db_query($query);
         }
         $result = db_query("DESCRIBE {$table} {$field}");
         $array = db_fetch_array($result);
         $out .= "<td>";
         $query = "";
         if ($array['Type'] != $type) {
             $out .= "Type: {$type}, ";
             $query .= ";";
         }
コード例 #25
0
ファイル: upgradelib.php プロジェクト: r007/PMoodle
/**
 * Drop, add fields and rename tables for groups upgrade from 1.8.*
 * @param XMLDBTable $table 'groups_groupings' table object.
 */
function upgrade_18_groups()
{
    global $CFG, $db;
    $result = upgrade_18_groups_drop_keys_indexes();
    /// Delete not used columns
    $fields_r = array('viewowngroup', 'viewallgroupsmembers', 'viewallgroupsactivities', 'teachersgroupmark', 'teachersgroupview', 'teachersoverride', 'teacherdeletable');
    foreach ($fields_r as $fname) {
        $table = new XMLDBTable('groups_groupings');
        $field = new XMLDBField($fname);
        if (field_exists($table, $field)) {
            $result = $result && drop_field($table, $field);
        }
    }
    /// Rename 'groups_groupings' to 'groupings'
    $table = new XMLDBTable('groups_groupings');
    $result = $result && rename_table($table, 'groupings');
    /// Add columns/key 'courseid', exclusivegroups, maxgroupsize, timemodified.
    $table = new XMLDBTable('groupings');
    $field = new XMLDBField('courseid');
    $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
    $result = $result && add_field($table, $field);
    $table = new XMLDBTable('groupings');
    $key = new XMLDBKey('courseid');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
    $result = $result && add_key($table, $key);
    $table = new XMLDBTable('groupings');
    $field = new XMLDBField('configdata');
    $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'description');
    $result = $result && add_field($table, $field);
    $table = new XMLDBTable('groupings');
    $field = new XMLDBField('timemodified');
    $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timecreated');
    $result = $result && add_field($table, $field);
    //==================
    /// Add columns/key 'courseid' into groups table
    $table = new XMLDBTable('groups');
    $field = new XMLDBField('courseid');
    $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
    $result = $result && add_field($table, $field);
    $table = new XMLDBTable('groups');
    $key = new XMLDBKey('courseid');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
    $result = $result && add_key($table, $key);
    /// Changing nullability of field enrolmentkey on table groups to null
    $table = new XMLDBTable('groups');
    $field = new XMLDBField('enrolmentkey');
    $field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'description');
    $result = $result && change_field_notnull($table, $field);
    //==================
    /// Now, rename 'groups_groupings_groups' to 'groupings_groups' and add keys
    $table = new XMLDBTable('groups_groupings_groups');
    $result = $result && rename_table($table, 'groupings_groups');
    $table = new XMLDBTable('groupings_groups');
    $key = new XMLDBKey('groupingid');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
    $result = $result && add_key($table, $key);
    $table = new XMLDBTable('groupings_groups');
    $key = new XMLDBKey('groupid');
    $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupid'), 'groups', array('id'));
    $result = $result && add_key($table, $key);
    ///=================
    /// Transfer courseid from 'mdl_groups_courses_groups' to 'mdl_groups'.
    if ($result) {
        $sql = "UPDATE {$CFG->prefix}groups\n                   SET courseid = (\n                        SELECT MAX(courseid)\n                          FROM {$CFG->prefix}groups_courses_groups gcg\n                         WHERE gcg.groupid = {$CFG->prefix}groups.id)";
        execute_sql($sql);
    }
    /// Transfer courseid from 'groups_courses_groupings' to 'mdl_groupings'.
    if ($result) {
        $sql = "UPDATE {$CFG->prefix}groupings\n                   SET courseid = (\n                        SELECT MAX(courseid)\n                          FROM {$CFG->prefix}groups_courses_groupings gcg\n                         WHERE gcg.groupingid = {$CFG->prefix}groupings.id)";
        execute_sql($sql);
    }
    /// Drop the old tables
    if ($result) {
        drop_table(new XMLDBTable('groups_courses_groups'));
        drop_table(new XMLDBTable('groups_courses_groupings'));
        drop_table(new XMLDBTable('groups_temp'));
        drop_table(new XMLDBTable('groups_members_temp'));
        unset_config('group_version');
    }
    return $result;
}
コード例 #26
0
ファイル: upgrade.php プロジェクト: sarahjcotton/mahara
function xmldb_artefact_comment_upgrade($oldversion = 0)
{
    $success = true;
    if ($oldversion < 2011011201) {
        $table = new XMLDBTable('artefact_comment_comment');
        $field = new XMLDBField('rating');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED);
        $success = $success && add_field($table, $field);
    }
    if ($oldversion < 2013072400) {
        $table = new XMLDBTable('artefact_comment_comment');
        $field = new XMLDBField('lastcontentupdate');
        $field->setAttributes(XMLDB_TYPE_DATETIME);
        $success = $success && add_field($table, $field);
        $success = $success && execute_sql('update {artefact_comment_comment} acc
            set lastcontentupdate = (
                select a.mtime
                from {artefact} a
                where a.id = acc.artefact
            )');
    }
    if ($oldversion < 2015081000) {
        // Set default maxindent for threaded comments
        set_config_plugin('artefact', 'comment', 'maxindent', 5);
    }
    if ($oldversion < 2015100100) {
        // Add new column '' to table artefact_comment_comment used for diplaying comments by threads
        $table = new XMLDBTable('artefact_comment_comment');
        $field = new XMLDBField('threadedposition');
        $field->setAttributes(XMLDB_TYPE_INTEGER, 4, null, null);
        if (!field_exists($table, $field)) {
            log_debug('Updating position for threaded comments');
            add_field($table, $field);
            $index = new XMLDBIndex('threadedpositionix');
            $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('threadedposition'));
            add_index($table, $index);
            // Update the threaded position for all exising comments
            // We assume there is no child comment in the database before this release
            // Comments on views
            $commented_views = get_column_sql('
                SELECT DISTINCT onview
                FROM {artefact_comment_comment}
                WHERE onview IS NOT NULL
                ORDER BY onview
            ');
            if ($commented_views) {
                $total = count($commented_views);
                $limit = 5000;
                $done = 0;
                foreach ($commented_views as $v) {
                    $comments = get_records_sql_array('
                        SELECT artefact
                        FROM {artefact_comment_comment}
                        WHERE onview = ?
                        ORDER BY artefact
                        ', array($v));
                    $p = 1;
                    foreach ($comments as $c) {
                        update_record('artefact_comment_comment', (object) array('threadedposition' => $p), array('artefact' => $c->artefact));
                        $p++;
                    }
                    $done++;
                    if ($done % $limit == 0 || $done >= $total) {
                        log_debug("Updating comments on views: {$done}/{$total}");
                        set_time_limit(30);
                    }
                }
            }
            // Comments on artefact
            $commented_views = get_column_sql('
                SELECT DISTINCT onartefact
                FROM {artefact_comment_comment}
                WHERE onartefact IS NOT NULL
                ORDER BY onartefact
            ');
            if ($commented_views) {
                $total = count($commented_views);
                $limit = 5000;
                $done = 0;
                foreach ($commented_views as $v) {
                    $comments = get_records_sql_array('
                        SELECT artefact
                        FROM {artefact_comment_comment}
                        WHERE onartefact = ?
                        ORDER BY artefact
                        ', array($v));
                    $p = 1;
                    foreach ($comments as $c) {
                        update_record('artefact_comment_comment', (object) array('threadedposition' => $p), array('artefact' => $c->artefact));
                        $p++;
                    }
                    $done++;
                    if ($done % $limit == 0 || $done >= $total) {
                        log_debug("Updating comments on artefacts: {$done}/{$total}");
                        set_time_limit(30);
                    }
                }
            }
        }
    }
    return $success;
}
コード例 #27
0
function xmldb_enrol_authorize_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2006111700) {
        $table = new XMLDBTable('enrol_authorize');
        if (!field_exists($table, new XMLDBField('refundinfo'))) {
            $field = new XMLDBField('cclastfour');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'paymentmethod');
            $result = $result && rename_field($table, $field, 'refundinfo');
        }
    }
    if ($result && $oldversion < 2006112900) {
        if (isset($CFG->an_login)) {
            if (empty($CFG->an_login)) {
                unset_config('an_login');
            } else {
                $result = $result && set_config('an_login', rc4encrypt($CFG->an_login), 'enrol/authorize') && unset_config('an_login');
            }
        }
        if (isset($CFG->an_tran_key)) {
            if (empty($CFG->an_tran_key)) {
                unset_config('an_tran_key');
            } else {
                $result = $result && set_config('an_tran_key', rc4encrypt($CFG->an_tran_key), 'enrol/authorize') && unset_config('an_tran_key');
            }
        }
        if (isset($CFG->an_password)) {
            if (empty($CFG->an_password)) {
                unset_config('an_password');
            } else {
                $result = $result && set_config('an_password', rc4encrypt($CFG->an_password), 'enrol/authorize') && unset_config('an_password');
            }
        }
    }
    if ($result && $oldversion < 2006112903) {
        /// enrol_authorize.transid
        /// Define index transid (not unique) to be dropped form enrol_authorize
        $table = new XMLDBTable('enrol_authorize');
        $index = new XMLDBIndex('transid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('transid'));
        drop_index($table, $index);
        /// Changing precision of field transid on table enrol_authorize to (20)
        $table = new XMLDBTable('enrol_authorize');
        $field = new XMLDBField('transid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '20', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'userid');
        change_field_precision($table, $field);
        /// Launch add index transid again
        $table = new XMLDBTable('enrol_authorize');
        $index = new XMLDBIndex('transid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('transid'));
        add_index($table, $index);
        /// enrol_authorize_refunds.transid
        /// Define index transid (not unique) to be dropped form enrol_authorize_refunds
        $table = new XMLDBTable('enrol_authorize_refunds');
        $index = new XMLDBIndex('transid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('transid'));
        drop_index($table, $index);
        /// Changing precision of field transid on table enrol_authorize_refunds to (20)
        $table = new XMLDBTable('enrol_authorize_refunds');
        $field = new XMLDBField('transid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '20', XMLDB_UNSIGNED, null, null, null, null, '0', 'amount');
        change_field_precision($table, $field);
        /// Launch add index transid again
        $table = new XMLDBTable('enrol_authorize_refunds');
        $index = new XMLDBIndex('transid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('transid'));
        add_index($table, $index);
    }
    return $result;
}
コード例 #28
0
function xmldb_main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $USER, $db;
    $result = true;
    if ($oldversion < 2006100401) {
        /// Only for those tracking Moodle 1.7 dev, others will have these dropped in moodle_install_roles()
        if (!empty($CFG->rolesactive)) {
            drop_table(new XMLDBTable('user_students'));
            drop_table(new XMLDBTable('user_teachers'));
            drop_table(new XMLDBTable('user_coursecreators'));
            drop_table(new XMLDBTable('user_admins'));
        }
        upgrade_main_savepoint($result, 2006100401);
    }
    if ($oldversion < 2006100601) {
        /// Disable the exercise module because it's unmaintained
        if ($module = get_record('modules', 'name', 'exercise')) {
            if ($module->visible) {
                // Hide/disable the module entry
                set_field('modules', 'visible', '0', 'id', $module->id);
                // Save existing visible state for all activities
                set_field('course_modules', 'visibleold', '1', 'visible', '1', 'module', $module->id);
                set_field('course_modules', 'visibleold', '0', 'visible', '0', 'module', $module->id);
                // Hide all activities
                set_field('course_modules', 'visible', '0', 'module', $module->id);
                require_once $CFG->dirroot . '/course/lib.php';
                rebuild_course_cache();
                // Rebuld cache for all modules because they might have changed
            }
        }
        upgrade_main_savepoint($result, 2006100601);
    }
    if ($oldversion < 2006101001) {
        /// Disable the LAMS module by default (if it is installed)
        if (count_records('modules', 'name', 'lams') && !count_records('lams')) {
            set_field('modules', 'visible', 0, 'name', 'lams');
            // Disable it by default
        }
        upgrade_main_savepoint($result, 2006101001);
    }
    if ($result && $oldversion < 2006102600) {
        /// Define fields to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('description');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'categoryid');
        $field1 = new XMLDBField('param1');
        $field1->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'defaultdata');
        $field2 = new XMLDBField('param2');
        $field2->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param1');
        $field3 = new XMLDBField('param3');
        $field3->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param2');
        $field4 = new XMLDBField('param4');
        $field4->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param3');
        $field5 = new XMLDBField('param5');
        $field5->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param4');
        /// Launch add fields
        $result = $result && add_field($table, $field);
        $result = $result && add_field($table, $field1);
        $result = $result && add_field($table, $field2);
        $result = $result && add_field($table, $field3);
        $result = $result && add_field($table, $field4);
        $result = $result && add_field($table, $field5);
        upgrade_main_savepoint($result, 2006102600);
    }
    if ($result && $oldversion < 2006112000) {
        /// Define field attachment to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('attachment');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'format');
        /// Launch add field attachment
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112000);
    }
    if ($result && $oldversion < 2006112200) {
        /// Define field imagealt to be added to user
        $table = new XMLDBTable('user');
        $field = new XMLDBField('imagealt');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'trustbitmask');
        /// Launch add field imagealt
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('user');
        $field = new XMLDBField('screenreader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'imagealt');
        /// Launch add field screenreader
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112200);
    }
    if ($oldversion < 2006120300) {
        /// Delete guest course section settings
        // following code can be executed repeatedly, such as when upgrading from 1.7.x - it is ok
        if ($guest = get_record('user', 'username', 'guest')) {
            execute_sql("DELETE FROM {$CFG->prefix}course_display where userid={$guest->id}", true);
        }
        upgrade_main_savepoint($result, 2006120300);
    }
    if ($oldversion < 2006120400) {
        /// Remove secureforms config setting
        execute_sql("DELETE FROM {$CFG->prefix}config where name='secureforms'", true);
        upgrade_main_savepoint($result, 2006120400);
    }
    if (!empty($CFG->rolesactive) && $oldversion < 2006120700) {
        // add moodle/user:viewdetails to all roles!
        // note: use of assign_capability() is discouraged in upgrade script!
        if ($roles = get_records('role')) {
            $context = get_context_instance(CONTEXT_SYSTEM);
            foreach ($roles as $roleid => $role) {
                assign_capability('moodle/user:viewdetails', CAP_ALLOW, $roleid, $context->id);
            }
        }
        upgrade_main_savepoint($result, 2006120700);
    }
    // Move the auth plugin settings into the config_plugin table
    if ($oldversion < 2007010300) {
        if ($CFG->auth == 'email') {
            set_config('registerauth', 'email');
        } else {
            set_config('registerauth', '');
        }
        $authplugins = get_list_of_plugins('auth');
        foreach ($CFG as $k => $v) {
            if (strpos($k, 'ldap_') === 0) {
                //upgrade nonstandard ldap settings
                $setting = substr($k, 5);
                if (set_config($setting, $v, "auth/ldap")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                continue;
            }
            if (strpos($k, 'auth_') !== 0) {
                continue;
            }
            $authsetting = substr($k, 5);
            foreach ($authplugins as $auth) {
                if (strpos($authsetting, $auth) !== 0) {
                    continue;
                }
                $setting = substr($authsetting, strlen($auth));
                if (set_config($setting, $v, "auth/{$auth}")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                break;
                // don't check the rest of the auth plugin names
            }
        }
        upgrade_main_savepoint($result, 2007010300);
    }
    if ($oldversion < 2007010301) {
        //
        // Core MNET tables
        //
        $table = new XMLDBTable('mnet_host');
        $table->comment = 'Information about the local and remote hosts for RPC';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f->comment = 'Unique Host ID';
        $f = $table->addFieldInfo('deleted', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('wwwroot', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('ip_address', XMLDB_TYPE_CHAR, '39', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key_expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('transport', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('portno', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_connect_time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_log_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_host2service');
        $table->comment = 'Information about the services for a given host';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('publish', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('subscribe', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_serviceid', XMLDB_INDEX_UNIQUE, array('hostid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_log');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('ip', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('coursename', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('module', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('host_user_course', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'userid', 'course'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_rpc');
        $table->comment = 'Functions or methods that we may publish or subscribe to';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('function_name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_path', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent_type', XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enabled', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('help', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('profile', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('enabled_xpath', XMLDB_INDEX_NOTUNIQUE, array('enabled', 'xmlrpc_path'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service');
        $table->comment = 'A service is a group of functions';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('description', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('apiversion', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('offer', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service2rpc');
        $table->comment = 'Group functions or methods under a service';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rpcid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('unique', XMLDB_INDEX_UNIQUE, array('rpcid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        //
        // Prime MNET configuration entries -- will be needed later by auth/mnet
        //
        include_once $CFG->dirroot . '/mnet/lib.php';
        $env = new mnet_environment();
        $env->init();
        unset($env);
        // add mnethostid to user-
        $table = new XMLDBTable('user');
        $field = new XMLDBField('mnethostid');
        $field->setType(XMLDB_TYPE_INTEGER);
        $field->setLength(10);
        $field->setNotNull(true);
        $field->setSequence(null);
        $field->setEnum(null);
        $field->setDefault('0');
        $field->setPrevious("deleted");
        $field->setNext("username");
        $result = $result && add_field($table, $field);
        // The default mnethostid is zero... we need to update this for all
        // users of the local IdP service.
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'mnethostid', '0');
        $index = new XMLDBIndex('username');
        $index->setUnique(true);
        $index->setFields(array('username'));
        drop_index($table, $index);
        $index->setFields(array('mnethostid', 'username'));
        if (!add_index($table, $index)) {
            notify(get_string('duplicate_usernames', 'mnet', 'http://docs.moodle.org/en/DuplicateUsernames'));
        }
        unset($table, $field, $index);
        /**
         ** auth/mnet tables
         **/
        $table = new XMLDBTable('mnet_session');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('useragent', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('confirm_timeout', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('session_id', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('token', XMLDB_INDEX_UNIQUE, array('token'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_sso_access_control');
        $table->comment = 'Users by host permitted (or not) to login from a remote provider';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnet_host_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('access', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, 'allow');
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('mnethostid_username', XMLDB_INDEX_UNIQUE, array('mnet_host_id', 'username'));
        // Create the table
        $result = $result && create_table($table);
        if (empty($USER->mnet_host_id)) {
            $USER->mnet_host_id = $CFG->mnet_localhost_id;
            // Something for the current user to prevent warnings
        }
        /**
         ** enrol/mnet tables
         **/
        $table = new XMLDBTable('mnet_enrol_course');
        $table->comment = 'Information about courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cat_description', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '254', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('summary', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('startdate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cost', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('currency', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('defaultroleid', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('defaultrolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_remoteid', XMLDB_INDEX_UNIQUE, array('hostid', 'remoteid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_enrol_assignments');
        $table->comment = 'Information about enrolments on courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enroltime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('enroltype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_courseid', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'courseid'));
        $table->addIndexInfo('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Create the table
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007010301);
    }
    if ($result && $oldversion < 2007010404) {
        /// Define field shortname to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, 'shortname', 'id');
        /// Launch add field shortname
        $result = $result && add_field($table, $field);
        /// Changing type of field name on table user_info_field to text
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null, 'shortname');
        /// Launch change of type for field name
        $result = $result && change_field_type($table, $field);
        /// For existing fields use 'name' as the 'shortname' entry
        if ($fields = get_records_select('user_info_field', '', '', 'id, name')) {
            foreach ($fields as $field) {
                $field->shortname = clean_param($field->name, PARAM_ALPHANUM);
                $result && update_record('user_info_field', $field);
            }
        }
        upgrade_main_savepoint($result, 2007010404);
    }
    if ($result && $oldversion < 2007011501) {
        if (!empty($CFG->enablerecordcache) && empty($CFG->rcache) && empty($CFG->cachetype) && empty($CFG->intcachemax)) {
            set_config('cachetype', 'internal');
            set_config('rcache', true);
            set_config('intcachemax', $CFG->enablerecordcache);
            unset_config('enablerecordcache');
            unset($CFG->enablerecordcache);
        }
        upgrade_main_savepoint($result, 2007011501);
    }
    if ($result && $oldversion < 2007012100) {
        /// Some old PG servers have user->firstname & user->lastname with 30cc. They must be 100cc.
        /// Fixing that conditionally. MDL-7110
        if ($CFG->dbfamily == 'postgres') {
            /// Get Metadata from user table
            $cols = array_change_key_case($db->MetaColumns($CFG->prefix . 'user'), CASE_LOWER);
            /// Process user->firstname if needed
            if ($col = $cols['firstname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field firstname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('firstname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'idnumber');
                    /// Launch change of precision for field firstname
                    $result = $result && change_field_precision($table, $field);
                }
            }
            /// Process user->lastname if needed
            if ($col = $cols['lastname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field lastname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('lastname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'firstname');
                    /// Launch change of precision for field lastname
                    $result = $result && change_field_precision($table, $field);
                }
            }
        }
        upgrade_main_savepoint($result, 2007012100);
    }
    if ($result && $oldversion < 2007012101) {
        /// Changing precision of field lang on table course to (30)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null, 'groupmodeforce');
        /// Launch change of precision for field course->lang
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field lang on table user to (30)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en', 'country');
        /// Launch change of precision for field user->lang
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007012101);
    }
    if ($result && $oldversion < 2007012400) {
        /// Rename field access on table mnet_sso_access_control to accessctrl
        $table = new XMLDBTable('mnet_sso_access_control');
        $field = new XMLDBField('access');
        $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'allow', 'mnet_host_id');
        /// Launch rename field accessctrl
        $result = $result && rename_field($table, $field, 'accessctrl');
        upgrade_main_savepoint($result, 2007012400);
    }
    if ($result && $oldversion < 2007012500) {
        execute_sql("DELETE FROM {$CFG->prefix}user WHERE username='******'", true);
        upgrade_main_savepoint($result, 2007012500);
    }
    if ($result && $oldversion < 2007020400) {
        /// Only for MySQL and PG, declare the user->ajax field as not null. MDL-8421.
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            /// Changing nullability of field ajax on table user to not null
            $table = new XMLDBTable('user');
            $field = new XMLDBField('ajax');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'htmleditor');
            /// Launch change of nullability for field ajax
            $result = $result && change_field_notnull($table, $field);
        }
        upgrade_main_savepoint($result, 2007020400);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007021401) {
        /// create default logged in user role if not present - upgrade rom 1.7.x
        if (empty($CFG->defaultuserroleid) or empty($CFG->guestroleid) or $CFG->defaultuserroleid == $CFG->guestroleid) {
            if (!get_records('role', 'shortname', 'user')) {
                $userroleid = create_role(addslashes(get_string('authenticateduser')), 'user', addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
                if ($userroleid) {
                    reset_role_capabilities($userroleid);
                    set_config('defaultuserroleid', $userroleid);
                }
            }
        }
        upgrade_main_savepoint($result, 2007021401);
    }
    if ($result && $oldversion < 2007021501) {
        /// delete removed setting from config
        unset_config('tabselectedtofront');
        upgrade_main_savepoint($result, 2007021501);
    }
    if ($result && $oldversion < 2007032200) {
        /// Define table role_sortorder to be created
        $table = new XMLDBTable('role_sortorder');
        /// Adding fields to table role_sortorder
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortoder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table role_sortorder
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        $table->addKeyInfo('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table role_sortorder
        $table->addIndexInfo('userid-roleid-contextid', XMLDB_INDEX_UNIQUE, array('userid', 'roleid', 'contextid'));
        /// Launch create table for role_sortorder
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007032200);
    }
    /// code to change lenghen tag field to 255, MDL-9095
    if ($result && $oldversion < 2007040400) {
        /// Define index text (not unique) to be dropped form tags
        $table = new XMLDBTable('tags');
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch drop index text
        $result = $result && drop_index($table, $index);
        $field = new XMLDBField('text');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'userid');
        /// Launch change of type for field text
        $result = $result && change_field_type($table, $field);
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch add index text
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007040400);
    }
    if ($result && $oldversion < 2007041100) {
        /// Define field idnumber to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'section');
        /// Launch add field idnumber
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007041100);
    }
    /* Changes to the custom profile menu type - store values rather than indices.
       We could do all this with one tricky SQL statement but it's a one-off so no
       harm in using PHP loops */
    if ($result && $oldversion < 2007041600) {
        /// Get the menu fields
        if ($fields = get_records('user_info_field', 'datatype', 'menu')) {
            foreach ($fields as $field) {
                /// Get user data for the menu field
                if ($data = get_records('user_info_data', 'fieldid', $field->id)) {
                    /// Get the menu options
                    $options = explode("\n", $field->param1);
                    foreach ($data as $d) {
                        $key = array_search($d->data, $options);
                        /// If the data is an integer and is not one of the options,
                        /// set the respective option value
                        if (is_int($d->data) and ($key === NULL or $key === false) and isset($options[$d->data])) {
                            $d->data = $options[$d->data];
                            $result = $result && update_record('user_info_data', $d);
                        }
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007041600);
    }
    /// adding new gradebook tables
    if ($result && $oldversion < 2007041800) {
        /// Define table events_handlers to be created
        $table = new XMLDBTable('events_handlers');
        /// Adding fields to table events_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventname', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlermodule', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfunction', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        /// Adding keys to table events_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table events_handlers
        $table->addIndexInfo('eventname-handlermodule', XMLDB_INDEX_UNIQUE, array('eventname', 'handlermodule'));
        /// Launch create table for events_handlers
        $result = $result && create_table($table);
        /// Define table events_queue to be created
        $table = new XMLDBTable('events_queue');
        /// Adding fields to table events_queue
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventdata', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('schedule', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('stackdump', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch create table for events_queue
        $result = $result && create_table($table);
        /// Define table events_queue_handlers to be created
        $table = new XMLDBTable('events_queue_handlers');
        /// Adding fields to table events_queue_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('queuedeventid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('status', XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null);
        $table->addFieldInfo('errormessage', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('queuedeventid', XMLDB_KEY_FOREIGN, array('queuedeventid'), 'events_queue', array('id'));
        $table->addKeyInfo('handlerid', XMLDB_KEY_FOREIGN, array('handlerid'), 'events_handlers', array('id'));
        /// Launch create table for events_queue_handlers
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007041800);
    }
    if ($result && $oldversion < 2007043001) {
        /// Define field schedule to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('schedule');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'handlerfunction');
        /// Launch add field schedule
        $result = $result && add_field($table, $field);
        /// Define field status to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('status');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'schedule');
        /// Launch add field status
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007043001);
    }
    if ($result && $oldversion < 2007050201) {
        /// Define field theme to be added to course_categories
        $table = new XMLDBTable('course_categories');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'path');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007050201);
    }
    if ($result && $oldversion < 2007051100) {
        /// Define field forceunique to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('forceunique');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'visible');
        /// Launch add field forceunique
        $result = $result && add_field($table, $field);
        /// Define field signup to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('signup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'forceunique');
        /// Launch add field signup
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007051100);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007051801) {
        // Get the role id of the "Auth. User" role and check if the default role id is different
        // note: use of assign_capability() is discouraged in upgrade script!
        $userrole = get_record('role', 'shortname', 'user');
        $defaultroleid = $CFG->defaultuserroleid;
        if ($defaultroleid != $userrole->id) {
            //  Add in the new moodle/my:manageblocks capibility to the default user role
            $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
            assign_capability('moodle/my:manageblocks', CAP_ALLOW, $defaultroleid, $context->id);
        }
        upgrade_main_savepoint($result, 2007051801);
    }
    if ($result && $oldversion < 2007052200) {
        /// Define field schedule to be dropped from events_queue
        $table = new XMLDBTable('events_queue');
        $field = new XMLDBField('schedule');
        /// Launch drop field stackdump
        $result = $result && drop_field($table, $field);
        upgrade_main_savepoint($result, 2007052200);
    }
    if ($result && $oldversion < 2007052300) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype();
        upgrade_main_savepoint($result, 2007052300);
    }
    if ($result && $oldversion < 2007060500) {
        /// Define field usermodified to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('usermodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'created');
        /// Launch add field usermodified
        $result = $result && add_field($table, $field);
        /// Define key usermodified (foreign) to be added to post
        $table = new XMLDBTable('post');
        $key = new XMLDBKey('usermodified');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch add key usermodified
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007060500);
    }
    if ($result && $oldversion < 2007070603) {
        // Small update of guest user to be 100% sure it has the correct mnethostid (MDL-10375)
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'username', 'guest');
        upgrade_main_savepoint($result, 2007070603);
    }
    if ($result && $oldversion < 2007071400) {
        /**
         ** mnet application table
         **/
        $table = new XMLDBTable('mnet_application');
        $table->comment = 'Information about applications on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('display_name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_server_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sso_land_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        // Insert initial applications (moodle and mahara)
        $application = new stdClass();
        $application->name = 'moodle';
        $application->display_name = 'Moodle';
        $application->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
        $application->sso_land_url = '/auth/mnet/land.php';
        if ($result) {
            $newid = insert_record('mnet_application', $application, false);
        }
        $application = new stdClass();
        $application->name = 'mahara';
        $application->display_name = 'Mahara';
        $application->xmlrpc_server_url = '/api/xmlrpc/server.php';
        $application->sso_land_url = '/auth/xmlrpc/land.php';
        $result = $result && insert_record('mnet_application', $application, false);
        // New mnet_host->applicationid field
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, $newid, 'last_log_id');
        $result = $result && add_field($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007071400);
    }
    if ($result && $oldversion < 2007071607) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype_config_string();
        upgrade_main_savepoint($result, 2007071607);
    }
    if ($result && $oldversion < 2007072200) {
        /// Remove all grade tables used in development phases - we need new empty tables for final gradebook upgrade
        $tables = array('grade_categories', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses', 'grade_history', 'grade_import_newitem', 'grade_import_values');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        $tables = array('grade_categories_history', 'grade_items_history', 'grade_grades_history', 'grade_grades_text_history', 'grade_scale_history', 'grade_outcomes_history');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define table grade_outcomes to be created
        $table = new XMLDBTable('grade_outcomes');
        /// Adding fields to table grade_outcomes
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_outcomes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch create table for grade_outcomes
        $result = $result && create_table($table);
        /// Define table grade_categories to be created
        $table = new XMLDBTable('grade_categories');
        /// Adding fields to table grade_categories
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_categories
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        /// Launch create table for grade_categories
        $result = $result && create_table($table);
        /// Define table grade_items to be created
        $table = new XMLDBTable('grade_items');
        /// Adding fields to table grade_items
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_items
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        $table->addIndexInfo('itemtype-needsupdate', XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        $table->addIndexInfo('gradetype', XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        /// Launch create table for grade_items
        $result = $result && create_table($table);
        /// Define table grade_grades to be created
        $table = new XMLDBTable('grade_grades');
        /// Adding fields to table grade_grades
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_grades
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        /// Launch create table for grade_grades
        $result = $result && create_table($table);
        /// Define table grade_outcomes_history to be created
        $table = new XMLDBTable('grade_outcomes_history');
        /// Adding fields to table grade_outcomes_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_outcomes_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_outcomes_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_outcomes_history
        $result = $result && create_table($table);
        /// Define table grade_categories_history to be created
        $table = new XMLDBTable('grade_categories_history');
        /// Adding fields to table grade_categories_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_categories_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_categories', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_categories_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_categories_history
        $result = $result && create_table($table);
        /// Define table grade_items_history to be created
        $table = new XMLDBTable('grade_items_history');
        /// Adding fields to table grade_items_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_items_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_items', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_items_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_items_history
        $result = $result && create_table($table);
        /// Define table grade_grades_history to be created
        $table = new XMLDBTable('grade_grades_history');
        /// Adding fields to table grade_grades_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_grades_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_grades', array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_grades_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_grades_history
        $result = $result && create_table($table);
        /// upgrade the old 1.8 gradebook - migrade data into new grade tables
        if ($result) {
            require_once $CFG->libdir . '/db/upgradelib.php';
            if ($rs = get_recordset('course')) {
                while ($course = rs_fetch_next_record($rs)) {
                    // this function uses SQL only, it must not be changed after 1.9 goes stable!!
                    if (!upgrade_18_gradebook($course->id)) {
                        $result = false;
                        break;
                    }
                }
                rs_close($rs);
            }
        }
        upgrade_main_savepoint($result, 2007072200);
    }
    if ($result && $oldversion < 2007072400) {
        /// Dropping one DEFAULT in a TEXT column. It's was only one remaining
        /// since Moodle 1.7, so new servers won't have those anymore.
        /// Changing the default of field sessdata on table sessions2 to drop it
        $table = new XMLDBTable('sessions2');
        $field = new XMLDBField('sessdata');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'modified');
        /// Launch change of default for field sessdata
        $result = $result && change_field_default($table, $field);
        upgrade_main_savepoint($result, 2007072400);
    }
    if ($result && $oldversion < 2007073100) {
        /// Define table grade_outcomes_courses to be created
        $table = new XMLDBTable('grade_outcomes_courses');
        /// Adding fields to table grade_outcomes_courses
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_outcomes_courses
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid-outcomeid', XMLDB_KEY_UNIQUE, array('courseid', 'outcomeid'));
        /// Launch create table for grade_outcomes_courses
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073100);
    }
    if ($result && $oldversion < 2007073101) {
        // Add new tag tables
        /// Define table tag to be created
        $table = new XMLDBTable('tag');
        /// Adding fields to table tag
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('tagtype', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('flag', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table tag
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag
        $table->addIndexInfo('name', XMLDB_INDEX_UNIQUE, array('name'));
        /// Launch create table for tag
        $result = $result && create_table($table);
        /// Define table tag_correlation to be created
        $table = new XMLDBTable('tag_correlation');
        /// Adding fields to table tag_correlation
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('correlatedtags', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_correlation
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_correlation
        $table->addIndexInfo('tagid', XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch create table for tag_correlation
        $result = $result && create_table($table);
        /// Define table tag_instance to be created
        $table = new XMLDBTable('tag_instance');
        /// Adding fields to table tag_instance
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_instance
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_instance
        $table->addIndexInfo('tagiditem', XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch create table for tag_instance
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073101);
    }
    if ($result && $oldversion < 2007073103) {
        /// Define field rawname to be added to tag
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('rawname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'name');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007073103);
    }
    if ($result && $oldversion < 2007073105) {
        /// Define field description to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_outcomes_history');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007073105);
    }
    // adding unique contraint on (courseid,shortname) of an outcome
    if ($result && $oldversion < 2007080100) {
        /// Define key courseid-shortname (unique) to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $key = new XMLDBKey('courseid-shortname');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('courseid', 'shortname'));
        /// Launch add key courseid-shortname
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007080100);
    }
    /// originally there was supportname and supportemail upgrade code - this is handled in upgradesettings.php instead
    if ($result && $oldversion < 2007080202) {
        /// Define index tagiditem (not unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        drop_index($table, $index);
        /// Define index tagiditem (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch add index tagiditem
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007080202);
    }
    if ($result && $oldversion < 2007080300) {
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007080300);
    }
    if ($result && $oldversion < 2007080800) {
        /// Normalize course->shortname MDL-10026
        /// Changing precision of field shortname on table course to (100)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'fullname');
        /// Launch change of precision for field shortname
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007080800);
    }
    if ($result && $oldversion < 2007080900) {
        /// Add context.path & index
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('context');
        $index = new XMLDBIndex('path');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('path'));
        $result = $result && add_index($table, $index);
        /// Add context.depth
        $table = new XMLDBTable('context');
        $field = new XMLDBField('depth');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'path');
        $result = $result && add_field($table, $field);
        /// make sure the system context has proper data
        get_system_context(false);
        upgrade_main_savepoint($result, 2007080900);
    }
    if ($result && $oldversion < 2007080903) {
        /// Define index
        $table = new XMLDBTable('grade_grades');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index itemtype-needsupdate (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('itemtype-needsupdate');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        if (!index_exists($table, $index)) {
            /// Launch add index itemtype-needsupdate
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('gradetype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007080903);
    }
    if ($result && $oldversion < 2007081000) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_upgrade_context_etc();
        upgrade_main_savepoint($result, 2007081000);
    }
    if ($result && $oldversion < 2007081302) {
        require_once $CFG->libdir . '/db/upgradelib.php';
        if (table_exists(new XMLDBTable('groups_groupings'))) {
            /// IF 'groups_groupings' table exists, this is for 1.8.* only.
            $result = $result && upgrade_18_groups();
        } else {
            /// ELSE, 1.7.*/1.6.*/1.5.* - create 'groupings' and 'groupings_groups' + rename password to enrolmentkey
            $result = $result && upgrade_17_groups();
        }
        /// For both 1.8.* and 1.7.*/1.6.*..
        // delete not used fields
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('theme');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('lang');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        /// Add groupingid field/f.key to 'course' table.
        $table = new XMLDBTable('course');
        $field = new XMLDBField('defaultgroupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmodeforce');
        $result = $result && add_field($table, $field);
        /// Add grouping ID, grouponly field/f.key to 'course_modules' table.
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmode');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupmembersonly');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupingid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $key = new XMLDBKey('groupingid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007081302);
    }
    if ($result && $oldversion < 2007082300) {
        /// Define field ordering to be added to tag_instance table
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'itemid');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082300);
    }
    if ($result && $oldversion < 2007082700) {
        /// Define field timemodified to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'ordering');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082700);
    }
    /// migrate all tags table to tag - this code MUST use SQL only,
    /// because if the db structure changes the library functions will fail in future
    if ($result && $oldversion < 2007082701) {
        $tagrefs = array();
        // $tagrefs[$oldtagid] = $newtagid
        if ($rs = get_recordset('tags')) {
            $db->debug = false;
            while ($oldtag = rs_fetch_next_record($rs)) {
                $raw_normalized = clean_param($oldtag->text, PARAM_TAG);
                $normalized = moodle_strtolower($raw_normalized);
                // if this tag does not exist in tag table yet
                if (!($newtag = get_record('tag', 'name', $normalized, '', '', '', '', 'id'))) {
                    $itag = new object();
                    $itag->name = $normalized;
                    $itag->rawname = $raw_normalized;
                    $itag->userid = $oldtag->userid;
                    $itag->timemodified = time();
                    $itag->descriptionformat = 0;
                    // default format
                    if ($oldtag->type == 'official') {
                        $itag->tagtype = 'official';
                    } else {
                        $itag->tagtype = 'default';
                    }
                    if ($idx = insert_record('tag', $itag)) {
                        $tagrefs[$oldtag->id] = $idx;
                    }
                    // if this tag is already used by tag table
                } else {
                    $tagrefs[$oldtag->id] = $newtag->id;
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        // fetch all the tag instances and migrate them as well
        if ($rs = get_recordset('blog_tag_instance')) {
            $db->debug = false;
            while ($blogtag = rs_fetch_next_record($rs)) {
                if (array_key_exists($blogtag->tagid, $tagrefs)) {
                    $tag_instance = new object();
                    $tag_instance->tagid = $tagrefs[$blogtag->tagid];
                    $tag_instance->itemtype = 'blog';
                    $tag_instance->itemid = $blogtag->entryid;
                    $tag_instance->ordering = 1;
                    // does not matter much, because originally there was no ordering in blogs
                    $tag_instance->timemodified = time();
                    insert_record('tag_instance', $tag_instance);
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        unset($tagrefs);
        // release memory
        $table = new XMLDBTable('tags');
        drop_table($table);
        $table = new XMLDBTable('blog_tag_instance');
        drop_table($table);
        upgrade_main_savepoint($result, 2007082701);
    }
    /// MDL-11015, MDL-11016
    if ($result && $oldversion < 2007082800) {
        /// Changing type of field userid on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field userid
        $result = $result && change_field_type($table, $field);
        /// Changing type of field descriptionformat on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('descriptionformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'description');
        /// Launch change of type for field descriptionformat
        $result = $result && change_field_type($table, $field);
        /// Define key userid (foreign) to be added to tag
        $table = new XMLDBTable('tag');
        $key = new XMLDBKey('userid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch add key userid
        $result = $result && add_key($table, $key);
        /// Define index tagiditem (unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_instance to int
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        /// Changing sign of field itemid on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('itemid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'itemtype');
        /// Launch change of sign for field itemid
        $result = $result && change_field_unsigned($table, $field);
        /// Changing sign of field ordering on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'itemid');
        /// Launch change of sign for field ordering
        $result = $result && change_field_unsigned($table, $field);
        /// Define index itemtype-itemid-tagid (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('itemtype-itemid-tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid'));
        /// Launch add index itemtype-itemid-tagid
        $result = $result && add_index($table, $index);
        /// Define index tagid (unique) to be dropped form tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $index = new XMLDBIndex('tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch drop index tagid
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_correlation to int
        $table = new XMLDBTable('tag_correlation');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082800);
    }
    if ($result && $oldversion < 2007082801) {
        /// Define table user_private_key to be created
        $table = new XMLDBTable('user_private_key');
        /// Adding fields to table user_private_key
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('script', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iprestriction', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('validuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table user_private_key
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table user_private_key
        $table->addIndexInfo('script-value', XMLDB_INDEX_NOTUNIQUE, array('script', 'value'));
        /// Launch create table for user_private_key
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007082801);
    }
    /// Going to modify the applicationid from int(1) to int(10). Dropping and
    /// re-creating the associated keys/indexes is mandatory to be cross-db. MDL-11042
    if ($result && $oldversion < 2007082803) {
        /// Define key applicationid (foreign) to be dropped form mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch drop key applicationid
        $result = $result && drop_key($table, $key);
        /// Changing type of field applicationid on table mnet_host to int
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'last_log_id');
        /// Launch change of type for field applicationid
        $result = $result && change_field_type($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082803);
    }
    if ($result && $oldversion < 2007090503) {
        /// Define field aggregatesubcats to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregatesubcats to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// upgrade path in grade_categrories table - now using slash on both ends
        $concat = sql_concat('path', "'/'");
        $sql = "UPDATE {$CFG->prefix}grade_categories SET path = {$concat} WHERE path NOT LIKE '/%/'";
        execute_sql($sql, true);
        /// convert old aggregation constants if needed
        for ($i = 0; $i <= 12; $i = $i + 2) {
            $j = $i + 1;
            $sql = "UPDATE {$CFG->prefix}grade_categories SET aggregation = {$i}, aggregateonlygraded = 1 WHERE aggregation = {$j}";
            execute_sql($sql, true);
        }
        upgrade_main_savepoint($result, 2007090503);
    }
    /// To have UNIQUE indexes over NULLable columns isn't cross-db at all
    /// so we create a non unique index and programatically enforce uniqueness
    if ($result && $oldversion < 2007090600) {
        /// Define index idnumber (unique) to be dropped form course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        $result = $result && drop_index($table, $index);
        /// Define index idnumber-course (not unique) to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'course'));
        /// Launch add index idnumber-course
        $result = $result && add_index($table, $index);
        /// Define index idnumber-courseid (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('idnumber-courseid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'courseid'));
        /// Launch add index idnumber-courseid
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007090600);
    }
    /// Create the permanent context_temp table to be used by build_context_path()
    if ($result && $oldversion < 2007092001) {
        /// Define table context_temp to be created
        $table = new XMLDBTable('context_temp');
        /// Adding fields to table context_temp
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table context_temp
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for context_temp
        $result = $result && create_table($table);
        /// make sure category depths, parents and paths are ok, categories from 1.5 may not be properly initialized (MDL-12585)
        upgrade_fix_category_depths();
        /// Recalculate depths, paths and so on
        if (!empty($CFG->rolesactive)) {
            cleanup_contexts();
            // make sure all course, category and user contexts exist - we need it for grade letter upgrade, etc.
            create_contexts(CONTEXT_COURSE, false, true);
            create_contexts(CONTEXT_USER, false, true);
            // we need all contexts path/depths filled properly
            build_context_path(true, true);
            load_all_capabilities();
        } else {
            // upgrade from 1.6 - build all contexts
            create_contexts(null, true, true);
        }
        upgrade_main_savepoint($result, 2007092001);
    }
    /**
     * Merging of grade_grades_text back into grade_grades
     */
    if ($result && $oldversion < 2007092002) {
        /// Define field feedback to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        /// Define field feedback to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_grades_text');
        if ($result and table_exists($table)) {
            //migrade existing data into grade_grades table - this is slow but works for all dbs,
            //it will be executed on development sites only
            $fields = array('feedback', 'information');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = (\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id)";
                $result = execute_sql($sql) && $result;
            }
            $fields = array('feedbackformat', 'informationformat');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = COALESCE((\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id), 0)";
                $result = execute_sql($sql) && $result;
            }
            if ($result) {
                $tables = array('grade_grades_text', 'grade_grades_text_history');
                foreach ($tables as $table) {
                    $table = new XMLDBTable($table);
                    if (table_exists($table)) {
                        drop_table($table);
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007092002);
    }
    if ($result && $oldversion < 2007092803) {
        /// Remove obsoleted unit tests tables - they will be recreated automatically
        $tables = array('grade_categories', 'scale', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses');
        foreach ($tables as $tablename) {
            $table = new XMLDBTable('unittest_' . $tablename);
            if (table_exists($table)) {
                drop_table($table);
            }
            $table = new XMLDBTable('unittest_' . $tablename . '_history');
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define field display to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
        }
        /// Define field display to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// Define field decimals to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
            $result = $result && change_field_notnull($table, $field);
        }
        /// Define field decimals to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// fix incorrect -1 default for grade_item->display
        execute_sql("UPDATE {$CFG->prefix}grade_items SET display=0 WHERE display=-1");
        upgrade_main_savepoint($result, 2007092803);
    }
    /// migrade grade letters - we can not do this in normal grades upgrade becuase we need all course contexts
    if ($result && $oldversion < 2007092806) {
        require_once $CFG->libdir . '/db/upgradelib.php';
        $result = upgrade_18_letters();
        /// Define index contextidlowerboundary (not unique) to be added to grade_letters
        $table = new XMLDBTable('grade_letters');
        $index = new XMLDBIndex('contextid-lowerboundary');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
        /// Launch add index contextidlowerboundary
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007092806);
    }
    if ($result && $oldversion < 2007100100) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        /// Adding fields to table cache_flags
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flagtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table cache_flags
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /*
         * Note: mysql can not create indexes on text fields larger than 333 chars! 
         */
        /// Adding indexes to table cache_flags
        $table->addIndexInfo('flagtype', XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        $table->addIndexInfo('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        /// Launch create table for cache_flags
        if (!table_exists($table)) {
            $result = $result && create_table($table);
        }
        upgrade_main_savepoint($result, 2007100100);
    }
    if ($oldversion < 2007100300) {
        /// MNET stuff for roaming theme
        /// Define field force_theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('force_theme');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'last_log_id');
        /// Launch add field force_theme
        $result = $result && add_field($table, $field);
        /// Define field theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'force_theme');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007100300);
    }
    if ($result && $oldversion < 2007100301) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('typename');
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('flagtype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('name');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007100301);
    }
    if ($result && $oldversion < 2007100303) {
        /// Changing nullability of field summary on table course to null
        $table = new XMLDBTable('course');
        $field = new XMLDBField('summary');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'idnumber');
        /// Launch change of nullability for field summary
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100303);
    }
    if ($result && $oldversion < 2007100500) {
        /// for dev sites - it is ok to do this repeatedly
        /// Changing nullability of field path on table context to null
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        /// Launch change of nullability for field path
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100500);
    }
    if ($result && $oldversion < 2007100700) {
        /// first drop existing tables - we do not need any data from there
        $table = new XMLDBTable('grade_import_values');
        if (table_exists($table)) {
            drop_table($table);
        }
        $table = new XMLDBTable('grade_import_newitem');
        if (table_exists($table)) {
            drop_table($table);
        }
        /// Define table grade_import_newitem to be created
        $table = new XMLDBTable('grade_import_newitem');
        /// Adding fields to table grade_import_newitem
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_import_newitem
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_newitem
        $result = $result && create_table($table);
        /// Define table grade_import_values to be created
        $table = new XMLDBTable('grade_import_values');
        /// Adding fields to table grade_import_values
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('newgradeitem', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_import_values
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('newgradeitem', XMLDB_KEY_FOREIGN, array('newgradeitem'), 'grade_import_newitem', array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_values
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100700);
    }
    /// dropping context_rel table - not used anymore
    if ($result && $oldversion < 2007100800) {
        /// Define table context_rel to be dropped
        $table = new XMLDBTable('context_rel');
        /// Launch drop table for context_rel
        if (table_exists($table)) {
            drop_table($table);
        }
        upgrade_main_savepoint($result, 2007100800);
    }
    /// Truncate the text_cahe table and add new index
    if ($result && $oldversion < 2007100802) {
        /// Truncate the cache_text table
        execute_sql("TRUNCATE TABLE {$CFG->prefix}cache_text", true);
        /// Define index timemodified (not unique) to be added to cache_text
        $table = new XMLDBTable('cache_text');
        $index = new XMLDBIndex('timemodified');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch add index timemodified
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007100802);
    }
    /// newtable for gradebook settings per course
    if ($result && $oldversion < 2007100803) {
        /// Define table grade_settings to be created
        $table = new XMLDBTable('grade_settings');
        /// Adding fields to table grade_settings
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_settings
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        /// Adding indexes to table grade_settings
        $table->addIndexInfo('courseid-name', XMLDB_INDEX_UNIQUE, array('courseid', 'name'));
        /// Launch create table for grade_settings
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100803);
    }
    /// cleanup in user_lastaccess
    if ($result && $oldversion < 2007100902) {
        $sql = "DELETE\n                  FROM {$CFG->prefix}user_lastaccess\n                 WHERE NOT EXISTS (SELECT 'x'\n                                    FROM {$CFG->prefix}course c\n                                   WHERE c.id = {$CFG->prefix}user_lastaccess.courseid)";
        execute_sql($sql);
        upgrade_main_savepoint($result, 2007100902);
    }
    /// drop old gradebook tables
    if ($result && $oldversion < 2007100903) {
        $tables = array('grade_category', 'grade_item', 'grade_letter', 'grade_preferences', 'grade_exceptions');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        upgrade_main_savepoint($result, 2007100903);
    }
    if ($result && $oldversion < 2007101500 && !file_exists($CFG->dataroot . '/user')) {
        // Get list of users by browsing moodledata/user
        $oldusersdir = $CFG->dataroot . '/users';
        $folders = get_directory_list($oldusersdir, '', false, true, false);
        foreach ($folders as $userid) {
            $olddir = $oldusersdir . '/' . $userid;
            $files = get_directory_list($olddir);
            if (empty($files)) {
                continue;
            }
            // Create new user directory
            if (!($newdir = make_user_directory($userid))) {
                $result = false;
                break;
            }
            // Move contents of old directory to new one
            if (file_exists($olddir) && file_exists($newdir)) {
                foreach ($files as $file) {
                    copy($olddir . '/' . $file, $newdir . '/' . $file);
                }
            } else {
                notify("Could not move the contents of {$olddir} into {$newdir}!");
                $result = false;
                break;
            }
        }
        // Leave a README in old users directory
        $readmefilename = $oldusersdir . '/README.txt';
        if ($handle = fopen($readmefilename, 'w+b')) {
            if (!fwrite($handle, get_string('olduserdirectory'))) {
                // Could not write to the readme file. No cause for huge concern
                notify("Could not write to the README.txt file in {$readmefilename}.");
            }
            fclose($handle);
        } else {
            // Could not create the readme file. No cause for huge concern
            notify("Could not create the README.txt file in {$readmefilename}.");
        }
    }
    if ($result && $oldversion < 2007101502) {
        /// try to remove duplicate entries
        $SQL = "SELECT userid, itemid, COUNT(*)\n               FROM {$CFG->prefix}grade_grades\n               GROUP BY userid, itemid\n               HAVING COUNT( * ) >1";
        // duplicates found
        if ($rs = get_recordset_sql($SQL)) {
            if ($rs && $rs->RecordCount() > 0) {
                while ($dup = rs_fetch_next_record($rs)) {
                    if ($thisdups = get_records_sql("SELECT id FROM {$CFG->prefix}grade_grades \n                                                    WHERE itemid = {$dup->itemid} AND userid = {$dup->userid}\n                                                    ORDER BY timemodified DESC")) {
                        $processed = 0;
                        // keep the first one
                        foreach ($thisdups as $thisdup) {
                            if ($processed) {
                                // remove the duplicates
                                delete_records('grade_grades', 'id', $thisdup->id);
                            }
                            $processed++;
                        }
                    }
                }
                rs_close($rs);
            }
        }
        /// Define key userid-itemid (unique) to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $key = new XMLDBKey('userid-itemid');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('userid', 'itemid'));
        /// Launch add key userid-itemid
        $result = $result && add_key($table, $key);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101502);
    }
    if ($result && $oldversion < 2007101505) {
        /// Changing precision of field dst_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('dst_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'dst_skipweeks');
        /// Launch change of precision for field dst_time
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field std_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('std_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'std_skipweeks');
        /// Launch change of precision for field std_time
        $result = $result && change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101505);
    }
    if ($result && $oldversion < 2007101506) {
        /// CONTEXT_PERSONAL was never implemented - removing
        $sql = "DELETE\n                  FROM {$CFG->prefix}context\n                 WHERE contextlevel=20";
        execute_sql($sql);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101506);
    }
    return $result;
}
コード例 #29
0
function xmldb_block_email_list_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    if ($result && $oldversion < 2007062205) {
        $fields = array('mod/email:viewmail', 'mod/email:addmail', 'mod/email:reply', 'mod/email:replyall', 'mod/email:forward', 'mod/email:addsubfolder', 'mod/email:updatesubfolder', 'mod/email:removesubfolder');
        /// Remove no more used fields
        $table = new XMLDBTable('capabilities');
        foreach ($fields as $name) {
            $field = new XMLDBField($name);
            $result = $result && drop_field($table, $field);
        }
        // Active cron block of email_list
        if ($result) {
            if ($email_list = get_record('block', 'name', 'email_list')) {
                $email_list->cron = 1;
                update_record('block', $email_list);
            }
        }
    }
    // force
    $result = true;
    if ($result && $oldversion < 2007072003) {
        // Add marriedfolder2courses flag on email_preferences
        $table = new XMLDBTable('email_preference');
        $field = new XMLDBField('marriedfolders2courses');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
        // Add course ID on email_folder
        $table = new XMLDBTable('email_folder');
        $field = new XMLDBField('course');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
        // Add index
        $key = new XMLDBKey('course');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));
        $result = $result && add_key($table, $key);
    }
    if ($result && $oldversion < 2008061400) {
        // Add reply and forwarded info field on email_mail.
        $table = new XMLDBTable('email_send');
        $field = new XMLDBField('answered');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
        $result = $result && add_field($table, $field);
    }
    // Solve old problems
    if ($result && $oldversion < 2008061600) {
        $table = new XMLDBTable('email_preference');
        $field = new XMLDBField('marriedfolders2courses');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('email_folder');
        $field = new XMLDBField('course');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && add_field($table, $field);
            // Add index
            $key = new XMLDBKey('course');
            $key->setAttributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));
            $result = $result && add_key($table, $key);
        }
    }
    // Add new index
    if ($result and $oldversion < 2008081600) {
        // Add combine key on foldermail
        $table = new XMLDBTable('email_foldermail');
        $index = new XMLDBIndex('folderid-mailid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('folderid', 'mailid'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
    }
    return $result;
}
コード例 #30
0
function xmldb_studynotes_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2009032400) {
        error("Version too old to be upgraded. Please delete the module and re-install it.");
    }
    if ($result && $oldversion < 2009041603) {
        /// Define table studynotes_uploads to be created
        $table = new XMLDBTable('studynotes_uploads');
        /// Adding fields to table studynotes_uploads
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('type', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('user_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('topic_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('filename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('created', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('modified', XMLDB_TYPE_DATETIME, null, null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table studynotes_uploads
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for studynotes_uploads
        $result = $result && create_table($table);
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_cards');
        $field = new XMLDBField('user');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'user_id');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_cards');
        $field = new XMLDBField('index');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        if ($CFG->dbfamily == "mysql" || $CFG->dbfamily == "mysqli") {
            if (field_exists($table, $field)) {
                $query = "ALTER TABLE {$CFG->prefix}studynotes_cards CHANGE `index` index_num BIGINT( 11 ) UNSIGNED NOT NULL";
                $db->Execute($query);
            }
        } else {
            /// Launch rename field
            $result = $result && rename_field($table, $field, 'index_num');
        }
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_cards');
        $field = new XMLDBField('level');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'level_num');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_flashcards');
        $field = new XMLDBField('user');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'user_id');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_flashcards');
        $field = new XMLDBField('number');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'num');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_flashcards');
        $field = new XMLDBField('level');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'level_num');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_groups');
        $field = new XMLDBField('access');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'access_num');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_markers');
        $field = new XMLDBField('user');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'user_id');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_markers');
        $field = new XMLDBField('range');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, null);
        if ($CFG->dbfamily == "mysql" || $CFG->dbfamily == "mysqli") {
            if (field_exists($table, $field)) {
                $query = "ALTER TABLE {$CFG->prefix}studynotes_markers CHANGE `range` range_store TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL";
                $db->Execute($query);
            }
        } else {
            /// Launch rename field
            $result = $result && rename_field($table, $field, 'range_store');
        }
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_memberships');
        $field = new XMLDBField('user');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'user_id');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_memberships');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        if ($CFG->dbfamily == "mysql" || $CFG->dbfamily == "mysqli") {
            if (field_exists($table, $field)) {
                $query = "ALTER TABLE {$CFG->prefix}studynotes_memberships CHANGE `group` group_id BIGINT( 11 ) UNSIGNED NOT NULL";
                $db->Execute($query);
            }
        } else {
            /// Launch rename field
            $result = $result && rename_field($table, $field, 'group_id');
        }
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_memberships');
        $field = new XMLDBField('level');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'level_num');
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_rights');
        $field = new XMLDBField('group');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        if ($CFG->dbfamily == "mysql" || $CFG->dbfamily == "mysqli") {
            if (field_exists($table, $field)) {
                $query = "ALTER TABLE {$CFG->prefix}studynotes_rights CHANGE `group` group_id BIGINT( 11 ) UNSIGNED NOT NULL";
                $db->Execute($query);
            }
        } else {
            /// Launch rename field
            $result = $result && rename_field($table, $field, 'group_id');
        }
    }
    /// Rename field
    if ($result && $oldversion < 2009042400) {
        $table = new XMLDBTable('studynotes_topics');
        $field = new XMLDBField('user');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, null, null, null, null, '0', null);
        /// Launch rename field
        $result = $result && rename_field($table, $field, 'user_id');
    }
    // Rename tables longer than 24 chars
    if ($result && $oldversion < 2009043001) {
        /// Define table studynotes_feed_msg_stat to be renamed
        $table = new XMLDBTable('studynotes_feed_messages_status');
        /// Launch rename table for studynotes_feed_msg_stat
        $result = $result && rename_table($table, 'studynotes_feed_msg_stat');
    }
    // Rename tables longer than 24 chars
    if ($result && $oldversion < 2009043001) {
        /// Define table studynotes_feed_subscrib to be renamed
        $table = new XMLDBTable('studynotes_feed_subscriptions');
        /// Launch rename table for studynotes_feed_subscrib
        $result = $result && rename_table($table, 'studynotes_feed_subscrib');
    }
    // Rename tables longer than 24 chars
    if ($result && $oldversion < 2009043001) {
        /// Define table studynotes_rel_questions to be renamed
        $table = new XMLDBTable('studynotes_relation_questions');
        /// Launch rename table for studynotes_rel_questions
        $result = $result && rename_table($table, 'studynotes_rel_questions');
    }
    // Rename tables longer than 24 chars
    if ($result && $oldversion < 2009043001) {
        /// Define table studynotes_rel_questions to be renamed
        $table = new XMLDBTable('studynotes_relation_translations');
        /// Launch rename table for studynotes_rel_questions
        $result = $result && rename_table($table, 'studynotes_rel_translations');
    }
    if ($result && $oldversion < 2009050301) {
        $fields = array(array('studynotes_cards', 'created'), array('studynotes_cards', 'modified'), array('studynotes_cards', 'locked_time'), array('studynotes_feed_messages', 'created'), array('studynotes_feed_messages', 'modified'), array('studynotes_feed_msg_stat', 'created'), array('studynotes_feed_msg_stat', 'modified'), array('studynotes_feeds', 'created'), array('studynotes_feeds', 'modified'), array('studynotes_groups', 'created'), array('studynotes_groups', 'modified'), array('studynotes_markers', 'created'), array('studynotes_markers', 'modified'), array('studynotes_memberships', 'created'), array('studynotes_memberships', 'modified'), array('studynotes_relations', 'created'), array('studynotes_relations', 'modified'), array('studynotes_relation_answers', 'created'), array('studynotes_relation_answers', 'modified'), array('studynotes_relation_links', 'created'), array('studynotes_relation_links', 'modified'), array('studynotes_rel_questions', 'created'), array('studynotes_rel_questions', 'modified'), array('studynotes_topics', 'created'), array('studynotes_topics', 'modified'), array('studynotes_uploads', 'created'), array('studynotes_uploads', 'modified'), array('studynotes_users', 'created'), array('studynotes_users', 'last_login'));
        foreach ($fields as $info) {
            $table = new XMLDBTable($info[0]);
            $tmpField = new XMLDBField($info[1] . "_cpy");
            $tmpField->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $info[1]);
            //add new integer field
            $result = $result && add_field($table, $tmpField);
            //get value
            if ($records = get_records($info[0], '', '', '', 'id,' . $info[1])) {
                //convert value
                foreach ($records as $record) {
                    $record->{$info[1] . "_cpy"} = strtotime($record->{$info[1]});
                    unset($record->{$info[1]});
                    print_r($record);
                    $result = $result && update_record($info[0], $record);
                }
            }
            //drop old field
            $field = new XMLDBField($info[1]);
            $result = $result && drop_field($table, $field);
            //rename copy
            $tmpField->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', null);
            $result = $result && change_field_default($table, $tmpField);
            $result = $result && rename_field($table, $tmpField, $info[1]);
        }
    }
    if ($result && $oldversion < 2009050301) {
        /// Define table studynotes_rel_translations to be dropped
        $table = new XMLDBTable('studynotes_rel_translations');
        /// Launch drop table for studynotes_rel_translations
        $result = $result && drop_table($table);
    }
    if ($result && $oldversion < 2009070300) {
        /// Define index link (not unique) to be dropped form studynotes_relation_links
        $table = new XMLDBTable('studynotes_relation_links');
        $index = new XMLDBIndex('link');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('link'));
        /// Launch drop index link
        $result = $result && drop_index($table, $index);
    }
    if ($result && $oldversion < 2009070300) {
        /// Changing type of field link on table studynotes_relation_links to text
        $table = new XMLDBTable('studynotes_relation_links');
        $field = new XMLDBField('link');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field link
        $result = $result && change_field_type($table, $field);
    }
    if ($result && $oldversion < 2009070300) {
        /// Changing type of field answer on table studynotes_relation_answers to text
        $table = new XMLDBTable('studynotes_relation_answers');
        $field = new XMLDBField('answer');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'id');
        /// Launch change of type for field answer
        $result = $result && change_field_type($table, $field);
    }
    if ($result && $oldversion < 2009070300) {
        /// Changing type of field question on table studynotes_rel_questions to text
        $table = new XMLDBTable('studynotes_rel_questions');
        $field = new XMLDBField('question');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field question
        $result = $result && change_field_type($table, $field);
    }
    return $result;
}