Example #1
0
function xmldb_forum_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 < 2007101000) {
        /// Define field timemodified to be added to forum_queue
        $table = new XMLDBTable('forum_queue');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'postid');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
    }
    //===== 1.9.0 upgrade line ======//
    if ($result and $oldversion < 2007101511) {
        notify('Processing forum grades, this may take a while if there are many forums...', 'notifysuccess');
        //MDL-13866 - send forum ratins to gradebook again
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        // too much debug output
        $db->debug = false;
        forum_update_grades();
        $db->debug = true;
    }
    if ($result && $oldversion < 2007101512) {
        /// Cleanup the forum subscriptions
        notify('Removing stale forum subscriptions', 'notifysuccess');
        $roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW);
        $roles = array_keys($roles);
        $roles = implode(',', $roles);
        $sql = "SELECT fs.userid, f.id AS forumid\n                  FROM {$CFG->prefix}forum f\n                       JOIN {$CFG->prefix}course c                 ON c.id = f.course\n                       JOIN {$CFG->prefix}context ctx              ON (ctx.instanceid = c.id AND ctx.contextlevel = " . CONTEXT_COURSE . ")\n                       JOIN {$CFG->prefix}forum_subscriptions fs   ON fs.forum = f.id\n                       LEFT JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = ctx.id AND ra.userid = fs.userid AND ra.roleid IN ({$roles}))\n                 WHERE ra.id IS NULL";
        if ($rs = get_recordset_sql($sql)) {
            $db->debug = false;
            while ($remove = rs_fetch_next_record($rs)) {
                delete_records('forum_subscriptions', 'userid', $remove->userid, 'forum', $remove->forumid);
                echo '.';
            }
            $db->debug = true;
            rs_close($rs);
        }
    }
    if ($result && $oldversion < 2007101513) {
        delete_records('forum_ratings', 'post', 0);
        /// Clean existing wrong rates. MDL-18227
    }
    return $result;
}
 /**
  * Add appropriate new criteria options to the form
  *
  */
 public function get_options(&$mform)
 {
     global $PAGE;
     $options = '';
     $none = true;
     $roles = get_roles_with_capability('moodle/badges:awardbadge', CAP_ALLOW, $PAGE->context);
     $roleids = array_map(create_function('$o', 'return $o->id;'), $roles);
     $existing = array();
     $missing = array();
     if ($this->id !== 0) {
         $existing = array_keys($this->params);
         $missing = array_diff($existing, $roleids);
     }
     if (!empty($missing)) {
         $mform->addElement('header', 'category_errors', get_string('criterror', 'badges'));
         $mform->addHelpButton('category_errors', 'criterror', 'badges');
         foreach ($missing as $m) {
             $this->config_options($mform, array('id' => $m, 'checked' => true, 'name' => get_string('error:nosuchrole', 'badges'), 'error' => true));
             $none = false;
         }
     }
     if (!empty($roleids)) {
         $mform->addElement('header', 'first_header', $this->get_title());
         $mform->addHelpButton('first_header', 'criteria_' . $this->criteriatype, 'badges');
         foreach ($roleids as $rid) {
             $checked = false;
             if (in_array($rid, $existing)) {
                 $checked = true;
             }
             $this->config_options($mform, array('id' => $rid, 'checked' => $checked, 'name' => self::get_role_name($rid), 'error' => false));
             $none = false;
         }
     }
     // Add aggregation.
     if (!$none) {
         $mform->addElement('header', 'aggregation', get_string('method', 'badges'));
         $agg = array();
         $agg[] =& $mform->createElement('radio', 'agg', '', get_string('allmethodmanual', 'badges'), 1);
         $agg[] =& $mform->createElement('static', 'none_break', null, '<br/>');
         $agg[] =& $mform->createElement('radio', 'agg', '', get_string('anymethodmanual', 'badges'), 2);
         $mform->addGroup($agg, 'methodgr', '', array(' '), false);
         if ($this->id !== 0) {
             $mform->setDefault('agg', $this->method);
         } else {
             $mform->setDefault('agg', BADGE_CRITERIA_AGGREGATION_ANY);
         }
     }
     return array($none, get_string('noparamstoadd', 'badges'));
 }
Example #3
0
function xmldb_glossary_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 < 2006111400) {
        /// MDL-10475, set override for legacy:student before dropping studentcanpost
        /// if the glossary disables student postings
        if ($glossaries = get_records('glossary', 'studentcanpost', '0')) {
            foreach ($glossaries as $glossary) {
                if ($cm = get_coursemodule_from_instance('glossary', $glossary->id)) {
                    // add student override in this instance
                    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
                    // find all roles with legacy:student
                    if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
                        foreach ($studentroles as $studentrole) {
                            assign_capability('mod/glossary:write', CAP_PREVENT, $studentrole->id, $context->id);
                        }
                    }
                }
            }
        }
        /// Define field studentcanpost to be dropped from glossary
        $table = new XMLDBTable('glossary');
        $field = new XMLDBField('studentcanpost');
        /// Launch drop field studentcanpost
        $result = $result && drop_field($table, $field);
    }
    if ($result && $oldversion < 2007072200) {
        require_once $CFG->dirroot . '/mod/glossary/lib.php';
        // too much debug output
        $db->debug = false;
        glossary_update_grades();
        $db->debug = true;
    }
    //===== 1.9.0 upgrade line ======//
    return $result;
}
Example #4
0
/**
 * Determines if a user is a teacher in any course, or an admin
 *
 * @global object
 * @global object
 * @global object
 * @uses CAP_ALLOW
 * @uses CONTEXT_SYSTEM
 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
 * @param bool $includeadmin Include anyone wo is an admin as well
 * @return bool
 */
function isteacherinanycourse($userid = 0, $includeadmin = true)
{
    global $USER, $CFG, $DB;
    if (!$userid) {
        if (empty($USER->id)) {
            return false;
        }
        $userid = $USER->id;
    }
    if (!$DB->record_exists('role_assignments', array('userid' => $userid))) {
        // Has no roles anywhere
        return false;
    }
    /// If this user is assigned as an editing teacher anywhere then return true
    if ($roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
        foreach ($roles as $role) {
            if ($DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $userid))) {
                return true;
            }
        }
    }
    /// If this user is assigned as a non-editing teacher anywhere then return true
    if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) {
        foreach ($roles as $role) {
            if ($DB->record_exists('role_assignments', array('roleid' => $role->id, 'userid' => $userid))) {
                return true;
            }
        }
    }
    /// Include admins if required
    if ($includeadmin) {
        $context = get_context_instance(CONTEXT_SYSTEM);
        if (has_capability('moodle/legacy:admin', $context, $userid, false)) {
            return true;
        }
    }
    return false;
}
Example #5
0
 public function role_unassigned($ra)
 {
     global $DB;
     if (!enrol_is_enabled('category')) {
         return true;
     }
     // only category level roles are interesting
     $parentcontext = get_context_instance_by_id($ra->contextid);
     if ($parentcontext->contextlevel != CONTEXT_COURSECAT) {
         return true;
     }
     // now this is going to be a bit slow, take all enrolments in child courses and verify each separately
     $syscontext = get_context_instance(CONTEXT_SYSTEM);
     if (!($roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext))) {
         return true;
     }
     $plugin = enrol_get_plugin('category');
     $sql = "SELECT e.*\n                  FROM {course} c\n                  JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)\n                  JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')\n                  JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)";
     $params = array('courselevel' => CONTEXT_COURSE, 'match' => $parentcontext->path . '/%', 'userid' => $ra->userid);
     $rs = $DB->get_recordset_sql($sql, $params);
     list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r');
     $params['userid'] = $ra->userid;
     foreach ($rs as $instance) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $instance->courseid);
         $contextids = get_parent_contexts($coursecontext);
         array_pop($contextids);
         // remove system context, we are interested in categories only
         list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c');
         $params = array_merge($params, $contextparams);
         $sql = "SELECT ra.id\n                      FROM {role_assignments} ra\n                     WHERE ra.userid = :userid AND ra.contextid {$contextids} AND ra.roleid {$roleids}";
         if (!$DB->record_exists_sql($sql, $params)) {
             // user does not have any interesting role in any parent context, let's unenrol
             $plugin->unenrol_user($instance, $ra->userid);
         }
     }
     $rs->close();
     return true;
 }
Example #6
0
    require_capability('moodle/course:viewparticipants', $context);
} else {
    require_capability('moodle/site:viewparticipants', $systemcontext);
    // override the default on frontpage
    $roleid = optional_param('roleid', -1, PARAM_INT);
}
/// front page course is different
$rolenames = array();
$avoidroles = array();
if ($roles = get_roles_used_in_context($context, true)) {
    // We should ONLY allow roles with moodle/course:view because otherwise we get little niggly issues
    // like MDL-8093
    // We should further exclude "admin" users (those with "doanything" at site level) because
    // Otherwise they appear in every participant list
    $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
    $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext);
    if ($context->id == $frontpagectx->id) {
        //we want admins listed on frontpage too
        foreach ($doanythingroles as $dar) {
            $canviewroles[$dar->id] = $dar;
        }
        $doanythingroles = array();
    }
    foreach ($roles as $role) {
        if (!isset($canviewroles[$role->id])) {
            // Avoid this role (eg course creator)
            $avoidroles[] = $role->id;
            unset($roles[$role->id]);
            continue;
        }
        if (isset($doanythingroles[$role->id])) {
Example #7
0
                    echo '<td><input type="checkbox"   name="check[]" class="check" value="' . $stu->id . '" /></td>';
            } else
                echo '<td><input type="checkbox"   name="check[]" class="check" value="' . $stu->id . '" /></td>';
            $studentservice_id = $DB->get_record('local_userdata', array('userid' => $stu->id));
            echo '<td>' . $studentservice_id->serviceid . '</td>';
            echo '<td>' . $stu->firstname . ' ' . $stu->lastname . '</td>';

            echo '<td>' . $stu->year . '</td>';
            echo'</tr>';
        }
        echo '</tbody>';
        echo '</table>';

        /* ---after select asignee role only...another dropdwon(filter is will be enabled)--- */
        $mentorlevel = "local/clclasses:approvemystudentclclasses";
        $roleid = get_roles_with_capability($mentorlevel, $permissions = NULL, $context = '');
        if (empty($roleid)) {
            $e = get_string('assigncap', 'local_assignmentor');
            throw new Exception($e);
        }
        foreach ($roleid as $roles) {
            if ($roles->shortname == 'mentor')
                $assignee_roleid = $roles->id;
        }

        $out = array();
        $out[0] = get_string('assignadvisor', 'local_assignmentor');
        if($assignee_roleid){
        $mentor_parentlist = $DB->get_records_sql("select u.id,u.firstname from {$CFG->prefix}local_school_permissions AS per
			JOIN {$CFG->prefix}user AS u ON u.id=per.userid	 where u.deleted<>1 and u.suspended<>1 and per.schoolid=$sid and per.roleid=$assignee_roleid ");
        
Example #8
0
function main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion == 0) {
        execute_sql("\n          CREATE TABLE `config` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `name` varchar(255) NOT NULL default '',\n            `value` varchar(255) NOT NULL default '',\n            PRIMARY KEY  (`id`),\n            UNIQUE KEY `name` (`name`)\n          ) COMMENT='Moodle configuration variables';");
        notify("Created a new table 'config' to hold configuration data");
    }
    if ($oldversion < 2002073100) {
        execute_sql(" DELETE FROM `modules` WHERE `name` = 'chat' ");
    }
    if ($oldversion < 2002080200) {
        execute_sql(" ALTER TABLE `modules` DROP `fullname`  ");
        execute_sql(" ALTER TABLE `modules` DROP `search`  ");
    }
    if ($oldversion < 2002080300) {
        execute_sql(" ALTER TABLE `log_display` CHANGE `table` `mtable` VARCHAR( 20 ) NOT NULL ");
        execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 3 ) DEFAULT '3' NOT NULL ");
    }
    if ($oldversion < 2002082100) {
        execute_sql(" ALTER TABLE `course` CHANGE `guest` `guest` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2002082101) {
        execute_sql(" ALTER TABLE `user` ADD `maildisplay` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL AFTER `mailformat` ");
    }
    if ($oldversion < 2002090100) {
        execute_sql(" ALTER TABLE `course_sections` CHANGE `summary` `summary` TEXT NOT NULL ");
    }
    if ($oldversion < 2002090701) {
        execute_sql(" ALTER TABLE `user_teachers` CHANGE `authority` `authority` TINYINT( 10 ) DEFAULT '3' NOT NULL ");
        execute_sql(" ALTER TABLE `user_teachers` ADD `role` VARCHAR(40) NOT NULL AFTER `authority` ");
    }
    if ($oldversion < 2002090800) {
        execute_sql(" ALTER TABLE `course` ADD `teachers` VARCHAR( 100 ) DEFAULT 'Teachers' NOT NULL AFTER `teacher` ");
        execute_sql(" ALTER TABLE `course` ADD `students` VARCHAR( 100 ) DEFAULT 'Students' NOT NULL AFTER `student` ");
    }
    if ($oldversion < 2002091000) {
        execute_sql(" ALTER TABLE `user` CHANGE `personality` `secret` VARCHAR( 15 ) NOT NULL DEFAULT ''  ");
    }
    if ($oldversion < 2002091400) {
        execute_sql(" ALTER TABLE `user` ADD `lang` VARCHAR( 3 ) DEFAULT 'en' NOT NULL AFTER `country`  ");
    }
    if ($oldversion < 2002091900) {
        notify("Most Moodle configuration variables have been moved to the database and can now be edited via the admin page.");
        notify("Although it is not vital that you do so, you might want to edit <U>config.php</U> and remove all the unused settings (except the database, URL and directory definitions).  See <U>config-dist.php</U> for an example of how your new slim config.php should look.");
    }
    if ($oldversion < 2002092000) {
        execute_sql(" ALTER TABLE `user` CHANGE `lang` `lang` VARCHAR(5) DEFAULT 'en' NOT NULL  ");
    }
    if ($oldversion < 2002092100) {
        execute_sql(" ALTER TABLE `user` ADD `deleted` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `confirmed` ");
    }
    if ($oldversion < 2002101001) {
        execute_sql(" ALTER TABLE `user` ADD `htmleditor` TINYINT(1) UNSIGNED DEFAULT '1' NOT NULL AFTER `maildisplay` ");
    }
    if ($oldversion < 2002101701) {
        execute_sql(" ALTER TABLE `reading` RENAME `resource` ");
        // Small line with big consequences!
        execute_sql(" DELETE FROM `log_display` WHERE module = 'reading'");
        execute_sql(" INSERT INTO log_display (module, action, mtable, field) VALUES ('resource', 'view', 'resource', 'name') ");
        execute_sql(" UPDATE log SET module = 'resource' WHERE module = 'reading' ");
        execute_sql(" UPDATE modules SET name = 'resource' WHERE name = 'reading' ");
    }
    if ($oldversion < 2002102503) {
        execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
        require_once "{$CFG->dirroot}/mod/forum/lib.php";
        require_once "{$CFG->dirroot}/course/lib.php";
        if (!($module = get_record("modules", "name", "forum"))) {
            notify("Could not find forum module!!");
            return false;
        }
        // First upgrade the site forums
        if ($site = get_site()) {
            print_heading("Making News forums editable for main site (moving to section 1)...");
            if ($news = forum_get_course_forum($site->id, "news")) {
                $mod->course = $site->id;
                $mod->module = $module->id;
                $mod->instance = $news->id;
                $mod->section = 1;
                if (!($mod->coursemodule = add_course_module($mod))) {
                    notify("Could not add a new course module to the site");
                    return false;
                }
                if (!($sectionid = add_mod_to_section($mod))) {
                    notify("Could not add the new course module to that section");
                    return false;
                }
                if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                    notify("Could not update the course module with the correct section");
                    return false;
                }
            }
        }
        // Now upgrade the courses.
        if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0")) {
            print_heading("Making News and Social forums editable for each course (moving to section 0)...");
            foreach ($courses as $course) {
                if ($course->format == "social") {
                    // we won't touch them
                    continue;
                }
                if ($news = forum_get_course_forum($course->id, "news")) {
                    $mod->course = $course->id;
                    $mod->module = $module->id;
                    $mod->instance = $news->id;
                    $mod->section = 0;
                    if (!($mod->coursemodule = add_course_module($mod))) {
                        notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
                        return false;
                    }
                    if (!($sectionid = add_mod_to_section($mod))) {
                        notify("Could not add the new course module to that section");
                        return false;
                    }
                    if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                        notify("Could not update the course module with the correct section");
                        return false;
                    }
                }
                if ($social = forum_get_course_forum($course->id, "social")) {
                    $mod->course = $course->id;
                    $mod->module = $module->id;
                    $mod->instance = $social->id;
                    $mod->section = 0;
                    if (!($mod->coursemodule = add_course_module($mod))) {
                        notify("Could not add a new course module to the course '" . format_string($course->fullname) . "'");
                        return false;
                    }
                    if (!($sectionid = add_mod_to_section($mod))) {
                        notify("Could not add the new course module to that section");
                        return false;
                    }
                    if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
                        notify("Could not update the course module with the correct section");
                        return false;
                    }
                }
            }
        }
    }
    if ($oldversion < 2002111003) {
        execute_sql(" ALTER TABLE `course` ADD `modinfo` TEXT NOT NULL AFTER `format` ");
        if ($courses = get_records_sql("SELECT * FROM course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2002111100) {
        print_simple_box_start("CENTER", "", "#FFCCCC");
        echo "<FONT SIZE=+1>";
        echo "<P>Changes have been made to all built-in themes, to add the new popup navigation menu.";
        echo "<P>If you have customised themes, you will need to edit theme/xxxx/header.html as follows:";
        echo "<UL><LI>Change anywhere it says <B>\$" . "button</B> to say <B>\$" . "menu</B>";
        echo "<LI>Add <B>\$" . "button</B> elsewhere (eg at the end of the navigation bar)</UL>";
        echo "<P>See the standard themes for examples, eg: theme/standard/header.html";
        print_simple_box_end();
    }
    if ($oldversion < 2002111200) {
        execute_sql(" ALTER TABLE `course` ADD `showrecent` TINYINT(5) UNSIGNED DEFAULT '1' NOT NULL AFTER `numsections` ");
    }
    if ($oldversion < 2002111400) {
        // Rebuild all course caches, because some may not be done in new installs (eg site page)
        if ($courses = get_records_sql("SELECT * FROM course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2002112000) {
        set_config("guestloginbutton", 1);
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `log` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_admins` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_teachers` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `start` `timestart` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `user_students` CHANGE `end` `timeend` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2002122700) {
        if (!record_exists("log_display", "module", "user", "action", "view")) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname,' ',lastname)') ");
        }
    }
    if ($oldversion < 2003010101) {
        delete_records("log_display", "module", "user");
        $new->module = "user";
        $new->action = "view";
        $new->mtable = "user";
        $new->field = "CONCAT(firstname,\" \",lastname)";
        insert_record("log_display", $new);
        delete_records("log_display", "module", "course");
        $new->module = "course";
        $new->action = "view";
        $new->mtable = "course";
        $new->field = "fullname";
        insert_record("log_display", $new);
        $new->action = "update";
        insert_record("log_display", $new);
        $new->action = "enrol";
        insert_record("log_display", $new);
    }
    if ($oldversion < 2003012200) {
        // execute_sql(" ALTER TABLE `log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
        // Commented out - see below where it's done properly
    }
    if ($oldversion < 2003032500) {
        modify_database("", "CREATE TABLE `prefix_user_coursecreators` (\n                             `id` int(10) unsigned NOT NULL auto_increment,\n                             `userid` int(10) unsigned NOT NULL default '0',\n                             PRIMARY KEY  (`id`),\n                             UNIQUE KEY `id` (`id`)\n                             ) TYPE=MyISAM COMMENT='One record per course creator';");
    }
    if ($oldversion < 2003032602) {
        // Redoing it because of no prefix last time
        execute_sql(" ALTER TABLE `{$CFG->prefix}log_display` CHANGE `module` `module` VARCHAR( 20 ) NOT NULL ");
        // Add some indexes for speed
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(course) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(userid) ");
    }
    if ($oldversion < 2003041400) {
        table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
    }
    if ($oldversion < 2003042104) {
        // Try to update permissions of all files
        if ($files = get_directory_list($CFG->dataroot)) {
            echo "Attempting to update permissions for all files... ignore any errors.";
            foreach ($files as $file) {
                echo "{$CFG->dataroot}/{$file}<br />";
                @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions);
            }
        }
    }
    if ($oldversion < 2003042400) {
        // Rebuild all course caches, because of changes to do with visible variable
        if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2003042500) {
        //  Convert all usernames to lowercase.
        $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
        $cerrors = "";
        $rarray = array();
        foreach ($users as $user) {
            // Check for possible conflicts
            $lcname = trim(moodle_strtolower($user->username));
            if (in_array($lcname, $rarray)) {
                $cerrors .= $user->id . "->" . $lcname . '<br/>';
            } else {
                array_push($rarray, $lcname);
            }
        }
        if ($cerrors != '') {
            notify("Error: Cannot convert usernames to lowercase.\n                    Following usernames would overlap (id->username):<br/> {$cerrors} .\n                    Please resolve overlapping errors.");
            $result = false;
        }
        $cerrors = "";
        echo "Checking userdatabase:<br />";
        foreach ($users as $user) {
            $lcname = trim(moodle_strtolower($user->username));
            if ($lcname != $user->username) {
                $convert = set_field("user", "username", $lcname, "id", $user->id);
                if (!$convert) {
                    if ($cerrors) {
                        $cerrors .= ", ";
                    }
                    $cerrors .= $item;
                } else {
                    echo ".";
                }
            }
        }
        if ($cerrors != '') {
            notify("There were errors when converting following usernames to lowercase.\n                   '{$cerrors}' . Sorry, but you will need to fix your database by hand.");
            $result = false;
        }
    }
    if ($oldversion < 2003042600) {
        /// Some more indexes - we need all the help we can get on the logs
        //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(module) ");
        //execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX(action) ");
    }
    if ($oldversion < 2003042700) {
        /// Changing to multiple indexes
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX module ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX action ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX course ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` DROP INDEX userid ", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX coursemoduleaction (course,module,action) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX courseuserid (course,userid) ");
    }
    if ($oldversion < 2003042801) {
        execute_sql("CREATE TABLE `{$CFG->prefix}course_display` (\n                        `id` int(10) unsigned NOT NULL auto_increment,\n                        `course` int(10) unsigned NOT NULL default '0',\n                        `userid` int(10) unsigned NOT NULL default '0',\n                        `display` int(10) NOT NULL default '0',\n                        PRIMARY KEY  (`id`),\n                        UNIQUE KEY `id` (`id`),\n                        KEY `courseuserid` (course,userid)\n                     ) TYPE=MyISAM COMMENT='Stores info about how to display the course'");
    }
    if ($oldversion < 2003050400) {
        table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050900) {
        table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050902) {
        if (get_records("modules", "name", "pgassignment")) {
            print_simple_box("Note: the pgassignment module has been removed (it will be replaced later by the workshop module).  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        }
    }
    if ($oldversion < 2003051600) {
        print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
    }
    if ($oldversion < 2003052300) {
        table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
    }
    if ($oldversion < 2003072100) {
        table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
    }
    if ($oldversion < 2003072101) {
        table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
    }
    if ($oldversion < 2003072800) {
        print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        flush();
        execute_sql(" ALTER TABLE `{$CFG->prefix}log` ADD INDEX timecoursemoduleaction (time,course,module,action) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX courseuserid (course,userid) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX courseuserid (course,userid) ");
    }
    if ($oldversion < 2003072803) {
        table_column("course_categories", "", "description", "text", "", "", "");
        table_column("course_categories", "", "parent", "integer", "10", "unsigned");
        table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
        table_column("course_categories", "", "courseorder", "text", "", "", "");
        table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
        table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
    }
    if ($oldversion < 2003080400) {
        table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
        table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
    }
    if ($oldversion < 2003080700) {
        notify("Cleaning up categories and course ordering...");
        fix_course_sortorder();
    }
    if ($oldversion < 2003081001) {
        table_column("course", "format", "format", "varchar", "10", "", "topics");
    }
    if ($oldversion < 2003081500) {
        //        print_simple_box("Some important changes have been made to how course creators work.  Formerly, they could create new courses and assign teachers, and teachers could edit courses.  Now, ordinary teachers can no longer edit courses - they <b>need to be a teacher of a course AND a course creator</b>.  A new site-wide configuration variable allows you to choose whether to allow course creators to create new courses as well (by default this is off).  <p>The following update will automatically convert all your existing teachers into course creators, to maintain backward compatibility.  Make sure you look at your upgraded site carefully and understand these new changes.", "center", "50%", "$THEME->cellheading", "20", "noticebox");
        //        $count = 0;
        //        $errorcount = 0;
        //        if ($teachers = get_records("user_teachers")) {
        //            foreach ($teachers as $teacher) {
        //                if (! record_exists("user_coursecreators", "userid", $teacher->userid)) {
        //                    $creator = NULL;
        //                    $creator->userid = $teacher->userid;
        //                    if (!insert_record("user_coursecreators", $creator)) {
        //                        $errorcount++;
        //                    } else {
        //                        $count++;
        //                    }
        //                }
        //            }
        //        }
        //        print_simple_box("$count teachers were upgraded to course creators (with $errorcount errors)", "center", "50%", "$THEME->cellheading", "20", "noticebox");
    }
    if ($oldversion < 2003081501) {
        execute_sql(" CREATE TABLE `{$CFG->prefix}scale` (\n                         `id` int(10) unsigned NOT NULL auto_increment,\n                         `courseid` int(10) unsigned NOT NULL default '0',\n                         `userid` int(10) unsigned NOT NULL default '0',\n                         `name` varchar(255) NOT NULL default '',\n                         `scale` text NOT NULL,\n                         `description` text NOT NULL,\n                         `timemodified` int(10) unsigned NOT NULL default '0',\n                         PRIMARY KEY  (id)\n                       ) TYPE=MyISAM COMMENT='Defines grading scales'");
    }
    if ($oldversion < 2003081503) {
        table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
        get_scales_menu(0);
        // Just to force the default scale to be created
    }
    if ($oldversion < 2003081600) {
        table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
        table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
    }
    if ($oldversion < 2003081900) {
        table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003082001) {
        table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
    }
    if ($oldversion < 2003082101) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX category (category) ");
    }
    if ($oldversion < 2003082702) {
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
    }
    if ($oldversion < 2003091400) {
        table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
    }
    if ($oldversion < 2003092900) {
        table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
    }
    if ($oldversion < 2003102700) {
        table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
        table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
        $db->debug = false;
        $CFG->debug = 0;
        notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
        flush();
        if ($courses = get_records_select("course", "category > 0")) {
            foreach ($courses as $course) {
                notify("Processing " . format_string($course->fullname) . " ...", "green");
                flush();
                if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '{$course->id}' and userid = '{$user->userid}'                                                               ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '{$loginfo->time}'\n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
                if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log\n                                                   WHERE course = '{$course->id}' and userid = '{$user->userid}'\n                                                   ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_students\n                                     SET timeaccess = '{$loginfo->time}'\n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
            }
        }
        notify("All courses complete.", "green");
        $db->debug = true;
    }
    if ($oldversion < 2003103100) {
        table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
    }
    if ($oldversion < 2003121600) {
        modify_database("", "CREATE TABLE `prefix_groups` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `courseid` int(10) unsigned NOT NULL default '0',\n                                `name` varchar(254) NOT NULL default '',\n                                `description` text NOT NULL,\n                                `lang` varchar(10) NOT NULL default 'en',\n                                `picture` int(10) unsigned NOT NULL default '0',\n                                `timecreated` int(10) unsigned NOT NULL default '0',\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `courseid` (`courseid`)\n                              ) TYPE=MyISAM COMMENT='Each record is a group in a course.'; ");
        modify_database("", "CREATE TABLE `prefix_groups_members` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `groupid` int(10) unsigned NOT NULL default '0',\n                                `userid` int(10) unsigned NOT NULL default '0',\n                                `timeadded` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `groupid` (`groupid`)\n                              ) TYPE=MyISAM COMMENT='Lists memberships of users in groups'; ");
    }
    if ($oldversion < 2003121800) {
        table_column("course", "modinfo", "modinfo", "longtext", "", "", "");
    }
    if ($oldversion < 2003122600) {
        table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "showreports");
        table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
    }
    if ($oldversion < 2004010900) {
        table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
    }
    if ($oldversion < 2004011700) {
        modify_database("", "CREATE TABLE `prefix_event` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `name` varchar(255) NOT NULL default '',\n                              `description` text NOT NULL,\n                              `courseid` int(10) unsigned NOT NULL default '0',\n                              `groupid` int(10) unsigned NOT NULL default '0',\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `modulename` varchar(20) NOT NULL default '',\n                              `instance` int(10) unsigned NOT NULL default '0',\n                              `eventtype` varchar(20) NOT NULL default '',\n                              `timestart` int(10) unsigned NOT NULL default '0',\n                              `timeduration` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`),\n                              UNIQUE KEY `id` (`id`),\n                              KEY `courseid` (`courseid`),\n                              KEY `userid` (`userid`)\n                            ) TYPE=MyISAM COMMENT='For everything with a time associated to it'; ");
    }
    if ($oldversion < 2004012800) {
        modify_database("", "CREATE TABLE `prefix_user_preferences` (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `name` varchar(50) NOT NULL default '',\n                              `value` varchar(255) NOT NULL default '',\n                              PRIMARY KEY  (`id`),\n                              UNIQUE KEY `id` (`id`),\n                              KEY `useridname` (userid,name)\n                            ) TYPE=MyISAM COMMENT='Allows modules to store arbitrary user preferences'; ");
    }
    if ($oldversion < 2004012900) {
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004013101) {
        table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
        set_config("upgrade", "logs");
    }
    if ($oldversion < 2004020900) {
        table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
    }
    if ($oldversion < 2004020903) {
        modify_database("", "CREATE TABLE `prefix_cache_text` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `md5key` varchar(32) NOT NULL default '',\n                                `formattedtext` longtext NOT NULL,\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `md5key` (`md5key`)\n                             ) TYPE=MyISAM COMMENT='For storing temporary copies of processed texts';");
    }
    if ($oldversion < 2004021000) {
        $textfilters = array();
        for ($i = 1; $i <= 10; $i++) {
            $variable = "textfilter{$i}";
            if (!empty($CFG->{$variable})) {
                /// No more filters
                if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) {
                    $textfilters[] = $CFG->{$variable};
                }
            }
        }
        $textfilters = implode(',', $textfilters);
        if (empty($textfilters)) {
            $textfilters = 'mod/glossary/dynalink.php';
        }
        set_config('textfilters', $textfilters);
    }
    if ($oldversion < 2004021201) {
        modify_database("", "CREATE TABLE `prefix_cache_filters` (\n                                `id` int(10) unsigned NOT NULL auto_increment,\n                                `filter` varchar(32) NOT NULL default '',\n                                `version` int(10) unsigned NOT NULL default '0',\n                                `md5key` varchar(32) NOT NULL default '',\n                                `rawtext` text NOT NULL,\n                                `timemodified` int(10) unsigned NOT NULL default '0',\n                                PRIMARY KEY  (`id`),\n                                KEY `filtermd5key` (filter,md5key)\n                              ) TYPE=MyISAM COMMENT='For keeping information about cached data';");
    }
    if ($oldversion < 2004021500) {
        table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
    }
    if ($oldversion < 2004021700) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004022000) {
        table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
    }
    if ($oldversion < 2004022200) {
        /// Final renaming I hope.  :-)
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
            $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
            $textfilters = explode(',', $CFG->textfilters);
            foreach ($textfilters as $key => $textfilter) {
                $textfilters[$key] = trim($textfilter);
            }
            set_config("textfilters", implode(',', $textfilters));
        }
    }
    if ($oldversion < 2004030702) {
        /// Because of the renaming of Czech language pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
    }
    if ($oldversion < 2004041800) {
        /// Integrate Block System from contrib
        table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
    }
    if ($oldversion < 2004042600) {
        /// Rebuild course caches for resource icons
        include_once "{$CFG->dirroot}/course/lib.php";
        rebuild_course_cache();
    }
    if ($oldversion < 2004042700) {
        /// Increase size of lang fields
        table_column("user", "lang", "lang", "varchar", "10", "", "en");
        table_column("groups", "lang", "lang", "varchar", "10", "", "");
        table_column("course", "lang", "lang", "varchar", "10", "", "");
    }
    if ($oldversion < 2004042701) {
        /// Add hiddentopics field to control hidden topics behaviour
        table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
    }
    if ($oldversion < 2004042702) {
        /// add a format field for the description
        table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
    }
    if ($oldversion < 2004042900) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP `showrecent` ");
    }
    if ($oldversion < 2004043001) {
        /// Change hiddentopics to hiddensections
        table_column("course", "hiddentopics", "hiddensections", "integer", "2", "unsigned", "0", "not null");
    }
    if ($oldversion < 2004050400) {
        /// add a visible field for events
        table_column("event", "", "visible", "tinyint", "1", "", "1", "not null", "timeduration");
        if ($events = get_records('event')) {
            foreach ($events as $event) {
                if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
                    if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
                        set_field('event', 'visible', 0, 'id', $event->id);
                    }
                }
            }
        }
    }
    if ($oldversion < 2004052800) {
        /// First version tagged "1.4 development", version.php 1.227
        set_config('siteblocksadded', true);
        /// This will be used later by the block upgrade
    }
    if ($oldversion < 2004053000) {
        /// set defaults for site course
        $site = get_site();
        set_field('course', 'numsections', 0, 'id', $site->id);
        set_field('course', 'groupmodeforce', 1, 'id', $site->id);
        set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
        set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
        set_field('course', 'student', get_string('user'), 'id', $site->id);
        set_field('course', 'students', get_string('users'), 'id', $site->id);
    }
    if ($oldversion < 2004060100) {
        set_config('digestmailtime', 0);
        table_column('user', "", 'maildigest', 'tinyint', '1', '', '0', 'not null', 'mailformat');
    }
    if ($oldversion < 2004062400) {
        table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
        table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
    }
    if ($oldversion < 2004062401) {
        table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
        execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname');
        // By default
    }
    if ($oldversion < 2004062600) {
        table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
    }
    if ($oldversion < 2004072900) {
        table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
    }
    if ($oldversion < 2004072901) {
        // Fixing error in schema
        if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
            delete_records('log_display', 'module', 'course', 'action', 'update');
            insert_record('log_display', $record, false);
        }
    }
    if ($oldversion < 2004081200) {
        // Fixing version errors in some blocks
        set_field('blocks', 'version', 2004081200, 'name', 'admin');
        set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
        set_field('blocks', 'version', 2004081200, 'name', 'course_list');
    }
    if ($oldversion < 2004081500) {
        // Adding new "auth" field to user table to allow more flexibility
        table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
        execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");
        // Set everyone to 'manual' to be sure
        if ($admins = get_admins()) {
            // Set all the NON-admins to whatever the current auth module is
            $adminlist = array();
            foreach ($admins as $user) {
                $adminlist[] = $user->id;
            }
            $adminlist = implode(',', $adminlist);
            execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})");
        }
    }
    if ($oldversion < 2004082200) {
        // Making admins teachers on site course
        $site = get_site();
        $admins = get_admins();
        foreach ($admins as $admin) {
            add_teacher($admin->id, $site->id);
        }
    }
    if ($oldversion < 2004082600) {
        //update auth-fields for external users
        // following code would not work in 1.8
        /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
                if (function_exists('auth_get_userlist')) {
                    $externalusers = auth_get_userlist();
                    if (!empty($externalusers)){
                        $externalusers = '\''. implode('\',\'',$externalusers).'\'';
                        execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
                    }
                }*/
    }
    if ($oldversion < 2004082900) {
        // Make sure guest is "manual" too.
        set_field('user', 'auth', 'manual', 'username', 'guest');
    }
    /* Commented out unused guid-field code
       if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
           table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
           execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX authguid (auth, guid)");
       }
       */
    if ($oldversion < 2004091900) {
        // modify idnumber to hold longer values
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_idnumber", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP INDEX user_auth", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX idnumber (idnumber)");
        execute_sql("ALTER TABLE {$CFG->prefix}user ADD INDEX auth (auth)");
    }
    if ($oldversion < 2004093001) {
        // add new table for sessions storage
        execute_sql(" CREATE TABLE `{$CFG->prefix}sessions` (\n                          `sesskey` char(32) NOT null,\n                          `expiry` int(11) unsigned NOT null,\n                          `expireref` varchar(64),\n                          `data` text NOT null,\n                          PRIMARY KEY (`sesskey`), \n                          KEY (`expiry`) \n                      ) TYPE=MyISAM COMMENT='Optional database session storage, not used by default';");
    }
    if ($oldversion < 2004111500) {
        // Update any users/courses using wrongly-named lang pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
    }
    if ($oldversion < 2004111700) {
        // add indexes. - drop them first silently to avoid conflicts when upgrading.
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX idnumber;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` DROP INDEX shortname;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` DROP INDEX userid;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` DROP INDEX userid;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX idnumber (idnumber);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}course` ADD INDEX shortname (shortname);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX userid (userid);");
        execute_sql(" ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX userid (userid);");
    }
    if ($oldversion < 2004111700) {
        // add an index to event for timestart and timeduration. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timestart;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}event DROP INDEX timeduration;", false);
        modify_database('', 'ALTER TABLE prefix_event ADD INDEX timestart (timestart);');
        modify_database('', 'ALTER TABLE prefix_event ADD INDEX timeduration (timeduration);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on modules and course_modules. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key visible;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key module;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key instance;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}course_modules drop key deleted;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}modules drop key name;", false);
        modify_database('', 'ALTER TABLE prefix_course_modules add key visible(visible);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key course(course);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key module(module);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key instance (instance);');
        modify_database('', 'ALTER TABLE prefix_course_modules add key deleted (deleted);');
        modify_database('', 'ALTER TABLE prefix_modules add key name(name);');
    }
    if ($oldversion < 2004111700) {
        // add an index on the groups_members table. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}groups_members DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_groups_members ADD INDEX userid (userid);');
    }
    if ($oldversion < 2004111700) {
        // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
        execute_sql("ALTER TABLE {$CFG->prefix}user_students DROP INDEX timeaccess;", false);
        modify_database('', 'ALTER TABLE prefix_user_students ADD INDEX timeaccess (timeaccess);');
    }
    if ($oldversion < 2004111700) {
        // add indexes on faux-foreign keys. - drop them first silently to avoid conflicts when upgrading.
        execute_sql("ALTER TABLE {$CFG->prefix}scale DROP INDEX courseid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}user_admins DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}user_coursecreators DROP INDEX userid;", false);
        modify_database('', 'ALTER TABLE prefix_scale ADD INDEX courseid (courseid);');
        modify_database('', 'ALTER TABLE prefix_user_admins ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_user_coursecreators ADD INDEX userid (userid);');
    }
    if ($oldversion < 2004111700) {
        // replace index on course
        fix_course_sortorder(0, 0, 1);
        execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}course` DROP KEY category_sortorder;", false);
        modify_database('', "ALTER TABLE `prefix_course` ADD UNIQUE KEY category_sortorder(category,sortorder)");
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_deleted_idx  (deleted)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_confirmed_idx (confirmed)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_firstname_idx (firstname)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastname_idx (lastname)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_city_idx (city)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_country_idx (country)");
        modify_database("", "ALTER TABLE `prefix_user` ADD INDEX prefix_user_lastaccess_idx (lastaccess)");
    }
    if ($oldversion < 2004111700) {
        // one more index for email (for sorting)
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false);
        modify_database('', 'ALTER TABLE `prefix_user` ADD INDEX prefix_user_email_idx (email);');
    }
    if ($oldversion < 2004112200) {
        // new 'enrol' field for enrolment tables
        table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
        table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
        execute_sql("ALTER TABLE `{$CFG->prefix}user_students` ADD INDEX enrol (enrol);");
        execute_sql("ALTER TABLE `{$CFG->prefix}user_teachers` ADD INDEX enrol (enrol);");
    }
    if ($oldversion < 2004112400) {
        /// Delete duplicate enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        modify_database('', 'ALTER TABLE prefix_user_students DROP INDEX courseuserid;');
        modify_database('', 'ALTER TABLE prefix_user_students ADD UNIQUE INDEX courseuserid(course,userid);');
        /// Delete duplicate teacher enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        modify_database('', 'ALTER TABLE prefix_user_teachers DROP INDEX courseuserid;');
        modify_database('', 'ALTER TABLE prefix_user_teachers ADD UNIQUE INDEX courseuserid(course,userid);');
    }
    if ($oldversion < 2004112900) {
        table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
    }
    if ($oldversion < 2004121400) {
        table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
    }
    if ($oldversion < 2004121500) {
        modify_database('', "CREATE TABLE prefix_dst_preset (\n            id int(10) NOT NULL auto_increment,\n            name char(48) default '' NOT NULL,\n            \n            apply_offset tinyint(3) default '0' NOT NULL,\n            \n            activate_index tinyint(1) default '1' NOT NULL,\n            activate_day tinyint(1) default '1' NOT NULL,\n            activate_month tinyint(2) default '1' NOT NULL,\n            activate_time char(5) default '03:00' NOT NULL,\n            \n            deactivate_index tinyint(1) default '1' NOT NULL,\n            deactivate_day tinyint(1) default '1' NOT NULL,\n            deactivate_month tinyint(2) default '2' NOT NULL,\n            deactivate_time char(5) default '03:00' NOT NULL,\n            \n            last_change int(10) default '0' NOT NULL,\n            next_change int(10) default '0' NOT NULL,\n            current_offset tinyint(3) default '0' NOT NULL,\n            \n            PRIMARY KEY (id))");
    }
    if ($oldversion < 2004122800) {
        execute_sql("DROP TABLE {$CFG->prefix}message", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
        modify_database('', "CREATE TABLE `prefix_message` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `useridfrom` int(10) NOT NULL default '0',\n                               `useridto` int(10) NOT NULL default '0',\n                               `message` text NOT NULL,\n                               `timecreated` int(10) NOT NULL default '0',\n                               `messagetype` varchar(50) NOT NULL default '',\n                               PRIMARY KEY  (`id`),\n                               KEY `useridfrom` (`useridfrom`),\n                               KEY `useridto` (`useridto`)\n                             ) TYPE=MyISAM COMMENT='Stores all unread messages';");
        modify_database('', "CREATE TABLE `prefix_message_read` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `useridfrom` int(10) NOT NULL default '0',\n                               `useridto` int(10) NOT NULL default '0',\n                               `message` text NOT NULL,\n                               `timecreated` int(10) NOT NULL default '0',\n                               `timeread` int(10) NOT NULL default '0',\n                               `messagetype` varchar(50) NOT NULL default '',\n                               `mailed` tinyint(1) NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               KEY `useridfrom` (`useridfrom`),\n                               KEY `useridto` (`useridto`)\n                             ) TYPE=MyISAM COMMENT='Stores all messages that have been read';");
        modify_database('', "CREATE TABLE `prefix_message_contacts` (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `userid` int(10) unsigned NOT NULL default '0',\n                               `contactid` int(10) unsigned NOT NULL default '0',\n                               `blocked` tinyint(1) unsigned NOT NULL default '0',\n                               PRIMARY KEY  (`id`),\n                               UNIQUE KEY `usercontact` (`userid`,`contactid`)\n                             ) TYPE=MyISAM COMMENT='Maintains lists of relationships between users';");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
    }
    if ($oldversion < 2004122801) {
        table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
        table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
    }
    if ($oldversion < 2005010100) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'CONCAT(firstname,\" \",lastname)'); ");
    }
    if ($oldversion < 2005011000) {
        // Create a .htaccess file in dataroot, just in case
        if (!file_exists($CFG->dataroot . '/.htaccess')) {
            if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) {
                // For safety
                @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
                @fclose($handle);
                notify("Created a default .htaccess file in {$CFG->dataroot}");
            }
        }
    }
    if ($oldversion < 2005012500) {
        /*
        // add new table for meta courses.
        modify_database("","CREATE TABLE `prefix_meta_course` (
            `id` int(1) unsigned NOT NULL auto_increment,
            `parent_course` int(10) NOT NULL default 0,
            `child_course` int(10) NOT NULL default 0,
            PRIMARY KEY (`id`),
            KEY `parent_course` (parent_course),
            KEY `child_course` (child_course)
        );");
        // add flag to course field
        table_column('course','','meta_course','integer','1','','0','not null');
        */
        // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
    }
    if ($oldversion < 2005012501) {
        execute_sql("DROP TABLE {$CFG->prefix}meta_course", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false);
        // drop silently
        // add new table for meta courses.
        modify_database("", "CREATE TABLE `prefix_course_meta` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `parent_course` int(10) NOT NULL default 0,\n            `child_course` int(10) NOT NULL default 0,\n            PRIMARY KEY (`id`),\n            KEY `parent_course` (parent_course),\n            KEY `child_course` (child_course)\n        );");
        // add flag to course field
        table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005012800) {
        // fix a typo (int 1 becomes int 10)
        table_column('course_meta', 'id', 'id', 'integer', '10', '', '0', 'not null');
    }
    if ($oldversion < 2005020100) {
        fix_course_sortorder(0, 1, 1);
    }
    if ($oldversion < 2005020101) {
        // hopefully this is the LAST TIME we need to do this ;)
        if ($rows = count_records("course_meta")) {
            // we need to upgrade
            modify_database("", "CREATE TABLE `prefix_course_meta_tmp` (\n            `parent_course` int(10) NOT NULL default 0,\n            `child_course` int(10) NOT NULL default 0);");
            execute_sql("INSERT INTO {$CFG->prefix}course_meta_tmp (parent_course,child_course) \n               SELECT {$CFG->prefix}course_meta.parent_course, {$CFG->prefix}course_meta.child_course\n               FROM {$CFG->prefix}course_meta");
            $insertafter = true;
        }
        execute_sql("DROP TABLE {$CFG->prefix}course_meta");
        modify_database("", "CREATE TABLE `prefix_course_meta` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `parent_course` int(10) unsigned NOT NULL default 0,\n            `child_course` int(10) unsigned NOT NULL default 0,\n            PRIMARY KEY (`id`),\n            KEY `parent_course` (parent_course),\n            KEY `child_course` (child_course));");
        if (!empty($insertafter)) {
            execute_sql("INSERT INTO {$CFG->prefix}course_meta (parent_course,child_course) \n               SELECT {$CFG->prefix}course_meta_tmp.parent_course, {$CFG->prefix}course_meta_tmp.child_course\n               FROM {$CFG->prefix}course_meta_tmp");
            execute_sql("DROP TABLE {$CFG->prefix}course_meta_tmp");
        }
    }
    if ($oldversion < 2005020800) {
        // Expand module column to max 20 chars
        table_column('log', 'module', 'module', 'varchar', '20', '', '', 'not null');
    }
    if ($oldversion < 2005021000) {
        // New fields for theme choices
        table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        set_config('theme', 'standardwhite');
        // Reset to a known good theme
    }
    if ($oldversion < 2005021600) {
        // course.idnumber should be varchar(100)
        table_column('course', 'idnumber', 'idnumber', 'varchar', '100', '', '', '', '');
    }
    if ($oldversion < 2005021700) {
        table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
    }
    if ($oldversion < 2005021800) {
        // For database debugging, not for normal use
        modify_database("", " CREATE TABLE `adodb_logsql` (\n                               `created` datetime NOT NULL,\n                               `sql0` varchar(250) NOT NULL,\n                               `sql1` text NOT NULL,\n                               `params` text NOT NULL,\n                               `tracer` text NOT NULL,\n                               `timer` decimal(16,6) NOT NULL\n                              );");
    }
    if ($oldversion < 2005022400) {
        // Add more visible digits to the fields
        table_column('dst_preset', 'activate_index', 'activate_index', 'tinyint', '2', '', '0', 'not null');
        table_column('dst_preset', 'activate_day', 'activate_day', 'tinyint', '2', '', '0', 'not null');
        // Add family and year fields
        table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
        table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
    }
    if ($oldversion < 2005030501) {
        table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
    }
    if ($oldversion < 2005032300) {
        table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
        execute_sql('UPDATE `' . $CFG->prefix . 'user` SET timezonename = \'\'');
    }
    if ($oldversion < 2005032600) {
        execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false);
        modify_database('', "CREATE TABLE `prefix_timezone` (\n                              `id` int(10) NOT NULL auto_increment,\n                              `name` varchar(100) NOT NULL default '',\n                              `year` int(11) NOT NULL default '0',\n                              `rule` varchar(20) NOT NULL default '',\n                              `gmtoff` int(11) NOT NULL default '0',\n                              `dstoff` int(11) NOT NULL default '0',\n                              `dst_month` tinyint(2) NOT NULL default '0',\n                              `dst_startday` tinyint(3) NOT NULL default '0',\n                              `dst_weekday` tinyint(3) NOT NULL default '0',\n                              `dst_skipweeks` tinyint(3) NOT NULL default '0',\n                              `dst_time` varchar(5) NOT NULL default '00:00',\n                              `std_month` tinyint(2) NOT NULL default '0',\n                              `std_startday` tinyint(3) NOT NULL default '0',\n                              `std_weekday` tinyint(3) NOT NULL default '0',\n                              `std_skipweeks` tinyint(3) NOT NULL default '0',\n                              `std_time` varchar(5) NOT NULL default '00:00',\n                              PRIMARY KEY (`id`)\n                            ) TYPE=MyISAM COMMENT='Rules for calculating local wall clock time for users';");
    }
    if ($oldversion < 2005032800) {
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_category` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `name` varchar(64) NOT NULL default '',\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `drop_x_lowest` int(10) unsigned NOT NULL default '0',\n            `bonus_points` int(10) unsigned NOT NULL default '0',\n            `hidden` int(10) unsigned NOT NULL default '0',\n            `weight` decimal(4,2) NOT NULL default '0.00',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_exceptions` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `grade_itemid` int(10) unsigned NOT NULL default '0',\n            `userid` int(10) unsigned NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_item` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `category` int(10) unsigned NOT NULL default '0',\n            `modid` int(10) unsigned NOT NULL default '0',\n            `cminstance` int(10) unsigned NOT NULL default '0',\n            `scale_grade` float(11,10) default '1.0000000000',\n            `extra_credit` int(10) unsigned NOT NULL default '0',\n            `sort_order` int(10) unsigned NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_letter` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `letter` varchar(8) NOT NULL default 'NA',\n            `grade_high` decimal(4,2) NOT NULL default '100.00',\n            `grade_low` decimal(4,2) NOT NULL default '0.00',\n            PRIMARY KEY  (`id`),\n            KEY `courseid` (`courseid`)\n          ) TYPE=MyISAM ;");
        execute_sql("CREATE TABLE `{$CFG->prefix}grade_preferences` (\n            `id` int(10) unsigned NOT NULL auto_increment,\n            `courseid` int(10) unsigned NOT NULL default '0',\n            `preference` int(10) NOT NULL default '0',\n            `value` int(10) NOT NULL default '0',\n            PRIMARY KEY  (`id`),\n            UNIQUE KEY `courseidpreference` (`courseid`,`preference`)\n          ) TYPE=MyISAM ;");
    }
    if ($oldversion < 2005033100) {
        // Get rid of defunct field from course modules table
        delete_records('course_modules', 'deleted', 1);
        // Delete old records we don't need any more
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP INDEX `deleted`');
        // Old index
        execute_sql('ALTER TABLE `' . $CFG->prefix . 'course_modules` DROP `deleted`');
        // Old field
    }
    if ($oldversion < 2005040800) {
        table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
        execute_sql(" ALTER TABLE `{$CFG->prefix}user` DROP `timezonename` ");
    }
    if ($oldversion < 2005041101) {
        require_once $CFG->libdir . '/filelib.php';
        if (is_readable($CFG->dirroot . '/lib/timezones.txt')) {
            // Distribution file
            if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) {
                $db->debug = false;
                update_timezone_records($timezones);
                notify(count($timezones) . ' timezones installed');
                $db->debug = true;
            }
        }
    }
    if ($oldversion < 2005041900) {
        // Copy all Dialogue entries into Messages, and hide Dialogue module
        if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
                                          FROM ' . $CFG->prefix . 'dialogue_conversations c,
                                               ' . $CFG->prefix . 'dialogue_entries e
                                         WHERE e.conversationid = c.id')) {
            foreach ($entries as $entry) {
                $message = new object();
                $message->useridfrom = $entry->userid;
                $message->useridto = $entry->recipientid;
                $message->message = addslashes($entry->text);
                $message->format = FORMAT_HTML;
                $message->timecreated = $entry->timecreated;
                $message->messagetype = 'direct';
                insert_record('message_read', $message);
            }
        }
        set_field('modules', 'visible', 0, 'name', 'dialogue');
        notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
    }
    if ($oldversion < 2005042100) {
        $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
    }
    if ($oldversion < 2005042400) {
        // Add user tracking prefs field.
        table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
    }
    if ($oldversion < 2005053000) {
        // Add config_plugins table
        // this table was created on the MOODLE_15_STABLE branch
        // so it may already exist.
        $result = execute_sql("CREATE TABLE IF NOT EXISTS `{$CFG->prefix}config_plugins` (\n                                  `id`         int(10) unsigned NOT NULL auto_increment,\n                                  `plugin`     varchar(100) NOT NULL default 'core',\n                                  `name`       varchar(100) NOT NULL default '',\n                                  `value`      text NOT NULL default '',\n                                  PRIMARY KEY  (`id`),\n                                           UNIQUE KEY `plugin_name` (`plugin`, `name`)\n                                  ) TYPE=MyISAM \n                                  COMMENT='Moodle modules and plugins configuration variables';");
    }
    if ($oldversion < 2005060200) {
        // migrate some config items to config_plugins table
        // NOTE: this block is in both postgres AND mysql upgrade
        // files. If you edit either, update the otherone.
        $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang");
        if (!empty($CFG->auth)) {
            // if we have no auth, just pass
            foreach ($user_fields as $field) {
                $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
                foreach ($suffixes as $suffix) {
                    $key = 'auth_user_' . $field . $suffix;
                    if (isset($CFG->{$key})) {
                        // translate keys & values
                        // to the new convention
                        // this should support upgrading
                        // even 1.5dev installs
                        $newkey = $key;
                        $newval = $CFG->{$key};
                        if ($suffix === '') {
                            $newkey = 'field_map_' . $field;
                        } elseif ($suffix === '_editlock') {
                            $newkey = 'field_lock_' . $field;
                            $newval = $newval == 1 ? 'locked' : 'unlocked';
                            // translate 0/1 to locked/unlocked
                        } elseif ($suffix === '_updateremote') {
                            $newkey = 'field_updateremote_' . $field;
                        } elseif ($suffix === '_updatelocal') {
                            $newkey = 'field_updatelocal_' . $field;
                            $newval = $newval == 1 ? 'onlogin' : 'oncreate';
                            // translate 0/1 to locked/unlocked
                        }
                        if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) {
                            notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} .");
                            $result = false;
                        }
                    }
                    // end if isset key
                }
                // end foreach suffix
            }
            // end foreach field
        }
    }
    if ($oldversion < 2005060201) {
        // Close down the Attendance module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) {
            if (count_records('attendance')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'attendance');
                notify('The Attendance module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Attendance activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false);
                delete_records('modules', 'name', 'attendance');
                notify("The Attendance module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005071700) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (count_records('dialogue')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'dialogue');
                notify('The Dialogue module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Dialogue activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false);
                delete_records('modules', 'name', 'dialogue');
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005072000) {
        // Add a couple fields to mdl_event to work towards iCal import/export
        table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
        table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
    }
    if ($oldversion < 2005072100) {
        // run the online assignment cleanup code
        include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php';
        if (function_exists('online_assignment_cleanup')) {
            online_assignment_cleanup();
        }
    }
    if ($oldversion < 2005072200) {
        // fix the mistakenly-added currency stuff from enrol/authorize
        execute_sql("DROP TABLE {$CFG->prefix}currencies", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
        $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
        table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
    }
    if ($oldversion < 2005081600) {
        //set up the course requests table
        modify_database('', "CREATE TABLE `prefix_course_request`  (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `fullname` varchar(254) NOT NULL default '',\n          `shortname` varchar(15) NOT NULL default '',\n          `summary` text NOT NULL,\n          `reason` text NOT NULL,\n          `requester` int(10) NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `shortname` (`shortname`)\n        ) TYPE=MyISAM;");
        table_column('course', '', 'requested');
    }
    if ($oldversion < 2005081601) {
        modify_database('', "CREATE TABLE `prefix_course_allowed_modules` (\n         `id` int(10) unsigned NOT NULL auto_increment,\n         `course` int(10) unsigned NOT NULL default 0,\n         `module` int(10) unsigned NOT NULL default 0,\n         PRIMARY KEY (`id`),\n         KEY `course` (`course`),\n         KEY `module` (`module`)\n      ) TYPE=MyISAM;");
        table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005081700) {
        table_column('course_categories', '', 'depth', 'integer');
        table_column('course_categories', '', 'path', 'varchar', '255');
    }
    if ($oldversion < 2005090100) {
        modify_database("", "CREATE TABLE `prefix_stats_daily` (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_weekly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_monthly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `students` int(10) unsigned NOT NULL default 0,\n          `teachers` int(10) unsigned NOT NULL default 0,\n          `activestudents` int(10) unsigned NOT NULL default 0,\n          `activeteachers` int(10) unsigned NOT NULL default 0,\n          `studentreads` int(10) unsigned NOT NULL default 0,\n          `studentwrites` int(10) unsigned NOT NULL default 0,\n          `teacherreads` int(10) unsigned NOT NULL default 0,\n          `teacherwrites` int(10) unsigned NOT NULL default 0,\n          `logins` int(10) unsigned NOT NULL default 0,\n          `uniquelogins` int(10) unsigned NOT NULL default 0,\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_daily (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
        modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `courseid` int(10) unsigned NOT NULL default 0,\n          `userid` int(10) unsigned NOT NULL default 0,\n          `roleid` int(10) unsigned NOT NULL default 0,\n          `timeend` int(10) unsigned NOT NULL default 0,\n          `statsreads` int(10) unsigned NOT NULL default 0,\n          `statswrites` int(10) unsigned NOT NULL default 0,\n          `stattype` varchar(30) NOT NULL default '',\n          PRIMARY KEY (`id`),\n          KEY `courseid` (`courseid`),\n          KEY `userid` (`userid`),\n          KEY `roleid` (`roleid`),\n          KEY `timeend` (`timeend`)\n       );");
    }
    if ($oldversion < 2005100300) {
        table_column('course', '', 'expirynotify', 'tinyint', '1');
        table_column('course', '', 'expirythreshold', 'int', '10');
        table_column('course', '', 'notifystudents', 'tinyint', '1');
        $new = new stdClass();
        $new->name = 'lastexpirynotify';
        $new->value = 0;
        insert_record('config', $new);
    }
    if ($oldversion < 2005100400) {
        table_column('course', '', 'enrollable', 'tinyint', '1', 'unsigned', '1');
        table_column('course', '', 'enrolstartdate', 'int');
        table_column('course', '', 'enrolenddate', 'int');
    }
    if ($oldversion < 2005101200) {
        // add enrolment key to course_request.
        table_column('course_request', '', 'password', 'varchar', 50);
    }
    if ($oldversion < 2006030800) {
        # add extra indexes to log (see bug #4112)
        modify_database('', "ALTER TABLE prefix_log ADD INDEX userid (userid);");
        modify_database('', "ALTER TABLE prefix_log ADD INDEX info (info);");
    }
    if ($oldversion < 2006030900) {
        table_column('course', '', 'enrol', 'varchar', '20', '', '');
        if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
            set_config('enrol_plugins_enabled', 'manual');
            set_config('enrol', 'manual');
        } else {
            set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol);
        }
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            // switch enrollable to off for all courses in this case
            modify_database('', 'UPDATE prefix_course SET enrollable = 0');
        }
        execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
        execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
    }
    if ($oldversion < 2006031000) {
        modify_database("", "CREATE TABLE prefix_post (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `userid` int(10) unsigned NOT NULL default '0',\n          `courseid` int(10) unsigned NOT NULL default'0',\n          `groupid` int(10) unsigned NOT NULL default'0',\n          `moduleid` int(10) unsigned NOT NULL default'0',\n          `coursemoduleid` int(10) unsigned NOT NULL default'0',\n          `subject` varchar(128) NOT NULL default '',\n          `summary` longtext,\n          `content` longtext,\n          `uniquehash` varchar(128) NOT NULL default '',\n          `rating` int(10) unsigned NOT NULL default'0',\n          `format` int(10) unsigned NOT NULL default'0',\n          `publishstate` enum('draft','site','public') NOT NULL default 'draft',\n          `lastmodified` int(10) unsigned NOT NULL default '0',\n          `created` int(10) unsigned NOT NULL default '0',\n          PRIMARY KEY  (`id`),\n          UNIQUE KEY `id_user_idx` (`id`, `userid`),\n          KEY `post_lastmodified_idx` (`lastmodified`),\n          KEY `post_subject_idx` (`subject`)\n        ) TYPE=MyISAM  COMMENT='New moodle post table. Holds data posts such as forum entries or blog entries.';");
        modify_database("", "CREATE TABLE prefix_tags (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `type` varchar(255) NOT NULL default 'official',\n          `userid` int(10) unsigned NOT NULL default'0',\n          `text` varchar(255) NOT NULL default '',\n          PRIMARY KEY  (`id`)\n        ) TYPE=MyISAM COMMENT ='tags structure for moodle.';");
        modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n          `id` int(10) unsigned NOT NULL auto_increment,\n          `entryid` int(10) unsigned NOT NULL default'0',\n          `tagid` int(10) unsigned NOT NULL default'0',\n          `groupid` int(10) unsigned NOT NULL default'0',\n          `courseid` int(10) unsigned NOT NULL default'0',\n          `userid` int(10) unsigned NOT NULL default'0',\n          PRIMARY KEY  (`id`)\n          ) TYPE=MyISAM COMMENT ='tag instance for blogs.';");
    }
    if ($oldversion < 2006031400) {
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            set_config('enrol', 'manual');
        }
    }
    if ($oldversion < 2006031600) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}grade_category` CHANGE `weight` `weight` decimal(5,2) default '0.00';");
    }
    if ($oldversion < 2006032000) {
        table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id');
        modify_database('', "ALTER TABLE prefix_post ADD INDEX post_module_idx (module);");
        modify_database('', "UPDATE prefix_post SET module = 'blog';");
    }
    if ($oldversion < 2006032001) {
        table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid');
        modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_entryid_idx (entryid);");
        modify_database('', "ALTER TABLE prefix_blog_tag_instance ADD INDEX bti_tagid_idx (tagid);");
        modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';");
    }
    if ($oldversion < 2006040500) {
        // Add an index to course_sections that was never upgraded (bug 5100)
        execute_sql(" CREATE INDEX coursesection ON {$CFG->prefix}course_sections (course,section) ", false);
    }
    /// change all the int(11) to int(10) for blogs and tags
    if ($oldversion < 2006041000) {
        table_column('post', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'moduleid', 'moduleid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'coursemoduleid', 'coursemoduleid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'rating', 'rating', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('post', 'format', 'format', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('tags', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('tags', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'id', 'id', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'entryid', 'entryid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'tagid', 'tagid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'groupid', 'groupid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'courseid', 'courseid', 'integer', '10', 'unsigned', '0', 'not null');
        table_column('blog_tag_instance', 'userid', 'userid', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006041001) {
        table_column('cache_text', 'formattedtext', 'formattedtext', 'longblob', '', '', '', 'not null');
    }
    if ($oldversion < 2006041100) {
        table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible');
    }
    if ($oldversion < 2006041801) {
        // forgot auto_increments for ids
        modify_database('', "ALTER TABLE prefix_post CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
        modify_database('', "ALTER TABLE prefix_tags CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
        modify_database('', "ALTER TABLE prefix_blog_tag_instance CHANGE id id INT UNSIGNED NOT NULL AUTO_INCREMENT");
    }
    // changed user->firstname, user->lastname, course->shortname to varchar(100)
    if ($oldversion < 2006041900) {
        table_column('course', 'shortname', 'shortname', 'varchar', '100', '', '', 'not null');
        table_column('user', 'firstname', 'firstname', 'varchar', '100', '', '', 'not null');
        table_column('user', 'lastname', 'lastname', 'varchar', '100', '', '', 'not null');
    }
    if ($oldversion < 2006042400) {
        // Look through table log_display and get rid of duplicates.
        $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display');
        // Drop the log_display table and create it back with an id field.
        execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
        modify_database('', "CREATE TABLE prefix_log_display (\n                               `id` int(10) unsigned NOT NULL auto_increment,\n                               `module` varchar(30),\n                               `action` varchar(40),\n                               `mtable` varchar(30),\n                               `field` varchar(50),\n                               PRIMARY KEY (`id`)\n                               ) TYPE=MyISAM");
        // Add index to ensure that module and action combination is unique.
        modify_database('', "ALTER TABLE prefix_log_display ADD UNIQUE `moduleaction`(`module` , `action`)");
        // Insert the records back in, sans duplicates.
        if ($rs && $rs->RecordCount() > 0) {
            while (!$rs->EOF) {
                $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')";
                execute_sql($sql, false);
                $rs->MoveNext();
            }
        }
    }
    // change tags->type to varchar(20), adding 2 indexes for tags table.
    if ($oldversion < 2006042401) {
        table_column('tags', 'type', 'type', 'varchar', '20', '', '', 'not null');
        modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_typeuserid_idx (type(20), userid)");
        modify_database('', "ALTER TABLE prefix_tags ADD INDEX tags_text_idx(text(255))");
    }
    /***************************************************
     * The following is an effort to change all the    *
     * default NULLs to NOT NULL defaut '' in all      *
     * mysql tables, to prevent 5303 and be consistent *
     ***************************************************/
    if ($oldversion < 2006042800) {
        execute_sql("UPDATE {$CFG->prefix}grade_category SET name='' WHERE name IS NULL");
        table_column('grade_category', 'name', 'name', 'varchar', '64', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_category SET weight='0' WHERE weight IS NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}grade_category change weight weight decimal(5,2) NOT NULL default 0.00");
        execute_sql("UPDATE {$CFG->prefix}grade_item SET courseid='0' WHERE courseid IS NULL");
        table_column('grade_item', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET category='0' WHERE category IS NULL");
        table_column('grade_item', 'category', 'category', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET modid='0' WHERE modid IS NULL");
        table_column('grade_item', 'modid', 'modid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET cminstance='0' WHERE cminstance IS NULL");
        table_column('grade_item', 'cminstance', 'cminstance', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}grade_item SET scale_grade='0' WHERE scale_grade IS NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}grade_item change scale_grade scale_grade float(11,10) NOT NULL default 1.0000000000");
        execute_sql("UPDATE {$CFG->prefix}grade_preferences SET courseid='0' WHERE courseid IS NULL");
        table_column('grade_preferences', 'courseid', 'courseid', 'int', '10', 'unsigned', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET idnumber='' WHERE idnumber IS NULL");
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET icq='' WHERE icq IS NULL");
        table_column('user', 'icq', 'icq', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET skype='' WHERE skype IS NULL");
        table_column('user', 'skype', 'skype', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET yahoo='' WHERE yahoo IS NULL");
        table_column('user', 'yahoo', 'yahoo', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET aim='' WHERE aim IS NULL");
        table_column('user', 'aim', 'aim', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET msn='' WHERE msn IS NULL");
        table_column('user', 'msn', 'msn', 'varchar', '50', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET phone1='' WHERE phone1 IS NULL");
        table_column('user', 'phone1', 'phone1', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET phone2='' WHERE phone2 IS NULL");
        table_column('user', 'phone2', 'phone2', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET institution='' WHERE institution IS NULL");
        table_column('user', 'institution', 'institution', 'varchar', '40', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET department='' WHERE department IS NULL");
        table_column('user', 'department', 'department', 'varchar', '30', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET address='' WHERE address IS NULL");
        table_column('user', 'address', 'address', 'varchar', '70', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET city='' WHERE city IS NULL");
        table_column('user', 'city', 'city', 'varchar', '20', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET country='' WHERE country IS NULL");
        table_column('user', 'country', 'country', 'char', '2', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET lang='' WHERE lang IS NULL");
        table_column('user', 'lang', 'lang', 'varchar', '10', '', 'en', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET lastIP='' WHERE lastIP IS NULL");
        table_column('user', 'lastIP', 'lastIP', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET secret='' WHERE secret IS NULL");
        table_column('user', 'secret', 'secret', 'varchar', '15', '', '', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET picture='0' WHERE picture IS NULL");
        table_column('user', 'picture', 'picture', 'tinyint', '1', '', '0', 'not null');
        execute_sql("UPDATE {$CFG->prefix}user SET url='' WHERE url IS NULL");
        table_column('user', 'url', 'url', 'varchar', '255', '', '', 'not null');
    }
    if ($oldversion < 2006050400) {
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` DROP INDEX {$CFG->prefix}user_email_idx;", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_deleted (deleted)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_confirmed (confirmed)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_firstname (firstname)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastname (lastname)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_city (city)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_country (country)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_lastaccess (lastaccess)", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}user` ADD INDEX user_email (email)", false);
    }
    if ($oldversion < 2006050500) {
        table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
    }
    if ($oldversion < 2006050501) {
        table_column('sessions', 'data', 'data', 'mediumtext', '', '', '', 'not null');
    }
    // renaming of reads and writes for stats_user_xyz
    if ($oldversion < 2006052400) {
        // change this later
        // we are using this because we want silent updates
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_daily` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_weekly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `reads` statsreads int(10) unsigned  NOT NULL default 0", false);
        execute_sql("ALTER TABLE `{$CFG->prefix}stats_user_monthly` CHANGE `writes` statswrites int(10) unsigned  NOT NULL default 0", false);
    }
    // Adding some missing log actions
    if ($oldversion < 2006060400) {
        // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
        if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
        }
    }
    //Renaming lastIP to lastip (all fields lowercase)
    if ($oldversion < 2006060900) {
        //Only if it exists
        $fields = $db->MetaColumnNames($CFG->prefix . 'user');
        if (in_array('lastIP', $fields)) {
            table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "not null", "currentlogin");
        }
    }
    // Change in MySQL 5.0.3 concerning how decimals are stored. Mimic from 16_STABLE
    // this isn't dangerous because it's a simple type change, but be careful with
    // versions and duplicate work in order to provide smooth upgrade paths.
    if ($oldversion < 2006071800) {
        table_column('grade_letter', 'grade_high', 'grade_high', 'decimal(5,2)', '', '', '100.00', 'not null', '');
        table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', '');
    }
    if ($oldversion < 2006080400) {
        execute_sql("CREATE TABLE {$CFG->prefix}role (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `name` varchar(255) NOT NULL default '',\n                              `shortname` varchar(100) NOT NULL default '',\n                              `description` text NOT NULL default '',\n                              `sortorder` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}context (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `level` int(10) unsigned NOT NULL default '0',\n                              `instanceid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_assignments (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `contextid` int(10) unsigned NOT NULL default '0',\n                              `userid` int(10) unsigned NOT NULL default '0',\n                              `hidden` int(1) unsigned NOT NULL default '0',\n                              `timestart` int(10) unsigned NOT NULL default '0',\n                              `timeend` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              `modifierid` int(10) unsigned NOT NULL default '0',\n                              `enrol` varchar(20) NOT NULL default '',\n                              `sortorder` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY  (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_capabilities (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `contextid` int(10) unsigned NOT NULL default '0',\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `capability` varchar(255) NOT NULL default '',\n                              `permission` int(10) unsigned NOT NULL default '0',\n                              `timemodified` int(10) unsigned NOT NULL default '0',\n                              `modifierid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_deny_grant (\n                              `id` int(10) unsigned NOT NULL auto_increment,\n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `unviewableroleid` int(10) unsigned NOT NULL default '0',\n                              PRIMARY KEY (`id`)\n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}capabilities ( \n                              `id` int(10) unsigned NOT NULL auto_increment, \n                              `name` varchar(255) NOT NULL default '', \n                              `captype` varchar(50) NOT NULL default '', \n                              `contextlevel` int(10) unsigned NOT NULL default '0', \n                              `component` varchar(100) NOT NULL default '', \n                              PRIMARY KEY (`id`) \n                            )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_names ( \n                              `id` int(10) unsigned NOT NULL auto_increment, \n                              `roleid` int(10) unsigned NOT NULL default '0',\n                              `contextid` int(10) unsigned NOT NULL default '0', \n                              `text` text NOT NULL default '',\n                              PRIMARY KEY (`id`) \n                            )", true);
    }
    if ($oldversion < 2006081000) {
        execute_sql("ALTER TABLE `{$CFG->prefix}role` ADD INDEX `sortorder` (`sortorder`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD INDEX `instanceid` (`instanceid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `level-instanceid` (`level`, `instanceid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `userid` (`userid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD UNIQUE INDEX `contextid-roleid-userid` (`contextid`, `roleid`, `userid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_assignments` ADD INDEX `sortorder` (`sortorder`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `modifierid` (`modifierid`)", true);
        // MDL-10640  adding missing index from upgrade
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD INDEX `capability` (`capability`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` ADD UNIQUE INDEX `roleid-contextid-capability` (`roleid`, `contextid`, `capability`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD INDEX `unviewableroleid` (`unviewableroleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_deny_grant` ADD UNIQUE INDEX `roleid-unviewableroleid` (`roleid`, `unviewableroleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}capabilities` ADD UNIQUE INDEX `name` (`name`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `roleid` (`roleid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD INDEX `contextid` (`contextid`)", true);
        execute_sql("ALTER TABLE `{$CFG->prefix}role_names` ADD UNIQUE INDEX `roleid-contextid` (`roleid`, `contextid`)", true);
    }
    if ($oldversion < 2006081600) {
        execute_sql("ALTER TABLE `{$CFG->prefix}role_capabilities` CHANGE permission permission int(10) NOT NULL default '0'", true);
    }
    // drop role_deny_grant table, and create 2 new ones
    if ($oldversion < 2006081700) {
        execute_sql("DROP TABLE `{$CFG->prefix}role_deny_grant`", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_allow_assign (\n                    `id` int(10) unsigned NOT NULL auto_increment,\n                    `roleid` int(10) unsigned NOT NULL default '0',\n                    `allowassign` int(10) unsigned NOT NULL default '0',\n                    KEY `roleid` (`roleid`),\n                    KEY `allowassign` (`allowassign`),\n                    UNIQUE KEY `roleid-allowassign` (`roleid`, `allowassign`),\n                    PRIMARY KEY (`id`)\n                    )", true);
        execute_sql("CREATE TABLE {$CFG->prefix}role_allow_override (\n                    `id` int(10) unsigned NOT NULL auto_increment,\n                    `roleid` int(10) unsigned NOT NULL default '0',\n                    `allowoverride` int(10) unsigned NOT NULL default '0',\n                    KEY `roleid` (`roleid`),\n                    KEY `allowoverride` (`allowoverride`),\n                    UNIQUE KEY `roleid-allowoverride` (`roleid`, `allowoverride`),\n                    PRIMARY KEY (`id`)\n                    )", true);
    }
    if ($oldversion < 2006082100) {
        execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `level-instanceid`;", false);
        table_column('context', 'level', 'aggregatelevel', 'int', '10', 'unsigned', '0', 'not null', '');
        execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `aggregatelevel-instanceid` (`aggregatelevel`, `instanceid`)", false);
    }
    if ($oldversion < 2006082200) {
        table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
    }
    if ($oldversion < 2006082800) {
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(64) NOT NULL default '',\n                expiry DATETIME NOT NULL,\n                expireref VARCHAR(250),\n                created DATETIME NOT NULL,\n                modified DATETIME NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT  PRIMARY KEY (sesskey)\n            ) COMMENT='Optional database session storage in new format, not used by default';", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083001) {
        table_column('sessions2', 'sessdata', 'sessdata', 'LONGTEXT', '', '', '', '', '');
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course CHANGE modinfo modinfo longtext NULL AFTER showgrades");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories CHANGE description description text NULL AFTER name");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user CHANGE description description text NULL AFTER url");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE summary summary text NULL AFTER section");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections CHANGE sequence sequence text NULL AFTER section");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    `id` int(10) unsigned NOT NULL auto_increment, \n                    `userid` int(10) unsigned NOT NULL default '0',\n                    `courseid` int(10) unsigned NOT NULL default '0', \n                    `timeaccess` int(10) unsigned NOT NULL default '0', \n                    KEY `userid` (`userid`),\n                    KEY `courseid` (`courseid`),\n                    UNIQUE KEY `userid-courseid` (`userid`, `courseid`),\n                    PRIMARY KEY (`id`) \n                    )TYPE=MYISAM COMMENT ='time user last accessed any page in a course';", true);
    }
    if ($oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if ($oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
                                $updated->id = $role->id;
                                $updated->shortname = $name . $i;
                                update_record('role', $updated);
                                $i++;
                            }
                        }
                    }
                }
            }
        }
    }
    /// Tables for customisable user profile fields
    if ($oldversion < 2006092000) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        name VARCHAR(255) NOT NULL default '',\n                        datatype VARCHAR(255) NOT NULL default '',\n                        categoryid BIGINT(10) unsigned NOT NULL default 0,\n                        sortorder BIGINT(10) unsigned NOT NULL default 0,\n                        required TINYINT(2) unsigned NOT NULL default 0,\n                        locked TINYINT(2) unsigned NOT NULL default 0,\n                        visible SMALLINT(4) unsigned NOT NULL default 0,\n                        defaultdata LONGTEXT,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_field COMMENT='Customisable user profile fields';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        name VARCHAR(255) NOT NULL default '',\n                        sortorder BIGINT(10) unsigned NOT NULL default 0,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_category COMMENT='Customisable fields categories';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n                        id BIGINT(10) NOT NULL auto_increment,\n                        userid BIGINT(10) unsigned NOT NULL default 0,\n                        fieldid BIGINT(10) unsigned NOT NULL default 0,\n                        data LONGTEXT NOT NULL,\n                        CONSTRAINT  PRIMARY KEY (id));", true);
        execute_sql("ALTER TABLE {$CFG->prefix}user_info_data COMMENT='Data for the customisable user fields';", true);
    }
    if ($oldversion < 2006092200) {
        table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
        /*        execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
                execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);   // see 2006092409 below  */
    }
    if ($oldversion < 2006092201) {
        execute_sql('TRUNCATE TABLE ' . $CFG->prefix . 'cache_text', true);
        table_column('cache_text', 'formattedtext', 'formattedtext', 'longtext', '', '', '', 'not null');
    }
    if ($oldversion < 2006092302) {
        // fix sortorder first if needed
        if ($roles = get_all_roles()) {
            $i = 0;
            foreach ($roles as $rolex) {
                if ($rolex->sortorder != $i) {
                    $r = new object();
                    $r->id = $rolex->id;
                    $r->sortorder = $i;
                    update_record('role', $r);
                }
                $i++;
            }
        }
        /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;", false);
                execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)", false);*/
    }
    if ($oldversion < 2006092400) {
        table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092409) {
        // ok, once more and now correctly!
        execute_sql("DROP INDEX `aggregatelevel-instanceid` ON {$CFG->prefix}context ;", false);
        execute_sql("DROP INDEX `contextlevel-instanceid` ON {$CFG->prefix}context ;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix ON {$CFG->prefix}role ;", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role ;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
    }
    if ($oldversion < 2006092601) {
        table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
 /**
  * (non-PHPdoc)
  *
  * @see offlinequiz_default_report::display()
  */
 public function display($offlinequiz, $cm, $course)
 {
     global $CFG, $OUTPUT, $SESSION, $DB;
     // Define some strings.
     $strtimeformat = get_string('strftimedatetime');
     $letterstr = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     offlinequiz_load_useridentification();
     $offlinequizconfig = get_config('offlinequiz');
     // Deal with actions.
     $action = optional_param('action', '', PARAM_ACTION);
     // Only print headers if not asked to download data or delete data.
     if (!($download = optional_param('download', null, PARAM_TEXT)) && !$action == 'delete') {
         $this->print_header_and_tabs($cm, $course, $offlinequiz, 'overview');
         echo $OUTPUT->box_start('linkbox');
         echo $OUTPUT->heading(format_string($offlinequiz->name));
         echo $OUTPUT->heading(get_string('results', 'offlinequiz'));
         require_once $CFG->libdir . '/grouplib.php';
         echo groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/offlinequiz/report.php?id=' . $cm->id . '&mode=overview', true);
         echo $OUTPUT->box_end();
         echo '<br/>';
     }
     $context = context_module::instance($cm->id);
     $systemcontext = context_system::instance();
     // Set table options.
     $noresults = optional_param('noresults', 0, PARAM_INT);
     $pagesize = optional_param('pagesize', 10, PARAM_INT);
     $groupid = optional_param('group', 0, PARAM_INT);
     if ($pagesize < 1) {
         $pagesize = 10;
     }
     $answerletters = 'abcdefghijklmnopqrstuvwxyz';
     if ($action == 'delete' && confirm_sesskey()) {
         $selectedresultids = array();
         $params = (array) data_submitted();
         foreach ($params as $key => $value) {
             if (preg_match('!^s([0-9]+)$!', $key, $matches)) {
                 $selectedresultids[] = $matches[1];
             }
         }
         if ($selectedresultids) {
             foreach ($selectedresultids as $resultid) {
                 if ($resultid && ($todelete = $DB->get_record('offlinequiz_results', array('id' => $resultid)))) {
                     offlinequiz_delete_result($resultid, $context);
                     // Log this event.
                     $params = array('objectid' => $resultid, 'relateduserid' => $todelete->userid, 'context' => context_module::instance($cm->id), 'other' => array('mode' => 'overview'));
                     $event = \mod_offlinequiz\event\attempt_deleted::create($params);
                     $event->trigger();
                     // Change the status of all related pages with error 'resultexists' to 'suspended'.
                     $user = $DB->get_record('user', array('id' => $todelete->userid));
                     $group = $DB->get_record('offlinequiz_groups', array('id' => $todelete->offlinegroupid));
                     $sql = "SELECT id\n                                  FROM {offlinequiz_scanned_pages}\n                                 WHERE offlinequizid = :offlinequizid\n                                   AND userkey = :userkey\n                                   AND groupnumber = :groupnumber\n                                   AND status = 'error'\n                                   AND (error = 'resultexists' OR error = 'differentresultexists')";
                     $params = array('offlinequizid' => $offlinequiz->id, 'userkey' => $user->{$offlinequizconfig->ID_field}, 'groupnumber' => $group->number);
                     $otherpages = $DB->get_records_sql($sql, $params);
                     foreach ($otherpages as $page) {
                         $DB->set_field('offlinequiz_scanned_pages', 'status', 'suspended', array('id' => $page->id));
                         $DB->set_field('offlinequiz_scanned_pages', 'error', '', array('id' => $page->id));
                     }
                 }
             }
             offlinequiz_grade_item_update($offlinequiz, 'reset');
             offlinequiz_update_grades($offlinequiz);
             redirect(new moodle_url('/mod/offlinequiz/report.php', array('mode' => 'overview', 'id' => $cm->id, 'noresults' => $noresults, 'pagesize' => $pagesize)));
         }
     }
     // Now check if asked download of data.
     if ($download) {
         $filename = clean_filename("{$course->shortname} " . format_string($offlinequiz->name, true));
         $sort = '';
     }
     // Fetch the group data.
     $groups = $DB->get_records('offlinequiz_groups', array('offlinequizid' => $offlinequiz->id), 'number', '*', 0, $offlinequiz->numgroups);
     // Define table columns.
     $tablecolumns = array('checkbox', 'picture', 'fullname', $offlinequizconfig->ID_field, 'timestart', 'offlinegroupid', 'sumgrades');
     $tableheaders = array('<input type="checkbox" name="toggle" onClick="if (this.checked) {select_all_in(\'DIV\',null,\'tablecontainer\');}
             else {deselect_all_in(\'DIV\',null,\'tablecontainer\');}"/>', '', get_string('fullname'), get_string($offlinequizconfig->ID_field), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
     $checked = array();
     // Get participants list.
     $withparticipants = false;
     if ($lists = $DB->get_records('offlinequiz_p_lists', array('offlinequizid' => $offlinequiz->id))) {
         $withparticipants = true;
         $tablecolumns[] = 'checked';
         $tableheaders[] = get_string('present', 'offlinequiz');
         foreach ($lists as $list) {
             $participants = $DB->get_records('offlinequiz_participants', array('listid' => $list->id));
             foreach ($participants as $participant) {
                 $checked[$participant->userid] = $participant->checked;
             }
         }
     }
     if (!$download) {
         // Set up the table.
         $params = array('offlinequiz' => $offlinequiz, 'noresults' => $noresults, 'pagesize' => $pagesize);
         $table = new offlinequiz_results_table('mod-offlinequiz-report-overview-report', $params);
         $table->define_columns($tablecolumns);
         $table->define_headers($tableheaders);
         $table->define_baseurl($CFG->wwwroot . '/mod/offlinequiz/report.php?mode=overview&amp;id=' . $cm->id . '&amp;noresults=' . $noresults . '&amp;pagesize=' . $pagesize);
         $table->sortable(true);
         $table->no_sorting('checkbox');
         if ($withparticipants) {
             $table->no_sorting('checked');
         }
         $table->column_suppress('picture');
         $table->column_suppress('fullname');
         $table->column_class('picture', 'picture');
         $table->column_class($offlinequizconfig->ID_field, 'userkey');
         $table->column_class('timestart', 'timestart');
         $table->column_class('offlinegroupid', 'offlinegroupid');
         $table->column_class('sumgrades', 'sumgrades');
         $table->set_attribute('cellpadding', '2');
         $table->set_attribute('id', 'attempts');
         $table->set_attribute('class', 'generaltable generalbox');
         // Start working -- this is necessary as soon as the niceties are over.
         $table->setup();
     } else {
         if ($download == 'ODS') {
             require_once "{$CFG->libdir}/odslib.class.php";
             $filename .= ".ods";
             // Creating a workbook.
             $workbook = new MoodleODSWorkbook("-");
             // Sending HTTP headers.
             $workbook->send($filename);
             // Creating the first worksheet.
             $sheettitle = get_string('reportoverview', 'offlinequiz');
             $myxls = $workbook->add_worksheet($sheettitle);
             // Format types.
             $format = $workbook->add_format();
             $format->set_bold(0);
             $formatbc = $workbook->add_format();
             $formatbc->set_bold(1);
             $formatbc->set_align('center');
             $formatb = $workbook->add_format();
             $formatb->set_bold(1);
             $formaty = $workbook->add_format();
             $formaty->set_bg_color('yellow');
             $formatc = $workbook->add_format();
             $formatc->set_align('center');
             $formatr = $workbook->add_format();
             $formatr->set_bold(1);
             $formatr->set_color('red');
             $formatr->set_align('center');
             $formatg = $workbook->add_format();
             $formatg->set_bold(1);
             $formatg->set_color('green');
             $formatg->set_align('center');
             // Here starts workshhet headers.
             $headers = array(get_string($offlinequizconfig->ID_field), get_string('firstname'), get_string('lastname'), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
             if (!empty($withparticipants)) {
                 $headers[] = get_string('present', 'offlinequiz');
             }
             $colnum = 0;
             foreach ($headers as $item) {
                 $myxls->write(0, $colnum, $item, $formatbc);
                 $colnum++;
             }
             $rownum = 1;
         } else {
             if ($download == 'Excel') {
                 require_once "{$CFG->libdir}/excellib.class.php";
                 $filename .= ".xls";
                 // Creating a workbook.
                 $workbook = new MoodleExcelWorkbook("-");
                 // Sending HTTP headers.
                 $workbook->send($filename);
                 // Creating the first worksheet.
                 $sheettitle = get_string('results', 'offlinequiz');
                 $myxls = $workbook->add_worksheet($sheettitle);
                 // Format types.
                 $format = $workbook->add_format();
                 $format->set_bold(0);
                 $formatbc = $workbook->add_format();
                 $formatbc->set_bold(1);
                 $formatbc->set_align('center');
                 $formatb = $workbook->add_format();
                 $formatb->set_bold(1);
                 $formaty = $workbook->add_format();
                 $formaty->set_bg_color('yellow');
                 $formatc = $workbook->add_format();
                 $formatc->set_align('center');
                 $formatr = $workbook->add_format();
                 $formatr->set_bold(1);
                 $formatr->set_color('red');
                 $formatr->set_align('center');
                 $formatg = $workbook->add_format();
                 $formatg->set_bold(1);
                 $formatg->set_color('green');
                 $formatg->set_align('center');
                 // Here starts worksheet headers.
                 $headers = array(get_string($offlinequizconfig->ID_field), get_string('firstname'), get_string('lastname'), get_string('importedon', 'offlinequiz'), get_string('group'), get_string('grade', 'offlinequiz'));
                 if (!empty($withparticipants)) {
                     $headers[] = get_string('present', 'offlinequiz');
                 }
                 $colnum = 0;
                 foreach ($headers as $item) {
                     $myxls->write(0, $colnum, $item, $formatbc);
                     $colnum++;
                 }
                 $rownum = 1;
             } else {
                 if ($download == 'CSV') {
                     $filename .= ".csv";
                     header("Content-Encoding: UTF-8");
                     header("Content-Type: text/csv; charset=utf-8");
                     header("Content-Disposition: attachment; filename=\"{$filename}\"");
                     header("Expires: 0");
                     header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                     header("Pragma: public");
                     echo "";
                     // UTF-8 BOM.
                     $headers = get_string($offlinequizconfig->ID_field) . ", " . get_string('fullname') . ", " . get_string('importedon', 'offlinequiz') . ", " . get_string('group') . ", " . get_string('grade', 'offlinequiz');
                     if (!empty($withparticipants)) {
                         $headers .= ", " . get_string('present', 'offlinequiz');
                     }
                     echo $headers . " \n";
                 } else {
                     if ($download == 'CSVplus1' || $download == 'CSVpluspoints') {
                         $filename .= ".csv";
                         header("Content-Encoding: UTF-8");
                         header("Content-Type: text/csv; charset=utf-8");
                         header("Content-Disposition: attachment; filename=\"{$filename}\"");
                         header("Expires: 0");
                         header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
                         header("Pragma: public");
                         echo "";
                         // UTF-8 BOM.
                         // Print the table headers.
                         echo get_string('firstname') . ',' . get_string('lastname') . ',' . get_string($offlinequizconfig->ID_field) . ',' . get_string('group');
                         $maxquestions = offlinequiz_get_maxquestions($offlinequiz, $groups);
                         for ($i = 0; $i < $maxquestions; $i++) {
                             echo ', ' . get_string('question') . ' ' . ($i + 1);
                         }
                         echo "\n";
                         // Print the correct answer bit-strings.
                         foreach ($groups as $group) {
                             if ($group->templateusageid) {
                                 $quba = question_engine::load_questions_usage_by_activity($group->templateusageid);
                                 $slots = $quba->get_slots();
                                 echo ', ,' . get_string('correct', 'offlinequiz');
                                 echo ',' . $group->number;
                                 foreach ($slots as $slot) {
                                     $slotquestion = $quba->get_question($slot);
                                     $qtype = $slotquestion->get_type_name();
                                     if ($qtype == 'multichoice' || $qtype == 'multichoiceset') {
                                         $attempt = $quba->get_question_attempt($slot);
                                         $order = $slotquestion->get_order($attempt);
                                         // Order of the answers.
                                         $tempstr = ",";
                                         $letters = array();
                                         $counter = 0;
                                         foreach ($order as $key => $answerid) {
                                             $fraction = $DB->get_field('question_answers', 'fraction', array('id' => $answerid));
                                             if ($fraction > 0) {
                                                 $letters[] = $answerletters[$counter];
                                             }
                                             $counter++;
                                         }
                                         if (empty($letters)) {
                                             $tempstr .= '99';
                                         } else {
                                             $tempstr .= implode('/', $letters);
                                         }
                                         echo $tempstr;
                                     }
                                 }
                                 echo "\n";
                             }
                         }
                     }
                 }
             }
         }
     }
     $coursecontext = context_course::instance($course->id);
     $contextids = $coursecontext->get_parent_context_ids(true);
     // Construct the SQL
     // First get roleids for students from leagcy.
     if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
         error("No roles with capability 'moodle/offlinequiz:attempt' defined in system context");
     }
     $roleids = array();
     foreach ($roles as $role) {
         $roleids[] = $role->id;
     }
     $rolelist = implode(',', $roleids);
     $select = "SELECT " . $DB->sql_concat('u.id', "'#'", "COALESCE(qa.usageid, 0)") . " AS uniqueid,\n        qa.id AS resultid, u.id, qa.usageid, qa.offlinegroupid, qa.status,\n        u.id AS userid, u.firstname, u.lastname,\n        u.alternatename, u.middlename, u.firstnamephonetic, u.lastnamephonetic,\n        u.picture, u." . $offlinequizconfig->ID_field . ",\n        qa.sumgrades, qa.timefinish, qa.timestart, qa.timefinish - qa.timestart AS duration ";
     $result = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
     list($contexttest, $cparams) = $result;
     list($roletest, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
     $from = "FROM {user} u\n                  JOIN {role_assignments} ra ON ra.userid = u.id\n             LEFT JOIN {offlinequiz_results} qa ON u.id = qa.userid AND qa.offlinequizid = :offlinequizid\n             ";
     $where = " WHERE ra.contextid {$contexttest} AND ra.roleid {$roletest} ";
     $params = array('offlinequizid' => $offlinequiz->id);
     $params = array_merge($params, $cparams, $rparams);
     if ($groupid) {
         $from .= " JOIN {groups_members} gm ON gm.userid = u.id ";
         $where .= " AND gm.groupid = :groupid ";
         $params['groupid'] = $groupid;
     }
     if (empty($noresults)) {
         $where = $where . " AND qa.userid IS NOT NULL\n                                AND qa.status = 'complete'";
         // Show ONLY students with results.
     } else {
         if ($noresults == 1) {
             // The value noresults = 1 means only no results, so make the left join ask for only records
             // where the right is null (no results).
             $where .= ' AND qa.userid IS NULL';
             // Show ONLY students without results.
         } else {
             if ($noresults == 3) {
                 // We want all results, also the partial ones.
                 $from = "FROM {user} u\n                      JOIN {offlinequiz_results} qa ON u.id = qa.userid ";
                 $where = " WHERE qa.offlinequizid = :offlinequizid";
             }
         }
     }
     // The value noresults = 2 means we want all students, with or without results.
     $countsql = 'SELECT COUNT(DISTINCT(u.id)) ' . $from . $where;
     if (!$download) {
         // Count the records NOW, before funky question grade sorting messes up $from.
         $totalinitials = $DB->count_records_sql($countsql, $params);
         // Add extra limits due to initials bar.
         list($ttest, $tparams) = $table->get_sql_where();
         if (!empty($ttest)) {
             $where .= ' AND ' . $ttest;
             $countsql .= ' AND ' . $ttest;
             $params = array_merge($params, $tparams);
         }
         $total = $DB->count_records_sql($countsql, $params);
         // Add extra limits due to sorting by question grade.
         $sort = $table->get_sql_sort();
         // Fix some wired sorting.
         if (empty($sort)) {
             $sort = ' ORDER BY u.lastname';
         } else {
             $sort = ' ORDER BY ' . $sort;
         }
         $table->pagesize($pagesize, $total);
     }
     // Fetch the results.
     if (!$download) {
         $results = $DB->get_records_sql($select . $from . $where . $sort, $params, $table->get_page_start(), $table->get_page_size());
     } else {
         $results = $DB->get_records_sql($select . $from . $where . $sort, $params);
     }
     // Build table rows.
     if (!$download) {
         $table->initialbars(true);
     }
     if (!empty($results) || !empty($noresults)) {
         foreach ($results as $result) {
             $user = $DB->get_record('user', array('id' => $result->userid));
             $picture = $OUTPUT->user_picture($user, array('courseid' => $course->id));
             if (!empty($result->resultid)) {
                 $checkbox = '<input type="checkbox" name="s' . $result->resultid . '" value="' . $result->resultid . '" />';
             } else {
                 $checkbox = '';
             }
             if (!empty($result) && (empty($result->resultid) || $result->timefinish == 0)) {
                 $resultdate = '-';
             } else {
                 $resultdate = userdate($result->timefinish, $strtimeformat);
             }
             if (!empty($result) && $result->offlinegroupid) {
                 $groupletter = $letterstr[$groups[$result->offlinegroupid]->number];
             } else {
                 $groupletter = '-';
             }
             $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $result->userid . '&amp;course=' . $course->id . '">' . fullname($result) . '</a>';
             if (!$download) {
                 $row = array($checkbox, $picture, $userlink, $result->{$offlinequizconfig->ID_field}, $resultdate, $groupletter);
             } else {
                 $row = array($result->{$offlinequizconfig->ID_field}, $result->firstname, $result->lastname, $resultdate, $groupletter);
             }
             if (!empty($result) && $result->offlinegroupid) {
                 $outputgrade = format_float($result->sumgrades / $groups[$result->offlinegroupid]->sumgrades * $offlinequiz->grade, $offlinequiz->decimalpoints);
             } else {
                 $outputgrade = '-';
             }
             if (!$download) {
                 if ($result->status == 'partial') {
                     $row[] = get_string('partial', 'offlinequiz');
                 } else {
                     if ($result->sumgrades === null) {
                         $row[] = '-';
                     } else {
                         $row[] = '<a href="review.php?q=' . $offlinequiz->id . '&amp;resultid=' . $result->resultid . '">' . $outputgrade . '</a>';
                     }
                 }
                 if ($withparticipants) {
                     $row[] = !empty($checked[$result->userid]) ? "<img src=\"{$CFG->wwwroot}/mod/offlinequiz/pix/tick.gif\" alt=\"" . get_string('ischecked', 'offlinequiz') . "\">" : "<img src=\"{$CFG->wwwroot}/mod/offlinequiz/pix/cross.gif\" alt=\"" . get_string('isnotchecked', 'offlinequiz') . "\">";
                 }
             } else {
                 if ($download != 'CSVplus1' || $download == 'CSVpluspoints') {
                     $row[] = $result->sumgrades === null ? '-' : $outputgrade;
                     if ($withparticipants) {
                         if (array_key_exists($result->userid, $checked)) {
                             $row[] = $checked[$result->userid] ? get_string('ok') : '-';
                         } else {
                             $row[] = '-';
                         }
                     }
                 }
             }
             if (!$download) {
                 $table->add_data($row);
             } else {
                 if ($download == 'Excel' or $download == 'ODS') {
                     $colnum = 0;
                     foreach ($row as $item) {
                         $myxls->write($rownum, $colnum, $item, $format);
                         $colnum++;
                     }
                     $rownum++;
                 } else {
                     if ($download == 'CSV') {
                         $text = implode(',', $row);
                         echo $text . "\n";
                     } else {
                         if ($download == 'CSVplus1' || $download == 'CSVpluspoints') {
                             $text = $row[1] . ',' . $row[2] . ',' . $row[0] . ',' . $groups[$result->offlinegroupid]->number;
                             if ($pages = $DB->get_records('offlinequiz_scanned_pages', array('resultid' => $result->resultid), 'pagenumber ASC')) {
                                 foreach ($pages as $page) {
                                     if ($page->status == 'ok' || $page->status == 'submitted') {
                                         $choices = $DB->get_records('offlinequiz_choices', array('scannedpageid' => $page->id), 'slotnumber, choicenumber');
                                         $counter = 0;
                                         $oldslot = -1;
                                         $letters = array();
                                         foreach ($choices as $choice) {
                                             if ($oldslot == -1) {
                                                 $oldslot = $choice->slotnumber;
                                             } else {
                                                 if ($oldslot != $choice->slotnumber) {
                                                     if (empty($letters)) {
                                                         $text .= ',99';
                                                     } else {
                                                         $text .= ',' . implode('/', $letters);
                                                     }
                                                     $counter = 0;
                                                     $oldslot = $choice->slotnumber;
                                                     $letters = array();
                                                 }
                                             }
                                             if ($choice->value == 1) {
                                                 $letters[] = $answerletters[$counter];
                                             }
                                             $counter++;
                                         }
                                         if (empty($letters)) {
                                             $text .= ',99';
                                         } else {
                                             $text .= ',' . implode('/', $letters);
                                         }
                                     }
                                 }
                             }
                             echo $text . "\n";
                             if ($download == 'CSVpluspoints') {
                                 $text = $row[1] . ',' . $row[2] . ',' . $row[0] . ',' . $groups[$result->offlinegroupid]->number;
                                 $quba = question_engine::load_questions_usage_by_activity($result->usageid);
                                 $slots = $quba->get_slots();
                                 foreach ($slots as $slot) {
                                     $slotquestion = $quba->get_question($slot);
                                     $attempt = $quba->get_question_attempt($slot);
                                     $text .= ',' . format_float($attempt->get_mark(), $offlinequiz->decimalpoints, false);
                                 }
                                 echo $text . "\n";
                             }
                         }
                     }
                 }
             }
         }
         // End foreach ($results...
     } else {
         if (!$download) {
             $table->print_initials_bar();
         }
     }
     if (!$download) {
         // Print table.
         $table->finish_html();
         if (!empty($results)) {
             echo '<form id="downloadoptions" action="report.php" method="get">';
             echo ' <input type="hidden" name="id" value="' . $cm->id . '" />';
             echo ' <input type="hidden" name="q" value="' . $offlinequiz->id . '" />';
             echo ' <input type="hidden" name="mode" value="overview" />';
             echo ' <input type="hidden" name="noheader" value="yes" />';
             echo ' <table class="boxaligncenter"><tr><td>';
             $options = array('Excel' => get_string('excelformat', 'offlinequiz'), 'ODS' => get_string('odsformat', 'offlinequiz'), 'CSV' => get_string('csvformat', 'offlinequiz'), 'CSVplus1' => get_string('csvplus1format', 'offlinequiz'), 'CSVpluspoints' => get_string('csvpluspointsformat', 'offlinequiz'));
             print_string('downloadresultsas', 'offlinequiz');
             echo "</td><td>";
             echo html_writer::select($options, 'download', '', false);
             echo ' <input type="submit" value="' . get_string('download') . '" />';
             echo ' <script type="text/javascript">' . "\n<!--\n" . 'document.getElementById("noscriptmenuaction").style.display = "none";' . "\n-->\n" . '</script>';
             echo " </td>\n";
             echo "<td>";
             echo "</td>\n";
             echo '</tr></table></form>';
         }
     } else {
         if ($download == 'Excel' || $download == 'ODS') {
             $workbook->close();
             exit;
         } else {
             if ($download == 'CSV' || $download == 'CSVplus1' || $download == 'CSVpluspoints') {
                 exit;
             }
         }
     }
     // Print display options.
     echo '<div class="controls">';
     echo '<form id="options" action="report.php" method="get">';
     echo '<div class=centerbox>';
     echo '<p>' . get_string('displayoptions', 'offlinequiz') . ': </p>';
     echo '<input type="hidden" name="id" value="' . $cm->id . '" />';
     echo '<input type="hidden" name="q" value="' . $offlinequiz->id . '" />';
     echo '<input type="hidden" name="mode" value="overview" />';
     echo '<input type="hidden" name="detailedmarks" value="0" />';
     echo '<table id="overview-options" class="boxaligncenter">';
     echo '<tr align="left">';
     echo '<td><label for="pagesize">' . get_string('pagesizeparts', 'offlinequiz') . '</label></td>';
     echo '<td><input type="text" id="pagesize" name="pagesize" size="3" value="' . $pagesize . '" /></td>';
     echo '</tr>';
     echo '<tr align="left">';
     echo '<td colspan="2">';
     $options = array();
     $options[] = get_string('attemptsonly', 'offlinequiz');
     $options[] = get_string('noattemptsonly', 'offlinequiz');
     $options[] = get_string('allstudents', 'offlinequiz');
     $options[] = get_string('allresults', 'offlinequiz');
     echo html_writer::select($options, 'noresults', $noresults, '');
     echo '</td></tr>';
     echo '<tr><td colspan="2" align="center">';
     echo '<input type="submit" value="' . get_string('go') . '" />';
     echo '</td></tr></table>';
     echo '</div>';
     echo '</form>';
     echo '</div>';
     echo "\n";
     return true;
 }
Example #10
0
/**
 * Gets potential group members for grouping
 * @param int $courseid The id of the course
 * @param int $roleid The role to select users from
 * @param string $orderby The colum to sort users by
 * @return array An array of the users
 */
function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname,firstname')
{
    global $CFG;
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    $rolenames = array();
    $avoidroles = array();
    if ($roles = get_roles_used_in_context($context, true)) {
        $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
        $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
        foreach ($roles as $role) {
            if (!isset($canviewroles[$role->id])) {
                // Avoid this role (eg course creator)
                $avoidroles[] = $role->id;
                unset($roles[$role->id]);
                continue;
            }
            if (isset($doanythingroles[$role->id])) {
                // Avoid this role (ie admin)
                $avoidroles[] = $role->id;
                unset($roles[$role->id]);
                continue;
            }
            $rolenames[$role->id] = strip_tags(role_get_name($role, $context));
            // Used in menus etc later on
        }
    }
    $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber ';
    $from = "FROM {$CFG->prefix}user u INNER JOIN\n               {$CFG->prefix}role_assignments r on u.id=r.userid ";
    if ($avoidroles) {
        $adminroles = 'AND r.roleid NOT IN (';
        $adminroles .= implode(',', $avoidroles);
        $adminroles .= ')';
    } else {
        $adminroles = '';
    }
    // we are looking for all users with this role assigned in this context or higher
    if ($usercontexts = get_parent_contexts($context)) {
        $listofcontexts = '(' . implode(',', $usercontexts) . ')';
    } else {
        $listofcontexts = '(' . $sitecontext->id . ')';
        // must be site
    }
    if ($roleid) {
        $selectrole = " AND r.roleid = {$roleid} ";
    } else {
        $selectrole = " ";
    }
    $where = "WHERE (r.contextid = {$context->id} OR r.contextid in {$listofcontexts})\n                     AND u.deleted = 0 {$selectrole}\n                     AND u.username != 'guest'\n                     {$adminroles} ";
    $order = "ORDER BY {$orderby} ";
    return get_records_sql($select . $from . $where . $order);
}
Example #11
0
/**
 * Deletes cached capabilities that are no longer needed by the component.
 * Also unassigns these capabilities from any roles that have them.
 *
 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
 * @param array $newcapdef array of the new capability definitions that will be
 *                     compared with the cached capabilities
 * @return int number of deprecated capabilities that have been removed
 */
function capabilities_cleanup($component, $newcapdef = null)
{
    global $DB;
    $removedcount = 0;
    if ($cachedcaps = get_cached_capabilities($component)) {
        foreach ($cachedcaps as $cachedcap) {
            if (empty($newcapdef) || array_key_exists($cachedcap->name, $newcapdef) === false) {
                // Remove from capabilities cache.
                $DB->delete_records('capabilities', array('name' => $cachedcap->name));
                $removedcount++;
                // Delete from roles.
                if ($roles = get_roles_with_capability($cachedcap->name)) {
                    foreach ($roles as $role) {
                        if (!unassign_capability($cachedcap->name, $role->id)) {
                            print_error('cannotunassigncap', 'error', '', (object) array('cap' => $cachedcap->name, 'role' => $role->name));
                        }
                    }
                }
            }
            // End if.
        }
    }
    return $removedcount;
}
Example #12
0
/**
 *  Returns a role object that is the default role for new enrolments
 *  in a given course
 *
 *  @param object $course
 *  @return object $role
 */
function get_default_course_role($course)
{
    global $DB, $CFG;
    /// First let's take the default role the course may have
    if (!empty($course->defaultrole)) {
        if ($role = $DB->get_record('role', array('id' => $course->defaultrole))) {
            return $role;
        }
    }
    /// Otherwise the site setting should tell us
    if ($CFG->defaultcourseroleid) {
        if ($role = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
            return $role;
        }
    }
    /// It's unlikely we'll get here, but just in case, try and find a student role
    if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
        return array_shift($studentroles);
        /// Take the first one
    }
    return NULL;
}
/**
 * Creates a PDF document for a list of participants
 *
 * @param unknown_type $offlinequiz
 * @param unknown_type $courseid
 * @param unknown_type $list
 * @param unknown_type $context
 * @return boolean|stored_file
 */
function offlinequiz_create_pdf_participants($offlinequiz, $courseid, $list, $context)
{
    global $CFG, $DB;
    $coursecontext = context_course::instance($courseid);
    // Course context.
    $systemcontext = context_system::instance();
    $offlinequizconfig = get_config('offlinequiz');
    $listname = $list->name;
    // First get roleids for students.
    if (!($roles = get_roles_with_capability('mod/offlinequiz:attempt', CAP_ALLOW, $systemcontext))) {
        print_error("No roles with capability 'mod/offlinequiz:attempt' defined in system context");
    }
    $roleids = array();
    foreach ($roles as $role) {
        $roleids[] = $role->id;
    }
    list($csql, $cparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
    list($rsql, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'role');
    $params = array_merge($cparams, $rparams);
    $sql = "SELECT DISTINCT u.id, u." . $offlinequizconfig->ID_field . ", u.firstname, u.lastname\n              FROM {user} u,\n                   {offlinequiz_participants} p,\n                   {role_assignments} ra,\n                   {offlinequiz_p_lists} pl\n             WHERE ra.userid = u.id\n               AND p.listid = :listid\n               AND p.listid = pl.id\n               AND pl.offlinequizid = :offlinequizid\n               AND p.userid = u.id\n               AND ra.roleid {$rsql} AND ra.contextid {$csql}\n          ORDER BY u.lastname, u.firstname";
    $params['offlinequizid'] = $offlinequiz->id;
    $params['listid'] = $list->id;
    $participants = $DB->get_records_sql($sql, $params);
    if (empty($participants)) {
        return false;
    }
    $pdf = new offlinequiz_participants_pdf('P', 'mm', 'A4');
    $pdf->listno = $list->number;
    $title = offlinequiz_str_html_pdf($offlinequiz->name);
    // Add the list name to the title.
    $title .= ', ' . offlinequiz_str_html_pdf($listname);
    $pdf->set_title($title);
    $pdf->SetMargins(15, 25, 15);
    $pdf->SetAutoPageBreak(true, 20);
    $pdf->AddPage();
    $pdf->Ln(9);
    $position = 1;
    $pdf->SetFont('FreeSans', '', 10);
    foreach ($participants as $participant) {
        $pdf->Cell(9, 3.5, "{$position}. ", 0, 0, 'R');
        $pdf->Cell(1, 3.5, '', 0, 0, 'C');
        $x = $pdf->GetX();
        $y = $pdf->GetY();
        $pdf->Rect($x, $y + 0.6, 3.5, 3.5);
        $pdf->Cell(3, 3.5, '', 0, 0, 'C');
        $pdf->Cell(6, 3.5, '', 0, 0, 'C');
        $userkey = substr($participant->{$offlinequizconfig->ID_field}, strlen($offlinequizconfig->ID_prefix), $offlinequizconfig->ID_digits);
        $pdf->Cell(13, 3.5, $userkey, 0, 0, 'R');
        $pdf->Cell(12, 3.5, '', 0, 0, 'L');
        if ($pdf->GetStringWidth($participant->firstname) > 40) {
            $participant->firstname = substr($participant->firstname, 0, 20);
        }
        if ($pdf->GetStringWidth($participant->lastname) > 55) {
            $participant->lastname = substr($participant->lastname, 0, 25);
        }
        $pdf->Cell(55, 3.5, $participant->lastname, 0, 0, 'L');
        $pdf->Cell(40, 3.5, $participant->firstname, 0, 0, 'L');
        $pdf->Cell(10, 3.5, '', 0, 1, 'R');
        // Print barcode.
        $value = substr('000000000000000000000000' . base_convert($participant->id, 10, 2), -25);
        $y = $pdf->GetY() - 3.5;
        $x = 170;
        $pdf->Rect($x, $y, 0.2, 3.5, 'F');
        $pdf->Rect($x, $y, 0.7, 0.2, 'F');
        $pdf->Rect($x, $y + 3.5, 0.7, 0.2, 'F');
        $x += 0.7;
        for ($i = 0; $i < 25; $i++) {
            if ($value[$i] == '1') {
                $pdf->Rect($x, $y, 0.7, 3.5, 'F');
                $pdf->Rect($x, $y, 1.2, 0.2, 'F');
                $pdf->Rect($x, $y + 3.5, 1.2, 0.2, 'F');
                $x += 1.2;
            } else {
                $pdf->Rect($x, $y, 0.2, 3.5, 'F');
                $pdf->Rect($x, $y, 0.7, 0.2, 'F');
                $pdf->Rect($x, $y + 3.5, 0.7, 0.2, 'F');
                $x += 0.7;
            }
        }
        $pdf->Rect($x, $y, 0.2, 3.7, 'F');
        $pdf->Rect(15, $pdf->GetY() + 1, 175, 0.2, 'F');
        if ($position % NUMBERS_PER_PAGE != 0) {
            $pdf->Ln(3.6);
        } else {
            $pdf->AddPage();
            $pdf->Ln(9);
        }
        $position++;
    }
    $fs = get_file_storage();
    // Prepare file record object.
    $timestamp = date('Ymd_His', time());
    $fileinfo = array('contextid' => $context->id, 'component' => 'mod_offlinequiz', 'filearea' => 'pdfs', 'filepath' => '/', 'itemid' => 0, 'filename' => 'participants_' . $list->id . '_' . $timestamp . '.pdf');
    if ($oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename'])) {
        $oldfile->delete();
    }
    $pdfstring = $pdf->Output('', 'S');
    $file = $fs->create_file_from_string($fileinfo, $pdfstring);
    return $file;
}
Example #14
0
function data_restore_mods($mod, $restore)
{
    global $CFG;
    $status = true;
    $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id);
    if ($data) {
        //Now get completed xmlized object
        $info = $data->info;
        // if necessary, write to restorelog and adjust date/time fields
        if ($restore->course_startdateoffset) {
            restore_log_date_changes('Database', $restore, $info['MOD']['#'], array('TIMEAVAILABLEFROM', 'TIMEAVAILABLETO', 'TIMEVIEWFROM', 'TIMEVIEWTO'));
        }
        //traverse_xmlize($info);                                                                     //Debug
        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
        //$GLOBALS['traverse_array']="";                                                              //Debug
        $database->course = $restore->course_id;
        $database->name = backup_todb($info['MOD']['#']['NAME']['0']['#']);
        $database->intro = backup_todb($info['MOD']['#']['INTRO']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['RATINGS']['0']['#'])) {
            $database->ratings = backup_todb($info['MOD']['#']['RATINGS']['0']['#']);
        }
        $database->comments = backup_todb($info['MOD']['#']['COMMENTS']['0']['#']);
        $database->timeavailablefrom = backup_todb($info['MOD']['#']['TIMEAVAILABLEFROM']['0']['#']);
        $database->timeavailableto = backup_todb($info['MOD']['#']['TIMEAVAILABLETO']['0']['#']);
        $database->timeviewfrom = backup_todb($info['MOD']['#']['TIMEVIEWFROM']['0']['#']);
        $database->timeviewto = backup_todb($info['MOD']['#']['TIMEVIEWTO']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['PARTICIPANTS']['0']['#'])) {
            $database->participants = backup_todb($info['MOD']['#']['PARTICIPANTS']['0']['#']);
        }
        $database->requiredentries = backup_todb($info['MOD']['#']['REQUIREDENTRIES']['0']['#']);
        $database->requiredentriestoview = backup_todb($info['MOD']['#']['REQUIREDENTRIESTOVIEW']['0']['#']);
        $database->maxentries = backup_todb($info['MOD']['#']['MAXENTRIES']['0']['#']);
        $database->rssarticles = backup_todb($info['MOD']['#']['RSSARTICLES']['0']['#']);
        $database->singletemplate = backup_todb($info['MOD']['#']['SINGLETEMPLATE']['0']['#']);
        $database->listtemplate = backup_todb($info['MOD']['#']['LISTTEMPLATE']['0']['#']);
        $database->listtemplateheader = backup_todb($info['MOD']['#']['LISTTEMPLATEHEADER']['0']['#']);
        $database->listtemplatefooter = backup_todb($info['MOD']['#']['LISTTEMPLATEFOOTER']['0']['#']);
        $database->addtemplate = backup_todb($info['MOD']['#']['ADDTEMPLATE']['0']['#']);
        $database->rsstemplate = backup_todb($info['MOD']['#']['RSSTEMPLATE']['0']['#']);
        $database->rsstitletemplate = backup_todb($info['MOD']['#']['RSSTITLETEMPLATE']['0']['#']);
        $database->csstemplate = backup_todb($info['MOD']['#']['CSSTEMPLATE']['0']['#']);
        $database->jstemplate = backup_todb($info['MOD']['#']['JSTEMPLATE']['0']['#']);
        $database->asearchtemplate = backup_todb($info['MOD']['#']['ASEARCHTEMPLATE']['0']['#']);
        $database->approval = backup_todb($info['MOD']['#']['APPROVAL']['0']['#']);
        $database->scale = backup_todb($info['MOD']['#']['SCALE']['0']['#']);
        $database->assessed = backup_todb($info['MOD']['#']['ASSESSED']['0']['#']);
        // Only relevant for restoring backups from 1.6 in a 1.7 install.
        if (isset($info['MOD']['#']['ASSESSPUBLIC']['0']['#'])) {
            $database->assesspublic = backup_todb($info['MOD']['#']['ASSESSPUBLIC']['0']['#']);
        }
        $database->defaultsort = backup_todb($info['MOD']['#']['DEFAULTSORT']['0']['#']);
        $database->defaultsortdir = backup_todb($info['MOD']['#']['DEFAULTSORTDIR']['0']['#']);
        $database->editany = backup_todb($info['MOD']['#']['EDITANY']['0']['#']);
        $database->notification = backup_todb($info['MOD']['#']['NOTIFICATION']['0']['#']);
        // We have to recode the scale field if it's <0 (positive is a grade, not a scale)
        if ($database->scale < 0) {
            $scale = backup_getid($restore->backup_unique_code, 'scale', abs($database->scale));
            if ($scale) {
                $database->scale = -$scale->new_id;
            }
        }
        $newid = insert_record('data', $database);
        //Do some output
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("modulename", "data") . " \"" . format_string(stripslashes($database->name), true) . "\"</li>";
        }
        if ($newid) {
            //We have the newid, update backup_ids
            backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid);
            //Now check if want to restore user data and do it.
            if (function_exists('restore_userdata_selected')) {
                // Moodle 1.6
                $restore_userdata_selected = restore_userdata_selected($restore, 'data', $mod->id);
            } else {
                // Moodle 1.5
                $restore_userdata_selected = $restore->mods['data']->userinfo;
            }
            global $fieldids;
            //Restore data_fields first!!! need to hold an array of [oldid]=>newid due to double dependencies
            $status = $status and data_fields_restore_mods($mod->id, $newid, $info, $restore);
            // now use the new field in the defaultsort
            $newdefaultsort = empty($fieldids[$database->defaultsort]) ? 0 : $fieldids[$database->defaultsort];
            set_field('data', 'defaultsort', $newdefaultsort, 'id', $newid);
            if ($restore_userdata_selected) {
                $status = $status and data_records_restore_mods($mod->id, $newid, $info, $restore);
            }
            // If the backup contained $data->participants, $data->assesspublic
            // and $data->groupmode, we need to convert the data to use Roles.
            // It means the backup was made pre Moodle 1.7. We check the
            // backup_version to make sure.
            if (isset($database->participants) && isset($database->assesspublic)) {
                if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                    notice('Default teacher role was not found. Roles and permissions ' . 'for your database modules will have to be manually set.');
                }
                if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                    notice('Default student role was not found. Roles and permissions ' . 'for all your database modules will have to be manually set.');
                }
                if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                    notice('Default guest role was not found. Roles and permissions ' . 'for all your database modules will have to be manually set.');
                }
                require_once $CFG->dirroot . '/mod/data/lib.php';
                data_convert_to_roles($database, $teacherroles, $studentroles, $restore->mods['data']->instances[$mod->id]->restored_as_course_module);
            }
        } else {
            $status = false;
        }
    } else {
        $status = false;
    }
    return $status;
}
 /**
  * Test role queries.
  */
 public function test_get_roles_with_capability()
 {
     global $DB;
     $this->resetAfterTest();
     $syscontext = context_system::instance();
     $frontcontext = context_course::instance(SITEID);
     $manager = $DB->get_record('role', array('shortname' => 'manager'), '*', MUST_EXIST);
     $teacher = $DB->get_record('role', array('shortname' => 'teacher'), '*', MUST_EXIST);
     $this->assertTrue($DB->record_exists('capabilities', array('name' => 'moodle/backup:backupcourse')));
     // Any capability is ok.
     $DB->delete_records('role_capabilities', array('capability' => 'moodle/backup:backupcourse'));
     $roles = get_roles_with_capability('moodle/backup:backupcourse');
     $this->assertEquals(array(), $roles);
     assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $manager->id, $syscontext->id);
     assign_capability('moodle/backup:backupcourse', CAP_PROHIBIT, $manager->id, $frontcontext->id);
     assign_capability('moodle/backup:backupcourse', CAP_PREVENT, $teacher->id, $frontcontext->id);
     $roles = get_roles_with_capability('moodle/backup:backupcourse');
     $this->assertEquals(array($teacher->id, $manager->id), array_keys($roles), '', 0, 10, true);
     $roles = get_roles_with_capability('moodle/backup:backupcourse', CAP_ALLOW);
     $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
     $roles = get_roles_with_capability('moodle/backup:backupcourse', null, $syscontext);
     $this->assertEquals(array($manager->id), array_keys($roles), '', 0, 10, true);
 }
Example #16
0
function xmldb_main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $USER, $SITE, $db;
    $result = true;
    if ($result && $oldversion < 2006100401) {
        /// Only for those tracking Moodle 1.7 dev, others will have these dropped in moodle_install_roles()
        if (!empty($CFG->rolesactive)) {
            drop_table(new XMLDBTable('user_students'));
            drop_table(new XMLDBTable('user_teachers'));
            drop_table(new XMLDBTable('user_coursecreators'));
            drop_table(new XMLDBTable('user_admins'));
        }
        upgrade_main_savepoint($result, 2006100401);
    }
    if ($result && $oldversion < 2006100601) {
        /// Disable the exercise module because it's unmaintained
        if ($module = get_record('modules', 'name', 'exercise')) {
            if ($module->visible) {
                // Hide/disable the module entry
                set_field('modules', 'visible', '0', 'id', $module->id);
                // Save existing visible state for all activities
                set_field('course_modules', 'visibleold', '1', 'visible', '1', 'module', $module->id);
                set_field('course_modules', 'visibleold', '0', 'visible', '0', 'module', $module->id);
                // Hide all activities
                set_field('course_modules', 'visible', '0', 'module', $module->id);
                //require_once($CFG->dirroot.'/course/lib.php');
                //rebuild_course_cache();  // Rebuld cache for all modules because they might have changed
            }
        }
        upgrade_main_savepoint($result, 2006100601);
    }
    if ($result && $oldversion < 2006101001) {
        /// Disable the LAMS module by default (if it is installed)
        if (count_records('modules', 'name', 'lams') && !count_records('lams')) {
            set_field('modules', 'visible', 0, 'name', 'lams');
            // Disable it by default
        }
        upgrade_main_savepoint($result, 2006101001);
    }
    if ($result && $oldversion < 2006102600) {
        /// Define fields to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('description');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'categoryid');
        $field1 = new XMLDBField('param1');
        $field1->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'defaultdata');
        $field2 = new XMLDBField('param2');
        $field2->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param1');
        $field3 = new XMLDBField('param3');
        $field3->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param2');
        $field4 = new XMLDBField('param4');
        $field4->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param3');
        $field5 = new XMLDBField('param5');
        $field5->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'param4');
        /// Launch add fields
        $result = $result && add_field($table, $field);
        $result = $result && add_field($table, $field1);
        $result = $result && add_field($table, $field2);
        $result = $result && add_field($table, $field3);
        $result = $result && add_field($table, $field4);
        $result = $result && add_field($table, $field5);
        upgrade_main_savepoint($result, 2006102600);
    }
    if ($result && $oldversion < 2006112000) {
        /// Define field attachment to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('attachment');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'format');
        /// Launch add field attachment
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112000);
    }
    if ($result && $oldversion < 2006112200) {
        /// Define field imagealt to be added to user
        $table = new XMLDBTable('user');
        $field = new XMLDBField('imagealt');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'trustbitmask');
        /// Launch add field imagealt
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('user');
        $field = new XMLDBField('screenreader');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0', 'imagealt');
        /// Launch add field screenreader
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2006112200);
    }
    if ($result && $oldversion < 2006120300) {
        /// Delete guest course section settings
        // following code can be executed repeatedly, such as when upgrading from 1.7.x - it is ok
        if ($guest = get_record('user', 'username', 'guest')) {
            execute_sql("DELETE FROM {$CFG->prefix}course_display where userid={$guest->id}", true);
        }
        upgrade_main_savepoint($result, 2006120300);
    }
    if ($result && $oldversion < 2006120400) {
        /// Remove secureforms config setting
        execute_sql("DELETE FROM {$CFG->prefix}config where name='secureforms'", true);
        upgrade_main_savepoint($result, 2006120400);
    }
    if (!empty($CFG->rolesactive) && $oldversion < 2006120700) {
        // add moodle/user:viewdetails to all roles!
        // note: use of assign_capability() is discouraged in upgrade script!
        if ($roles = get_records('role')) {
            $context = get_context_instance(CONTEXT_SYSTEM);
            foreach ($roles as $roleid => $role) {
                assign_capability('moodle/user:viewdetails', CAP_ALLOW, $roleid, $context->id);
            }
        }
        upgrade_main_savepoint($result, 2006120700);
    }
    // Move the auth plugin settings into the config_plugin table
    if ($result && $oldversion < 2007010300) {
        if ($CFG->auth == 'email') {
            set_config('registerauth', 'email');
        } else {
            set_config('registerauth', '');
        }
        $authplugins = get_list_of_plugins('auth');
        foreach ($CFG as $k => $v) {
            if (strpos($k, 'ldap_') === 0) {
                //upgrade nonstandard ldap settings
                $setting = substr($k, 5);
                if (set_config($setting, $v, "auth/ldap")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                continue;
            }
            if (strpos($k, 'auth_') !== 0) {
                continue;
            }
            $authsetting = substr($k, 5);
            foreach ($authplugins as $auth) {
                if (strpos($authsetting, $auth) !== 0) {
                    continue;
                }
                $setting = substr($authsetting, strlen($auth));
                if (set_config($setting, $v, "auth/{$auth}")) {
                    delete_records('config', 'name', $k);
                    unset($CFG->{$k});
                }
                break;
                // don't check the rest of the auth plugin names
            }
        }
        upgrade_main_savepoint($result, 2007010300);
    }
    if ($result && $oldversion < 2007010301) {
        //
        // Core MNET tables
        //
        $table = new XMLDBTable('mnet_host');
        $table->comment = 'Information about the local and remote hosts for RPC';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f->comment = 'Unique Host ID';
        $f = $table->addFieldInfo('deleted', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('wwwroot', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('ip_address', XMLDB_TYPE_CHAR, '39', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $f = $table->addFieldInfo('public_key_expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('transport', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('portno', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_connect_time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        $f = $table->addFieldInfo('last_log_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_host2service');
        $table->comment = 'Information about the services for a given host';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('publish', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('subscribe', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_serviceid', XMLDB_INDEX_UNIQUE, array('hostid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_log');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('time', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('ip', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('coursename', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('module', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('url', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('info', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('host_user_course', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'userid', 'course'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_rpc');
        $table->comment = 'Functions or methods that we may publish or subscribe to';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('function_name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_path', XMLDB_TYPE_CHAR, '80', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent_type', XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('parent', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enabled', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('help', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('profile', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('enabled_xpath', XMLDB_INDEX_NOTUNIQUE, array('enabled', 'xmlrpc_path'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service');
        $table->comment = 'A service is a group of functions';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('description', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('apiversion', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('offer', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_service2rpc');
        $table->comment = 'Group functions or methods under a service';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('serviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rpcid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('unique', XMLDB_INDEX_UNIQUE, array('rpcid', 'serviceid'));
        // Create the table
        $result = $result && create_table($table);
        //
        // Prime MNET configuration entries -- will be needed later by auth/mnet
        //
        include_once $CFG->dirroot . '/mnet/lib.php';
        $env = new mnet_environment();
        $env->init();
        unset($env);
        // add mnethostid to user-
        $table = new XMLDBTable('user');
        $field = new XMLDBField('mnethostid');
        $field->setType(XMLDB_TYPE_INTEGER);
        $field->setLength(10);
        $field->setNotNull(true);
        $field->setSequence(null);
        $field->setEnum(null);
        $field->setDefault('0');
        $field->setPrevious("deleted");
        $field->setNext("username");
        $result = $result && add_field($table, $field);
        // The default mnethostid is zero... we need to update this for all
        // users of the local IdP service.
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'mnethostid', '0');
        $index = new XMLDBIndex('username');
        $index->setUnique(true);
        $index->setFields(array('username'));
        drop_index($table, $index);
        $index->setFields(array('mnethostid', 'username'));
        if (!add_index($table, $index)) {
            notify(get_string('duplicate_usernames', 'mnet', 'http://docs.moodle.org/en/DuplicateUsernames'));
        }
        unset($table, $field, $index);
        /**
         ** auth/mnet tables
         **/
        $table = new XMLDBTable('mnet_session');
        $table->comment = 'Store session data from users migrating to other sites';
        // fields
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('useragent', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('confirm_timeout', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('session_id', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('expires', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('token', XMLDB_INDEX_UNIQUE, array('token'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_sso_access_control');
        $table->comment = 'Users by host permitted (or not) to login from a remote provider';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('mnet_host_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('access', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, 'allow');
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('mnethostid_username', XMLDB_INDEX_UNIQUE, array('mnet_host_id', 'username'));
        // Create the table
        $result = $result && create_table($table);
        if (empty($USER->mnet_host_id)) {
            $USER->mnet_host_id = $CFG->mnet_localhost_id;
            // Something for the current user to prevent warnings
        }
        /**
         ** enrol/mnet tables
         **/
        $table = new XMLDBTable('mnet_enrol_course');
        $table->comment = 'Information about courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('remoteid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cat_name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('cat_description', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '254', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '15', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('summary', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('startdate', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('cost', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('currency', XMLDB_TYPE_CHAR, '3', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('defaultroleid', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('defaultrolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_remoteid', XMLDB_INDEX_UNIQUE, array('hostid', 'remoteid'));
        // Create the table
        $result = $result && create_table($table);
        $table = new XMLDBTable('mnet_enrol_assignments');
        $table->comment = 'Information about enrolments on courses on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('hostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('rolename', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('enroltime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, NULL, null, null, 0);
        $f = $table->addFieldInfo('enroltype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addIndexInfo('hostid_courseid', XMLDB_INDEX_NOTUNIQUE, array('hostid', 'courseid'));
        $table->addIndexInfo('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
        // Create the table
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007010301);
    }
    if ($result && $oldversion < 2007010404) {
        /// Define field shortname to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, 'shortname', 'id');
        /// Launch add field shortname
        $result = $result && add_field($table, $field);
        /// Changing type of field name on table user_info_field to text
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null, 'shortname');
        /// Launch change of type for field name
        $result = $result && change_field_type($table, $field);
        /// For existing fields use 'name' as the 'shortname' entry
        if ($fields = get_records_select('user_info_field', '', '', 'id, name')) {
            foreach ($fields as $field) {
                $field->shortname = clean_param($field->name, PARAM_ALPHANUM);
                $result && update_record('user_info_field', $field);
            }
        }
        upgrade_main_savepoint($result, 2007010404);
    }
    if ($result && $oldversion < 2007011501) {
        if (!empty($CFG->enablerecordcache) && empty($CFG->rcache) && empty($CFG->cachetype) && empty($CFG->intcachemax)) {
            set_config('cachetype', 'internal');
            set_config('rcache', true);
            set_config('intcachemax', $CFG->enablerecordcache);
            unset_config('enablerecordcache');
            unset($CFG->enablerecordcache);
        }
        upgrade_main_savepoint($result, 2007011501);
    }
    if ($result && $oldversion < 2007012100) {
        /// Some old PG servers have user->firstname & user->lastname with 30cc. They must be 100cc.
        /// Fixing that conditionally. MDL-7110
        if ($CFG->dbfamily == 'postgres') {
            /// Get Metadata from user table
            $cols = array_change_key_case($db->MetaColumns($CFG->prefix . 'user'), CASE_LOWER);
            /// Process user->firstname if needed
            if ($col = $cols['firstname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field firstname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('firstname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'idnumber');
                    /// Launch change of precision for field firstname
                    $result = $result && change_field_precision($table, $field);
                }
            }
            /// Process user->lastname if needed
            if ($col = $cols['lastname']) {
                if ($col->max_length < 100) {
                    /// Changing precision of field lastname on table user to (100)
                    $table = new XMLDBTable('user');
                    $field = new XMLDBField('lastname');
                    $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'firstname');
                    /// Launch change of precision for field lastname
                    $result = $result && change_field_precision($table, $field);
                }
            }
        }
        upgrade_main_savepoint($result, 2007012100);
    }
    if ($result && $oldversion < 2007012101) {
        /// Changing precision of field lang on table course to (30)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null, 'groupmodeforce');
        /// Launch change of precision for field course->lang
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field lang on table user to (30)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en', 'country');
        /// Launch change of precision for field user->lang
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007012101);
    }
    if ($result && $oldversion < 2007012400) {
        /// Rename field access on table mnet_sso_access_control to accessctrl
        $table = new XMLDBTable('mnet_sso_access_control');
        $field = new XMLDBField('access');
        $field->setAttributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, 'allow', 'mnet_host_id');
        /// Launch rename field accessctrl
        $result = $result && rename_field($table, $field, 'accessctrl');
        upgrade_main_savepoint($result, 2007012400);
    }
    if ($result && $oldversion < 2007012500) {
        execute_sql("DELETE FROM {$CFG->prefix}user WHERE username='******'", true);
        upgrade_main_savepoint($result, 2007012500);
    }
    if ($result && $oldversion < 2007020400) {
        /// Only for MySQL and PG, declare the user->ajax field as not null. MDL-8421.
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            /// Changing nullability of field ajax on table user to not null
            $table = new XMLDBTable('user');
            $field = new XMLDBField('ajax');
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'htmleditor');
            /// Launch change of nullability for field ajax
            $result = $result && change_field_notnull($table, $field);
        }
        upgrade_main_savepoint($result, 2007020400);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007021401) {
        /// create default logged in user role if not present - upgrade rom 1.7.x
        if (empty($CFG->defaultuserroleid) or empty($CFG->guestroleid) or $CFG->defaultuserroleid == $CFG->guestroleid) {
            if (!get_records('role', 'shortname', 'user')) {
                $userroleid = create_role(addslashes(get_string('authenticateduser')), 'user', addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
                if ($userroleid) {
                    reset_role_capabilities($userroleid);
                    set_config('defaultuserroleid', $userroleid);
                }
            }
        }
        upgrade_main_savepoint($result, 2007021401);
    }
    if ($result && $oldversion < 2007021501) {
        /// delete removed setting from config
        unset_config('tabselectedtofront');
        upgrade_main_savepoint($result, 2007021501);
    }
    if ($result && $oldversion < 2007032200) {
        /// Define table role_sortorder to be created
        $table = new XMLDBTable('role_sortorder');
        /// Adding fields to table role_sortorder
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('roleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('sortoder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table role_sortorder
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('roleid', XMLDB_KEY_FOREIGN, array('roleid'), 'role', array('id'));
        $table->addKeyInfo('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
        /// Adding indexes to table role_sortorder
        $table->addIndexInfo('userid-roleid-contextid', XMLDB_INDEX_UNIQUE, array('userid', 'roleid', 'contextid'));
        /// Launch create table for role_sortorder
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007032200);
    }
    /// code to change lenghen tag field to 255, MDL-9095
    if ($result && $oldversion < 2007040400) {
        /// Define index text (not unique) to be dropped form tags
        $table = new XMLDBTable('tags');
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch drop index text
        $result = $result && drop_index($table, $index);
        $field = new XMLDBField('text');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'userid');
        /// Launch change of type for field text
        $result = $result && change_field_type($table, $field);
        $index = new XMLDBIndex('text');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('text'));
        /// Launch add index text
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007040400);
    }
    if ($result && $oldversion < 2007041100) {
        /// Define field idnumber to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'section');
        /// Launch add field idnumber
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007041100);
    }
    /* Changes to the custom profile menu type - store values rather than indices.
       We could do all this with one tricky SQL statement but it's a one-off so no
       harm in using PHP loops */
    if ($result && $oldversion < 2007041600) {
        /// Get the menu fields
        if ($fields = get_records('user_info_field', 'datatype', 'menu')) {
            foreach ($fields as $field) {
                /// Get user data for the menu field
                if ($data = get_records('user_info_data', 'fieldid', $field->id)) {
                    /// Get the menu options
                    $options = explode("\n", $field->param1);
                    foreach ($data as $d) {
                        $key = array_search($d->data, $options);
                        /// If the data is an integer and is not one of the options,
                        /// set the respective option value
                        if (is_int($d->data) and ($key === NULL or $key === false) and isset($options[$d->data])) {
                            $d->data = $options[$d->data];
                            $result = $result && update_record('user_info_data', $d);
                        }
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007041600);
    }
    /// adding new gradebook tables
    if ($result && $oldversion < 2007041800) {
        /// Define table events_handlers to be created
        $table = new XMLDBTable('events_handlers');
        /// Adding fields to table events_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventname', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlermodule', XMLDB_TYPE_CHAR, '166', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfile', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerfunction', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        /// Adding keys to table events_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table events_handlers
        $table->addIndexInfo('eventname-handlermodule', XMLDB_INDEX_UNIQUE, array('eventname', 'handlermodule'));
        /// Launch create table for events_handlers
        $result = $result && create_table($table);
        /// Define table events_queue to be created
        $table = new XMLDBTable('events_queue');
        /// Adding fields to table events_queue
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('eventdata', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('schedule', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('stackdump', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch create table for events_queue
        $result = $result && create_table($table);
        /// Define table events_queue_handlers to be created
        $table = new XMLDBTable('events_queue_handlers');
        /// Adding fields to table events_queue_handlers
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('queuedeventid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('handlerid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('status', XMLDB_TYPE_INTEGER, '10', null, null, null, null, null, null);
        $table->addFieldInfo('errormessage', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table events_queue_handlers
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('queuedeventid', XMLDB_KEY_FOREIGN, array('queuedeventid'), 'events_queue', array('id'));
        $table->addKeyInfo('handlerid', XMLDB_KEY_FOREIGN, array('handlerid'), 'events_handlers', array('id'));
        /// Launch create table for events_queue_handlers
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007041800);
    }
    if ($result && $oldversion < 2007043001) {
        /// Define field schedule to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('schedule');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'handlerfunction');
        /// Launch add field schedule
        $result = $result && add_field($table, $field);
        /// Define field status to be added to events_handlers
        $table = new XMLDBTable('events_handlers');
        $field = new XMLDBField('status');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'schedule');
        /// Launch add field status
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007043001);
    }
    if ($result && $oldversion < 2007050201) {
        /// Define field theme to be added to course_categories
        $table = new XMLDBTable('course_categories');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '50', null, null, null, null, null, null, 'path');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007050201);
    }
    if ($result && $oldversion < 2007051100) {
        /// Define field forceunique to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('forceunique');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'visible');
        /// Launch add field forceunique
        $result = $result && add_field($table, $field);
        /// Define field signup to be added to user_info_field
        $table = new XMLDBTable('user_info_field');
        $field = new XMLDBField('signup');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'forceunique');
        /// Launch add field signup
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007051100);
    }
    if (!empty($CFG->rolesactive) && $result && $oldversion < 2007051801) {
        // Get the role id of the "Auth. User" role and check if the default role id is different
        // note: use of assign_capability() is discouraged in upgrade script!
        $userrole = get_record('role', 'shortname', 'user');
        $defaultroleid = $CFG->defaultuserroleid;
        if ($defaultroleid != $userrole->id) {
            //  Add in the new moodle/my:manageblocks capibility to the default user role
            $context = get_context_instance(CONTEXT_SYSTEM);
            assign_capability('moodle/my:manageblocks', CAP_ALLOW, $defaultroleid, $context->id);
        }
        upgrade_main_savepoint($result, 2007051801);
    }
    if ($result && $oldversion < 2007052200) {
        /// Define field schedule to be dropped from events_queue
        $table = new XMLDBTable('events_queue');
        $field = new XMLDBField('schedule');
        /// Launch drop field stackdump
        $result = $result && drop_field($table, $field);
        upgrade_main_savepoint($result, 2007052200);
    }
    if ($result && $oldversion < 2007052300) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype();
        upgrade_main_savepoint($result, 2007052300);
    }
    if ($result && $oldversion < 2007060500) {
        /// Define field usermodified to be added to post
        $table = new XMLDBTable('post');
        $field = new XMLDBField('usermodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'created');
        /// Launch add field usermodified
        $result = $result && add_field($table, $field);
        /// Define key usermodified (foreign) to be added to post
        $table = new XMLDBTable('post');
        $key = new XMLDBKey('usermodified');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch add key usermodified
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007060500);
    }
    if ($result && $oldversion < 2007070603) {
        // Small update of guest user to be 100% sure it has the correct mnethostid (MDL-10375)
        set_field('user', 'mnethostid', $CFG->mnet_localhost_id, 'username', 'guest');
        upgrade_main_savepoint($result, 2007070603);
    }
    if ($result && $oldversion < 2007071400) {
        /**
         ** mnet application table
         **/
        $table = new XMLDBTable('mnet_application');
        $table->comment = 'Information about applications on remote hosts';
        $f = $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', false, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $f = $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('display_name', XMLDB_TYPE_CHAR, '50', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('xmlrpc_server_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        $f = $table->addFieldInfo('sso_land_url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, NULL, null, null, null);
        // PK and indexes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        // Create the table
        $result = $result && create_table($table);
        // Insert initial applications (moodle and mahara)
        $application = new stdClass();
        $application->name = 'moodle';
        $application->display_name = 'Moodle';
        $application->xmlrpc_server_url = '/mnet/xmlrpc/server.php';
        $application->sso_land_url = '/auth/mnet/land.php';
        if ($result) {
            $newid = insert_record('mnet_application', $application, false);
        }
        $application = new stdClass();
        $application->name = 'mahara';
        $application->display_name = 'Mahara';
        $application->xmlrpc_server_url = '/api/xmlrpc/server.php';
        $application->sso_land_url = '/auth/xmlrpc/land.php';
        $result = $result && insert_record('mnet_application', $application, false);
        // New mnet_host->applicationid field
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, $newid, 'last_log_id');
        $result = $result && add_field($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007071400);
    }
    if ($result && $oldversion < 2007071607) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_remove_rqp_qtype_config_string();
        upgrade_main_savepoint($result, 2007071607);
    }
    if ($result && $oldversion < 2007072200) {
        /// Remove all grade tables used in development phases - we need new empty tables for final gradebook upgrade
        $tables = array('grade_categories', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses', 'grade_history', 'grade_import_newitem', 'grade_import_values');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        $tables = array('grade_categories_history', 'grade_items_history', 'grade_grades_history', 'grade_grades_text_history', 'grade_scale_history', 'grade_outcomes_history');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define table grade_outcomes to be created
        $table = new XMLDBTable('grade_outcomes');
        /// Adding fields to table grade_outcomes
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_outcomes
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Launch create table for grade_outcomes
        $result = $result && create_table($table);
        /// Define table grade_categories to be created
        $table = new XMLDBTable('grade_categories');
        /// Adding fields to table grade_categories
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_categories
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        /// Launch create table for grade_categories
        $result = $result && create_table($table);
        /// Define table grade_items to be created
        $table = new XMLDBTable('grade_items');
        /// Adding fields to table grade_items
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_items
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        $table->addIndexInfo('itemtype-needsupdate', XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        $table->addIndexInfo('gradetype', XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        /// Launch create table for grade_items
        $result = $result && create_table($table);
        /// Define table grade_grades to be created
        $table = new XMLDBTable('grade_grades');
        /// Adding fields to table grade_grades
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_grades
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        /// Adding indexes to table grade_grades
        $table->addIndexInfo('locked-locktime', XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        /// Launch create table for grade_grades
        $result = $result && create_table($table);
        /// Define table grade_outcomes_history to be created
        $table = new XMLDBTable('grade_outcomes_history');
        /// Adding fields to table grade_outcomes_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_outcomes_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_outcomes_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_outcomes_history
        $result = $result && create_table($table);
        /// Define table grade_categories_history to be created
        $table = new XMLDBTable('grade_categories_history');
        /// Adding fields to table grade_categories_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('parent', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('fullname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('aggregation', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('keephigh', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('droplow', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateonlygraded', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregateoutcomes', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregatesubcats', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_categories_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_categories', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('parent', XMLDB_KEY_FOREIGN, array('parent'), 'grade_categories', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_categories_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_categories_history
        $result = $result && create_table($table);
        /// Define table grade_items_history to be created
        $table = new XMLDBTable('grade_items_history');
        /// Adding fields to table grade_items_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('categoryid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemmodule', XMLDB_TYPE_CHAR, '30', null, null, null, null, null, null);
        $table->addFieldInfo('iteminstance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemnumber', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iteminfo', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('calculation', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('gradetype', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1');
        $table->addFieldInfo('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('gradepass', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('multfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '1.0');
        $table->addFieldInfo('plusfactor', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('aggregationcoef', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('sortorder', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('display', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('decimals', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('needsupdate', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_items_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_items', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('categoryid', XMLDB_KEY_FOREIGN, array('categoryid'), 'grade_categories', array('id'));
        $table->addKeyInfo('scaleid', XMLDB_KEY_FOREIGN, array('scaleid'), 'scale', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_items_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_items_history
        $result = $result && create_table($table);
        /// Define table grade_grades_history to be created
        $table = new XMLDBTable('grade_grades_history');
        /// Adding fields to table grade_grades_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('rawgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('rawgrademax', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '100');
        $table->addFieldInfo('rawgrademin', XMLDB_TYPE_NUMBER, '10, 5', null, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('rawscaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('usermodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locked', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('locktime', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exported', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('overridden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('excluded', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('feedbackformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('information', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('informationformat', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        /// Adding keys to table grade_grades_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'grade_grades', array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        $table->addKeyInfo('rawscaleid', XMLDB_KEY_FOREIGN, array('rawscaleid'), 'scale', array('id'));
        $table->addKeyInfo('usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table grade_grades_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for grade_grades_history
        $result = $result && create_table($table);
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch create table for scale_history
        $result = $result && create_table($table);
        /// upgrade the old 1.8 gradebook - migrade data into new grade tables
        if ($result) {
            if ($rs = get_recordset('course')) {
                while ($course = rs_fetch_next_record($rs)) {
                    // this function uses SQL only, it must not be changed after 1.9 goes stable!!
                    if (!upgrade_18_gradebook($course->id)) {
                        $result = false;
                        break;
                    }
                }
                rs_close($rs);
            }
        }
        upgrade_main_savepoint($result, 2007072200);
    }
    if ($result && $oldversion < 2007072400) {
        /// Dropping one DEFAULT in a TEXT column. It's was only one remaining
        /// since Moodle 1.7, so new servers won't have those anymore.
        /// Changing the default of field sessdata on table sessions2 to drop it
        $table = new XMLDBTable('sessions2');
        $field = new XMLDBField('sessdata');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, null, 'modified');
        /// Launch change of default for field sessdata
        $result = $result && change_field_default($table, $field);
        upgrade_main_savepoint($result, 2007072400);
    }
    if ($result && $oldversion < 2007073100) {
        /// Define table grade_outcomes_courses to be created
        $table = new XMLDBTable('grade_outcomes_courses');
        /// Adding fields to table grade_outcomes_courses
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('outcomeid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_outcomes_courses
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('outcomeid', XMLDB_KEY_FOREIGN, array('outcomeid'), 'grade_outcomes', array('id'));
        $table->addKeyInfo('courseid-outcomeid', XMLDB_KEY_UNIQUE, array('courseid', 'outcomeid'));
        /// Launch create table for grade_outcomes_courses
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073100);
    }
    if ($result && $oldversion < 2007073101) {
        // Add new tag tables
        /// Define table tag to be created
        $table = new XMLDBTable('tag');
        /// Adding fields to table tag
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('tagtype', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        $table->addFieldInfo('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('flag', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, null, null, null, null, '0');
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table tag
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag
        $table->addIndexInfo('name', XMLDB_INDEX_UNIQUE, array('name'));
        /// Launch create table for tag
        $result = $result && create_table($table);
        /// Define table tag_correlation to be created
        $table = new XMLDBTable('tag_correlation');
        /// Adding fields to table tag_correlation
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('correlatedtags', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_correlation
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_correlation
        $table->addIndexInfo('tagid', XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch create table for tag_correlation
        $result = $result && create_table($table);
        /// Define table tag_instance to be created
        $table = new XMLDBTable('tag_instance');
        /// Adding fields to table tag_instance
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('tagid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table tag_instance
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Adding indexes to table tag_instance
        $table->addIndexInfo('tagiditem', XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch create table for tag_instance
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007073101);
    }
    if ($result && $oldversion < 2007073103) {
        /// Define field rawname to be added to tag
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('rawname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'name');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007073103);
    }
    if ($result && $oldversion < 2007073105) {
        /// Define field description to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_outcomes_history');
        $field = new XMLDBField('description');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'scaleid');
            /// Launch add field description
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007073105);
    }
    // adding unique contraint on (courseid,shortname) of an outcome
    if ($result && $oldversion < 2007080100) {
        /// Define key courseid-shortname (unique) to be added to grade_outcomes
        $table = new XMLDBTable('grade_outcomes');
        $key = new XMLDBKey('courseid-shortname');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('courseid', 'shortname'));
        /// Launch add key courseid-shortname
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007080100);
    }
    /// originally there was supportname and supportemail upgrade code - this is handled in upgradesettings.php instead
    if ($result && $oldversion < 2007080202) {
        /// Define index tagiditem (not unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        drop_index($table, $index);
        /// Define index tagiditem (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch add index tagiditem
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007080202);
    }
    if ($result && $oldversion < 2007080300) {
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateoutcomes to be added to grade_categories
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateoutcomes');
        if (!field_exists($table, $field)) {
            $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
            /// Launch add field aggregateoutcomes
            $result = $result && add_field($table, $field);
        }
        upgrade_main_savepoint($result, 2007080300);
    }
    if ($result && $oldversion < 2007080800) {
        /// Normalize course->shortname MDL-10026
        /// Changing precision of field shortname on table course to (100)
        $table = new XMLDBTable('course');
        $field = new XMLDBField('shortname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, null, null, 'fullname');
        /// Launch change of precision for field shortname
        $result = $result && change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007080800);
    }
    if ($result && $oldversion < 2007080900) {
        /// Add context.path & index
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('context');
        $index = new XMLDBIndex('path');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('path'));
        $result = $result && add_index($table, $index);
        /// Add context.depth
        $table = new XMLDBTable('context');
        $field = new XMLDBField('depth');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'path');
        $result = $result && add_field($table, $field);
        /// make sure the system context has proper data
        get_system_context(false);
        upgrade_main_savepoint($result, 2007080900);
    }
    if ($result && $oldversion < 2007080903) {
        /// Define index
        $table = new XMLDBTable('grade_grades');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('locked-locktime');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('locked', 'locktime'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        /// Define index itemtype-needsupdate (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('itemtype-needsupdate');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('itemtype', 'needsupdate'));
        if (!index_exists($table, $index)) {
            /// Launch add index itemtype-needsupdate
            $result = $result && add_index($table, $index);
        }
        /// Define index
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('gradetype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('gradetype'));
        if (!index_exists($table, $index)) {
            /// Launch add index
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007080903);
    }
    if ($result && $oldversion < 2007081000) {
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_upgrade_context_etc();
        upgrade_main_savepoint($result, 2007081000);
    }
    if ($result && $oldversion < 2007081302) {
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('password');
        if (field_exists($table, $field)) {
            /// 1.7.*/1.6.*/1.5.* - create 'groupings' and 'groupings_groups' + rename password to enrolmentkey
            /// or second run after fixing structure broken from 1.8.x
            $result = $result && upgrade_17_groups();
        } else {
            if (table_exists(new XMLDBTable('groups_groupings'))) {
                /// ELSE 'groups_groupings' table exists, this is 1.8.* properly upgraded
                $result = $result && upgrade_18_groups();
            } else {
                /// broken groups, failed 1.8.x upgrade
                upgrade_18_broken_groups();
                notify('Warning: failed groups upgrade detected! Unfortunately this problem ' . 'can not be fixed automatically. Mapping of groups to courses was lost, ' . 'you can either revert to backup from 1.7.x and run ugprade again or ' . 'continue and fill in the missing course ids into groups table manually.');
                $result = false;
            }
        }
        upgrade_main_savepoint($result, 2007081302);
    }
    if ($result && $oldversion < 2007081303) {
        /// Common groups upgrade for 1.8.* and 1.7.*/1.6.*..
        // delete not used fields
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('theme');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        $table = new XMLDBTable('groups');
        $field = new XMLDBField('lang');
        if (field_exists($table, $field)) {
            drop_field($table, $field);
        }
        /// Add groupingid field/f.key to 'course' table.
        $table = new XMLDBTable('course');
        $field = new XMLDBField('defaultgroupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmodeforce');
        $result = $result && add_field($table, $field);
        /// Add grouping ID, grouponly field/f.key to 'course_modules' table.
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupingid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupmode');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $field = new XMLDBField('groupmembersonly');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', $prev = 'groupingid');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('course_modules');
        $key = new XMLDBKey('groupingid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('groupingid'), 'groupings', array('id'));
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007081303);
    }
    if ($result && $oldversion < 2007082300) {
        /// Define field ordering to be added to tag_instance table
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'itemid');
        /// Launch add field rawname
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082300);
    }
    if ($result && $oldversion < 2007082700) {
        /// Define field timemodified to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'ordering');
        /// Launch add field timemodified
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007082700);
    }
    /// migrate all tags table to tag - this code MUST use SQL only,
    /// because if the db structure changes the library functions will fail in future
    if ($result && $oldversion < 2007082701) {
        $tagrefs = array();
        // $tagrefs[$oldtagid] = $newtagid
        if ($rs = get_recordset('tags')) {
            $db->debug = false;
            while ($oldtag = rs_fetch_next_record($rs)) {
                $raw_normalized = clean_param($oldtag->text, PARAM_TAG);
                $normalized = moodle_strtolower($raw_normalized);
                // if this tag does not exist in tag table yet
                if (!($newtag = get_record('tag', 'name', addslashes($normalized), '', '', '', '', 'id'))) {
                    $itag = new object();
                    $itag->name = $normalized;
                    $itag->rawname = $raw_normalized;
                    $itag->userid = $oldtag->userid;
                    $itag->timemodified = time();
                    $itag->descriptionformat = 0;
                    // default format
                    if ($oldtag->type == 'official') {
                        $itag->tagtype = 'official';
                    } else {
                        $itag->tagtype = 'default';
                    }
                    if ($idx = insert_record('tag', addslashes_recursive($itag))) {
                        $tagrefs[$oldtag->id] = $idx;
                    }
                    // if this tag is already used by tag table
                } else {
                    $tagrefs[$oldtag->id] = $newtag->id;
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        // fetch all the tag instances and migrate them as well
        if ($rs = get_recordset('blog_tag_instance')) {
            $db->debug = false;
            while ($blogtag = rs_fetch_next_record($rs)) {
                if (array_key_exists($blogtag->tagid, $tagrefs)) {
                    $tag_instance = new object();
                    $tag_instance->tagid = $tagrefs[$blogtag->tagid];
                    $tag_instance->itemtype = 'blog';
                    $tag_instance->itemid = $blogtag->entryid;
                    $tag_instance->ordering = 1;
                    // does not matter much, because originally there was no ordering in blogs
                    $tag_instance->timemodified = time();
                    insert_record('tag_instance', $tag_instance);
                }
            }
            $db->debug = true;
            rs_close($rs);
        }
        unset($tagrefs);
        // release memory
        $table = new XMLDBTable('tags');
        drop_table($table);
        $table = new XMLDBTable('blog_tag_instance');
        drop_table($table);
        upgrade_main_savepoint($result, 2007082701);
    }
    /// MDL-11015, MDL-11016
    if ($result && $oldversion < 2007082800) {
        /// Changing type of field userid on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field userid
        $result = $result && change_field_type($table, $field);
        /// Changing type of field descriptionformat on table tag to int
        $table = new XMLDBTable('tag');
        $field = new XMLDBField('descriptionformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'description');
        /// Launch change of type for field descriptionformat
        $result = $result && change_field_type($table, $field);
        /// Define key userid (foreign) to be added to tag
        $table = new XMLDBTable('tag');
        $key = new XMLDBKey('userid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Launch add key userid
        $result = $result && add_key($table, $key);
        /// Define index tagiditem (unique) to be dropped form tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('tagiditem');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid', 'itemtype', 'itemid'));
        /// Launch drop index tagiditem
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_instance to int
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        /// Changing sign of field itemid on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('itemid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'itemtype');
        /// Launch change of sign for field itemid
        $result = $result && change_field_unsigned($table, $field);
        /// Changing sign of field ordering on table tag_instance to unsigned
        $table = new XMLDBTable('tag_instance');
        $field = new XMLDBField('ordering');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'itemid');
        /// Launch change of sign for field ordering
        $result = $result && change_field_unsigned($table, $field);
        /// Define index itemtype-itemid-tagid (unique) to be added to tag_instance
        $table = new XMLDBTable('tag_instance');
        $index = new XMLDBIndex('itemtype-itemid-tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('itemtype', 'itemid', 'tagid'));
        /// Launch add index itemtype-itemid-tagid
        $result = $result && add_index($table, $index);
        /// Define index tagid (unique) to be dropped form tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $index = new XMLDBIndex('tagid');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('tagid'));
        /// Launch drop index tagid
        $result = $result && drop_index($table, $index);
        /// Changing type of field tagid on table tag_correlation to int
        $table = new XMLDBTable('tag_correlation');
        $field = new XMLDBField('tagid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch change of type for field tagid
        $result = $result && change_field_type($table, $field);
        /// Define key tagid (foreign) to be added to tag_correlation
        $table = new XMLDBTable('tag_correlation');
        $key = new XMLDBKey('tagid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('tagid'), 'tag', array('id'));
        /// Launch add key tagid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082800);
    }
    if ($result && $oldversion < 2007082801) {
        /// Define table user_private_key to be created
        $table = new XMLDBTable('user_private_key');
        /// Adding fields to table user_private_key
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('script', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('instance', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('iprestriction', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('validuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table user_private_key
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
        /// Adding indexes to table user_private_key
        $table->addIndexInfo('script-value', XMLDB_INDEX_NOTUNIQUE, array('script', 'value'));
        /// Launch create table for user_private_key
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007082801);
    }
    /// Going to modify the applicationid from int(1) to int(10). Dropping and
    /// re-creating the associated keys/indexes is mandatory to be cross-db. MDL-11042
    if ($result && $oldversion < 2007082803) {
        /// Define key applicationid (foreign) to be dropped form mnet_host
        $table = new XMLDBTable('mnet_host');
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch drop key applicationid
        $result = $result && drop_key($table, $key);
        /// Changing type of field applicationid on table mnet_host to int
        $field = new XMLDBField('applicationid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'last_log_id');
        /// Launch change of type for field applicationid
        $result = $result && change_field_type($table, $field);
        /// Define key applicationid (foreign) to be added to mnet_host
        $key = new XMLDBKey('applicationid');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('applicationid'), 'mnet_application', array('id'));
        /// Launch add key applicationid
        $result = $result && add_key($table, $key);
        upgrade_main_savepoint($result, 2007082803);
    }
    if ($result && $oldversion < 2007090503) {
        /// Define field aggregatesubcats to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories
        $table = new XMLDBTable('grade_categories');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregatesubcats to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregatesubcats');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'aggregateoutcomes');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// Define field aggregateonlygraded to be added to grade_categories_history
        $table = new XMLDBTable('grade_categories_history');
        $field = new XMLDBField('aggregateonlygraded');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'droplow');
        if (!field_exists($table, $field)) {
            /// Launch add field aggregateonlygraded
            $result = $result && add_field($table, $field);
        }
        /// upgrade path in grade_categrories table - now using slash on both ends
        $concat = sql_concat('path', "'/'");
        $sql = "UPDATE {$CFG->prefix}grade_categories SET path = {$concat} WHERE path NOT LIKE '/%/'";
        execute_sql($sql, true);
        /// convert old aggregation constants if needed
        /*for ($i=0; $i<=12; $i=$i+2) {
              $j = $i+1;
              $sql = "UPDATE {$CFG->prefix}grade_categories SET aggregation = $i, aggregateonlygraded = 1 WHERE aggregation = $j";
              execute_sql($sql, true);
          }*/
        // not needed anymore - breaks upgrade now
        upgrade_main_savepoint($result, 2007090503);
    }
    /// To have UNIQUE indexes over NULLable columns isn't cross-db at all
    /// so we create a non unique index and programatically enforce uniqueness
    if ($result && $oldversion < 2007090600) {
        /// Define index idnumber (unique) to be dropped form course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_UNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        $result = $result && drop_index($table, $index);
        /// Define index idnumber-course (not unique) to be added to course_modules
        $table = new XMLDBTable('course_modules');
        $index = new XMLDBIndex('idnumber-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'course'));
        /// Launch add index idnumber-course
        $result = $result && add_index($table, $index);
        /// Define index idnumber-courseid (not unique) to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $index = new XMLDBIndex('idnumber-courseid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber', 'courseid'));
        /// Launch add index idnumber-courseid
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007090600);
    }
    /// Create the permanent context_temp table to be used by build_context_path()
    if ($result && $oldversion < 2007092001) {
        /// Define table context_temp to be created
        $table = new XMLDBTable('context_temp');
        /// Adding fields to table context_temp
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('depth', XMLDB_TYPE_INTEGER, '2', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table context_temp
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /// Launch create table for context_temp
        $result = $result && create_table($table);
        /// make sure category depths, parents and paths are ok, categories from 1.5 may not be properly initialized (MDL-12585)
        upgrade_fix_category_depths();
        /// Recalculate depths, paths and so on
        if (!empty($CFG->rolesactive)) {
            cleanup_contexts();
            // make sure all course, category and user contexts exist - we need it for grade letter upgrade, etc.
            create_contexts(CONTEXT_COURSE, false, true);
            create_contexts(CONTEXT_USER, false, true);
            // we need all contexts path/depths filled properly
            build_context_path(true, true);
            load_all_capabilities();
        } else {
            // upgrade from 1.6 - build all contexts
            create_contexts(null, true, true);
        }
        upgrade_main_savepoint($result, 2007092001);
    }
    /**
     * Merging of grade_grades_text back into grade_grades
     */
    if ($result && $oldversion < 2007092002) {
        /// Define field feedback to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        /// Define field feedback to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedback');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'excluded');
        if (!field_exists($table, $field)) {
            /// Launch add field feedback
            $result = $result && add_field($table, $field);
        }
        /// Define field feedbackformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('feedbackformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'feedback');
        if (!field_exists($table, $field)) {
            /// Launch add field feedbackformat
            $result = $result && add_field($table, $field);
        }
        /// Define field information to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('information');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null, 'feedbackformat');
        if (!field_exists($table, $field)) {
            /// Launch add field information
            $result = $result && add_field($table, $field);
        }
        /// Define field informationformat to be added to grade_grades_history
        $table = new XMLDBTable('grade_grades_history');
        $field = new XMLDBField('informationformat');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'information');
        if (!field_exists($table, $field)) {
            /// Launch add field informationformat
            $result = $result && add_field($table, $field);
        }
        $table = new XMLDBTable('grade_grades_text');
        if ($result and table_exists($table)) {
            //migrade existing data into grade_grades table - this is slow but works for all dbs,
            //it will be executed on development sites only
            $fields = array('feedback', 'information');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = (\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id)";
                $result = execute_sql($sql) && $result;
            }
            $fields = array('feedbackformat', 'informationformat');
            foreach ($fields as $field) {
                $sql = "UPDATE {$CFG->prefix}grade_grades\n                           SET {$field} = COALESCE((\n                                SELECT {$field}\n                                  FROM {$CFG->prefix}grade_grades_text ggt\n                                 WHERE ggt.gradeid = {$CFG->prefix}grade_grades.id), 0)";
                $result = execute_sql($sql) && $result;
            }
            if ($result) {
                $tables = array('grade_grades_text', 'grade_grades_text_history');
                foreach ($tables as $table) {
                    $table = new XMLDBTable($table);
                    if (table_exists($table)) {
                        drop_table($table);
                    }
                }
            }
        }
        upgrade_main_savepoint($result, 2007092002);
    }
    if ($result && $oldversion < 2007092803) {
        /// Remove obsoleted unit tests tables - they will be recreated automatically
        $tables = array('grade_categories', 'scale', 'grade_items', 'grade_calculations', 'grade_grades', 'grade_grades_raw', 'grade_grades_final', 'grade_grades_text', 'grade_outcomes', 'grade_outcomes_courses');
        foreach ($tables as $tablename) {
            $table = new XMLDBTable('unittest_' . $tablename);
            if (table_exists($table)) {
                drop_table($table);
            }
            $table = new XMLDBTable('unittest_' . $tablename . '_history');
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        /// Define field display to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
        }
        /// Define field display to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('display');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '0', 'sortorder');
        /// Launch add field display
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// Define field decimals to be added to grade_items
        $table = new XMLDBTable('grade_items');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        } else {
            $result = $result && change_field_default($table, $field);
            $result = $result && change_field_notnull($table, $field);
        }
        /// Define field decimals to be added to grade_items_history
        $table = new XMLDBTable('grade_items_history');
        $field = new XMLDBField('decimals');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, null, null, null, null, null, 'display');
        /// Launch add field decimals
        if (!field_exists($table, $field)) {
            $result = $result && add_field($table, $field);
        }
        /// fix incorrect -1 default for grade_item->display
        execute_sql("UPDATE {$CFG->prefix}grade_items SET display=0 WHERE display=-1");
        upgrade_main_savepoint($result, 2007092803);
    }
    /// migrade grade letters - we can not do this in normal grades upgrade becuase we need all course contexts
    if ($result && $oldversion < 2007092806) {
        $result = upgrade_18_letters();
        /// Define index contextidlowerboundary (not unique) to be added to grade_letters
        $table = new XMLDBTable('grade_letters');
        $index = new XMLDBIndex('contextid-lowerboundary');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('contextid', 'lowerboundary'));
        /// Launch add index contextidlowerboundary
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007092806);
    }
    if ($result && $oldversion < 2007100100) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        /// Adding fields to table cache_flags
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('flagtype', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table cache_flags
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        /*
         * Note: mysql can not create indexes on text fields larger than 333 chars! 
         */
        /// Adding indexes to table cache_flags
        $table->addIndexInfo('flagtype', XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        $table->addIndexInfo('name', XMLDB_INDEX_NOTUNIQUE, array('name'));
        /// Launch create table for cache_flags
        if (!table_exists($table)) {
            $result = $result && create_table($table);
        }
        upgrade_main_savepoint($result, 2007100100);
    }
    if ($result && $oldversion < 2007100300) {
        /// MNET stuff for roaming theme
        /// Define field force_theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('force_theme');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'last_log_id');
        /// Launch add field force_theme
        $result = $result && add_field($table, $field);
        /// Define field theme to be added to mnet_host
        $table = new XMLDBTable('mnet_host');
        $field = new XMLDBField('theme');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'force_theme');
        /// Launch add field theme
        $result = $result && add_field($table, $field);
        upgrade_main_savepoint($result, 2007100300);
    }
    if ($result && $oldversion < 2007100301) {
        /// Define table cache_flags to be created
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('typename');
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('flagtype');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('flagtype'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        $table = new XMLDBTable('cache_flags');
        $index = new XMLDBIndex('name');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('name'));
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        upgrade_main_savepoint($result, 2007100301);
    }
    if ($result && $oldversion < 2007100303) {
        /// Changing nullability of field summary on table course to null
        $table = new XMLDBTable('course');
        $field = new XMLDBField('summary');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'idnumber');
        /// Launch change of nullability for field summary
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100303);
    }
    if ($result && $oldversion < 2007100500) {
        /// for dev sites - it is ok to do this repeatedly
        /// Changing nullability of field path on table context to null
        $table = new XMLDBTable('context');
        $field = new XMLDBField('path');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'instanceid');
        /// Launch change of nullability for field path
        $result = $result && change_field_notnull($table, $field);
        upgrade_main_savepoint($result, 2007100500);
    }
    if ($result && $oldversion < 2007100700) {
        /// first drop existing tables - we do not need any data from there
        $table = new XMLDBTable('grade_import_values');
        if (table_exists($table)) {
            drop_table($table);
        }
        $table = new XMLDBTable('grade_import_newitem');
        if (table_exists($table)) {
            drop_table($table);
        }
        /// Define table grade_import_newitem to be created
        $table = new XMLDBTable('grade_import_newitem');
        /// Adding fields to table grade_import_newitem
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table grade_import_newitem
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_newitem
        $result = $result && create_table($table);
        /// Define table grade_import_values to be created
        $table = new XMLDBTable('grade_import_values');
        /// Adding fields to table grade_import_values
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('itemid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('newgradeitem', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('finalgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, null, null);
        $table->addFieldInfo('feedback', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
        $table->addFieldInfo('importcode', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('importer', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        /// Adding keys to table grade_import_values
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('itemid', XMLDB_KEY_FOREIGN, array('itemid'), 'grade_items', array('id'));
        $table->addKeyInfo('newgradeitem', XMLDB_KEY_FOREIGN, array('newgradeitem'), 'grade_import_newitem', array('id'));
        $table->addKeyInfo('importer', XMLDB_KEY_FOREIGN, array('importer'), 'user', array('id'));
        /// Launch create table for grade_import_values
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100700);
    }
    /// dropping context_rel table - not used anymore
    if ($result && $oldversion < 2007100800) {
        /// Define table context_rel to be dropped
        $table = new XMLDBTable('context_rel');
        /// Launch drop table for context_rel
        if (table_exists($table)) {
            drop_table($table);
        }
        upgrade_main_savepoint($result, 2007100800);
    }
    /// Truncate the text_cahe table and add new index
    if ($result && $oldversion < 2007100802) {
        /// Truncate the cache_text table
        execute_sql("TRUNCATE TABLE {$CFG->prefix}cache_text", true);
        /// Define index timemodified (not unique) to be added to cache_text
        $table = new XMLDBTable('cache_text');
        $index = new XMLDBIndex('timemodified');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
        /// Launch add index timemodified
        $result = $result && add_index($table, $index);
        upgrade_main_savepoint($result, 2007100802);
    }
    /// newtable for gradebook settings per course
    if ($result && $oldversion < 2007100803) {
        /// Define table grade_settings to be created
        $table = new XMLDBTable('grade_settings');
        /// Adding fields to table grade_settings
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('value', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null);
        /// Adding keys to table grade_settings
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        /// Adding indexes to table grade_settings
        $table->addIndexInfo('courseid-name', XMLDB_INDEX_UNIQUE, array('courseid', 'name'));
        /// Launch create table for grade_settings
        $result = $result && create_table($table);
        upgrade_main_savepoint($result, 2007100803);
    }
    /// cleanup in user_lastaccess
    if ($result && $oldversion < 2007100902) {
        $sql = "DELETE\n                  FROM {$CFG->prefix}user_lastaccess\n                 WHERE NOT EXISTS (SELECT 'x'\n                                    FROM {$CFG->prefix}course c\n                                   WHERE c.id = {$CFG->prefix}user_lastaccess.courseid)";
        execute_sql($sql);
        upgrade_main_savepoint($result, 2007100902);
    }
    /// drop old gradebook tables
    if ($result && $oldversion < 2007100903) {
        $tables = array('grade_category', 'grade_item', 'grade_letter', 'grade_preferences', 'grade_exceptions');
        foreach ($tables as $table) {
            $table = new XMLDBTable($table);
            if (table_exists($table)) {
                drop_table($table);
            }
        }
        upgrade_main_savepoint($result, 2007100903);
    }
    if ($result && $oldversion < 2007101500 && !file_exists($CFG->dataroot . '/user')) {
        // Get list of users by browsing moodledata/user
        $oldusersdir = $CFG->dataroot . '/users';
        $folders = get_directory_list($oldusersdir, '', false, true, false);
        foreach ($folders as $userid) {
            $olddir = $oldusersdir . '/' . $userid;
            $files = get_directory_list($olddir);
            if (empty($files)) {
                continue;
            }
            // Create new user directory
            if (!($newdir = make_user_directory($userid))) {
                // some weird directory - do not stop the upgrade, just ignore it
                continue;
            }
            // Move contents of old directory to new one
            if (file_exists($olddir) && file_exists($newdir)) {
                foreach ($files as $file) {
                    copy($olddir . '/' . $file, $newdir . '/' . $file);
                }
            } else {
                notify("Could not move the contents of {$olddir} into {$newdir}!");
                $result = false;
                break;
            }
        }
        // Leave a README in old users directory
        $readmefilename = $oldusersdir . '/README.txt';
        if ($handle = fopen($readmefilename, 'w+b')) {
            if (!fwrite($handle, get_string('olduserdirectory'))) {
                // Could not write to the readme file. No cause for huge concern
                notify("Could not write to the README.txt file in {$readmefilename}.");
            }
            fclose($handle);
        } else {
            // Could not create the readme file. No cause for huge concern
            notify("Could not create the README.txt file in {$readmefilename}.");
        }
    }
    if ($result && $oldversion < 2007101502) {
        /// try to remove duplicate entries
        $SQL = "SELECT userid, itemid, COUNT(*)\n               FROM {$CFG->prefix}grade_grades\n               GROUP BY userid, itemid\n               HAVING COUNT( * ) >1";
        // duplicates found
        if ($rs = get_recordset_sql($SQL)) {
            if ($rs && $rs->RecordCount() > 0) {
                while ($dup = rs_fetch_next_record($rs)) {
                    if ($thisdups = get_records_sql("SELECT id FROM {$CFG->prefix}grade_grades \n                                                    WHERE itemid = {$dup->itemid} AND userid = {$dup->userid}\n                                                    ORDER BY timemodified DESC")) {
                        $processed = 0;
                        // keep the first one
                        foreach ($thisdups as $thisdup) {
                            if ($processed) {
                                // remove the duplicates
                                delete_records('grade_grades', 'id', $thisdup->id);
                            }
                            $processed++;
                        }
                    }
                }
                rs_close($rs);
            }
        }
        /// Define key userid-itemid (unique) to be added to grade_grades
        $table = new XMLDBTable('grade_grades');
        $key = new XMLDBKey('userid-itemid');
        $key->setAttributes(XMLDB_KEY_UNIQUE, array('userid', 'itemid'));
        /// Launch add key userid-itemid
        $result = $result && add_key($table, $key);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101502);
    }
    if ($result && $oldversion < 2007101505) {
        /// Changing precision of field dst_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('dst_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'dst_skipweeks');
        /// Launch change of precision for field dst_time
        $result = $result && change_field_precision($table, $field);
        /// Changing precision of field std_time on table timezone to (6)
        $table = new XMLDBTable('timezone');
        $field = new XMLDBField('std_time');
        $field->setAttributes(XMLDB_TYPE_CHAR, '6', null, XMLDB_NOTNULL, null, null, null, '00:00', 'std_skipweeks');
        /// Launch change of precision for field std_time
        $result = $result && change_field_precision($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101505);
    }
    if ($result && $oldversion < 2007101506) {
        /// CONTEXT_PERSONAL was never implemented - removing
        $sql = "DELETE\n                  FROM {$CFG->prefix}context\n                 WHERE contextlevel=20";
        execute_sql($sql);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101506);
    }
    if ($result && $oldversion < 2007101507) {
        $db->debug = false;
        require_once $CFG->dirroot . '/course/lib.php';
        notify('Started rebuilding of course cache...', 'notifysuccess');
        rebuild_course_cache();
        // Rebuild course cache - new group related fields there
        notify('...finished rebuilding of course cache.', 'notifysuccess');
        $db->debug = true;
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101507);
    }
    if ($result && $oldversion < 2007101508) {
        $db->debug = false;
        notify('Updating country list according to recent official ISO listing...', 'notifysuccess');
        // re-assign users to valid countries
        set_field('user', 'country', 'CD', 'country', 'ZR');
        // Zaire is now Congo Democratique
        set_field('user', 'country', 'TL', 'country', 'TP');
        // Timor has changed
        set_field('user', 'country', 'FR', 'country', 'FX');
        // France metropolitaine doesn't exist
        set_field('user', 'country', 'RS', 'country', 'KO');
        // Kosovo is part of Serbia, "under the auspices of the United Nations, pursuant to UN Security Council Resolution 1244 of 10 June 1999."
        set_field('user', 'country', 'GB', 'country', 'WA');
        // Wales is part of UK (ie Great Britain)
        set_field('user', 'country', 'RS', 'country', 'CS');
        // Re-assign Serbia-Montenegro to Serbia.  This is arbitrary, but there is no way to make an automatic decision on this.
        notify('...update complete. Remember to update the language pack to get the most recent country names defitions and codes.  This is specialy important for sites with users from Congo (now CD), Timor (now TL), Kosovo (now RS), Wales (now GB), Serbia (RS) and Montenegro (ME).  Users based in Montenegro (ME) will need to manually update their profile.', 'notifysuccess');
        $db->debug = true;
        upgrade_main_savepoint($result, 2007101508);
    }
    if ($result && $oldversion < 2007101508.01) {
        // add forgotten table
        /// Define table scale_history to be created
        $table = new XMLDBTable('scale_history');
        /// Adding fields to table scale_history
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('action', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('source', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        $table->addFieldInfo('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('loggeduser', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('courseid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('scale', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('description', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table scale_history
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('oldid', XMLDB_KEY_FOREIGN, array('oldid'), 'scale', array('id'));
        $table->addKeyInfo('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
        $table->addKeyInfo('loggeduser', XMLDB_KEY_FOREIGN, array('loggeduser'), 'user', array('id'));
        /// Adding indexes to table scale_history
        $table->addIndexInfo('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
        if ($result and !table_exists($table)) {
            /// Launch create table for scale_history
            $result = $result && create_table($table);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.01);
    }
    if ($result && $oldversion < 2007101508.02) {
        // upgade totals, no big deal if it fails
        require_once $CFG->libdir . '/statslib.php';
        stats_upgrade_totals();
        if (isset($CFG->loglifetime) and $CFG->loglifetime == 30) {
            set_config('loglifetime', 35);
            // we need more than 31 days for monthly stats!
        }
        notify('Upgrading log table indexes, this may take a long time, please be patient.', 'notifysuccess');
        /// Define index time-course-module-action (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time-course-module-action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time', 'course', 'module', 'action'));
        /// Launch drop index time-course-module-action
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid'));
        /// Launch drop index userid
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index info (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('info');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('info'));
        /// Launch drop index info
        if (index_exists($table, $index)) {
            $result = drop_index($table, $index) && $result;
        }
        /// Define index time (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('time');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('time'));
        /// Launch add index time
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Define index action (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('action');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('action'));
        /// Launch add index action
        if (!index_exists($table, $index)) {
            $result = add_index($table, $index) && $result;
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.02);
    }
    if ($result && $oldversion < 2007101508.03) {
        /// Define index course-userid (not unique) to be dropped form log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('course-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'userid'));
        /// Launch drop index course-userid
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Define index userid-course (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('userid-course');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('userid', 'course'));
        /// Launch add index userid-course
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.03);
    }
    if ($result && $oldversion < 2007101508.04) {
        set_field('tag_instance', 'itemtype', 'post', 'itemtype', 'blog');
        upgrade_main_savepoint($result, 2007101508.04);
    }
    if ($result && $oldversion < 2007101508.05) {
        /// Define index cmid (not unique) to be added to log
        $table = new XMLDBTable('log');
        $index = new XMLDBIndex('cmid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('cmid'));
        /// Launch add index cmid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.05);
    }
    if ($result && $oldversion < 2007101508.06) {
        /// Define index groupid-courseid-visible-userid (not unique) to be added to event
        $table = new XMLDBTable('event');
        $index = new XMLDBIndex('groupid-courseid-visible-userid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('groupid', 'courseid', 'visible', 'userid'));
        /// Launch add index groupid-courseid-visible-userid
        if (!index_exists($table, $index)) {
            $result = $result && add_index($table, $index);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.06);
    }
    if ($result && $oldversion < 2007101508.07) {
        /// Define table webdav_locks to be created
        $table = new XMLDBTable('webdav_locks');
        /// Adding fields to table webdav_locks
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('token', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('path', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('expiry', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('recursive', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('exclusivelock', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('created', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('modified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('owner', XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null);
        /// Adding keys to table webdav_locks
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('token', XMLDB_KEY_UNIQUE, array('token'));
        /// Adding indexes to table webdav_locks
        $table->addIndexInfo('path', XMLDB_INDEX_NOTUNIQUE, array('path'));
        $table->addIndexInfo('expiry', XMLDB_INDEX_NOTUNIQUE, array('expiry'));
        /// Launch create table for webdav_locks
        $result = $result && create_table($table);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.07);
    }
    if ($result && $oldversion < 2007101508.08) {
        // MDL-13676
        /// Define field name to be added to role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('name');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'text');
        /// Launch add field name
        $result = $result && add_field($table, $field);
        /// Copy data from old field to new field
        $result = $result && execute_sql('UPDATE ' . $CFG->prefix . 'role_names SET name = text');
        /// Define field text to be dropped from role_names
        $table = new XMLDBTable('role_names');
        $field = new XMLDBField('text');
        /// Launch drop field text
        $result = $result && drop_field($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101508.08);
    }
    if ($result && $oldversion < 2007101509) {
        // force full regrading
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101510) {
        /// Fix minor problem caused by MDL-5482.
        require_once $CFG->dirroot . '/question/upgrade.php';
        $result = $result && question_fix_random_question_parents();
        upgrade_main_savepoint($result, 2007101510);
    }
    if ($result && $oldversion < 2007101511) {
        // if guest role used as default user role unset it and force admin to choose new setting
        if (!empty($CFG->defaultuserroleid)) {
            if ($role = get_record('role', 'id', $CFG->defaultuserroleid)) {
                if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
                    if (isset($guestroles[$role->id])) {
                        set_config('defaultuserroleid', null);
                        notify('Guest role removed from "Default role for all users" setting, please select another role.', 'notifysuccess');
                    }
                }
            } else {
                set_config('defaultuserroleid', null);
            }
        }
    }
    if ($result && $oldversion < 2007101512) {
        notify('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
        /// Under MySQL and Postgres... detect old NULL contents and change them by correct empty string. MDL-14859
        if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
            execute_sql("UPDATE {$CFG->prefix}user SET idnumber = '' WHERE idnumber IS NULL", true);
        }
        /// Define index idnumber (not unique) to be dropped form user
        $table = new XMLDBTable('user');
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        /// Launch drop index idnumber
        if (index_exists($table, $index)) {
            $result = $result && drop_index($table, $index);
        }
        /// Changing precision of field idnumber on table user to (255)
        $table = new XMLDBTable('user');
        $field = new XMLDBField('idnumber');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'password');
        /// Launch change of precision for field idnumber
        $result = $result && change_field_precision($table, $field);
        /// Launch add index idnumber again
        $index = new XMLDBIndex('idnumber');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
        $result = $result && add_index($table, $index);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101512);
    }
    if ($result && $oldversion < 2007101513) {
        $log_action = new stdClass();
        $log_action->module = 'course';
        $log_action->action = 'unenrol';
        $log_action->mtable = 'course';
        $log_action->field = 'fullname';
        if (!record_exists("log_display", "action", "unenrol", "module", "course")) {
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101513);
    }
    if ($result && $oldversion < 2007101514) {
        $table = new XMLDBTable('mnet_enrol_course');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', true, true, null, false, false, 0);
        $result = change_field_precision($table, $field);
        upgrade_main_savepoint($result, 2007101514);
    }
    if ($result && $oldversion < 2007101515) {
        $result = delete_records_select('role_names', sql_isempty('role_names', 'name', false, false));
        upgrade_main_savepoint($result, 2007101515);
    }
    if ($result && $oldversion < 2007101517) {
        if (isset($CFG->defaultuserroleid) and isset($CFG->guestroleid) and $CFG->defaultuserroleid == $CFG->guestroleid) {
            // guest can not be selected in defaultuserroleid!
            unset_config('defaultuserroleid');
        }
        upgrade_main_savepoint($result, 2007101517);
    }
    if ($result && $oldversion < 2007101526) {
        /// Changing the default of field lang on table user to en_utf8
        $table = new XMLDBTable('user');
        $field = new XMLDBField('lang');
        $field->setAttributes(XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, null, 'en_utf8', 'country');
        /// Launch change of default for field lang
        $result = $result && change_field_default($table, $field);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101526);
    }
    if ($result && $oldversion < 2007101527) {
        if (!get_config(NULL, 'statsruntimedays')) {
            set_config('statsruntimedays', '31');
        }
    }
    /// For MDL-17501. Ensure that any role that has moodle/course:update also
    /// has moodle/course:visibility.
    if ($result && $oldversion < 2007101532.1) {
        if (!empty($CFG->rolesactive)) {
            // In case we are upgrading from Moodle 1.6.
            /// Get the roles with 'moodle/course:update'.
            $systemcontext = get_context_instance(CONTEXT_SYSTEM);
            $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
            /// Give those roles 'moodle/course:visibility'.
            foreach ($roles as $role) {
                assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
            }
            /// Force all sessions to refresh access data.
            mark_context_dirty($systemcontext->path);
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101532.1);
    }
    if ($result && $oldversion < 2007101542) {
        if (empty($CFG->hiddenuserfields)) {
            set_config('hiddenuserfields', 'firstaccess');
        } else {
            if (strpos($CFG->hiddenuserfields, 'firstaccess') === false) {
                //firstaccess should not already be listed but just in case
                set_config('hiddenuserfields', $CFG->hiddenuserfields . ',firstaccess');
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101542);
    }
    if ($result && $oldversion < 2007101545.01) {
        require_once "{$CFG->dirroot}/filter/tex/lib.php";
        filter_tex_updatedcallback(null);
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101545.01);
    }
    if ($result && $oldversion < 2007101546.02) {
        if (empty($CFG->gradebook_latest195_upgrade)) {
            require_once $CFG->libdir . '/gradelib.php';
            // we need constants only
            // reset current coef for simple mean items - it may contain some rubbish ;-)
            $sql = "UPDATE {$CFG->prefix}grade_items\n                       SET aggregationcoef = 0\n                     WHERE categoryid IN (SELECT gc.id\n                                            FROM {$CFG->prefix}grade_categories gc\n                                           WHERE gc.aggregation = " . GRADE_AGGREGATE_WEIGHTED_MEAN2 . ")";
            $result = execute_sql($sql);
        } else {
            // direct upgrade from 1.8.x - no need to reset coef, because it is already ok
            unset_config('gradebook_latest195_upgrade');
        }
        upgrade_main_savepoint($result, 2007101546.02);
    }
    if ($result && $oldversion < 2007101546.03) {
        /// Deleting orphaned messages from deleted users.
        require_once $CFG->dirroot . '/message/lib.php';
        /// Detect deleted users with messages sent(useridfrom) and not read
        if ($deletedusers = get_records_sql("SELECT DISTINCT u.id\n                                           FROM {$CFG->prefix}user u\n                                           JOIN {$CFG->prefix}message m ON m.useridfrom = u.id\n                                          WHERE u.deleted = 1")) {
            foreach ($deletedusers as $deleteduser) {
                message_move_userfrom_unread2read($deleteduser->id);
                // move messages
            }
        }
        /// Main savepoint reached
        upgrade_main_savepoint($result, 2007101546.03);
    }
    if ($result && $oldversion < 2007101546.05) {
        // force full regrading - the max grade for sum aggregation was not correct when scales involved,
        //                        extra credit grade is not dropped anymore in aggregations if drop low or keep high specified
        //                        sum aggragetion respects drop low and keep high when calculation max value
        set_field('grade_items', 'needsupdate', 1, 'needsupdate', 0);
    }
    if ($result && $oldversion < 2007101546.06) {
        unset_config('grade_report_showgroups');
        upgrade_main_savepoint($result, 2007101546.06);
    }
    if ($result && $oldversion < 2007101547) {
        // Let's check the status of mandatory mnet_host records, fixing them
        // and moving "orphan" users to default localhost record. MDL-16879
        notify('Fixing mnet records, this may take a while...', 'notifysuccess');
        $db->debug = false;
        // Can output too much. Disabling
        upgrade_fix_incorrect_mnethostids();
        $db->debug = true;
        // Restoring debug level
        upgrade_main_savepoint($result, 2007101547);
    }
    if ($result && $oldversion < 2007101551) {
        //insert new record for log_display table
        //used to record tag update.
        if (!record_exists("log_display", "action", "update", "module", "tag")) {
            $log_action = new stdClass();
            $log_action->module = 'tag';
            $log_action->action = 'update';
            $log_action->mtable = 'tag';
            $log_action->field = 'name';
            $result = $result && insert_record('log_display', $log_action);
        }
        upgrade_main_savepoint($result, 2007101551);
    }
    if ($result && $oldversion < 2007101561.01) {
        // As part of security changes password policy will now be enabled by default.
        // If it has not already been enabled then we will enable it... Admins will still
        // be able to switch it off after this upgrade
        if (record_exists('config', 'name', 'passwordpolicy', 'value', 0)) {
            unset_config('passwordpolicy');
        }
        $message = get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        notify($message, 'notifysuccess');
        unset($message);
        upgrade_main_savepoint($result, 2007101561.01);
    }
    if ($result && $oldversion < 2007101561.02) {
        $messagesubject = s($SITE->shortname) . ': ' . get_string('upgrade197noticesubject', 'admin');
        $message = '<p>' . s($SITE->fullname) . ' (' . s($CFG->wwwroot) . '):</p>' . get_string('upgrade197notice', 'admin');
        if (empty($CFG->passwordmainsalt)) {
            $docspath = $CFG->docroot . '/' . str_replace('_utf8', '', current_language()) . '/report/security/report_security_check_passwordsaltmain';
            $message .= "\n" . get_string('upgrade197salt', 'admin', $docspath);
        }
        // Force administrators to change password on next login
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password, u.mailformat\n              FROM {$CFG->prefix}role_capabilities rc\n              JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n              JOIN {$CFG->prefix}user u ON u.id = ra.userid\n             WHERE rc.capability = 'moodle/site:doanything'\n                   AND rc.permission = " . CAP_ALLOW . "\n                   AND u.deleted = 0\n                   AND rc.contextid = " . $systemcontext->id . " AND (u.auth='manual' OR u.auth='email')";
        $adminusers = get_records_sql($sql);
        foreach ($adminusers as $adminuser) {
            if ($preference = get_record('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange')) {
                if ($preference->value == '1') {
                    continue;
                }
                set_field('user_preferences', 'value', '1', 'id', $preference->id);
            } else {
                $preference = new stdClass();
                $preference->userid = $adminuser->id;
                $preference->name = 'auth_forcepasswordchange';
                $preference->value = '1';
                insert_record('user_preferences', $preference);
            }
            $adminuser->maildisplay = 0;
            // do not use return email to self, it might actually help emails to get through and prevents notices
            // Message them with the notice about upgrading
            email_to_user($adminuser, $adminuser, $messagesubject, html_to_text($message), $message);
        }
        unset($adminusers);
        unset($preference);
        unset($message);
        unset($messagesubject);
        upgrade_main_savepoint($result, 2007101561.02);
    }
    if ($result && $oldversion < 2007101563.02) {
        // this block tries to undo incorrect forcing of new passwords for admins that have no
        // way to change passwords MDL-20933
        $systemcontext = get_context_instance(CONTEXT_SYSTEM);
        $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, u.password\n                  FROM {$CFG->prefix}role_capabilities rc\n                  JOIN {$CFG->prefix}role_assignments ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)\n                  JOIN {$CFG->prefix}user u ON u.id = ra.userid\n                 WHERE rc.capability = 'moodle/site:doanything'\n                       AND rc.permission = " . CAP_ALLOW . "\n                       AND u.deleted = 0\n                       AND rc.contextid = " . $systemcontext->id . " AND u.auth<>'manual' AND u.auth<>'email'";
        if ($adminusers = get_records_sql($sql)) {
            foreach ($adminusers as $adminuser) {
                delete_records('user_preferences', 'userid', $adminuser->id, 'name', 'auth_forcepasswordchange');
            }
        }
        unset($adminusers);
        upgrade_main_savepoint($result, 2007101563.02);
    }
    if ($result && $oldversion < 2007101563.03) {
        // NOTE: this is quite hacky, but anyway it should work fine in 1.9,
        //       in 2.0 we should always use plugin upgrade code for things like this
        $authsavailable = get_list_of_plugins('auth');
        foreach ($authsavailable as $authname) {
            if (!($auth = get_auth_plugin($authname))) {
                continue;
            }
            if ($auth->prevent_local_passwords()) {
                execute_sql("UPDATE {$CFG->prefix}user SET password='******' WHERE auth='{$authname}'");
            }
        }
        upgrade_main_savepoint($result, 2007101563.03);
    }
    return $result;
}
Example #17
0
/**
 * Returns all the users of a course: students and teachers
 *
 * @param int $courseid The course in question.
 * @param string $sort ?
 * @param string $exceptions ?
 * @param string $fields A comma separated list of fields to be returned from the chosen table.
 * @return object
 * @todo Finish documenting this function
 */
function get_course_users($courseid, $sort = 'ul.timeaccess DESC', $exceptions = '', $fields = 'u.*, ul.timeaccess as lastaccess')
{
    global $CFG;
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    /// If the course id is the SITEID, we need to return all the users if the "defaultuserroleid"
    /// has the capbility of accessing the site course. $CFG->nodefaultuserrolelists set to true can
    /// over-rule using this.
    if ($courseid == SITEID && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
        if ($roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
            $hascap = false;
            foreach ($roles as $role) {
                if ($role->id == $CFG->defaultuserroleid) {
                    $hascap = true;
                    break;
                }
            }
            if ($hascap) {
                if (empty($fields)) {
                    $fields = '*';
                }
                return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
            }
        }
    }
    return get_users_by_capability($context, 'moodle/course:view', $fields, $sort, '', '', '', $exceptions, false);
}
Example #18
0
/**
 * Returns list of non administrator roles
 */
function uu_allowed_roles($shortname = false)
{
    global $CFG;
    $roles = get_all_roles();
    $choices = array();
    foreach ($roles as $role) {
        if ($shortname) {
            $choices[$role->id] = $role->shortname;
        } else {
            $choices[$role->id] = format_string($role->name);
        }
    }
    // get rid of all admin roles
    if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW)) {
        foreach ($adminroles as $adminrole) {
            unset($choices[$adminrole->id]);
        }
    }
    return $choices;
}
 /**
  * Create a course in Moodle (Migration)
  *
  * @global type $DB
  * @global type $CFG
  * @global type $USER
  * @param int $tiicourseid The course id on Turnitin
  * @param string $tiicoursetitle The course title on Turnitin
  * @param string $coursename The new course name on Moodle
  * @param int $coursecategory The category that the course is to be created in
  * @return mixed course object if created or 0 if failed
  */
 public static function create_moodle_course($tiicourseid, $tiicoursetitle, $coursename, $coursecategory)
 {
     global $DB, $CFG, $USER;
     require_once $CFG->dirroot . "/course/lib.php";
     $data = new stdClass();
     $data->category = $coursecategory;
     $data->fullname = $coursename;
     $data->shortname = "Turnitin (" . $tiicourseid . ")";
     $data->maxbytes = 2097152;
     if ($course = create_course($data)) {
         $turnitincourse = new stdClass();
         $turnitincourse->courseid = $course->id;
         $turnitincourse->turnitin_cid = $tiicourseid;
         $turnitincourse->turnitin_ctl = $tiicoursetitle;
         $turnitincourse->ownerid = $USER->id;
         $turnitincourse->course_type = 'TT';
         // Enrol user as instructor on course in moodle if they are not a site admin.
         if (!is_siteadmin()) {
             // Get the role id for a teacher.
             $roles1 = get_roles_with_capability('mod/turnitintooltwo:grade');
             $roles2 = get_roles_with_capability('mod/turnitintooltwo:addinstance');
             $roles = array_intersect_key($roles1, $roles2);
             $role = current($roles);
             // Enrol $USER in the courses using the manual plugin.
             $enrol = enrol_get_plugin('manual');
             $enrolinstances = enrol_get_instances($course->id, true);
             foreach ($enrolinstances as $courseenrolinstance) {
                 if ($courseenrolinstance->enrol == "manual") {
                     $instance = $courseenrolinstance;
                     break;
                 }
             }
             $enrol->enrol_user($instance, $USER->id, $role->id);
         } else {
             // Enrol admin as an instructor incase they are not on the account.
             $turnitintooltwouser = new turnitintooltwo_user($USER->id, "Instructor");
             $turnitintooltwouser->join_user_to_class($tiicourseid);
         }
         if (!($insertid = $DB->insert_record('turnitintooltwo_courses', $turnitincourse))) {
             turnitintooltwo_activitylog(get_string('migrationcoursecreatederror', 'turnitintooltwo', $tiicourseid) . ' - ' . $course->id, "REQUEST");
             return 0;
         } else {
             turnitintooltwo_activitylog(get_string('migrationcoursecreated', 'turnitintooltwo') . ' - ' . $course->id . ' (' . $tiicourseid . ')', "REQUEST");
             return $course;
         }
     } else {
         turnitintooltwo_activitylog(get_string('migrationcoursecreateerror', 'turnitintooltwo', $tiicourseid), "REQUEST");
         return 0;
     }
 }
Example #20
0
 function definition()
 {
     global $USER, $CFG, $DB;
     $courseconfig = get_config('moodlecourse');
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 // if users already enrolled directly into coures, do not allow switching to meta,
                 // users with metacourse manage permission are exception
                 // please note that we do not need exact results - anything unexpected here prevents metacourse
                 $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
                 $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext);
                 if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
                     foreach ($users as $user) {
                         if (!isset($managers[$user->id])) {
                             $disable_meta = get_string('metaalreadyhasenrolments');
                             break;
                         }
                     }
                 }
                 unset($managers);
                 unset($users);
                 unset($enrolroles);
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist, 'moodle/course:create');
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $fullname = get_string('defaultcoursefullname');
     $shortname = get_string('defaultcourseshortname');
     while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) {
         $fullname++;
         $shortname++;
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true);
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->setDefault('fullname', $fullname);
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true);
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->setDefault('shortname', $shortname);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text2', get_string('helptext')), true);
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', $courseconfig->format);
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', $courseconfig->metacourse);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $mform->setDefault('enrol', $courseconfig->enrol);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', $courseconfig->enrollable);
     $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
     $mform->setDefault('enrolstartdate', 0);
     $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
     $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
     $mform->setDefault('enrolenddate', 0);
     $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
     $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
     $mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', $courseconfig->expirynotify);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', $courseconfig->notifystudents);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', $courseconfig->visible);
     if ($course and !has_capability('moodle/course:visibility', $coursecontext)) {
         $mform->hardFreeze('visible');
         $mform->setConstant('visible', $course->visible);
     }
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
     $mform->setType('enrolpassword', PARAM_RAW);
     if (empty($course) or $course->password !== '' and $course->id != SITEID) {
         // do not require password in existing courses that do not have password yet - backwards compatibility ;-)
         if (!empty($CFG->enrol_manual_requirekey)) {
             $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
         }
     }
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', $courseconfig->guest);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     require_once $CFG->libdir . '/completionlib.php';
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true);
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
 }
function xmldb_oublog_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($result && $oldversion < 2008022600) {
        /// Define field views to be added to oublog_instances
        $table = new XMLDBTable('oublog_instances');
        $field = new XMLDBField('views');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'accesstoken');
        /// Launch add field views
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('oublog');
        $field = new XMLDBField('views');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'global');
        /// Launch add field views
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008022700) {
        /// Define field oublogid to be added to oublog_links
        $table = new XMLDBTable('oublog_links');
        $field = new XMLDBField('oublogid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'id');
        /// Launch add field oublogid
        $result = $result && add_field($table, $field);
        /// Define key oublog_links_oublog_fk (foreign) to be added to oublog_links
        $table = new XMLDBTable('oublog_links');
        $key = new XMLDBKey('oublog_links_oublog_fk');
        $key->setAttributes(XMLDB_KEY_FOREIGN, array('oublogid'), 'oublog', array('id'));
        /// Launch add key oublog_links_oublog_fk
        $result = $result && add_key($table, $key);
        /// Changing nullability of field oubloginstancesid on table oublog_links to null
        $table = new XMLDBTable('oublog_links');
        $field = new XMLDBField('oubloginstancesid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'oublogid');
        /// Launch change of nullability for field oubloginstancesid
        $result = $result && change_field_notnull($table, $field);
    }
    if ($result && $oldversion < 2008022701) {
        /// Define field sortorder to be added to oublog_links
        $table = new XMLDBTable('oublog_links');
        $field = new XMLDBField('sortorder');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'url');
        /// Launch add field sortorder
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008030704) {
        /// Add search data
        require_once dirname(__FILE__) . '/../locallib.php';
        require_once dirname(__FILE__) . '/../lib.php';
        if (oublog_search_installed()) {
            global $db;
            $olddebug = $db->debug;
            $db->debug = false;
            print '<ul>';
            oublog_ousearch_update_all(true);
            print '</ul>';
            $db->debug = $olddebug;
        }
    }
    if ($result && $oldversion < 2008030707) {
        /// Define field lasteditedby to be added to oublog_posts
        $table = new XMLDBTable('oublog_posts');
        $field = new XMLDBField('lasteditedby');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'visibility');
        /// Launch add field lasteditedby
        $result = $result && add_field($table, $field);
        /// Transfer edit data to lasteditedby
        $result = $result && execute_sql("\r\nUPDATE {$CFG->prefix}oublog_posts SET lasteditedby=(\r\n    SELECT userid FROM {$CFG->prefix}oublog_edits WHERE {$CFG->prefix}oublog_posts.id=postid ORDER BY id DESC LIMIT 1 \r\n) WHERE editsummary IS NOT NULL\r\n        ");
        /// Define field editsummary to be dropped from oublog_posts
        $table = new XMLDBTable('oublog_posts');
        $field = new XMLDBField('editsummary');
        /// Launch drop field editsummary
        $result = $result && drop_field($table, $field);
    }
    if ($result && $oldversion < 2008073000) {
        /// Define field completionposts to be added to oublog
        $table = new XMLDBTable('oublog');
        $field = new XMLDBField('completionposts');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'views');
        /// Launch add field completionposts
        $result = $result && add_field($table, $field);
        /// Define field completioncomments to be added to oublog
        $field = new XMLDBField('completioncomments');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '9', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'completionposts');
        /// Launch add field completioncomments
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2008121100) {
        // remove oublog:view from legacy:user roles
        $roles = get_roles_with_capability('moodle/legacy:user', CAP_ALLOW);
        foreach ($roles as $role) {
            $result = $result && unassign_capability('mod/oublog:view', $role->id);
        }
    }
    if ($result && $oldversion < 2009012600) {
        // Remove oublog:post and oublog:comment from legacy:user roles (if present)
        $roles = get_roles_with_capability('moodle/legacy:user', CAP_ALLOW);
        // Also from default user role if not already included
        if (!array_key_exists($CFG->defaultuserroleid, $roles)) {
            $roles[] = get_record('role', 'id', $CFG->defaultuserroleid);
        }
        print '<p><strong>Warning</strong>: The OU blog system capabilities 
            have changed (again) in order to fix bugs and clarify access control.
            The system will automatically remove the capabilities 
            <tt>mod/oublog:view</tt>, <tt>mod/oublog:post</tt>, and
            <tt>mod/oublog:comment</tt> from the following role(s):</p><ul>';
        foreach ($roles as $role) {
            print '<li>' . htmlspecialchars($role->name) . '</li>';
            $result = $result && unassign_capability('mod/oublog:view', $role->id);
            $result = $result && unassign_capability('mod/oublog:post', $role->id);
            $result = $result && unassign_capability('mod/oublog:comment', $role->id);
        }
        print '</ul><p>On a default Moodle installation this is the correct 
            behaviour. Personal blog access is now controlled via the 
            <tt>mod/oublog:viewpersonal</tt> and 
            <tt>mod/oublog:contributepersonal</tt>
            capabilities. These capabilities have been added to the 
            authenticated user role and any equivalent roles.</p>
            <p>If in doubt, please examine your role configuration with regard
            to these <tt>mod/oublog</tt> capabilities.</p>';
    }
    if ($result && $oldversion < 2010031200) {
        /// Define field completionposts to be added to oublog
        $table = new XMLDBTable('oublog');
        $field = new XMLDBField('individual');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'completioncomments');
        /// Launch add field completioncomments
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010062400) {
        /// Define table oublog_comments_moderated to be created
        $table = new XMLDBTable('oublog_comments_moderated');
        /// Adding fields to table oublog_comments_moderated
        $table->addFieldInfo('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
        $table->addFieldInfo('postid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('message', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('timeposted', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('authorname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('ipaddress', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        $table->addFieldInfo('approval', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0');
        $table->addFieldInfo('timeset', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null);
        $table->addFieldInfo('secretkey', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null);
        /// Adding keys to table oublog_comments_moderated
        $table->addKeyInfo('primary', XMLDB_KEY_PRIMARY, array('id'));
        $table->addKeyInfo('postid', XMLDB_KEY_FOREIGN, array('postid'), 'oublog_posts', array('id'));
        /// Adding indexes to table oublog_comments_moderated
        $table->addIndexInfo('ipaddress', XMLDB_INDEX_NOTUNIQUE, array('ipaddress'));
        /// Launch create table for oublog_comments_moderated
        $result = $result && create_table($table);
        /// Changing nullability of field userid on table oublog_comments to null
        $table = new XMLDBTable('oublog_comments');
        $field = new XMLDBField('userid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'postid');
        /// Launch change of nullability for field userid
        $result = $result && change_field_notnull($table, $field);
        /// Define field authorname to be added to oublog_comments
        $field = new XMLDBField('authorname');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'timedeleted');
        /// Launch add field authorname
        $result = $result && add_field($table, $field);
        /// Define field authorip to be added to oublog_comments
        $field = new XMLDBField('authorip');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, null, null, null, null, null, 'authorname');
        /// Launch add field authorip
        $result = $result && add_field($table, $field);
        /// Define field timeapproved to be added to oublog_comments
        $field = new XMLDBField('timeapproved');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'authorip');
        /// Launch add field timeapproved
        $result = $result && add_field($table, $field);
    }
    if ($result && $oldversion < 2010062500) {
        // Change the 'allow comments' value to 2 on global blog, if it is
        // currently set to 1
        $result = $result && set_field('oublog', 'allowcomments', 2, 'global', 1, 'allowcomments', 1);
    }
    if ($result && $oldversion < 2010063000) {
        /// Define index ipaddress (not unique) to be dropped form oublog_comments_moderated
        $table = new XMLDBTable('oublog_comments_moderated');
        $index = new XMLDBIndex('ipaddress');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('ipaddress'));
        /// Launch drop index authorip
        $result = $result && drop_index($table, $index);
        /// Rename field ipaddress on table oublog_comments_moderated to authorip
        $field = new XMLDBField('ipaddress');
        $field->setAttributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, null, 'authorname');
        /// Launch rename field ipaddress
        $result = $result && rename_field($table, $field, 'authorip');
        /// Define index authorip (not unique) to be added to oublog_comments_moderated
        $table = new XMLDBTable('oublog_comments_moderated');
        $index = new XMLDBIndex('authorip');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('authorip'));
        /// Launch add index authorip
        $result = $result && add_index($table, $index);
    }
    if ($result && $oldversion < 2010070101) {
        // Make cron start working - in some servers I found there was
        // 9999999999 in the lastcron field which caused it never to run; not
        // very helpful
        $result = $result && set_field('modules', 'lastcron', 1, 'name', 'oublog');
    }
    return $result;
}
Example #22
0
/**
 * Searches for teachers using a substring match.
 *
 * @param string $query The substring to search for.
 * @param array $courses An array of Arrays with indicies 'id' and 'name'.
 * @param array $coursecategories An array of Arrays with indicies 'id' and 'name'.
 * @return array An array of matching teachers or returns an array with a no matches found string.
 */
function report_ncccscensus_teacher_search($query, $courses = array(), $coursecategories = array())
{
    global $DB;
    $results = array();
    $users = array();
    if (empty($coursecategories) && empty($courses)) {
        $contextlevels = null;
        // Get roles with capability.
        $roles = get_roles_with_capability('moodle/grade:edit', CAP_ALLOW);
        $roles = array_keys($roles);
        // Retrieving all user columns because the user object needs to be passed through to Moodle's fullname() function.
        $rolelist = $DB->get_in_or_equal($roles);
        $rolelist[1][] = "%{$query}%";
        $rolelist[1][] = "%{$query}%";
        $rolelist[1][] = "%{$query}%";
        $sql = "SELECT ra.id AS raid, u.*, ra.contextid\n                  FROM {role_assignments} ra\n                  JOIN {user} u ON u.id = ra.userid\n                 WHERE ra.roleid {$rolelist[0]}\n                       AND (u.username LIKE ?\n                       OR u.firstname LIKE ?\n                       OR u.lastname LIKE ?)";
        $records = $DB->get_records_sql($sql, $rolelist[1]);
        $usersadded = array();
        foreach ($records as $record) {
            if (isset($usersadded[$record->id])) {
                continue;
            }
            if (has_capability('moodle/grade:edit', context::instance_by_id($record->contextid), $record->id)) {
                $usersadded[$record->id] = 0;
                $results[] = array('id' => $record->id, 'name' => fullname($record) . " ({$record->username})");
            }
        }
    } elseif (empty($coursecategories) && !empty($courses) || !empty($coursecategories) && !empty($courses)) {
        // Search of users within a course.
        $courses = array_map('report_ncccscensus_format_category_data', $courses);
        $results = report_ncccscensus_get_users_with_capability_in_contexts($courses, 'moodle/grade:edit', $query);
    } elseif (!empty($coursecategories) && empty($courses)) {
        // Search for courses within a category and for users within those courses.
        // Format coursecategories so that it's only an array of course category ids.
        $coursecategories = array_map('report_ncccscensus_format_category_data', $coursecategories);
        // Get an array of courses in the course category.
        $courses = report_ncccscensus_get_category_courses($coursecategories);
        $results = report_ncccscensus_get_users_with_capability_in_contexts($courses, 'moodle/grade:edit', $query);
    }
    if (empty($results)) {
        return array(array('name' => get_string('noresults', 'report_ncccscensus') . " {$query}"));
    }
    return $results;
}
Example #23
0
 }
 if ($userroles = get_roles_with_capability('moodle/legacy:user', CAP_ALLOW)) {
     $userrole = array_shift($userroles);
     /// Take the first one
 } else {
     $userrole->id = 0;
 }
 if (empty($CFG->creatornewroleid)) {
     if ($teacherroles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, $context)) {
         $teachereditrole = array_shift($teacherroles);
         set_config('creatornewroleid', $teachereditrole->id);
     } else {
         set_config('creatornewroleid', 0);
     }
 }
 if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
     $guestroles = array();
     $defaultguestid = null;
 } else {
     $defaultguestid = reset($guestroles);
     $defaultguestid = $defaultguestid->id;
 }
 // we must not use assignable roles here:
 //   1/ unsetting roles as assignable for admin might bork the settings!
 //   2/ default user role should not be assignable anyway
 $allroles = array();
 $nonguestroles = array();
 if ($roles = get_all_roles()) {
     foreach ($roles as $role) {
         $rolename = strip_tags(format_string($role->name, true));
         $allroles[$role->id] = $rolename;
Example #24
0
/**
 * Removes a teacher from a given course (or ALL courses)
 * Does not delete the user account
 *
 * @param int $courseid The id of the course that is being viewed, if any
 * @param int $userid The id of the user that is being tested against.
 * @return bool
 */
function remove_teacher($userid, $courseid = 0)
{
    global $CFG;
    $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
    if ($roles) {
        $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
    } else {
        $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
    }
    if (empty($roles)) {
        return true;
    }
    $return = true;
    if ($courseid) {
        if (!($context = get_context_instance(CONTEXT_COURSE, $courseid))) {
            return false;
        }
        /// First delete any crucial stuff that might still send mail
        if ($forums = get_records('forum', 'course', $courseid)) {
            foreach ($forums as $forum) {
                delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
            }
        }
        /// No need to remove from groups now
        foreach ($roles as $role) {
            // Unassign them from all the teacher roles
            $newreturn = role_unassign($role->id, $userid, 0, $context->id);
            if (empty($newreturn)) {
                $return = false;
            }
        }
    } else {
        delete_records('forum_subscriptions', 'userid', $userid);
        $return = true;
        foreach ($roles as $role) {
            // Unassign them from all the teacher roles
            $newreturn = role_unassign($role->id, $userid, 0, 0);
            if (empty($newreturn)) {
                $return = false;
            }
        }
    }
    return $return;
}
Example #25
0
function data_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2006011900) {
        table_column("data_content", "", "content1", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content2", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content3", "longtext", "", "", "", "not null");
        table_column("data_content", "", "content4", "longtext", "", "", "", "not null");
    }
    if ($oldversion < 2006011901) {
        table_column("data", "", "approval", "tinyint", "4");
        table_column("data_records", "", "approved", "tinyint", "4");
    }
    if ($oldversion < 2006020801) {
        table_column("data", "", "scale", "integer", "10", "signed");
        table_column("data", "", "assessed", "integer", "10");
        table_column("data", "", "assesspublic", "integer", "4");
    }
    if ($oldversion < 2006022700) {
        table_column("data_comments", "", "created", "integer", "10");
        table_column("data_comments", "", "modified", "integer", "10");
    }
    if ($oldversion < 2006030700) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'add', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'update', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'record delete', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'fields add', 'data_fields', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'fields update', 'data_fields', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'templates saved', 'data', 'name')");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'templates def', 'data', 'name')");
    }
    if ($oldversion < 2006032700) {
        table_column('data', '', 'defaultsort', 'integer', '10', 'unsigned', '0');
        table_column('data', '', 'defaultsortdir', 'tinyint', '4', 'unsigned', '0', 'not null', 'defaultsort');
        table_column('data', '', 'editany', 'tinyint', '4', 'unsigned', '0', 'not null', 'defaultsortdir');
    }
    if ($oldversion < 2006032900) {
        table_column('data', '', 'csstemplate', 'text', '', '', '', 'not null', 'rsstemplate');
    }
    if ($oldversion < 2006050500) {
        // 2 fields have got no default null values
        table_column('data_comments', 'content', 'content', 'text', '', '', '', 'not null');
        table_column('data_fields', 'description', 'description', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param1', 'param1', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param2', 'param2', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param3', 'param3', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param4', 'param4', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param5', 'param5', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param6', 'param6', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param7', 'param7', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param8', 'param8', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param9', 'param9', 'text', '', '', '', 'not null');
        table_column('data_fields', 'param10', 'param10', 'text', '', '', '', 'not null');
    }
    if ($oldversion < 2006052400) {
        table_column('data', '', 'rsstitletemplate', 'text', '', '', '', 'not null', 'rsstemplate');
    }
    if ($oldversion < 2006081700) {
        table_column('data', '', 'jstemplate', 'text', '', '', '', 'not null', 'csstemplate');
    }
    if ($oldversion < 2006092000) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/data/lib.php';
        $datamod = get_record('modules', 'name', 'data');
        if ($data = get_records('data')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($data as $d) {
                if (!data_convert_to_roles($d, $teacherroles, $studentroles)) {
                    notify('Data with id ' . $d->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            include_once "{$CFG->dirroot}/course/lib.php";
            rebuild_course_cache();
        }
        // End if.
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN participants;');
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN assesspublic;');
        modify_database('', 'ALTER TABLE prefix_data DROP COLUMN ratings;');
    }
    if ($oldversion < 2006092302) {
        // Changing some TEXT fields to NULLable and no default
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE singletemplate singletemplate text NULL AFTER rssarticles");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplate listtemplate text NULL AFTER singletemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplateheader listtemplateheader text NULL AFTER listtemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE listtemplatefooter listtemplatefooter text NULL AFTER listtemplateheader");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE addtemplate addtemplate text NULL AFTER listtemplatefooter");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE rsstemplate rsstemplate text NULL AFTER addtemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE rsstitletemplate rsstitletemplate text NULL AFTER rsstemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE csstemplate csstemplate text NULL AFTER rsstitletemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data CHANGE jstemplate jstemplate text NULL AFTER csstemplate");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param1 param1 text NULL AFTER description");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param2 param2 text NULL AFTER param1");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param3 param3 text NULL AFTER param2");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param4 param4 text NULL AFTER param3");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param5 param5 text NULL AFTER param4");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param6 param6 text NULL AFTER param5");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param7 param7 text NULL AFTER param6");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param8 param8 text NULL AFTER param7");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param9 param9 text NULL AFTER param8");
        execute_sql("ALTER TABLE {$CFG->prefix}data_fields CHANGE param10 param10 text NULL AFTER param9");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content content longtext NULL AFTER recordid");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content1 content1 longtext NULL AFTER content");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content2 content2 longtext NULL AFTER content1");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content3 content3 longtext NULL AFTER content2");
        execute_sql("ALTER TABLE {$CFG->prefix}data_content CHANGE content4 content4 longtext NULL AFTER content3");
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
Example #26
0
function rss_client_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $CFG;
    if ($oldversion < 2005111400) {
        // title and description should be TEXT as we don't have control over their length.
        table_column('block_rss_client', 'title', 'title', 'text');
        table_column('block_rss_client', 'description', 'description', 'text');
    }
    if ($oldversion < 2005090201) {
        modify_database('', 'ALTER TABLE prefix_block_rss_client
            ALTER COLUMN title SET DEFAULT \'\',
            ALTER COLUMN description SET DEFAULT \'\'');
    }
    if ($oldversion < 2006091100) {
        // We need a new field to store whether an RSS feed is shared or private.
        table_column('block_rss_client', '', 'shared', 'integer');
        // Admin feeds used to be displayed to everybody (shared feeds).
        $admins = get_admins();
        if (!empty($admins)) {
            $count = 0;
            foreach ($admins as $admin) {
                if (!$count) {
                    $adminsql = 'userid = ' . $admin->id;
                } else {
                    $adminsql .= ' OR userid = ' . $admin->id;
                }
                $count++;
            }
            if ($rssfeeds = get_records_select('block_rss_client', $adminsql)) {
                foreach ($rssfeeds as $rssfeed) {
                    if (!set_field('block_rss_client', 'shared', 1)) {
                        notice('Could not set ' . $rssfeed->title . ' as a shared RSS feed.');
                    }
                }
            }
        }
    }
    /// see MDL-6707 for more info about problem that was here
    if ($oldversion < 2006100101) {
        // Upgrade block to use the Roles System.
        $block = get_record('block', 'name', 'rss_client');
        if ($blockinstances = get_records('block_instance', 'blockid', $block->id)) {
            if (!($adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW))) {
                notice('Default student role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notice('Default teacher role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notice('Default student role was not found. Roles and permissions ' . 'for all your Remote RSS Feed blocks will have to be ' . 'manually set after this upgrade.');
            }
            foreach ($blockinstances as $bi) {
                $context = get_context_instance(CONTEXT_BLOCK, $bi->id);
                if ($bi->pagetype == 'course-view' && $bi->pageid == SITEID) {
                    // Only the admin was allowed to manage the RSS feed block
                    // on the site home page.
                    // Since this is already the default behavior set in
                    // blocks/rss_client/db/access.php, we don't need to
                    // specifically assign the capabilities here.
                } else {
                    // Who can add shared feeds? This was defined in lib/rsslib.php
                    // for config var block_rss_client_submitters.
                    switch ($CFG->block_rss_client_submitters) {
                        case 0:
                            // SUBMITTERS_ALL_ACCOUNT_HOLDERS
                            foreach ($adminroles as $adminrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $adminrole->id, $context->id);
                            }
                            foreach ($teacherroles as $teacherrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $teacherrole->id, $context->id);
                            }
                            foreach ($studentroles as $studentrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $studentrole->id, $context->id);
                            }
                            break;
                        case 1:
                            // SUBMITTERS_ADMIN_ONLY
                            // Since this is already the default behavior set in
                            // blocks/rss_client/db/access.php, we don't need to
                            // specifically assign the capabilities here.
                            break;
                        case 2:
                            // SUBMITTERS_ADMIN_AND_TEACHER
                            foreach ($adminroles as $adminrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $adminrole->id, $context->id);
                            }
                            foreach ($teacherroles as $teacherrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_ALLOW, $teacherrole->id, $context->id);
                            }
                            foreach ($studentroles as $studentrole) {
                                assign_capability('block/rss_client:createsharedfeeds', CAP_PREVENT, $studentrole->id, $context->id);
                            }
                            break;
                    }
                    // End switch.
                }
            }
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}
function main_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    if ($oldversion < 2003010101) {
        delete_records("log_display", "module", "user");
        $new->module = "user";
        $new->action = "view";
        $new->mtable = "user";
        $new->field = "CONCAT(firstname,\" \",lastname)";
        insert_record("log_display", $new);
        delete_records("log_display", "module", "course");
        $new->module = "course";
        $new->action = "view";
        $new->mtable = "course";
        $new->field = "fullname";
        insert_record("log_display", $new);
        $new->action = "update";
        insert_record("log_display", $new);
        $new->action = "enrol";
        insert_record("log_display", $new);
    }
    //support user based course creating
    if ($oldversion < 2003032400) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_coursecreators (\n                                  id int8 SERIAL PRIMARY KEY,\n                                  userid int8  NOT NULL default '0'\n                                  )");
    }
    if ($oldversion < 2003041400) {
        table_column("course_modules", "", "visible", "integer", "1", "unsigned", "1", "not null", "score");
    }
    if ($oldversion < 2003042104) {
        // Try to update permissions of all files
        if ($files = get_directory_list($CFG->dataroot)) {
            echo "Attempting to update permissions for all files... ignore any errors.";
            foreach ($files as $file) {
                echo "{$CFG->dataroot}/{$file}<br />";
                @chmod("{$CFG->dataroot}/{$file}", $CFG->directorypermissions);
            }
        }
    }
    if ($oldversion < 2003042400) {
        // Rebuild all course caches, because of changes to do with visible variable
        if ($courses = get_records_sql("SELECT * FROM {$CFG->prefix}course")) {
            require_once "{$CFG->dirroot}/course/lib.php";
            foreach ($courses as $course) {
                $modinfo = serialize(get_array_of_activities($course->id));
                if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
                    notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
                }
            }
        }
    }
    if ($oldversion < 2003042500) {
        //  Convert all usernames to lowercase.
        $users = get_records_sql("SELECT id, username FROM {$CFG->prefix}user");
        $cerrors = "";
        $rarray = array();
        foreach ($users as $user) {
            // Check for possible conflicts
            $lcname = trim(moodle_strtolower($user->username));
            if (in_array($lcname, $rarray)) {
                $cerrors .= $user->id . "->" . $lcname . '<br/>';
            } else {
                array_push($rarray, $lcname);
            }
        }
        if ($cerrors != '') {
            notify("Error: Cannot convert usernames to lowercase. \n                    Following usernames would overlap (id->username):<br/> {$cerrors} . \n                    Please resolve overlapping errors.");
            $result = false;
        }
        $cerrors = "";
        echo "Checking userdatabase:<br />";
        foreach ($users as $user) {
            $lcname = trim(moodle_strtolower($user->username));
            if ($lcname != $user->username) {
                $convert = set_field("user", "username", $lcname, "id", $user->id);
                if (!$convert) {
                    if ($cerrors) {
                        $cerrors .= ", ";
                    }
                    $cerrors .= $item;
                } else {
                    echo ".";
                }
            }
        }
        if ($cerrors != '') {
            notify("There were errors when converting following usernames to lowercase. \n                   '{$cerrors}' . Sorry, but you will need to fix your database by hand.");
            $result = false;
        }
    }
    if ($oldversion < 2003042700) {
        /// Changing to multiple indexes
        execute_sql(" CREATE INDEX {$CFG->prefix}log_coursemoduleaction_idx ON {$CFG->prefix}log (course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}log_courseuserid_idx ON {$CFG->prefix}log (course,userid) ");
    }
    if ($oldversion < 2003042801) {
        execute_sql("CREATE TABLE {$CFG->prefix}course_display (\n                         id SERIAL PRIMARY KEY,\n                         course integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         display integer NOT NULL default '0'\n                      )");
        execute_sql("CREATE INDEX {$CFG->prefix}course_display_courseuserid_idx ON {$CFG->prefix}course_display (course,userid)");
    }
    if ($oldversion < 2003050400) {
        table_column("course_sections", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050401) {
        table_column("user", "", "lang", "VARCHAR", "5", "", "{$CFG->lang}", "NOT NULL", "");
    }
    if ($oldversion < 2003050900) {
        table_column("modules", "", "visible", "integer", "1", "unsigned", "1", "", "");
    }
    if ($oldversion < 2003050902) {
        if (get_records("modules", "name", "pgassignment")) {
            print_simple_box("Note: the pgassignment module will soon be deleted from CVS!  Go to the new 'Manage Modules' page and DELETE IT from your system", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        }
    }
    if ($oldversion < 2003051600) {
        print_simple_box("Thanks for upgrading!<p>There are many changes since the last release.  Please read the release notes carefully.  If you are using CUSTOM themes you will need to edit them.  You will also need to check your site's config.php file.", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
    }
    if ($oldversion < 2003052300) {
        table_column("user", "", "autosubscribe", "integer", "1", "unsigned", "1", "", "htmleditor");
    }
    if ($oldversion < 2003072100) {
        table_column("course", "", "visible", "integer", "1", "unsigned", "1", "", "marker");
    }
    if ($oldversion < 2003072101) {
        table_column("course_sections", "sequence", "sequence", "text", "", "", "", "", "");
    }
    if ($oldversion < 2003072800) {
        print_simple_box("The following database index improves performance, but can be quite large - if you are upgrading and you have problems with a limited quota you may want to delete this index later from the '{$CFG->prefix}log' table in your database", "center", "50%", "{$THEME->cellheading}", "20", "noticebox");
        flush();
        execute_sql(" CREATE INDEX {$CFG->prefix}log_timecoursemoduleaction_idx ON {$CFG->prefix}log (time,course,module,action) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_students_courseuserid_idx ON {$CFG->prefix}user_students (course,userid) ");
        execute_sql(" CREATE INDEX {$CFG->prefix}user_teachers_courseuserid_idx ON {$CFG->prefix}user_teachers (course,userid) ");
    }
    if ($oldversion < 2003072802) {
        table_column("course_categories", "", "description", "text", "", "", "");
        table_column("course_categories", "", "parent", "integer", "10", "unsigned");
        table_column("course_categories", "", "sortorder", "integer", "10", "unsigned");
        table_column("course_categories", "", "courseorder", "text", "", "", "");
        table_column("course_categories", "", "visible", "integer", "1", "unsigned", "1");
        table_column("course_categories", "", "timemodified", "integer", "10", "unsigned");
    }
    if ($oldversion < 2003080400) {
        notify("If the following command fails you may want to change the type manually, from TEXT to INTEGER.  Moodle should keep working even if you don't.");
        table_column("course_categories", "courseorder", "courseorder", "integer", "10", "unsigned");
        table_column("course", "", "sortorder", "integer", "10", "unsigned", "0", "", "category");
    }
    if ($oldversion < 2003081502) {
        execute_sql(" CREATE TABLE {$CFG->prefix}scale (\n                         id SERIAL PRIMARY KEY,\n                         courseid integer NOT NULL default '0',\n                         userid integer NOT NULL default '0',\n                         name varchar(255) NOT NULL default '',\n                         scale text,\n                         description text,\n                         timemodified integer NOT NULL default '0'\n                      )");
    }
    if ($oldversion < 2003081503) {
        table_column("forum", "", "scale", "integer", "10", "unsigned", "0", "", "assessed");
        get_scales_menu(0);
        // Just to force the default scale to be created
    }
    if ($oldversion < 2003081600) {
        table_column("user_teachers", "", "editall", "integer", "1", "unsigned", "1", "", "role");
        table_column("user_teachers", "", "timemodified", "integer", "10", "unsigned", "0", "", "editall");
    }
    if ($oldversion < 2003081900) {
        table_column("course_categories", "courseorder", "coursecount", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003080700) {
        notify("Cleaning up categories and course ordering...");
        fix_course_sortorder();
    }
    if ($oldversion < 2003082001) {
        table_column("course", "", "showgrades", "integer", "2", "unsigned", "1", "", "format");
    }
    if ($oldversion < 2003082101) {
        execute_sql(" CREATE INDEX {$CFG->prefix}course_category_idx ON {$CFG->prefix}course (category) ");
    }
    if ($oldversion < 2003082702) {
        execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname,\" \",lastname)') ");
    }
    if ($oldversion < 2003091000) {
        # Old field that was never added!
        table_column("course", "", "showrecent", "integer", "10", "unsigned", "1", "", "numsections");
    }
    if ($oldversion < 2003091400) {
        table_column("course_modules", "", "indent", "integer", "5", "unsigned", "0", "", "score");
    }
    if ($oldversion < 2003092900) {
        table_column("course", "", "maxbytes", "integer", "10", "unsigned", "0", "", "marker");
    }
    if ($oldversion < 2003102700) {
        table_column("user_students", "", "timeaccess", "integer", "10", "unsigned", "0", "", "time");
        table_column("user_teachers", "", "timeaccess", "integer", "10", "unsigned", "0", "", "timemodified");
        $db->debug = false;
        $CFG->debug = 0;
        notify("Calculating access times.  Please wait - this may take a long time on big sites...", "green");
        flush();
        if ($courses = get_records_select("course", "category > 0")) {
            foreach ($courses as $course) {
                notify("Processing " . format_string($course->fullname) . " ...", "green");
                flush();
                if ($users = get_records_select("user_teachers", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log                                                                                  WHERE course = '{$course->id}' and userid = '{$user->userid}'                                                               ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_teachers                                                                                      SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
                if ($users = get_records_select("user_students", "course = '{$course->id}'", "id", "id, userid, timeaccess")) {
                    foreach ($users as $user) {
                        $loginfo = get_record_sql("SELECT id, time FROM {$CFG->prefix}log \n                                                   WHERE course = '{$course->id}' and userid = '{$user->userid}' \n                                                   ORDER by time DESC");
                        if (empty($loginfo->time)) {
                            $loginfo->time = 0;
                        }
                        execute_sql("UPDATE {$CFG->prefix}user_students \n                                     SET timeaccess = '{$loginfo->time}' \n                                     WHERE userid = '{$user->userid}' AND course = '{$course->id}'", false);
                    }
                }
            }
        }
        notify("All courses complete.", "green");
        $db->debug = true;
    }
    if ($oldversion < 2003103100) {
        table_column("course", "", "showreports", "integer", "4", "unsigned", "0", "", "maxbytes");
    }
    if ($oldversion < 2003121600) {
        execute_sql("CREATE TABLE {$CFG->prefix}groups (\n                        id SERIAL PRIMARY KEY,\n                        courseid integer NOT NULL default '0',\n                        name varchar(255) NOT NULL default '',\n                        description text,\n                        lang varchar(10) NOT NULL default '',\n                        picture integer NOT NULL default '0',\n                        timecreated integer NOT NULL default '0',\n                        timemodified integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_idx ON {$CFG->prefix}groups (courseid) ");
        execute_sql("CREATE TABLE {$CFG->prefix}groups_members (\n                        id SERIAL PRIMARY KEY,\n                        groupid integer NOT NULL default '0',\n                        userid integer NOT NULL default '0',\n                        timeadded integer NOT NULL default '0'\n                     )");
        execute_sql("CREATE INDEX {$CFG->prefix}groups_members_idx ON {$CFG->prefix}groups_members (groupid) ");
    }
    if ($oldversion < 2003122600) {
        table_column("course", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
        table_column("course", "", "groupmodeforce", "integer", "4", "unsigned", "0", "", "groupmode");
    }
    if ($oldversion < 2004010900) {
        table_column("course_modules", "", "groupmode", "integer", "4", "unsigned", "0", "", "visible");
    }
    if ($oldversion < 2004011700) {
        modify_database("", "CREATE TABLE prefix_event (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(255) NOT NULL default '',\n                                description text,\n                                courseid integer NOT NULL default '0',\n                                groupid integer NOT NULL default '0',\n                                userid integer NOT NULL default '0',\n                                modulename varchar(20) NOT NULL default '',\n                                instance integer NOT NULL default '0',\n                                eventtype varchar(20) NOT NULL default '',\n                                timestart integer NOT NULL default '0',\n                                timeduration integer NOT NULL default '0',\n                                timemodified integer NOT NULL default '0'\n                             ); ");
        modify_database("", "CREATE INDEX prefix_event_courseid_idx ON prefix_event (courseid);");
        modify_database("", "CREATE INDEX prefix_event_userid_idx ON prefix_event (userid);");
    }
    if ($oldversion < 2004012800) {
        modify_database("", "CREATE TABLE prefix_user_preferences (\n                                id SERIAL PRIMARY KEY,\n                                userid integer NOT NULL default '0',\n                                name varchar(50) NOT NULL default '',\n                                value varchar(255) NOT NULL default ''\n                             ); ");
        modify_database("", "CREATE INDEX prefix_user_preferences_useridname_idx ON prefix_user_preferences (userid,name);");
    }
    if ($oldversion < 2004012900) {
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004013101) {
        table_column("log", "", "cmid", "integer", "10", "unsigned", "0", "", "module");
        set_config("upgrade", "logs");
    }
    if ($oldversion < 2004020900) {
        table_column("course", "", "lang", "varchar", "5", "", "", "", "groupmodeforce");
    }
    if ($oldversion < 2004020903) {
        modify_database("", "CREATE TABLE prefix_cache_text (\n                                id SERIAL PRIMARY KEY,\n                                md5key varchar(32) NOT NULL default '',\n                                formattedtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004021000) {
        $textfilters = array();
        for ($i = 1; $i <= 10; $i++) {
            $variable = "textfilter{$i}";
            if (!empty($CFG->{$variable})) {
                /// No more filters
                if (is_readable("{$CFG->dirroot}/" . $CFG->{$variable})) {
                    $textfilters[] = $CFG->{$variable};
                }
            }
        }
        $textfilters = implode(',', $textfilters);
        if (empty($textfilters)) {
            $textfilters = 'mod/glossary/dynalink.php';
        }
        set_config('textfilters', $textfilters);
    }
    if ($oldversion < 2004021201) {
        modify_database("", "CREATE TABLE prefix_cache_filters (\n                                id SERIAL PRIMARY KEY,\n                                filter varchar(32) NOT NULL default '',\n                                version integer NOT NULL default '0',\n                                md5key varchar(32) NOT NULL default '',\n                                rawtext text,\n                                timemodified integer NOT NULL default '0'\n                             );");
        modify_database("", "CREATE INDEX prefix_cache_filters_filtermd5key_idx ON prefix_cache_filters (filter,md5key);");
        modify_database("", "CREATE INDEX prefix_cache_text_md5key_idx ON prefix_cache_text (md5key);");
    }
    if ($oldversion < 2004021500) {
        table_column("groups", "", "hidepicture", "integer", "2", "unsigned", "0", "", "picture");
    }
    if ($oldversion < 2004021700) {
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("tex_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("multilang.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("censor.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("mediaplugin.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("algebra_filter.php", "filter.php", $CFG->textfilters);
            $CFG->textfilters = str_replace("dynalink.php", "filter.php", $CFG->textfilters);
            set_config("textfilters", $CFG->textfilters);
        }
    }
    if ($oldversion < 2004022000) {
        table_column("user", "", "emailstop", "integer", "1", "unsigned", "0", "not null", "email");
    }
    if ($oldversion < 2004022200) {
        /// Final renaming I hope.  :-)
        if (!empty($CFG->textfilters)) {
            $CFG->textfilters = str_replace("/filter.php", "", $CFG->textfilters);
            $CFG->textfilters = str_replace("mod/glossary/dynalink.php", "mod/glossary", $CFG->textfilters);
            $textfilters = explode(',', $CFG->textfilters);
            foreach ($textfilters as $key => $textfilter) {
                $textfilters[$key] = trim($textfilter);
            }
            set_config("textfilters", implode(',', $textfilters));
        }
    }
    if ($oldversion < 2004030702) {
        /// Because of the renaming of Czech language pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'cs' WHERE lang = 'cz'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'cs' WHERE lang = 'cz'");
    }
    if ($oldversion < 2004041800) {
        /// Integrate Block System from contrib
        table_column("course", "", "blockinfo", "varchar", "255", "", "", "not null", "modinfo");
    }
    if ($oldversion < 2004042600) {
        /// Rebuild course caches for resource icons
        //include_once("$CFG->dirroot/course/lib.php");
        //rebuild_course_cache();
    }
    if ($oldversion < 2004042700) {
        /// Increase size of lang fields
        table_column("user", "lang", "lang", "varchar", "10", "", "en");
        table_column("groups", "lang", "lang", "varchar", "10", "", "");
        table_column("course", "lang", "lang", "varchar", "10", "", "");
    }
    if ($oldversion < 2004042701) {
        /// Add hiddentopics field to control hidden topics behaviour
        #table_column("course", "", "hiddentopics", "integer", "1", "unsigned", "0", "not null", "visible");
        #See 'hiddensections' further down
    }
    if ($oldversion < 2004042702) {
        /// Add a format field for the description
        table_column("event", "", "format", "integer", "4", "unsigned", "0", "not null", "description");
    }
    if ($oldversion < 2004043001) {
        /// Add hiddentopics field to control hidden topics behaviour
        table_column("course", "", "hiddensections", "integer", "2", "unsigned", "0", "not null", "visible");
    }
    if ($oldversion < 2004050400) {
        /// add a visible field for events
        table_column("event", "", "visible", "smallint", "1", "", "1", "not null", "timeduration");
        if ($events = get_records('event')) {
            foreach ($events as $event) {
                if ($moduleid = get_field('modules', 'id', 'name', $event->modulename)) {
                    if (get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $event->instance) == 0) {
                        set_field('event', 'visible', 0, 'id', $event->id);
                    }
                }
            }
        }
    }
    if ($oldversion < 2004052800) {
        /// First version tagged "1.4 development", version.php 1.227
        set_config('siteblocksadded', true);
        /// This will be used later by the block upgrade
    }
    if ($oldversion < 2004053000) {
        /// set defaults for site course
        $site = get_site();
        set_field('course', 'numsections', 0, 'id', $site->id);
        set_field('course', 'groupmodeforce', 1, 'id', $site->id);
        set_field('course', 'teacher', get_string('administrator'), 'id', $site->id);
        set_field('course', 'teachers', get_string('administrators'), 'id', $site->id);
        set_field('course', 'student', get_string('user'), 'id', $site->id);
        set_field('course', 'students', get_string('users'), 'id', $site->id);
    }
    if ($oldversion < 2004060100) {
        set_config('digestmailtime', 0);
        table_column('user', "", 'maildigest', 'smallint', '1', '', '0', 'not null', 'mailformat');
    }
    if ($oldversion < 2004062400) {
        table_column('user_teachers', "", 'timeend', 'int', '10', 'unsigned', '0', 'not null', 'editall');
        table_column('user_teachers', "", 'timestart', 'int', '10', 'unsigned', '0', 'not null', 'editall');
    }
    if ($oldversion < 2004062401) {
        table_column('course', '', 'idnumber', 'varchar', '100', '', '', 'not null', 'shortname');
        execute_sql('UPDATE ' . $CFG->prefix . 'course SET idnumber = shortname');
        // By default
    }
    if ($oldversion < 2004062600) {
        table_column('course', '', 'cost', 'varchar', '10', '', '', 'not null', 'lang');
    }
    if ($oldversion < 2004072900) {
        table_column('course', '', 'enrolperiod', 'int', '10', 'unsigned', '0', 'not null', 'startdate');
    }
    if ($oldversion < 2004072901) {
        // Fixing error in schema
        if ($record = get_record('log_display', 'module', 'course', 'action', 'update')) {
            delete_records('log_display', 'module', 'course', 'action', 'update');
            insert_record('log_display', $record, false);
        }
    }
    if ($oldversion < 2004081200) {
        // Fixing version errors in some blocks
        set_field('blocks', 'version', 2004081200, 'name', 'admin');
        set_field('blocks', 'version', 2004081200, 'name', 'calendar_month');
        set_field('blocks', 'version', 2004081200, 'name', 'course_list');
    }
    if ($oldversion < 2004081500) {
        // Adding new "auth" field to user table to allow more flexibility
        table_column('user', '', 'auth', 'varchar', '20', '', 'manual', 'not null', 'id');
        execute_sql("UPDATE {$CFG->prefix}user SET auth = 'manual'");
        // Set everyone to 'manual' to be sure
        if ($admins = get_admins()) {
            // Set all the NON-admins to whatever the current auth module is
            $adminlist = array();
            foreach ($admins as $user) {
                $adminlist[] = $user->id;
            }
            $adminlist = implode(',', $adminlist);
            execute_sql("UPDATE {$CFG->prefix}user SET auth = '{$CFG->auth}' WHERE id NOT IN ({$adminlist})");
        }
    }
    if ($oldversion < 2004082600) {
        //update auth-fields for external users
        // following code would not work in 1.8
        /*        include_once ($CFG->dirroot."/auth/".$CFG->auth."/lib.php");
                if (function_exists('auth_get_userlist')) {
                    $externalusers = auth_get_userlist();
                    if (!empty($externalusers)){
                        $externalusers = '\''. implode('\',\'',$externalusers).'\'';
                        execute_sql("UPDATE {$CFG->prefix}user SET auth = '$CFG->auth' WHERE username  IN ($externalusers)");
                    }
                }*/
    }
    if ($oldversion < 2004082900) {
        // Make sure guest is "manual" too.
        set_field('user', 'auth', 'manual', 'username', 'guest');
    }
    /* Just commenteed unused fields out
       if ($oldversion < 2004090300) { // Add guid-field used in user syncronization
               table_column('user', '', 'guid', 'varchar', '128', '', '', '', 'auth');
               execute_sql("CREATE INDEX {$CFG->prefix}user_auth_guid_idx ON {$CFG->prefix}user (auth, guid)"); 
       }
       */
    if ($oldversion < 2004091900) {
        //Modify idnumber to hold longer keys
        set_field('user', 'auth', 'manual', 'username', 'guest');
        table_column('user', 'idnumber', 'idnumber', 'varchar', '64', '', '', '', '');
        execute_sql("DROP INDEX {$CFG->prefix}user_idnumber_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("DROP INDEX {$CFG->prefix}user_auth_idx ;", false);
        // added in case of conflicts with upgrade from 14stable
        execute_sql("CREATE INDEX {$CFG->prefix}user_idnumber_idx ON {$CFG->prefix}user (idnumber)");
        execute_sql("CREATE INDEX {$CFG->prefix}user_auth_idx ON {$CFG->prefix}user (auth)");
    }
    if ($oldversion < 2004092000) {
        //redoing this just to be sure that column type is text (postgres type changes didnt work when this was done first time)
        table_column("config", "value", "value", "text", "", "", "");
    }
    if ($oldversion < 2004093001) {
        // add new table for sessions storage
        execute_sql(" CREATE TABLE {$CFG->prefix}sessions (\n                          sesskey char(32) PRIMARY KEY,\n                          expiry integer NOT null,\n                          expireref varchar(64),\n                          data text NOT null\n                      );");
        execute_sql(" CREATE INDEX {$CFG->prefix}sessions_expiry_idx ON {$CFG->prefix}sessions (expiry)");
    }
    if ($oldversion < 2004111500) {
        // Update any users/courses using wrongly-named lang pack
        execute_sql("UPDATE {$CFG->prefix}user SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
        execute_sql("UPDATE {$CFG->prefix}course SET lang = 'mi_nt' WHERE lang = 'ma_nt'");
    }
    if ($oldversion < 2004111700) {
        // add indexes- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_idnumber_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_shortname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_userid_idx;", false);
        modify_database("", "CREATE INDEX {$CFG->prefix}course_idnumber_idx ON {$CFG->prefix}course (idnumber);");
        modify_database("", "CREATE INDEX {$CFG->prefix}course_shortname_idx ON {$CFG->prefix}course (shortname);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_userid_idx ON {$CFG->prefix}user_students (userid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_userid_idx ON {$CFG->prefix}user_teachers (userid);");
    }
    if ($oldversion < 2004111700) {
        // add an index to event for timestart and timeduration- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}event_timestart_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}event_timeduration_idx;", false);
        modify_database('', 'CREATE INDEX prefix_event_timestart_idx ON prefix_event (timestart);');
        modify_database('', 'CREATE INDEX prefix_event_timeduration_idx ON prefix_event (timeduration);');
    }
    if ($oldversion < 2004117000) {
        // add an index on the groups_members table- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}groups_members_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_groups_members_userid_idx ON prefix_groups_members (userid);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on modules and course_modules- drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_visible_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_course_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_module_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_instance_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_modules_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}modules_name_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_modules_visible_idx ON prefix_course_modules (visible);');
        modify_database('', 'CREATE INDEX prefix_course_modules_course_idx ON prefix_course_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_modules_module_idx ON prefix_course_modules (module);');
        modify_database('', 'CREATE INDEX prefix_course_modules_instance_idx ON prefix_course_modules (instance);');
        modify_database('', 'CREATE INDEX prefix_course_modules_deleted_idx ON prefix_course_modules (deleted);');
        modify_database('', 'CREATE INDEX prefix_modules_name_idx ON prefix_modules (name);');
    }
    if ($oldversion < 2004111700) {
        // add an index on user students timeaccess (used for sorting)- drop them first silently to avoid conflicts when upgrading
        execute_sql("DROP INDEX {$CFG->prefix}user_students_timeaccess_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_students_timeaccess_idx ON prefix_user_students (timeaccess);');
    }
    if ($oldversion < 2004111700) {
        //add indexes on faux foreign keys  - drop them first silently to avoid conflicts when upgrading.
        execute_sql("DROP INDEX {$CFG->prefix}course_sections_coursesection_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}scale_courseid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_admins_userid_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_coursecreators_userid_idx;", false);
        modify_database('', 'CREATE INDEX prefix_course_sections_coursesection_idx ON prefix_course_sections (course,section);');
        modify_database('', 'CREATE INDEX prefix_scale_courseid_idx ON prefix_scale (courseid);');
        modify_database('', 'CREATE INDEX prefix_user_admins_userid_idx ON prefix_user_admins (userid);');
        modify_database('', 'CREATE INDEX prefix_user_coursecreators_userid_idx ON prefix_user_coursecreators (userid);');
    }
    if ($oldversion < 2004111700) {
        // make new indexes on user table.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk;", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder)");
        execute_sql("DROP INDEX {$CFG->prefix}user_deleted_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_confirmed_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_firstname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastname_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_city_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_country_idx;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_lastaccess_idx;", false);
        modify_database("", "CREATE INDEX prefix_user_deleted_idx ON prefix_user (deleted)");
        modify_database("", "CREATE INDEX prefix_user_confirmed_idx ON prefix_user (confirmed)");
        modify_database("", "CREATE INDEX prefix_user_firstname_idx ON prefix_user (firstname)");
        modify_database("", "CREATE INDEX prefix_user_lastname_idx ON prefix_user (lastname)");
        modify_database("", "CREATE INDEX prefix_user_city_idx ON prefix_user (city)");
        modify_database("", "CREATE INDEX prefix_user_country_idx ON prefix_user (country)");
        modify_database("", "CREATE INDEX prefix_user_lastaccess_idx ON prefix_user (lastaccess)");
    }
    if ($oldversion < 2004111700) {
        // one more index for email (for sorting)
        execute_sql("DROP INDEX {$CFG->prefix}user_email_idx;", false);
        modify_database('', 'CREATE INDEX prefix_user_email_idx ON prefix_user (email);');
    }
    if ($oldversion < 2004112200) {
        // new 'enrol' field for enrolment tables
        table_column('user_students', '', 'enrol', 'varchar', '20', '', '', 'not null');
        table_column('user_teachers', '', 'enrol', 'varchar', '20', '', '', 'not null');
        modify_database("", "CREATE INDEX {$CFG->prefix}user_students_enrol_idx ON {$CFG->prefix}user_students (enrol);");
        modify_database("", "CREATE INDEX {$CFG->prefix}user_teachers_enrol_idx ON {$CFG->prefix}user_teachers (enrol);");
    }
    if ($oldversion < 2004112300) {
        // update log display to use correct postgres friendly sql
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='user' AND action='view' AND mtable='user'");
        execute_sql("UPDATE {$CFG->prefix}log_display SET field='firstname||\\' \\'||lastname' WHERE module='course' AND action='user report' AND mtable='user'");
    }
    if ($oldversion < 2004112400) {
        /// Delete duplicate enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_students", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_students", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_students_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_students_courseuserid_uk ON prefix_user_students (course,userid);');
        /// Delete duplicate teacher enrolments
        /// and then tell the database course,userid is a unique combination
        if ($users = get_records_select("user_teachers", "userid > 0 GROUP BY course, userid " . "HAVING count(*) > 1", "", "max(id) as id, userid, course ,count(*)")) {
            foreach ($users as $user) {
                delete_records_select("user_teachers", "userid = '{$user->userid}' " . "AND course = '{$user->course}' AND id <> '{$user->id}'");
            }
        }
        flush();
        // drop some indexes quietly -- they may or may not exist depending on what version
        // the user upgrades from
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_idx ", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_teachers_courseuserid_uk  ", false);
        modify_database('', 'CREATE UNIQUE INDEX prefix_user_teachers_courseuserid_uk ON prefix_user_teachers (course,userid);');
    }
    if ($oldversion < 2004112401) {
        // some postgres databases may have a non-unique index mislabeled unique.
        fix_course_sortorder(0, 0, 1);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_sortorder_uk  ", false);
        execute_sql("DROP INDEX {$CFG->prefix}course_category_idx  ", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_course_category_sortorder_uk ON prefix_course(category,sortorder);");
        // odd! username was missing its unique index!
        // first silently drop it just in case...
        execute_sql("ALTER TABLE {$CFG->prefix}user DROP CONSTRAINT {$CFG->prefix}user_username_uk;", false);
        execute_sql("DROP INDEX {$CFG->prefix}user_username_uk", false);
        modify_database('', "CREATE UNIQUE INDEX prefix_user_username_uk ON prefix_user (username);");
    }
    if ($oldversion < 2004112900) {
        table_column('user', '', 'policyagreed', 'integer', '1', 'unsigned', '0', 'not null', 'confirmed');
    }
    if ($oldversion < 2004121400) {
        table_column('groups', '', 'password', 'varchar', '50', '', '', 'not null', 'description');
    }
    if ($oldversion < 2004121600) {
        modify_database('', "CREATE TABLE prefix_dst_preset (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(48) NOT NULL default '',\n                                apply_offset integer NOT NULL default '0',\n                                activate_index integer NOT NULL default '1',\n                                activate_day integer NOT NULL default '1',\n                                activate_month integer NOT NULL default '1',\n                                activate_time char(5) NOT NULL default '03:00',\n                                deactivate_index integer NOT NULL default '1',\n                                deactivate_day integer NOT NULL default '1',\n                                deactivate_month integer NOT NULL default '2',\n                                deactivate_time char(5) NOT NULL default '03:00',\n                                last_change integer NOT NULL default '0',\n                                next_change integer NOT NULL default '0',\n                                current_offset integer NOT NULL default '0'\n                             );");
    }
    if ($oldversion < 2004122800) {
        execute_sql("DROP TABLE {$CFG->prefix}message", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_read", false);
        execute_sql("DROP TABLE {$CFG->prefix}message_contacts", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridfrom_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_read_useridto_idx", false);
        execute_sql("DROP INDEX {$CFG->prefix}message_contacts_useridcontactid_idx", false);
        modify_database('', "CREATE TABLE prefix_message (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default ''\n                            );\n\n                            CREATE INDEX prefix_message_useridfrom_idx ON prefix_message (useridfrom);\n                            CREATE INDEX prefix_message_useridto_idx ON prefix_message (useridto);\n\n                            CREATE TABLE prefix_message_read (\n                               id SERIAL PRIMARY KEY,\n                               useridfrom integer NOT NULL default '0',\n                               useridto integer NOT NULL default '0',\n                               message text,\n                               timecreated integer NOT NULL default '0',\n                               timeread integer NOT NULL default '0',\n                               messagetype varchar(50) NOT NULL default '',\n                               mailed integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_read_useridfrom_idx ON prefix_message_read (useridfrom);\n                            CREATE INDEX prefix_message_read_useridto_idx ON prefix_message_read (useridto);\n                            ");
        modify_database('', "CREATE TABLE prefix_message_contacts (\n                               id SERIAL PRIMARY KEY,\n                               userid integer NOT NULL default '0',\n                               contactid integer NOT NULL default '0',\n                               blocked integer NOT NULL default '0'\n                            );\n\n                            CREATE INDEX prefix_message_contacts_useridcontactid_idx ON prefix_message_contacts (userid,contactid);\n                            ");
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'write', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'read', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2004122801) {
        table_column('message', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
        table_column('message_read', '', 'format', 'integer', '4', 'unsigned', '0', 'not null', 'message');
    }
    if ($oldversion < 2005010100) {
        modify_database('', "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'add contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'remove contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'block contact', 'user', 'firstname||\\' \\'||lastname');\n                            INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('message', 'unblock contact', 'user', 'firstname||\\' \\'||lastname');\n                            ");
    }
    if ($oldversion < 2005011000) {
        // Create a .htaccess file in dataroot, just in case
        if (!file_exists($CFG->dataroot . '/.htaccess')) {
            if ($handle = fopen($CFG->dataroot . '/.htaccess', 'w')) {
                // For safety
                @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
                @fclose($handle);
                notify("Created a default .htaccess file in {$CFG->dataroot}");
            }
        }
    }
    if ($oldversion < 2005012500) {
        // add new table for meta courses.
        /*
        modify_database("","CREATE TABLE prefix_meta_course (
             id SERIAL primary key,
             parent_course integer NOT NULL,
             child_course integer NOT NULL
             );");
        
        modify_database("","CREATE INDEX prefix_meta_course_parent_idx ON prefix_meta_course (parent_course);");
        modify_database("","CREATE INDEX prefix_meta_course_child_idx ON prefix_meta_course (child_course);");
        table_column('course','','meta_course','integer','1','','0','not null');
        */
        // taking this OUT for upgrade from 1.4 to 1.5 (those tracking head will have already seen it)
    }
    if ($oldversion < 2005012501) {
        //fix table names for consistency
        execute_sql("DROP TABLE {$CFG->prefix}meta_course", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP COLUMN meta_course", false);
        // drop silently
        modify_database("", "CREATE TABLE prefix_course_meta (\n             id SERIAL primary key,\n             parent_course integer NOT NULL,\n             child_course integer NOT NULL\n             );");
        modify_database("", "CREATE INDEX prefix_course_meta_parent_idx ON prefix_course_meta (parent_course);");
        modify_database("", "CREATE INDEX prefix_course_meta_child_idx ON prefix_course_meta (child_course);");
        table_column('course', '', 'metacourse', 'integer', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005020100) {
        fix_course_sortorder(0, 1, 1);
    }
    if ($oldversion < 2005021000) {
        // New fields for theme choices
        table_column('course', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('groups', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        table_column('user', '', 'theme', 'varchar', '50', '', '', '', 'lang');
        set_config('theme', 'standardwhite');
        // Reset to a known good theme
    }
    if ($oldversion < 2005021700) {
        table_column('user', '', 'dstpreset', 'int', '10', '', '0', 'not null', 'timezone');
    }
    if ($oldversion < 2005021800) {
        modify_database("", "CREATE TABLE adodb_logsql (\n                              created timestamp NOT NULL,\n                              sql0 varchar(250) NOT NULL,\n                              sql1 text NOT NULL,\n                              params text NOT NULL,\n                              tracer text NOT NULL,\n                              timer decimal(16,6) NOT NULL\n                           );");
    }
    if ($oldversion < 2005022400) {
        table_column('dst_preset', '', 'family', 'varchar', '100', '', '', 'not null', 'name');
        table_column('dst_preset', '', 'year', 'int', '10', '', '0', 'not null', 'family');
    }
    if ($oldversion < 2005030501) {
        table_column('user', '', 'msn', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'aim', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'yahoo', 'varchar', '50', '', '', '', 'icq');
        table_column('user', '', 'skype', 'varchar', '50', '', '', '', 'icq');
    }
    if ($oldversion < 2005032300) {
        table_column('user', 'dstpreset', 'timezonename', 'varchar', '100');
        execute_sql('UPDATE ' . $CFG->prefix . 'user SET timezonename = \'\'');
    }
    if ($oldversion < 2005032600) {
        execute_sql('DROP TABLE ' . $CFG->prefix . 'dst_preset', false);
        modify_database('', "CREATE TABLE prefix_timezone (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(100) NOT NULL default '',\n                              year integer NOT NULL default '0',\n                              rule varchar(20) NOT NULL default '',\n                              gmtoff integer NOT NULL default '0',\n                              dstoff integer NOT NULL default '0',\n                              dst_month integer NOT NULL default '0',\n                              dst_startday integer NOT NULL default '0',\n                              dst_weekday integer NOT NULL default '0',\n                              dst_skipweeks integer NOT NULL default '0',\n                              dst_time varchar(5) NOT NULL default '00:00',\n                              std_month integer NOT NULL default '0',\n                              std_startday integer NOT NULL default '0',\n                              std_weekday integer NOT NULL default '0',\n                              std_skipweeks integer NOT NULL default '0',\n                              std_time varchar(5) NOT NULL default '00:00'\n                            );");
    }
    if ($oldversion < 2005032800) {
        modify_database('', "CREATE TABLE prefix_grade_category (\n                              id SERIAL PRIMARY KEY,\n                              name varchar(64) default NULL,\n                              courseid integer NOT NULL default '0',\n                              drop_x_lowest integer NOT NULL default '0',\n                              bonus_points integer NOT NULL default '0',\n                              hidden integer NOT NULL default '0',\n                              weight decimal(4,2) default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_category_courseid_idx ON prefix_grade_category (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_exceptions (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer  NOT NULL default '0',\n                              grade_itemid integer  NOT NULL default '0',\n                              userid integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_exceptions_courseid_idx ON prefix_grade_exceptions (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_item (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              category integer default NULL,\n                              modid integer default NULL,\n                              cminstance integer default NULL,\n                              scale_grade float(11) default '1.0000000000',\n                              extra_credit integer NOT NULL default '0',\n                              sort_order integer  NOT NULL default '0'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_item_courseid_idx ON prefix_grade_item (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_letter (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer NOT NULL default '0',\n                              letter varchar(8) NOT NULL default 'NA',\n                              grade_high decimal(6,2) NOT NULL default '100.00',\n                              grade_low decimal(6,2) NOT NULL default '0.00'\n                            );");
        modify_database('', "CREATE INDEX prefix_grade_letter_courseid_idx ON prefix_grade_letter (courseid);");
        modify_database('', "CREATE TABLE prefix_grade_preferences (\n                              id SERIAL PRIMARY KEY,\n                              courseid integer default NULL,\n                              preference integer NOT NULL default '0',\n                              value integer NOT NULL default '0'\n                            );");
        modify_database('', "CREATE UNIQUE INDEX prefix_grade_prefs_courseidpref_uk ON prefix_grade_preferences (courseid,preference);");
    }
    if ($oldversion < 2005033100) {
        // Get rid of defunct field from course modules table
        delete_records('course_modules', 'deleted', 1);
        // Delete old records we don't need any more
        execute_sql('DROP INDEX ' . $CFG->prefix . 'course_modules_deleted_idx;');
        // Old index
        execute_sql('ALTER TABLE ' . $CFG->prefix . 'course_modules DROP deleted;');
        // Old field
    }
    if ($oldversion < 2005040800) {
        table_column('user', 'timezone', 'timezone', 'varchar', '100', '', '99');
        execute_sql(" ALTER TABLE {$CFG->prefix}user DROP timezonename ");
    }
    if ($oldversion < 2005041101) {
        require_once $CFG->libdir . '/filelib.php';
        if (is_readable($CFG->dirroot . '/lib/timezones.txt')) {
            // Distribution file
            if ($timezones = get_records_csv($CFG->dirroot . '/lib/timezones.txt', 'timezone')) {
                $db->debug = false;
                update_timezone_records($timezones);
                notify(count($timezones) . ' timezones installed');
                $db->debug = true;
            }
        }
    }
    if ($oldversion < 2005041900) {
        // Copy all Dialogue entries into Messages, and hide Dialogue module
        if ($entries = get_records_sql('SELECT e.id, e.userid, c.recipientid, e.text, e.timecreated
                                          FROM ' . $CFG->prefix . 'dialogue_conversations c,
                                               ' . $CFG->prefix . 'dialogue_entries e
                                         WHERE e.conversationid = c.id')) {
            foreach ($entries as $entry) {
                $message = NULL;
                $message->useridfrom = $entry->userid;
                $message->useridto = $entry->recipientid;
                $message->message = addslashes($entry->text);
                $message->format = FORMAT_HTML;
                $message->timecreated = $entry->timecreated;
                $message->messagetype = 'direct';
                insert_record('message_read', $message);
            }
        }
        set_field('modules', 'visible', 0, 'name', 'dialogue');
        notify('The Dialogue module has been disabled, and all the old Messages from it copied into the new standard Message feature.  If you really want Dialogue back, you can enable it using the "eye" icon here:  Admin >> Modules >> Dialogue');
    }
    if ($oldversion < 2005042100) {
        $result = table_column('event', '', 'repeatid', 'int', '10', 'unsigned', '0', 'not null', 'userid') && $result;
    }
    if ($oldversion < 2005042400) {
        // Add user tracking prefs field.
        table_column('user', '', 'trackforums', 'int', '4', 'unsigned', '0', 'not null', 'autosubscribe');
    }
    if ($oldversion < 2005051500) {
        // Add user tracking prefs field.
        table_column('grade_category', 'weight', 'weight', 'numeric(5,2)', '', '', '0.00', '', '');
    }
    if ($oldversion < 2005053000) {
        // Add config_plugins table
        // this table was created on the MOODLE_15_STABLE branch
        // so it may already exist. Therefore we hide potential errors
        // (Postgres doesn't support CREATE TABLE IF NOT EXISTS)
        execute_sql("CREATE TABLE {$CFG->prefix}config_plugins (\n                        id     SERIAL PRIMARY KEY,\n                        plugin varchar(100) NOT NULL default 'core',\n                        name   varchar(100) NOT NULL default '',\n                        value  text NOT NULL default '',\n                        CONSTRAINT {$CFG->prefix}config_plugins_plugin_name_uk UNIQUE (plugin, name)\n                     );", false);
    }
    if ($oldversion < 2005060200) {
        // migrate some config items to config_plugins table
        // NOTE: this block is in both postgres AND mysql upgrade
        // files. If you edit either, update the otherone.
        $user_fields = array("firstname", "lastname", "email", "phone1", "phone2", "department", "address", "city", "country", "description", "idnumber", "lang");
        if (!empty($CFG->auth)) {
            // if we have no auth, just pass
            foreach ($user_fields as $field) {
                $suffixes = array('', '_editlock', '_updateremote', '_updatelocal');
                foreach ($suffixes as $suffix) {
                    $key = 'auth_user_' . $field . $suffix;
                    if (isset($CFG->{$key})) {
                        // translate keys & values
                        // to the new convention
                        // this should support upgrading
                        // even 1.5dev installs
                        $newkey = $key;
                        $newval = $CFG->{$key};
                        if ($suffix === '') {
                            $newkey = 'field_map_' . $field;
                        } elseif ($suffix === '_editlock') {
                            $newkey = 'field_lock_' . $field;
                            $newval = $newval == 1 ? 'locked' : 'unlocked';
                            // translate 0/1 to locked/unlocked
                        } elseif ($suffix === '_updateremote') {
                            $newkey = 'field_updateremote_' . $field;
                        } elseif ($suffix === '_updatelocal') {
                            $newkey = 'field_updatelocal_' . $field;
                            $newval = $newval == 1 ? 'onlogin' : 'oncreate';
                            // translate 0/1 to locked/unlocked
                        }
                        if (!(set_config($newkey, addslashes($newval), 'auth/' . $CFG->auth) && delete_records('config', 'name', $key))) {
                            notify("Error updating Auth configuration {$key} to {$CFG->auth} {$newkey} .");
                            $result = false;
                        }
                    }
                    // end if isset key
                }
                // end foreach suffix
            }
            // end foreach field
        }
    }
    if ($oldversion < 2005060201) {
        // Close down the Attendance module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/attendance/lib.php')) {
            if (count_records('attendance')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'attendance');
                notify('The Attendance module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Attendance activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'attendance', false);
                delete_records('modules', 'name', 'attendance');
                notify("The Attendance module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005060223) {
        // Mass cleanup of bad postgres upgrade scripts
        execute_sql("DROP TABLE {$CFG->prefix}attendance_roll", false);
        // There are no attendance module anymore
        modify_database('', 'ALTER TABLE prefix_config ALTER value SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER metacourse SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_course ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_event ALTER repeatid SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER password SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_message_read ALTER format SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_groups ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER aim DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER idnumber DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER msn DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER policyagreed SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER skype DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user ALTER theme SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER timezone SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER trackforums SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user ALTER yahoo DROP DEFAULT');
        modify_database('', 'ALTER TABLE prefix_user_students ALTER enrol SET NOT NULL');
        modify_database('', 'ALTER TABLE prefix_user_teachers ALTER enrol SET NOT NULL');
    }
    if ($oldversion < 2005071700) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (count_records('dialogue')) {
                // We have some data, so should keep it
                set_field('modules', 'visible', 0, 'name', 'dialogue');
                notify('The Dialogue module has been discontinued.  If you really want to 
                        continue using it, you should download it individually from 
                        http://download.moodle.org/modules and install it, then 
                        reactivate it from Admin >> Configuration >> Modules.  
                        None of your existing data has been deleted, so all existing 
                        Dialogue activities should re-appear.');
            } else {
                // No data, so do a complete delete
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue', false);
                delete_records('modules', 'name', 'dialogue');
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
    }
    if ($oldversion < 2005072000) {
        // Add a couple fields to mdl_event to work towards iCal import/export
        table_column('event', '', 'uuid', 'char', '36', '', '', 'not null', 'visible');
        table_column('event', '', 'sequence', 'integer', '10', 'unsigned', '1', 'not null', 'uuid');
    }
    if ($oldversion < 2005072100) {
        // run the online assignment cleanup code
        include $CFG->dirroot . '/' . $CFG->admin . '/oacleanup.php';
        if (function_exists('online_assignment_cleanup')) {
            online_assignment_cleanup();
        }
    }
    if ($oldversion < 2005072200) {
        // fix the mistakenly-added currency stuff from enrol/authorize
        execute_sql("DROP TABLE {$CFG->prefix}currencies", false);
        // drop silently
        execute_sql("ALTER TABLE {$CFG->prefix}course DROP currency", false);
        $defaultcurrency = empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency;
        table_column('course', '', 'currency', 'char', '3', '', $defaultcurrency, 'not null', 'cost');
    }
    if ($oldversion < 2005081600) {
        //set up the course requests table
        modify_database('', "CREATE TABLE prefix_course_request (\n           id SERIAL PRIMARY KEY,\n           fullname varchar(254) NOT NULL default '',\n           shortname varchar(15) NOT NULL default '',\n           summary text NOT NULL default '',\n           reason text NOT NULL default '',\n           requester INTEGER NOT NULL default 0\n         );");
        modify_database('', 'CREATE INDEX prefix_course_request_shortname_idx ON prefix_course_request (shortname);');
        table_column('course', '', 'requested');
    }
    if ($oldversion < 2005081601) {
        modify_database('', 'CREATE TABLE prefix_course_allowed_modules (
            id SERIAL PRIMARY KEY,
            course INTEGER NOT NULL default 0,
            module INTEGER NOT NULL default 0
         );');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_course_idx ON prefix_course_allowed_modules (course);');
        modify_database('', 'CREATE INDEX prefix_course_allowed_modules_module_idx ON prefix_course_allowed_modules (module);');
        table_column('course', '', 'restrictmodules', 'int', '1', '', '0', 'not null');
    }
    if ($oldversion < 2005081700) {
        table_column('course_categories', '', 'depth', 'integer');
        table_column('course_categories', '', 'path', 'varchar', '255');
    }
    if ($oldversion < 2005090100) {
        // stats!
        modify_database('', 'CREATE TABLE prefix_stats_daily (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_daily_courseid_idx ON prefix_stats_daily (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_daily_timeend_idx ON prefix_stats_daily (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_weekly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_courseid_idx ON prefix_stats_weekly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_weekly_timeend_idx ON prefix_stats_weekly (timeend);');
        modify_database('', 'CREATE TABLE prefix_stats_monthly (
           id SERIAL PRIMARY KEY,
           courseid INTEGER NOT NULL default 0,
           timeend INTEGER NOT NULL default 0,
           students INTEGER NOT NULL default 0,
           teachers INTEGER NOT NULL default 0,
           activestudents INTEGER NOT NULL default 0,
           activeteachers INTEGER NOT NULL default 0,
           studentreads INTEGER NOT NULL default 0,
           studentwrites INTEGER NOT NULL default 0,
           teacherreads INTEGER NOT NULL default 0,
           teacherwrites INTEGER NOT NULL default 0,
           logins INTEGER NOT NULL default 0,
           uniquelogins INTEGER NOT NULL default 0
        );');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_courseid_idx ON prefix_stats_monthly (courseid);');
        modify_database('', 'CREATE INDEX prefix_stats_monthly_timeend_idx ON prefix_stats_monthly (timeend);');
        modify_database("", "CREATE TABLE prefix_stats_user_daily (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_courseid_idx ON prefix_stats_user_daily (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_userid_idx ON prefix_stats_user_daily (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_roleid_idx ON prefix_stats_user_daily (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_daily_timeend_idx ON prefix_stats_user_daily (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_weekly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_courseid_idx ON prefix_stats_user_weekly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_userid_idx ON prefix_stats_user_weekly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_roleid_idx ON prefix_stats_user_weekly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_weekly_timeend_idx ON prefix_stats_user_weekly (timeend);");
        modify_database("", "CREATE TABLE prefix_stats_user_monthly (\n           id SERIAL PRIMARY KEY,\n           courseid INTEGER NOT NULL default 0,\n           userid INTEGER NOT NULL default 0,\n           roleid INTEGER NOT NULL default 0,\n           timeend INTEGER NOT NULL default 0,\n           statsreads INTEGER NOT NULL default 0,\n           statswrites INTEGER NOT NULL default 0,\n           stattype varchar(30) NOT NULL default ''\n         );");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_courseid_idx ON prefix_stats_user_monthly (courseid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_userid_idx ON prefix_stats_user_monthly (userid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_roleid_idx ON prefix_stats_user_monthly (roleid);");
        modify_database("", "CREATE INDEX prefix_stats_user_monthly_timeend_idx ON prefix_stats_user_monthly (timeend);");
    }
    if ($oldversion < 2005100300) {
        table_column('course', '', 'expirynotify', 'integer', '1');
        table_column('course', '', 'expirythreshold', 'integer');
        table_column('course', '', 'notifystudents', 'integer', '1');
        $new = new stdClass();
        $new->name = 'lastexpirynotify';
        $new->value = 0;
        insert_record('config', $new);
    }
    if ($oldversion < 2005100400) {
        table_column('course', '', 'enrollable', 'integer', '1', 'unsigned', '1');
        table_column('course', '', 'enrolstartdate', 'integer');
        table_column('course', '', 'enrolenddate', 'integer');
    }
    if ($oldversion < 2005101200) {
        // add enrolment key to course_request.
        table_column('course_request', '', 'password', 'text');
    }
    if ($oldversion < 2006030800) {
        # add extra indexes to log (see bug #4112)
        modify_database('', "CREATE INDEX prefix_log_userid_idx ON prefix_log (userid);");
        modify_database('', "CREATE INDEX prefix_log_info_idx ON prefix_log (info);");
    }
    if ($oldversion < 2006030900) {
        table_column('course', '', 'enrol', 'varchar', '20', '', '');
        if ($CFG->enrol == 'internal' || $CFG->enrol == 'manual') {
            set_config('enrol_plugins_enabled', 'manual');
            set_config('enrol', 'manual');
        } else {
            set_config('enrol_plugins_enabled', 'manual,' . $CFG->enrol);
        }
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            // switch enrollable to off for all courses in this case
            modify_database('', 'UPDATE prefix_course SET enrollable = 0');
        }
        execute_sql("UPDATE {$CFG->prefix}user_students SET enrol='manual' WHERE enrol='' OR enrol='internal'");
        execute_sql("UPDATE {$CFG->prefix}user_teachers SET enrol='manual' WHERE enrol=''");
    }
    if ($oldversion < 2006031000) {
        modify_database("", "CREATE TABLE prefix_post (\n          id SERIAL PRIMARY KEY,\n          userid INTEGER NOT NULL default 0,\n          courseid INTEGER NOT NULL default 0,\n          groupid INTEGER NOT NULL default 0,\n          moduleid INTEGER NOT NULL default 0,\n          coursemoduleid INTEGER NOT NULL default 0,\n          subject varchar(128) NOT NULL default '',\n          summary text,\n          content text,\n          uniquehash varchar(128) NOT NULL default '',\n          rating INTEGER NOT NULL default 0,\n          format INTEGER NOT NULL default 0,\n          publishstate varchar(10) CHECK (publishstate IN ('draft','site','public')) NOT NULL default 'draft',\n          lastmodified INTEGER NOT NULL default '0',\n          created INTEGER NOT NULL default '0'\n        );");
        modify_database("", "CREATE INDEX id_user_idx ON prefix_post  (id, courseid);");
        modify_database("", "CREATE INDEX post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX post_subject_idx ON prefix_post (subject);");
        modify_database("", "CREATE TABLE prefix_tags (\n          id SERIAL PRIMARY KEY,\n          type varchar(255) NOT NULL default 'official',\n          userid INTEGER NOT NULL default 0,\n          text varchar(255) NOT NULL default ''\n        );");
        modify_database("", "CREATE TABLE prefix_blog_tag_instance (\n          id SERIAL PRIMARY KEY,\n          entryid integer NOT NULL default 0,\n          tagid integer NOT NULL default 0,\n          groupid integer NOT NULL default 0,\n          courseid integer NOT NULL default 0,\n          userid integer NOT NULL default 0\n        );");
    }
    if ($oldversion < 2006031400) {
        require_once "{$CFG->dirroot}/enrol/enrol.class.php";
        $defaultenrol = enrolment_factory::factory($CFG->enrol);
        if (!method_exists($defaultenrol, 'print_entry')) {
            set_config('enrol', 'manual');
        }
    }
    if ($oldversion < 2006032000) {
        table_column('post', '', 'module', 'varchar', '20', '', '', 'not null', 'id');
        modify_database('', "CREATE INDEX post_module_idx ON prefix_post (module);");
        modify_database('', "UPDATE prefix_post SET module = 'blog';");
    }
    if ($oldversion < 2006032001) {
        table_column('blog_tag_instance', '', 'timemodified', 'integer', '10', 'unsigned', '0', 'not null', 'userid');
        modify_database('', "CREATE INDEX bti_entryid_idx ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX bti_tagid_idx ON prefix_blog_tag_instance (tagid);");
        modify_database('', "UPDATE prefix_blog_tag_instance SET timemodified = '" . time() . "';");
    }
    if ($oldversion < 2006040500) {
        // Add an index to course_sections that was never upgraded (bug 5100)
        execute_sql(" CREATE INDEX {$CFG->prefix}course_sections_coursesection_idx ON {$CFG->prefix}course_sections (course,section) ", false);
    }
    if ($oldversion < 2006041100) {
        table_column('course_modules', '', 'visibleold', 'integer', '1', 'unsigned', '1', 'not null', 'visible');
    }
    if ($oldversion < 2006042400) {
        // Look through table log_display and get rid of duplicates.
        $rs = get_recordset_sql('SELECT DISTINCT * FROM ' . $CFG->prefix . 'log_display');
        // Drop the log_display table and create it back with an id field.
        execute_sql("DROP TABLE {$CFG->prefix}log_display", false);
        modify_database('', "CREATE TABLE prefix_log_display (\n                               id SERIAL PRIMARY KEY,\n                               module varchar(30) NOT NULL default '',\n                               action varchar(40) NOT NULL default '',\n                               mtable varchar(30) NOT NULL default '',\n                               field varchar(50) NOT NULL default '')");
        // Add index to ensure that module and action combination is unique.
        modify_database('', 'CREATE INDEX prefix_log_display_moduleaction ON prefix_log_display (module,action)');
        // Insert the records back in, sans duplicates.
        if ($rs) {
            while (!$rs->EOF) {
                $sql = "INSERT INTO {$CFG->prefix}log_display " . "VALUES('', '" . $rs->fields['module'] . "', " . "'" . $rs->fields['action'] . "', " . "'" . $rs->fields['mtable'] . "', " . "'" . $rs->fields['field'] . "')";
                execute_sql($sql, false);
                $rs->MoveNext();
            }
            rs_close($rs);
        }
    }
    // add 2 indexes to tags table
    if ($oldversion < 2006042401) {
        modify_database('', "CREATE INDEX tags_typeuserid_idx ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX tags_text_idx ON prefix_tags (text);");
    }
    if ($oldversion < 2006050500) {
        table_column('log', 'action', 'action', 'varchar', '40', '', '', 'not null');
    }
    if ($oldversion < 2006050502) {
        // Close down the Dialogue module, we are removing it from CVS.
        if (!file_exists($CFG->dirroot . '/mod/dialogue/lib.php')) {
            if (!count_records('dialogue_conversations')) {
                // no data, drop the extra tables
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_conversations', false);
                execute_sql('DROP TABLE ' . $CFG->prefix . 'dialogue_entries', false);
                notify("The Dialogue module has been discontinued and removed from your site.  \n                        You weren't using it anyway.  ;-)");
            }
        }
        table_column('course_request', 'password', 'password', 'varchar', '50', '', '');
        table_column('course', 'currency', 'currency', 'varchar', '3');
        modify_database('', 'ALTER TABLE prefix_course_categories
            ALTER COLUMN path SET DEFAULT \'\'');
        table_column('log_display', 'module', 'module', 'varchar', '20');
        modify_database("", "DROP INDEX id_user_idx");
        modify_database("", "DROP INDEX post_lastmodified_idx");
        modify_database("", "DROP INDEX post_subject_idx");
        modify_database('', "DROP INDEX bti_entryid_idx");
        modify_database('', "DROP INDEX bti_tagid_idx");
        modify_database('', "DROP INDEX post_module_idx");
        modify_database('', "DROP INDEX tags_typeuserid_idx");
        modify_database('', "DROP INDEX tags_text_idx");
        modify_database("", "CREATE INDEX {$CFG->prefix}id_user_idx           ON prefix_post (id, courseid);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_lastmodified_idx ON prefix_post (lastmodified);");
        modify_database("", "CREATE INDEX {$CFG->prefix}post_subject_idx      ON prefix_post (subject);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_entryid_idx       ON prefix_blog_tag_instance (entryid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}bti_tagid_idx         ON prefix_blog_tag_instance (tagid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}post_module_idx       ON prefix_post (moduleid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_typeuserid_idx   ON prefix_tags (type, userid);");
        modify_database('', "CREATE INDEX {$CFG->prefix}tags_text_idx         ON prefix_tags (text);");
    }
    // renaming of reads and writes for stats_user_xyz
    if ($oldversion < 2006052400) {
        // change this later
        // we are using this because we want silent updates
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_daily RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_weekly RENAME COLUMN writes TO statswrites", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN reads TO statsreads", false);
        execute_sql("ALTER TABLE {$CFG->prefix}stats_user_monthly RENAME COLUMN writes TO statswrites", false);
    }
    // Adding some missing log actions
    if ($oldversion < 2006060400) {
        // But only if they doesn't exist (because this was introduced after branch and we could be duplicating!)
        if (!record_exists('log_display', 'module', 'course', 'action', 'report log')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report log', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report live')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report live', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report outline')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report outline', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report participation')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report participation', 'course', 'fullname')");
        }
        if (!record_exists('log_display', 'module', 'course', 'action', 'report stats')) {
            execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('course', 'report stats', 'course', 'fullname')");
        }
    }
    //Renaming lastIP to lastip (all fields lowercase)
    if ($oldversion < 2006060900) {
        //Not needed unded PG because it stores fieldnames lowecase by default
        //Only if it exists (because MOODLE_16_STABLE could have done this work before. Bug 5763)
        //$fields = $db->MetaColumnNames($CFG->prefix.'user');
        //if (in_array('lastIP',$fields)) {
        //    table_column("user", "lastIP", "lastip", "varchar", "15", "", "", "", "currentlogin");
        //}
    }
    if ($oldversion < 2006080400) {
        modify_database('', "CREATE TABLE prefix_role (\n                                  id SERIAL PRIMARY KEY,\n                                  name varchar(255) NOT NULL default '',\n                                  shortname varchar(100) NOT NULL default '',     \n                                  description text NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_context (\n                                  id SERIAL PRIMARY KEY,\n                                  level integer NOT NULL default 0,\n                                  instanceid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_assignments (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default 0,\n                                  contextid integer NOT NULL default 0,\n                                  userid integer NOT NULL default 0,\n                                  hidden integer NOT NULL default 0,\n                                  timestart integer NOT NULL default 0,\n                                  timeend integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0,\n                                  enrol varchar(20) NOT NULL default '',\n                                  sortorder integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_role_capabilities (\n                                  id SERIAL PRIMARY KEY,\n                                  contextid integer NOT NULL default 0,\n                                  roleid integer NOT NULL default 0,\n                                  capability varchar(255) NOT NULL default '',\n                                  permission integer NOT NULL default 0,\n                                  timemodified integer NOT NULL default 0,\n                                  modifierid integer NOT NULL default 0\n                                );");
        modify_database('', "CREATE TABLE prefix_role_deny_grant (\n                                  id SERIAL PRIMARY KEY,\n                                  roleid integer NOT NULL default '0',\n                                  unviewableroleid integer NOT NULL default '0'\n                                );");
        modify_database('', "CREATE TABLE prefix_capabilities ( \n                              id SERIAL PRIMARY KEY,\n                              name varchar(255) NOT NULL default '', \n                              captype varchar(50) NOT NULL default '', \n                              contextlevel integer NOT NULL default 0, \n                              component varchar(100) NOT NULL default ''\n                                );");
        modify_database('', "CREATE TABLE prefix_role_names ( \n                              id SERIAL PRIMARY KEY,\n                              roleid integer NOT NULL default 0,\n                              contextid integer NOT NULL default 0, \n                              text text NOT NULL default ''\n                                );");
    }
    if ($oldversion < 2006081000) {
        modify_database('', "CREATE INDEX prefix_role_sortorder_idx ON prefix_role (sortorder);");
        modify_database('', "CREATE INDEX prefix_context_instanceid_idx ON prefix_context (instanceid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_context_levelinstanceid_idx ON prefix_context (level, instanceid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_roleid_idx ON prefix_role_assignments (roleid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_contextidid_idx ON prefix_role_assignments (contextid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_userid_idx ON prefix_role_assignments (userid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_assignments_contextidroleiduserid_idx ON prefix_role_assignments (contextid, roleid, userid);");
        modify_database('', "CREATE INDEX prefix_role_assignments_sortorder_idx ON prefix_role_assignments (sortorder);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_roleid_idx ON prefix_role_capabilities (roleid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_contextid_idx ON prefix_role_capabilities (contextid);");
        modify_database('', "CREATE INDEX prefix_role_capabilities_modifierid_idx ON prefix_role_capabilities (modifierid);");
        // MDL-10640  adding missing index from upgrade
        modify_database('', "CREATE INDEX prefix_role_capabilities_capability_idx ON prefix_role_capabilities (capability);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_capabilities_roleidcontextidcapability_idx ON prefix_role_capabilities (roleid, contextid, capability);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_roleid_idx ON prefix_role_deny_grant (roleid);");
        modify_database('', "CREATE INDEX prefix_role_deny_grant_unviewableroleid_idx ON prefix_role_deny_grant (unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_deny_grant_roleidunviewableroleid_idx ON prefix_role_deny_grant (roleid, unviewableroleid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_capabilities_name_idx ON prefix_capabilities (name);");
        modify_database('', "CREATE INDEX prefix_role_names_roleid_idx ON prefix_role_names (roleid);");
        modify_database('', "CREATE INDEX prefix_role_names_contextid_idx ON prefix_role_names (contextid);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_names_roleidcontextid_idx ON prefix_role_names (roleid, contextid);");
    }
    if ($oldversion < 2006081700) {
        modify_database('', "DROP TABLE prefix_role_deny_grant");
        modify_database('', "CREATE TABLE prefix_role_allow_assign (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowassign integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_roleid_idx ON prefix_role_allow_assign (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_assign_allowassign_idx ON prefix_role_allow_assign (allowassign);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_assign_roleidallowassign_idx ON prefix_role_allow_assign (roleid, allowassign);");
        modify_database('', "CREATE TABLE prefix_role_allow_override (    \n            id SERIAL PRIMARY KEY,     \n            roleid integer NOT NULL default '0',   \n            allowoverride integer NOT NULL default '0'      \n        );");
        modify_database('', "CREATE INDEX prefix_role_allow_override_roleid_idx ON prefix_role_allow_override (roleid);");
        modify_database('', "CREATE INDEX prefix_role_allow_override_allowoverride_idx ON prefix_role_allow_override (allowoverride);");
        modify_database('', "CREATE UNIQUE INDEX prefix_role_allow_override_roleidallowoverride_idx ON prefix_role_allow_override (roleid, allowoverride);");
    }
    if ($oldversion < 2006082100) {
        execute_sql("DROP INDEX {$CFG->prefix}context_levelinstanceid_idx;", false);
        table_column('context', 'level', 'aggregatelevel', 'integer', '10', 'unsigned', '0', 'not null', '');
        modify_database('', "CREATE UNIQUE INDEX prefix_context_aggregatelevelinstanceid_idx ON prefix_context (aggregatelevel, instanceid);");
    }
    if ($oldversion < 2006082200) {
        table_column('timezone', 'rule', 'tzrule', 'varchar', '20', '', '', 'not null', '');
    }
    if ($oldversion < 2006082800) {
        table_column('user', '', 'ajax', 'integer', '1', 'unsigned', '1', 'not null', 'htmleditor');
    }
    if ($oldversion < 2006082900) {
        execute_sql("DROP TABLE {$CFG->prefix}sessions", true);
        execute_sql("\n            CREATE TABLE {$CFG->prefix}sessions2 (\n                sesskey VARCHAR(255) NOT NULL default '',\n                expiry TIMESTAMP NOT NULL,\n                expireref VARCHAR(255),\n                created TIMESTAMP NOT NULL,\n                modified TIMESTAMP NOT NULL,\n                sessdata TEXT,\n                CONSTRAINT {$CFG->prefix}sess_ses_pk PRIMARY KEY (sesskey)\n            );", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp_ix ON {$CFG->prefix}sessions2 (expiry);", true);
        execute_sql("\n            CREATE INDEX {$CFG->prefix}sess_exp2_ix ON {$CFG->prefix}sessions2 (expireref);", true);
    }
    if ($oldversion < 2006083002) {
        table_column('capabilities', '', 'riskbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006083100) {
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course ALTER COLUMN modinfo DROP DEFAULT");
    }
    if ($oldversion < 2006083101) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_categories ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006083102) {
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}user ALTER COLUMN description DROP DEFAULT");
    }
    if ($oldversion < 2006090200) {
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN summary DROP DEFAULT");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP NOT NULL");
        execute_sql("ALTER TABLE {$CFG->prefix}course_sections ALTER COLUMN sequence DROP DEFAULT");
    }
    // table to keep track of course page access times, used in online participants block, and participants list
    if ($oldversion < 2006091200) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_lastaccess ( \n                    id SERIAL PRIMARY KEY,     \n                    userid integer NOT NULL default 0,\n                    courseid integer NOT NULL default 0, \n                    timeaccess integer NOT NULL default 0\n                    );", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_userid_idx ON {$CFG->prefix}user_lastaccess (userid);", true);
        execute_sql("CREATE INDEX {$CFG->prefix}user_lastaccess_courseid_idx ON {$CFG->prefix}user_lastaccess (courseid);", true);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}user_lastaccess_useridcourseid_idx ON {$CFG->prefix}user_lastaccess (userid, courseid);", true);
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091212) {
        // Reload the guest roles completely with new defaults
        if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            delete_records('capabilities');
            $sitecontext = get_context_instance(CONTEXT_SYSTEM);
            foreach ($guestroles as $guestrole) {
                delete_records('role_capabilities', 'roleid', $guestrole->id);
                assign_capability('moodle/legacy:guest', CAP_ALLOW, $guestrole->id, $sitecontext->id);
            }
        }
    }
    if ($oldversion < 2006091700) {
        table_column('course', '', 'defaultrole', 'integer', '10', 'unsigned', '0', 'not null');
    }
    if ($oldversion < 2006091800) {
        delete_records('config', 'name', 'showsiteparticipantslist');
        delete_records('config', 'name', 'requestedteachername');
        delete_records('config', 'name', 'requestedteachersname');
        delete_records('config', 'name', 'requestedstudentname');
        delete_records('config', 'name', 'requestedstudentsname');
    }
    if (!empty($CFG->rolesactive) and $oldversion < 2006091901) {
        if ($roles = get_records('role')) {
            $first = array_shift($roles);
            if (!empty($first->shortname)) {
                // shortnames already exist
            } else {
                table_column('role', '', 'shortname', 'varchar', '100', '', '', 'not null', 'name');
                $legacy_names = array('admin', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest');
                foreach ($legacy_names as $name) {
                    if ($roles = get_roles_with_capability('moodle/legacy:' . $name, CAP_ALLOW)) {
                        $i = '';
                        foreach ($roles as $role) {
                            if (empty($role->shortname)) {
                                $updated = new object();
                                $updated->id = $role->id;
                                $updated->shortname = $name . $i;
                                update_record('role', $updated);
                                $i++;
                            }
                        }
                    }
                }
            }
        }
    }
    /// Tables for customisable user profile fields
    if ($oldversion < 2006092000) {
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_field (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        datatype VARCHAR(255) NOT NULL default '',\n                        categoryid BIGINT NOT NULL default 0,\n                        sortorder BIGINT NOT NULL default 0,\n                        required SMALLINT NOT NULL default 0,\n                        locked SMALLINT NOT NULL default 0,\n                        visible SMALLINT NOT NULL default 0,\n                        defaultdata TEXT,\n                        CONSTRAINT {$CFG->prefix}userinfofiel_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_field IS 'Customisable user profile fields';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_category (\n                        id BIGSERIAL,\n                        name VARCHAR(255) NOT NULL default '',\n                        sortorder BIGINT NOT NULL default 0,\n                        CONSTRAINT {$CFG->prefix}userinfocate_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_category IS 'Customisable fields categories';", true);
        execute_sql("CREATE TABLE {$CFG->prefix}user_info_data (\n                        id BIGSERIAL,\n                        userid BIGINT NOT NULL default 0,\n                        fieldid BIGINT NOT NULL default 0,\n                        data TEXT NOT NULL,\n                        CONSTRAINT {$CFG->prefix}userinfodata_id_pk PRIMARY KEY (id));", true);
        execute_sql("COMMENT ON TABLE {$CFG->prefix}user_info_data IS 'Data for the customisable user fields';", true);
    }
    if ($oldversion < 2006092200) {
        table_column('context', 'aggregatelevel', 'contextlevel', 'int', '10', 'unsigned', '0', 'not null', '');
        /*      execute_sql("ALTER TABLE `{$CFG->prefix}context` DROP INDEX `aggregatelevel-instanceid`;",false);
                execute_sql("ALTER TABLE `{$CFG->prefix}context` ADD UNIQUE INDEX `contextlevel-instanceid` (`contextlevel`, `instanceid`)",false);  // see 2006092409 below */
    }
    if ($oldversion < 2006092302) {
        // fix sortorder first if needed
        if ($roles = get_all_roles()) {
            $i = 0;
            foreach ($roles as $rolex) {
                if ($rolex->sortorder != $i) {
                    $r = new object();
                    $r->id = $rolex->id;
                    $r->sortorder = $i;
                    update_record('role', $r);
                }
                $i++;
            }
        }
        /*        execute_sql("ALTER TABLE {$CFG->prefix}role DROP INDEX {$CFG->prefix}role_sor_ix;");
                execute_sql("ALTER TABLE {$CFG->prefix}role ADD UNIQUE INDEX {$CFG->prefix}role_sor_uix (sortorder)");*/
    }
    if ($oldversion < 2006092400) {
        table_column('user', '', 'trustbitmask', 'INTEGER', '10', 'unsigned', '0', 'not null', '');
    }
    if ($oldversion < 2006092409) {
        // ok, once more and now correctly!
        execute_sql("DROP INDEX \"aggregatelevel-instanceid\";", false);
        execute_sql("DROP INDEX \"contextlevel-instanceid\";", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}cont_conins_uix ON {$CFG->prefix}context (contextlevel, instanceid);", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_ix;", false);
        execute_sql("DROP INDEX {$CFG->prefix}role_sor_uix;", false);
        execute_sql("CREATE UNIQUE INDEX {$CFG->prefix}role_sor_uix ON {$CFG->prefix}role (sortorder);", false);
    }
    if ($oldversion < 2006092410) {
        /// Convert all the PG unique keys into their corresponding unique indexes
        /// we don't want such keys inside Moodle 1.7 and above
        /// Look for all the UNIQUE CONSTRAINSTS existing in DB
        $uniquecons = get_records_sql("SELECT conname, relname, conkey, clas.oid AS tableoid\n                                          FROM pg_constraint cons,\n                                               pg_class clas\n                                         WHERE cons.contype='u'\n                                           AND cons.conrelid = clas.oid");
        /// Iterate over every unique constraint, calculating its fields
        if ($uniquecons) {
            foreach ($uniquecons as $uniquecon) {
                $conscols = trim(trim($uniquecon->conkey, '}'), '{');
                $conscols = explode(',', $conscols);
                /// Iterate over each column to fetch its name
                $indexcols = array();
                foreach ($conscols as $conscol) {
                    $column = get_record_sql("SELECT attname, attname\n                                                 FROM pg_attribute\n                                                WHERE attrelid = {$uniquecon->tableoid}\n                                                  AND attnum   = {$conscol}");
                    $indexcols[] = $column->attname;
                }
                /// Drop the old UNIQUE CONSTRAINT
                execute_sql("ALTER TABLE {$uniquecon->relname} DROP CONSTRAINT {$uniquecon->conname}", false);
                /// Create the new UNIQUE INDEX
                execute_sql("CREATE UNIQUE INDEX {$uniquecon->relname}_" . implode('_', $indexcols) . "_uix ON {$uniquecon->relname} (" . implode(', ', $indexcols) . ')', false);
            }
        }
    }
    if ($oldversion < 2006092601) {
        table_column('log_display', 'field', 'field', 'varchar', '200', '', '', 'not null', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $result;
}
Example #28
0
function restore_execute(&$restore, $info, $course_header, &$errorstr)
{
    global $CFG, $USER;
    $status = true;
    //Checks for the required files/functions to restore every module
    //and include them
    if ($allmods = get_records("modules")) {
        foreach ($allmods as $mod) {
            $modname = $mod->name;
            $modfile = "{$CFG->dirroot}/mod/{$modname}/restorelib.php";
            //If file exists and we have selected to restore that type of module
            if (file_exists($modfile) and !empty($restore->mods[$modname]) and $restore->mods[$modname]->restore) {
                include_once $modfile;
            }
        }
    }
    if (!defined('RESTORE_SILENTLY')) {
        //Start the main table
        echo "<table cellpadding=\"5\">";
        echo "<tr><td>";
        //Start the main ul
        echo "<ul>";
    }
    //Location of the xml file
    $xml_file = $CFG->dataroot . "/temp/backup/" . $restore->backup_unique_code . "/moodle.xml";
    //Preprocess the moodle.xml file spliting into smaller chucks (modules, users, logs...)
    //for optimal parsing later in the restore process.
    if (!empty($CFG->experimentalsplitrestore)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>' . get_string('preprocessingbackupfile') . '</li>';
        }
        //First of all, split moodle.xml into handy files
        if (!restore_split_xml($xml_file, $restore)) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Error proccessing moodle.xml file. Process ended.");
            } else {
                $errorstr = "Error proccessing moodle.xml file. Process ended.";
            }
            return false;
        }
    }
    //If we've selected to restore into new course
    //create it (course)
    //Saving conversion id variables into backup_tables
    if ($restore->restoreto == RESTORETO_NEW_COURSE) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>' . get_string('creatingnewcourse') . '</li>';
        }
        $oldidnumber = $course_header->course_idnumber;
        if (!($status = restore_create_new_course($restore, $course_header))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Error while creating the new empty course.");
            } else {
                $errorstr = "Error while creating the new empty course.";
                return false;
            }
        }
        //Print course fullname and shortname and category
        if ($status) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<ul>";
                echo "<li>" . $course_header->course_fullname . " (" . $course_header->course_shortname . ")" . '</li>';
                echo "<li>" . get_string("category") . ": " . $course_header->category->name . '</li>';
                if (!empty($oldidnumber)) {
                    echo "<li>" . get_string("nomoreidnumber", "moodle", $oldidnumber) . "</li>";
                }
                echo "</ul>";
                //Put the destination course_id
            }
            $restore->course_id = $course_header->course_id;
        }
        if ($status = restore_open_html($restore, $course_header)) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>Creating the Restorelog.html in the course backup folder</li>";
            }
        }
    } else {
        $course = get_record("course", "id", $restore->course_id);
        if ($course) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>" . get_string("usingexistingcourse");
                echo "<ul>";
                echo "<li>" . get_string("from") . ": " . $course_header->course_fullname . " (" . $course_header->course_shortname . ")" . '</li>';
                echo "<li>" . get_string("to") . ": " . format_string($course->fullname) . " (" . format_string($course->shortname) . ")" . '</li>';
                if ($restore->deleting) {
                    echo "<li>" . get_string("deletingexistingcoursedata") . '</li>';
                } else {
                    echo "<li>" . get_string("addingdatatoexisting") . '</li>';
                }
                echo "</ul></li>";
            }
            //If we have selected to restore deleting, we do it now.
            if ($restore->deleting) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<li>" . get_string("deletingolddata") . '</li>';
                }
                $status = remove_course_contents($restore->course_id, false) and delete_dir_contents($CFG->dataroot . "/" . $restore->course_id, "backupdata");
                if ($status) {
                    //Now , this situation is equivalent to the "restore to new course" one (we
                    //have a course record and nothing more), so define it as "to new course"
                    $restore->restoreto = RESTORETO_NEW_COURSE;
                } else {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("An error occurred while deleting some of the course contents.");
                    } else {
                        $errrostr = "An error occurred while deleting some of the course contents.";
                        return false;
                    }
                }
            }
        } else {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Error opening existing course.");
                $status = false;
            } else {
                $errorstr = "Error opening existing course.";
                return false;
            }
        }
    }
    //Now create users as needed
    if ($status and ($restore->users == 0 or $restore->users == 1)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingusers") . "<br />";
        }
        if (!($status = restore_create_users($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore users.");
            } else {
                $errorstr = "Could not restore users.";
                return false;
            }
        }
        //Now print info about the work done
        if ($status) {
            $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids\n                                     where backup_code = '{$restore->backup_unique_code}' and\n                                     table_name = 'user'");
            //We've records
            if ($recs) {
                $new_count = 0;
                $exists_count = 0;
                $student_count = 0;
                $teacher_count = 0;
                $counter = 0;
                //Iterate, filling counters
                foreach ($recs as $rec) {
                    //Get full record, using backup_getids
                    $record = backup_getid($restore->backup_unique_code, "user", $rec->old_id);
                    if (strpos($record->info, "new") !== false) {
                        $new_count++;
                    }
                    if (strpos($record->info, "exists") !== false) {
                        $exists_count++;
                    }
                    if (strpos($record->info, "student") !== false) {
                        $student_count++;
                    } else {
                        if (strpos($record->info, "teacher") !== false) {
                            $teacher_count++;
                        }
                    }
                    //Do some output
                    $counter++;
                    if ($counter % 10 == 0) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo ".";
                            if ($counter % 200 == 0) {
                                echo "<br />";
                            }
                        }
                        backup_flush(300);
                    }
                }
                if (!defined('RESTORE_SILENTLY')) {
                    //Now print information gathered
                    echo " (" . get_string("new") . ": " . $new_count . ", " . get_string("existing") . ": " . $exists_count . ")";
                    echo "<ul>";
                    echo "<li>" . get_string("students") . ": " . $student_count . '</li>';
                    echo "<li>" . get_string("teachers") . ": " . $teacher_count . '</li>';
                    echo "</ul>";
                }
            } else {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("No users were found!");
                }
                // no need to return false here, it's recoverable.
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</li>";
        }
    }
    //Now create groups as needed
    if ($status and ($restore->groups == RESTORE_GROUPS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatinggroups");
        }
        if (!($status = restore_create_groups($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore groups!");
            } else {
                $errorstr = "Could not restore groups!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create groupings as needed
    if ($status and ($restore->groups == RESTORE_GROUPINGS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatinggroupings");
        }
        if (!($status = restore_create_groupings($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore groupings!");
            } else {
                $errorstr = "Could not restore groupings!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create groupingsgroups as needed
    if ($status and $restore->groups == RESTORE_GROUPS_GROUPINGS) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatinggroupingsgroups");
        }
        if (!($status = restore_create_groupings_groups($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore groups in groupings!");
            } else {
                $errorstr = "Could not restore groups in groupings!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create the course_sections and their associated course_modules
    //we have to do this after groups and groupings are restored, because we need the new groupings id
    if ($status) {
        //Into new course
        if ($restore->restoreto == RESTORETO_NEW_COURSE) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>" . get_string("creatingsections");
            }
            if (!($status = restore_create_sections($restore, $xml_file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error creating sections in the existing course.");
                } else {
                    $errorstr = "Error creating sections in the existing course.";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
            //Into existing course
        } else {
            if ($restore->restoreto != RESTORETO_NEW_COURSE) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo "<li>" . get_string("checkingsections");
                }
                if (!($status = restore_create_sections($restore, $xml_file))) {
                    if (!defined('RESTORE_SILENTLY')) {
                        notify("Error creating sections in the existing course.");
                    } else {
                        $errorstr = "Error creating sections in the existing course.";
                        return false;
                    }
                }
                if (!defined('RESTORE_SILENTLY')) {
                    echo '</li>';
                }
                //Error
            } else {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Neither a new course or an existing one was specified.");
                    $status = false;
                } else {
                    $errorstr = "Neither a new course or an existing one was specified.";
                    return false;
                }
            }
        }
    }
    //Now create metacourse info
    if ($status and $restore->metacourse) {
        //Only to new courses!
        if ($restore->restoreto == RESTORETO_NEW_COURSE) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>" . get_string("creatingmetacoursedata");
            }
            if (!($status = restore_create_metacourse($restore, $xml_file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Error creating metacourse in the course.");
                } else {
                    $errorstr = "Error creating metacourse in the course.";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
        }
    }
    //Now create categories and questions as needed
    if ($status) {
        include_once "{$CFG->dirroot}/question/restorelib.php";
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingcategoriesandquestions");
            echo "<ul>";
        }
        if (!($status = restore_create_questions($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore categories and questions!");
            } else {
                $errorstr = "Could not restore categories and questions!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</ul></li>";
        }
    }
    //Now create user_files as needed
    if ($status and $restore->user_files) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("copyinguserfiles");
        }
        if (!($status = restore_user_files($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore user files!");
            } else {
                $errorstr = "Could not restore user files!";
                return false;
            }
        }
        //If all is ok (and we have a counter)
        if ($status and $status !== true) {
            //Inform about user dirs created from backup
            if (!defined('RESTORE_SILENTLY')) {
                echo "<ul>";
                echo "<li>" . get_string("userzones") . ": " . $status;
                echo "</li></ul>";
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create course files as needed
    if ($status and $restore->course_files) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("copyingcoursefiles");
        }
        if (!($status = restore_course_files($restore))) {
            if (empty($status)) {
                notify("Could not restore course files!");
            } else {
                $errorstr = "Could not restore course files!";
                return false;
            }
        }
        //If all is ok (and we have a counter)
        if ($status and $status !== true) {
            //Inform about user dirs created from backup
            if (!defined('RESTORE_SILENTLY')) {
                echo "<ul>";
                echo "<li>" . get_string("filesfolders") . ": " . $status . '</li>';
                echo "</ul>";
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</li>";
        }
    }
    //Now create site files as needed
    if ($status and $restore->site_files) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string('copyingsitefiles');
        }
        if (!($status = restore_site_files($restore))) {
            if (empty($status)) {
                notify("Could not restore site files!");
            } else {
                $errorstr = "Could not restore site files!";
                return false;
            }
        }
        //If all is ok (and we have a counter)
        if ($status and $status !== true) {
            //Inform about user dirs created from backup
            if (!defined('RESTORE_SILENTLY')) {
                echo "<ul>";
                echo "<li>" . get_string("filesfolders") . ": " . $status . '</li>';
                echo "</ul>";
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</li>";
        }
    }
    //Now create messages as needed
    if ($status and $restore->messages) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingmessagesinfo");
        }
        if (!($status = restore_create_messages($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore messages!");
            } else {
                $errorstr = "Could not restore messages!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</li>";
        }
    }
    //Now create blogs as needed
    if ($status and $restore->blogs) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingblogsinfo");
        }
        if (!($status = restore_create_blogs($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore blogs!");
            } else {
                $errorstr = "Could not restore blogs!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo "</li>";
        }
    }
    //Now create scales as needed
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingscales");
        }
        if (!($status = restore_create_scales($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore custom scales!");
            } else {
                $errorstr = "Could not restore custom scales!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create events as needed
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingevents");
        }
        if (!($status = restore_create_events($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore course events!");
            } else {
                $errorstr = "Could not restore course events!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create course modules as needed
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatingcoursemodules");
        }
        if (!($status = restore_create_modules($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore modules!");
            } else {
                $errorstr = "Could not restore modules!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Bring back the course blocks -- do it AFTER the modules!!!
    if ($status) {
        //If we are deleting and bringing into a course or making a new course, same situation
        if ($restore->restoreto == RESTORETO_CURRENT_DELETING || $restore->restoreto == RESTORETO_EXISTING_DELETING || $restore->restoreto == RESTORETO_NEW_COURSE) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('creatingblocks');
            }
            $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
            if (!($status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify('Error while creating the course blocks');
                } else {
                    $errorstr = "Error while creating the course blocks";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
        }
    }
    if ($status) {
        //If we are deleting and bringing into a course or making a new course, same situation
        if ($restore->restoreto == RESTORETO_CURRENT_DELETING || $restore->restoreto == RESTORETO_EXISTING_DELETING || $restore->restoreto == RESTORETO_NEW_COURSE) {
            if (!defined('RESTORE_SILENTLY')) {
                echo '<li>' . get_string('courseformatdata');
            }
            if (!($status = restore_set_format_data($restore, $xml_file))) {
                $error = "Error while setting the course format data";
                if (!defined('RESTORE_SILENTLY')) {
                    notify($error);
                } else {
                    $errorstr = $error;
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
        }
    }
    //Now create log entries as needed
    if ($status and $restore->logs) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("creatinglogentries");
        }
        if (!($status = restore_create_logs($restore, $xml_file))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not restore logs!");
            } else {
                $errorstr = "Could not restore logs!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now, if all is OK, adjust the instance field in course_modules !!
    //this also calculates the final modinfo information so, after this,
    //code needing it can be used (like role_assignments. MDL-13740)
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("checkinginstances");
        }
        if (!($status = restore_check_instances($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not adjust instances in course_modules!");
            } else {
                $errorstr = "Could not adjust instances in course_modules!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now, if all is OK, adjust activity events
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("refreshingevents");
        }
        if (!($status = restore_refresh_events($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not refresh events for activities!");
            } else {
                $errorstr = "Could not refresh events for activities!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now, if all is OK, adjust inter-activity links
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("decodinginternallinks");
        }
        if (!($status = restore_decode_content_links($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not decode content links!");
            } else {
                $errorstr = "Could not decode content links!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now, with backup files prior to version 2005041100,
    //convert all the wiki texts in the course to markdown
    if ($status && $restore->backup_version < 2005041100) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("convertingwikitomarkdown");
        }
        if (!($status = restore_convert_wiki2markdown($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not convert wiki texts to markdown!");
            } else {
                $errorstr = "Could not convert wiki texts to markdown!";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Now create gradebook as needed -- AFTER modules and blocks!!!
    if ($status) {
        if ($restore->backup_version > 2007090500) {
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>" . get_string("creatinggradebook");
            }
            if (!($status = restore_create_gradebook($restore, $xml_file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not restore gradebook!");
                } else {
                    $errorstr = "Could not restore gradebook!";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
        } else {
            // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
            // this code needs to execute *after* the course_modules are sorted out
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>" . get_string("migratinggrades");
            }
            /// force full refresh of grading data before migration == crete all items first
            if (!($status = restore_migrate_old_gradebook($restore, $xml_file))) {
                if (!defined('RESTORE_SILENTLY')) {
                    notify("Could not migrate gradebook!");
                } else {
                    $errorstr = "Could not migrade gradebook!";
                    return false;
                }
            }
            if (!defined('RESTORE_SILENTLY')) {
                echo '</li>';
            }
        }
        /// force full refresh of grading data after all items are created
        grade_force_full_regrading($restore->course_id);
        grade_grab_course_grades($restore->course_id);
    }
    /*******************************************************************************
     ************* Restore of Roles and Capabilities happens here ******************
     *******************************************************************************/
    // try to restore roles even when restore is going to fail - teachers might have
    // at least some role assigned - this is not correct though
    $status = restore_create_roles($restore, $xml_file) && $status;
    $status = restore_roles_settings($restore, $xml_file) && $status;
    //Now if all is OK, update:
    //   - course modinfo field
    //   - categories table
    //   - add user as teacher
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("checkingcourse");
        }
        //categories table
        $course = get_record("course", "id", $restore->course_id);
        fix_course_sortorder();
        // Check if the user has course update capability in the newly restored course
        // there is no need to load his capabilities again, because restore_roles_settings
        // would have loaded it anyway, if there is any assignments.
        // fix for MDL-6831
        $newcontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
        if (!has_capability('moodle/course:manageactivities', $newcontext)) {
            // fix for MDL-9065, use the new config setting if exists
            if ($CFG->creatornewroleid) {
                role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
            } else {
                if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM))) {
                    if ($legacyteacher = array_shift($legacyteachers)) {
                        role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
                    }
                } else {
                    notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
                }
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    //Cleanup temps (files and db)
    if ($status) {
        if (!defined('RESTORE_SILENTLY')) {
            echo "<li>" . get_string("cleaningtempdata");
        }
        if (!($status = clean_temp_data($restore))) {
            if (!defined('RESTORE_SILENTLY')) {
                notify("Could not clean up temporary data from files and database");
            } else {
                $errorstr = "Could not clean up temporary data from files and database";
                return false;
            }
        }
        if (!defined('RESTORE_SILENTLY')) {
            echo '</li>';
        }
    }
    // this is not a critical check - the result can be ignored
    if (restore_close_html($restore)) {
        if (!defined('RESTORE_SILENTLY')) {
            echo '<li>Closing the Restorelog.html file.</li>';
        }
    } else {
        if (!defined('RESTORE_SILENTLY')) {
            notify("Could not close the restorelog.html file");
        }
    }
    if (!defined('RESTORE_SILENTLY')) {
        //End the main ul
        echo "</ul>";
        //End the main table
        echo "</td></tr>";
        echo "</table>";
    }
    return $status;
}
Example #29
0
 // mod or block (or group?)
 /************************************************************************
  *                                                                      *
  * context level is above or equal course context level                 *
  * in this case we pull out all users matching search criteria (if any) *
  *                                                                      *
  * MDL-11324                                                            *
  * a mini get_users_by_capability() call here, this is done instead of  *
  * get_users_by_capability() because                                    *
  * 1) get_users_by_capability() does not deal with searching by name    *
  * 2) exceptions array can be potentially large for large courses       *
  * 3) get_recordset_sql() is more efficient                             *
  *                                                                      *
  ************************************************************************/
 if ($possibleroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
     $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM));
     $validroleids = array();
     foreach ($possibleroles as $possiblerole) {
         if (isset($doanythingroles[$possiblerole->id])) {
             // We don't want these included
             continue;
         }
         if ($caps = role_context_capabilities($possiblerole->id, $context, 'moodle/course:view')) {
             // resolved list
             if (isset($caps['moodle/course:view']) && $caps['moodle/course:view'] > 0) {
                 // resolved capability > 0
                 $validroleids[] = $possiblerole->id;
             }
         }
     }
     if ($validroleids) {
Example #30
-1
function forum_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    if ($oldversion < 2002073008) {
        execute_sql("DELETE FROM modules WHERE name = 'discuss' ");
        execute_sql("ALTER TABLE `discuss` RENAME `forum_discussions` ");
        execute_sql("ALTER TABLE `discuss_posts` RENAME `forum_posts` ");
        execute_sql("ALTER TABLE `discuss_ratings` RENAME `forum_ratings` ");
        execute_sql("ALTER TABLE `forum` CHANGE `intro` `intro` TEXT NOT NULL ");
        execute_sql("ALTER TABLE `forum` ADD `forcesubscribe` TINYINT(1) UNSIGNED DEFAULT '0' NOT NULL AFTER `assessed`");
        execute_sql("ALTER TABLE `forum` CHANGE `type` `type` ENUM( 'single', 'news', 'social', 'general', \n                             'eachuser', 'teacher' ) DEFAULT 'general' NOT NULL ");
        execute_sql("ALTER TABLE `forum_posts` CHANGE `discuss` `discussion` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name') ");
        execute_sql("DELETE FROM log_display WHERE module = 'discuss' ");
        execute_sql("UPDATE log SET action = 'view discussion' WHERE module = 'discuss' AND action = 'view' ");
        execute_sql("UPDATE log SET action = 'add discussion' WHERE module = 'discuss' AND action = 'add' ");
        execute_sql("UPDATE log SET module = 'forum' WHERE module = 'discuss' ");
        notify("Renamed all the old discuss tables (now part of forum) and created new forum_types");
    }
    if ($oldversion < 2002080100) {
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name') ");
        execute_sql("INSERT INTO log_display (module, action, mtable, field) VALUES ('forum', 'update', 'forum', 'name') ");
    }
    if ($oldversion < 2002082900) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002091000) {
        if (!execute_sql(" ALTER TABLE `forum_posts` ADD `attachment` VARCHAR(100) NOT NULL AFTER `message` ")) {
            echo "<p>Don't worry about this error - your server already had this upgrade applied";
        }
    }
    if ($oldversion < 2002100300) {
        execute_sql(" ALTER TABLE `forum` CHANGE `open` `open` TINYINT(2) UNSIGNED DEFAULT '2' NOT NULL ");
        execute_sql(" UPDATE `forum` SET `open` = 2 WHERE `open` = 1 ");
        execute_sql(" UPDATE `forum` SET `open` = 1 WHERE `open` = 0 ");
    }
    if ($oldversion < 2002101001) {
        execute_sql(" ALTER TABLE `forum_posts` ADD `format` TINYINT(2) UNSIGNED DEFAULT '0' NOT NULL AFTER `message` ");
    }
    if ($oldversion < 2002122300) {
        execute_sql("ALTER TABLE `forum_posts` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_ratings` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
        execute_sql("ALTER TABLE `forum_subscriptions` CHANGE `user` `userid` INT(10) UNSIGNED DEFAULT '0' NOT NULL ");
    }
    if ($oldversion < 2003042402) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name')");
    }
    if ($oldversion < 2003081403) {
        table_column("forum", "assessed", "assessed", "integer", "10", "unsigned", "0");
    }
    if ($oldversion < 2003082500) {
        table_column("forum", "", "assesstimestart", "integer", "10", "unsigned", "0", "", "assessed");
        table_column("forum", "", "assesstimefinish", "integer", "10", "unsigned", "0", "", "assesstimestart");
    }
    if ($oldversion < 2003082502) {
        table_column("forum", "scale", "scale", "integer", "10", "", "0");
        execute_sql("UPDATE {$CFG->prefix}forum SET scale = (- scale)");
    }
    if ($oldversion < 2003100600) {
        table_column("forum", "", "maxbytes", "integer", "10", "unsigned", "0", "", "scale");
    }
    if ($oldversion < 2004010100) {
        table_column("forum", "", "assesspublic", "integer", "4", "unsigned", "0", "", "assessed");
    }
    if ($oldversion < 2004011404) {
        table_column("forum_discussions", "", "userid", "integer", "10", "unsigned", "0", "", "firstpost");
        if ($discussions = get_records_sql("SELECT d.id, p.userid\n                                            FROM {$CFG->prefix}forum_discussions as d, \n                                                 {$CFG->prefix}forum_posts as p\n                                           WHERE d.firstpost = p.id")) {
            foreach ($discussions as $discussion) {
                update_record("forum_discussions", $discussion);
            }
        }
    }
    if ($oldversion < 2004012200) {
        table_column("forum_discussions", "", "groupid", "integer", "10", "unsigned", "0", "", "userid");
    }
    if ($oldversion < 2004013000) {
        table_column("forum_posts", "mailed", "mailed", "tinyint", "2");
    }
    if ($oldversion < 2004020600) {
        table_column("forum_discussions", "", "usermodified", "integer", "10", "unsigned", "0", "", "timemodified");
    }
    if ($oldversion < 2004050300) {
        table_column("forum", "", "rsstype", "tinyint", "2", "unsigned", "0", "", "forcesubscribe");
        table_column("forum", "", "rssarticles", "tinyint", "2", "unsigned", "0", "", "rsstype");
        set_config("forum_enablerssfeeds", 0);
    }
    if ($oldversion < 2004060100) {
        modify_database('', "CREATE TABLE `prefix_forum_queue` (\n                                `id` int(11) unsigned NOT NULL auto_increment,\n                                `userid` int(11) unsigned default 0 NOT NULL,\n                                `discussionid` int(11) unsigned default 0 NOT NULL,\n                                `postid` int(11) unsigned default 0 NOT NULL,\n                                PRIMARY KEY  (`id`),\n                                KEY `user` (userid),\n                                KEY `post` (postid)\n                              ) TYPE=MyISAM COMMENT='For keeping track of posts that will be mailed in digest form';");
    }
    if ($oldversion < 2004070700) {
        // This may be redoing it from STABLE but that's OK
        table_column("forum_discussions", "groupid", "groupid", "integer", "10", "", "0", "");
    }
    if ($oldversion < 2004111700) {
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_parent_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_discussion_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` DROP INDEX {$CFG->prefix}forum_posts_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_forum_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` DROP INDEX {$CFG->prefix}forum_discussions_userid_idx;", false);
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_parent_idx (parent) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_discussion_idx (discussion) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_posts` ADD INDEX {$CFG->prefix}forum_posts_userid_idx (userid) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_forum_idx (forum) ");
        execute_sql(" ALTER TABLE `{$CFG->prefix}forum_discussions` ADD INDEX {$CFG->prefix}forum_discussions_userid_idx (userid) ");
    }
    if ($oldversion < 2004111700) {
        execute_sql("ALTER TABLE {$CFG->prefix}forum DROP INDEX course;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_ratings DROP INDEX post;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX userid;", false);
        execute_sql("ALTER TABLE {$CFG->prefix}forum_subscriptions DROP INDEX forum;", false);
        modify_database('', 'ALTER TABLE prefix_forum ADD INDEX course (course);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_ratings ADD INDEX post (post);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX userid (userid);');
        modify_database('', 'ALTER TABLE prefix_forum_subscriptions ADD INDEX forum (forum);');
    }
    if ($oldversion < 2005011500) {
        modify_database('', 'CREATE TABLE prefix_forum_read (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  `discussionid` int(10) NOT NULL default \'0\',
                  `postid` int(10) NOT NULL default \'0\',
                  `firstread` int(10) NOT NULL default \'0\',
                  `lastread` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `prefix_forum_user_forum_idx` (`userid`,`forumid`),
                  KEY `prefix_forum_user_discussion_idx` (`userid`,`discussionid`),
                  KEY `prefix_forum_user_post_idx` (`userid`,`postid`)
                  ) COMMENT=\'Tracks each users read posts\';');
        set_config('upgrade', 'forumread');
        // The upgrade of this table will be done later by admin/upgradeforumread.php
    }
    if ($oldversion < 2005032900) {
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_created_idx (created);');
        modify_database('', 'ALTER TABLE prefix_forum_posts ADD INDEX prefix_form_posts_mailed_idx (mailed);');
    }
    if ($oldversion < 2005041100) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}forum_discussions, {$CFG->prefix}forum_posts ";
        $sql .= "where {$CFG->prefix}forum_posts.discussion = {$CFG->prefix}forum_discussions.id ";
        $sql .= "and {$CFG->prefix}forum_posts.id = ";
        $wtm->update('forum_posts', 'message', 'format', $sql);
    }
    if ($oldversion < 2005042300) {
        // Add tracking prefs table
        modify_database('', 'CREATE TABLE prefix_forum_track_prefs (
                  `id` int(10) unsigned NOT NULL auto_increment, 
                  `userid` int(10) NOT NULL default \'0\',
                  `forumid` int(10) NOT NULL default \'0\',
                  PRIMARY KEY  (`id`),
                  KEY `user_forum_idx` (`userid`,`forumid`)
                  ) COMMENT=\'Tracks each users untracked forums.\';');
    }
    if ($oldversion < 2005042500) {
        table_column('forum', '', 'trackingtype', 'tinyint', '2', 'unsigned', '1', '', 'forcesubscribe');
    }
    if ($oldversion < 2005111100) {
        table_column('forum_discussions', '', 'timestart', 'integer');
        table_column('forum_discussions', '', 'timeend', 'integer');
    }
    if ($oldversion < 2006011600) {
        execute_sql("alter table " . $CFG->prefix . "forum change column type type enum('single','news','general','social','eachuser','teacher','qanda') not null default 'general'");
    }
    if ($oldversion < 2006011601) {
        table_column('forum', '', 'warnafter');
        table_column('forum', '', 'blockafter');
        table_column('forum', '', 'blockperiod');
    }
    if ($oldversion < 2006011700) {
        table_column('forum_posts', '', 'mailnow', 'integer');
    }
    if ($oldversion < 2006011702) {
        execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'CONCAT(firstname,\\' \\',lastname)')");
    }
    if ($oldversion < 2006081800) {
        // Upgrades for new roles and capabilities support.
        require_once $CFG->dirroot . '/mod/forum/lib.php';
        $forummod = get_record('modules', 'name', 'forum');
        if ($forums = get_records('forum')) {
            if (!($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW))) {
                notify('Default teacher role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW))) {
                notify('Default student role was not found. Roles and permissions ' . 'for all your forums will have to be manually set after ' . 'this upgrade.');
            }
            if (!($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW))) {
                notify('Default guest role was not found. Roles and permissions ' . 'for teacher forums will have to be manually set after ' . 'this upgrade.');
            }
            foreach ($forums as $forum) {
                if (!forum_convert_to_roles($forum, $forummod->id, $teacherroles, $studentroles, $guestroles)) {
                    notify('Forum with id ' . $forum->id . ' was not upgraded');
                }
            }
            // We need to rebuild all the course caches to refresh the state of
            // the forum modules.
            include_once "{$CFG->dirroot}/course/lib.php";
            rebuild_course_cache();
        }
        // End if.
        // Drop column forum.open.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN open;');
        // Drop column forum.assesspublic.
        modify_database('', 'ALTER TABLE prefix_forum DROP COLUMN assesspublic;');
    }
    if ($oldversion < 2006082700) {
        $sql = "UPDATE {$CFG->prefix}forum_posts SET message = REPLACE(message, '" . TRUSTTEXT . "', '');";
        $likecond = sql_ilike() . " '%" . TRUSTTEXT . "%'";
        while (true) {
            if (!count_records_select('forum_posts', "message {$likecond}")) {
                break;
            }
            execute_sql($sql);
        }
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return true;
}