Пример #1
0
function xmldb_oublog_install()
{
    global $DB, $CFG;
    require_once $CFG->dirroot . '/course/lib.php';
    // Setup the global blog.
    $oublog = new stdClass();
    $oublog->course = SITEID;
    $oublog->name = 'Personal Blogs';
    $oublog->intro = '';
    $oublog->introformat = FORMAT_HTML;
    $oublog->accesstoken = md5(uniqid(rand(), true));
    $oublog->maxvisibility = 300;
    // OUBLOG_VISIBILITY_PUBLIC.
    $oublog->global = 1;
    $oublog->allowcomments = 2;
    // OUBLOG_COMMENTS_ALLOWPUBLIC.
    if (!($oublog->id = $DB->insert_record('oublog', $oublog))) {
        return false;
    }
    $mod = new stdClass();
    $mod->course = SITEID;
    $mod->module = $DB->get_field('modules', 'id', array('name' => 'oublog'));
    $mod->instance = $oublog->id;
    $mod->visible = 1;
    $mod->visibleold = 0;
    $mod->section = 1;
    if (!($cm = add_course_module($mod))) {
        return true;
    }
    set_config('oublogsetup', null);
    // For unit tests to work, it's necessary to create context now.
    context_module::instance($cm);
    return true;
}
Пример #2
0
 /**
  * Create a course module object.
  *
  * @param  stdClass $course     The course to apply to.
  * @param  stdClass $section    The section to apply to.
  * @param  stdClass $module     The module to apply to.
  * @param  stdClass $instance   The instance to apply to.
  * @param  stdClass $data       The original data we extracted.
  */
 private function create_cm($course, $section, $module, $instance, $data)
 {
     // Create a module container.
     $cm = new \stdClass();
     $cm->course = $course->id;
     $cm->module = $module->id;
     $cm->instance = $instance->id;
     $cm->section = $section->id;
     $cm->visible = 1;
     if (isset($data->showdescription)) {
         $cm->showdescription = $data->showdescription;
     }
     // Create the module.
     $cm->id = add_course_module($cm);
     return $cm;
 }
 function add_instance($resource)
 {
     $result = parent::add_instance($resource);
     $entry = new kaltura_entry();
     $entry->entry_id = $resource->alltext;
     $entry->dimensions = $_POST['dimensions'];
     $entry->size = $_POST['size'];
     $entry->custom_width = $_POST['custom_width'];
     $entry->design = $_POST['design'];
     $entry->title = $_POST['title'];
     $entry->context = "R_" . $result;
     $entry->entry_type = KalturaEntryType::DOCUMENT;
     $entry->media_type = KalturaMediaType::VIDEO;
     $entry->id = insert_record('kaltura_entries', $entry);
     //for backup we need a to tell moolde that kaltura is connected to this course
     $mod = new object();
     $mod->course = $this->course->id;
     $mod->module = get_field('modules', 'id', 'name', 'kaltura');
     $mod->instance = $entry->id;
     $mod->section = 0;
     add_course_module($mod);
     return $result;
 }
Пример #4
0
 /**
  *
  * @param unknown $user
  * @param unknown $courseid
  * @param unknown $sectionid
  * @param unknown $itemUuid
  * @param unknown $itemVersion
  * @param unknown $url
  * @param unknown $title
  * @param unknown $description
  * @param unknown $attachmentUuid
  * @return array
  */
 public static function add_item_to_course($username, $courseid, $sectionnum, $itemUuid, $itemVersion, $url, $title, $description, $attachmentUuid)
 {
     global $DB, $USER;
     $params = self::validate_parameters(self::add_item_to_course_parameters(), array('user' => $username, 'courseid' => $courseid, 'sectionid' => $sectionnum, 'itemUuid' => $itemUuid, 'itemVersion' => $itemVersion, 'url' => $url, 'title' => $title, 'description' => $description, 'attachmentUuid' => $attachmentUuid));
     self::check_modify_permissions($username, $courseid);
     $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
     $modname = 'equella';
     $module = $DB->get_record('modules', array('name' => $modname));
     $eq = new stdClass();
     $eq->course = $courseid;
     $eq->module = $module->id;
     $eq->name = $title;
     $eq->intro = $description;
     $eq->introformat = FORMAT_HTML;
     $eq->url = $url;
     $eq->uuid = $itemUuid;
     $eq->version = $itemVersion;
     $eq->mimetype = mimeinfo('type', $title);
     if (!empty($attachmentUuid)) {
         $eq->filename = $title;
         $eq->attachmentuuid = $attachmentUuid;
     }
     $eqid = equella_add_instance($eq);
     $cmid = null;
     $mod = new stdClass();
     $mod->course = $courseid;
     $mod->module = $module->id;
     $mod->instance = $eqid;
     $mod->modulename = $modname;
     $mod->section = 0;
     if (!($cmid = add_course_module($mod))) {
         throw new moodle_exception('cannotaddcoursemodule');
     }
     if (!($addedsectionid = course_add_cm_to_section($courseid, $cmid, $sectionnum))) {
         throw new moodle_exception('cannotaddcoursemoduletosection');
     }
     set_coursemodule_visible($cmid, true);
     if (class_exists('core\\event\\course_module_created')) {
         $cm = get_coursemodule_from_id('equella', $cmid, 0, false, MUST_EXIST);
         $event = \core\event\course_module_created::create_from_cm($cm);
         $event->trigger();
     } else {
         $eventdata = new stdClass();
         $eventdata->modulename = $modname;
         $eventdata->name = $eq->name;
         $eventdata->cmid = $cmid;
         $eventdata->courseid = $eq->course;
         $eventdata->userid = $USER->id;
         events_trigger('mod_created', $eventdata);
         add_to_log($eq->course, "course", "add mod", "../mod/{$modname}/view.php?id={$cmid}", "{$modname} {$eqid}");
         add_to_log($eq->course, $modname, "add equella resource", "view.php?id={$cmid}", "{$eqid}", $cmid);
     }
     $result = array('courseid' => $courseid, 'coursename' => $course->fullname, 'sectionid' => $params['sectionid'], 'sectionname' => get_section_name($courseid, $sectionnum));
     //flog("DB queries: " . $DB->perf_get_queries());
     return $result;
 }
Пример #5
0
function assignment_type_online_upgrade($oldversion)
{
    global $CFG, $db;
    if ($oldversion < 2005042900 and empty($CFG->noconvertjournals)) {
        // Phase out Journals, convert them
        $affectedcourses = array();
        // to Online Assignment
        if ($journals = get_records('journal')) {
            require_once $CFG->dirroot . '/course/lib.php';
            $assignmentmodule = get_record('modules', 'name', 'assignment');
            foreach ($journals as $journal) {
                $affectedcourses[$journal->course] = $journal->course;
                /// First create the assignment instance
                $assignment = new object();
                $assignment->course = $journal->course;
                $assignment->name = addslashes($journal->name);
                $assignment->description = addslashes($journal->intro);
                $assignment->format = FORMAT_MOODLE;
                $assignment->assignmenttype = 'online';
                $assignment->resubmit = 1;
                $assignment->preventlate = 0;
                $assignment->emailteachers = 0;
                $assignment->var1 = 1;
                $assignment->var2 = 0;
                $assignment->var3 = 0;
                $assignment->var4 = 0;
                $assignment->var5 = 0;
                $assignment->var5 = 0;
                $assignment->maxbytes = 0;
                $assignment->timedue = 0;
                /// Don't have time to work this out .... :-(
                $assignment->timeavailable = 0;
                $assignment->grade = $journal->assessed;
                $assignment->timemodified = $journal->timemodified;
                $assignment->id = insert_record('assignment', $assignment);
                /// Now create a new course module record
                $oldcm = get_coursemodule_from_instance('journal', $journal->id, $journal->course);
                $newcm = clone $oldcm;
                $newcm->module = $assignmentmodule->id;
                $newcm->instance = $assignment->id;
                $newcm->added = time();
                if (!($newcm->id = add_course_module($newcm))) {
                    error("Could not add a new course module");
                }
                /// And locate it above the old one
                if (!($section = get_record('course_sections', 'id', $oldcm->section))) {
                    $section->section = 0;
                    // So it goes somewhere!
                }
                $newcm->coursemodule = $newcm->id;
                $newcm->section = $section->section;
                // need relative reference
                if (!($sectionid = add_mod_to_section($newcm, $oldcm))) {
                    // Add it before Journal
                    error("Could not add the new course module to that section");
                }
                /// Convert any existing entries from users
                if ($entries = get_records('journal_entries', 'journal', $journal->id)) {
                    foreach ($entries as $entry) {
                        $submission = new object();
                        $submission->assignment = $assignment->id;
                        $submission->userid = $entry->userid;
                        $submission->timecreated = $entry->modified;
                        $submission->timemodified = $entry->modified;
                        $submission->numfiles = 0;
                        $submission->data1 = addslashes($entry->text);
                        $submission->data2 = $entry->format;
                        $submission->grade = $entry->rating;
                        $submission->submissioncomment = addslashes($entry->comment);
                        $submission->format = FORMAT_MOODLE;
                        $submission->teacher = $entry->teacher;
                        $submission->timemarked = $entry->timemarked;
                        $submission->mailed = $entry->mailed;
                        $submission->id = insert_record('assignment_submissions', $submission);
                    }
                }
            }
            /// Clear the cache so this stuff appears
            foreach ($affectedcourses as $courseid) {
                rebuild_course_cache($courseid);
            }
        }
        /// Hide the whole Journal module (but not individual items, just to make undo easier)
        set_field('modules', 'visible', 0, 'name', 'journal');
        if ($journals === false) {
            notify('The Journal module is becoming obsolete and being replaced by the superior Online Assignments, and  
                    it has been disabled on your site.  If you really want Journal back, you can enable it using the 
                    "eye" icon here:  Admin >> Modules >> Journal.');
        } else {
            notify('The Journal module is becoming obsolete and being replaced by the superior Online Assignments.  
                    It has been disabled on your site, and the ' . count($journals) . ' Journal activites you had have been
                    converted into Online Assignments.  If you really want Journal back, you can enable it using the 
                    "eye" icon here:  Admin >> Modules >> Journal.');
        }
    }
    return true;
}
Пример #6
0
/**
 * @global object
 * @global object
 * @param int $courseid
 * @param string $type
 */
function forum_get_course_forum($courseid, $type)
{
    // How to set up special 1-per-course forums
    global $CFG, $DB, $OUTPUT, $USER;
    if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
        // There should always only be ONE, but with the right combination of
        // errors there might be more.  In this case, just return the oldest one (lowest ID).
        foreach ($forums as $forum) {
            return $forum;
            // ie the first one
        }
    }
    // Doesn't exist, so create one now.
    $forum = new stdClass();
    $forum->course = $courseid;
    $forum->type = "{$type}";
    if (!empty($USER->htmleditor)) {
        $forum->introformat = $USER->htmleditor;
    }
    switch ($forum->type) {
        case "news":
            $forum->name = get_string("namenews", "forum");
            $forum->intro = get_string("intronews", "forum");
            $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
            $forum->assessed = 0;
            if ($courseid == SITEID) {
                $forum->name = get_string("sitenews");
                $forum->forcesubscribe = 0;
            }
            break;
        case "social":
            $forum->name = get_string("namesocial", "forum");
            $forum->intro = get_string("introsocial", "forum");
            $forum->assessed = 0;
            $forum->forcesubscribe = 0;
            break;
        case "blog":
            $forum->name = get_string('blogforum', 'forum');
            $forum->intro = get_string('introblog', 'forum');
            $forum->assessed = 0;
            $forum->forcesubscribe = 0;
            break;
        default:
            echo $OUTPUT->notification("That forum type doesn't exist!");
            return false;
            break;
    }
    $forum->timemodified = time();
    $forum->id = $DB->insert_record("forum", $forum);
    if (!($module = $DB->get_record("modules", array("name" => "forum")))) {
        echo $OUTPUT->notification("Could not find forum module!!");
        return false;
    }
    $mod = new stdClass();
    $mod->course = $courseid;
    $mod->module = $module->id;
    $mod->instance = $forum->id;
    $mod->section = 0;
    include_once "{$CFG->dirroot}/course/lib.php";
    if (!($mod->coursemodule = add_course_module($mod))) {
        echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
        return false;
    }
    $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
    return $DB->get_record("forum", array("id" => "{$forum->id}"));
}
Пример #7
0
         die;
     }
     error("Could not add a new instance of {$mod->modulename}", "view.php?id={$course->id}");
 }
 if (is_string($return)) {
     error($return, "view.php?id={$course->id}");
 }
 if (!isset($mod->groupmode)) {
     // to deal with pre-1.5 modules
     $mod->groupmode = $course->groupmode;
     /// Default groupmode the same as course
 }
 $mod->instance = $return;
 // course_modules and course_sections each contain a reference
 // to each other, so we have to update one of them twice.
 if (!($mod->coursemodule = add_course_module($mod))) {
     error("Could not add a new course module");
 }
 if (!($sectionid = add_mod_to_section($mod))) {
     error("Could not add the new course module to that section");
 }
 if (!set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
     error("Could not update the course module with the correct section");
 }
 if (!isset($mod->visible)) {
     // We get the section's visible field status
     $mod->visible = get_field("course_sections", "visible", "id", $sectionid);
 }
 // make sure visibility is set correctly (in particular in calendar)
 set_coursemodule_visible($mod->coursemodule, $mod->visible);
 if (isset($mod->redirect)) {
Пример #8
0
 /**
  * Create the coursemodule to hold the file/content that has been uploaded
  */
 protected function create_course_module()
 {
     global $CFG;
     if (!course_allowed_module($this->course, $this->module->name)) {
         throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
     }
     $this->cm = new stdClass();
     $this->cm->course = $this->course->id;
     $this->cm->section = $this->section;
     $this->cm->module = $this->module->id;
     $this->cm->modulename = $this->module->name;
     $this->cm->instance = 0;
     // This will be filled in after we create the instance.
     $this->cm->visible = 1;
     $this->cm->groupmode = $this->course->groupmode;
     $this->cm->groupingid = $this->course->defaultgroupingid;
     // Set the correct default for completion tracking.
     $this->cm->completion = COMPLETION_TRACKING_NONE;
     $completion = new completion_info($this->course);
     if ($completion->is_enabled() && $CFG->completiondefault) {
         if (plugin_supports('mod', $this->cm->modulename, FEATURE_MODEDIT_DEFAULT_COMPLETION, true)) {
             $this->cm->completion = COMPLETION_TRACKING_MANUAL;
         }
     }
     if (!($this->cm->id = add_course_module($this->cm))) {
         throw new coding_exception("Unable to create the course module");
     }
     $this->cm->coursemodule = $this->cm->id;
 }
Пример #9
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;
}
Пример #10
0
 /**
  * Create the coursemodule to hold the file/content that has been uploaded
  */
 protected function create_course_module()
 {
     if (!course_allowed_module($this->course, $this->module->name)) {
         throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
     }
     $this->cm = new stdClass();
     $this->cm->course = $this->course->id;
     $this->cm->section = $this->section;
     $this->cm->module = $this->module->id;
     $this->cm->modulename = $this->module->name;
     $this->cm->instance = 0;
     // This will be filled in after we create the instance.
     $this->cm->visible = 1;
     $this->cm->groupmode = $this->course->groupmode;
     $this->cm->groupingid = $this->course->defaultgroupingid;
     // Set the correct default for completion tracking.
     $this->cm->completion = COMPLETION_TRACKING_NONE;
     $completion = new completion_info($this->course);
     if ($completion->is_enabled()) {
         if (plugin_supports('mod', $this->cm->modulename, FEATURE_MODEDIT_DEFAULT_COMPLETION, true)) {
             $this->cm->completion = COMPLETION_TRACKING_MANUAL;
         }
     }
     if (!($this->cm->id = add_course_module($this->cm))) {
         throw new coding_exception("Unable to create the course module");
     }
     // The following are used inside some few core functions, so may as well set them here.
     $this->cm->coursemodule = $this->cm->id;
     $groupbuttons = ($this->course->groupmode or !$this->course->groupmodeforce);
     if ($groupbuttons and plugin_supports('mod', $this->module->name, FEATURE_GROUPS, 0)) {
         $this->cm->groupmodelink = !$this->course->groupmodeforce;
     } else {
         $this->cm->groupmodelink = false;
         $this->cm->groupmode = false;
     }
 }
Пример #11
0
function link_to_gdoc($name, $link, $type = null, $modtype = 'url')
{
    global $COURSE, $DB, $CFG, $USER;
    require_once "{$CFG->dirroot}/mod/{$modtype}/lib.php";
    //add
    $fromform = new stdClass();
    $newform = new stdClass();
    $mform = new MoodleQuickForm(null, 'POST', 'nothing');
    $module = $DB->get_record("modules", array('name' => $modtype));
    $course = $COURSE;
    $cw = get_course_section(0, $course->id);
    $cm = null;
    // fields for mdl_url
    $fromform->course = $course->id;
    $fromform->name = $name;
    $fromform->introformat = 0;
    $fromform->introeditor = 0;
    $fromform->externalurl = $link;
    /*    if ($type !== 'dir') {
            $fromform->display          = 6;
            $fromform->displayoptions = 'a:2:{s:10:"popupwidth";i:1024;s:11:"popupheight";i:768;}';
        } else {
    */
    $fromform->display = 0;
    $fromform->popupwidth = 1024;
    $fromform->popupheight = 768;
    $fromform->popupwidth = null;
    $fromform->popupheight = null;
    $fromform->displayoptions = 'a:1:{s:10:"printintro";i:0;}';
    //    }
    // fields for mdl_course_module
    $fromform->module = $module->id;
    $fromform->instance = '';
    $fromform->section = 0;
    // The section number itself - relative!!! (section column in course_sections)
    $fromform->idnumber = null;
    $fromform->score = 0;
    $fromform->indent = 0;
    $fromform->visible = 1;
    $fromform->visibleold = 1;
    $fromform->groupmode = $course->groupmode;
    $fromform->groupingid = 0;
    $fromform->groupmembersonly = 0;
    $fromform->completion = 0;
    $fromform->completionview = 0;
    $fromform->completionexpected = 0;
    $fromform->availablefrom = 0;
    $fromform->availableuntil = 0;
    $fromform->showavailability = 0;
    $fromform->showdescription = 0;
    $fromform->conditiongradegroup = array();
    $fromform->conditionfieldgroup = array();
    // fields for mdl_course_sections
    $fromform->summaryformat = 0;
    $fromform->modulename = clean_param($module->name, PARAM_SAFEDIR);
    // For safety
    //	$fromform->add              = 'resource';
    //	$fromform->type             = $type == 'dir' ? 'collection' : 'file';
    //	$fromform->return           = 0; //must be false if this is an add, go back to course view on cancel
    //    $fromform->coursemodule 	= '';
    //	$fromform->popup			= 'resizable=1,scrollbars=1,directories=1,location=1,menubar=1,toolbar=1,status=1,width=1024,height=768';
    //	require_login($course->id); // needed to setup proper $COURSE
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    require_capability('moodle/course:manageactivities', $context);
    if (!empty($course->groupmodeforce) or !isset($fromform->groupmode)) {
        $fromform->groupmode = 0;
        // do not set groupmode
    }
    if (!course_allowed_module($course, $fromform->modulename)) {
        print_error('moduledisable', '', '', $fromform->modulename);
    }
    // first add course_module record because we need the context
    $newcm = new stdClass();
    $newcm->course = $course->id;
    $newcm->module = $fromform->module;
    $newcm->instance = 0;
    // not known yet, will be updated later (this is similar to restore code)
    $newcm->visible = $fromform->visible;
    $newcm->groupmode = $fromform->groupmode;
    $newcm->groupingid = $fromform->groupingid;
    $newcm->groupmembersonly = $fromform->groupmembersonly;
    $completion = new completion_info($course);
    if ($completion->is_enabled()) {
        $newcm->completion = $fromform->completion;
        $newcm->completiongradeitemnumber = $fromform->completiongradeitemnumber;
        $newcm->completionview = $fromform->completionview;
        $newcm->completionexpected = $fromform->completionexpected;
    }
    if (!empty($CFG->enableavailability)) {
        $newcm->availablefrom = $fromform->availablefrom;
        $newcm->availableuntil = $fromform->availableuntil;
        $newcm->showavailability = $fromform->showavailability;
    }
    if (isset($fromform->showdescription)) {
        $newcm->showdescription = $fromform->showdescription;
    } else {
        $newcm->showdescription = 0;
    }
    if (!($fromform->coursemodule = add_course_module($newcm))) {
        print_error('cannotaddcoursemodule');
    }
    if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) {
        $draftid_editor = file_get_submitted_draft_itemid('introeditor');
        file_prepare_draft_area($draftid_editor, null, null, null, null);
        $fromform->introeditor = array('text' => '', 'format' => FORMAT_HTML, 'itemid' => $draftid_editor);
        // TODO: add better default
    }
    if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) {
        $introeditor = $fromform->introeditor;
        unset($fromform->introeditor);
        $fromform->intro = $introeditor['text'];
        $fromform->introformat = $introeditor['format'];
    }
    $addinstancefunction = $fromform->modulename . "_add_instance";
    $updateinstancefunction = $fromform->modulename . "_update_instance";
    $returnfromfunc = $addinstancefunction($fromform, $mform);
    //	$returnfromfunc = url_add_instance($fromform, $mform);
    if (!$returnfromfunc or !is_number($returnfromfunc)) {
        // undo everything we can
        $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule);
        delete_context(CONTEXT_MODULE, $fromform->coursemodule);
        $DB->delete_records('course_modules', array('id' => $fromform->coursemodule));
        if (!is_number($returnfromfunc)) {
            print_error('invalidfunction', '', course_get_url($course, $cw->section));
        } else {
            print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $fromform->modulename);
        }
    }
    $fromform->instance = $returnfromfunc;
    $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $fromform->coursemodule));
    // update embedded links and save files
    $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule);
    if (!empty($introeditor)) {
        $fromform->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $fromform->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']);
        $DB->set_field($fromform->modulename, 'intro', $fromform->intro, array('id' => $fromform->instance));
    }
    // course_modules and course_sections each contain a reference
    // to each other, so we have to update one of them twice.
    $sectionid = add_mod_to_section($fromform);
    $DB->set_field('course_modules', 'section', $sectionid, array('id' => $fromform->coursemodule));
    // make sure visibility is set correctly (in particular in calendar)
    set_coursemodule_visible($fromform->coursemodule, $fromform->visible);
    if (isset($fromform->cmidnumber)) {
        //label
        // set cm idnumber
        set_coursemodule_idnumber($fromform->coursemodule, $fromform->cmidnumber);
    }
    // Set up conditions
    if ($CFG->enableavailability) {
        condition_info::update_cm_from_form((object) array('id' => $fromform->coursemodule), $fromform, false);
    }
    $eventname = 'mod_created';
    add_to_log($course->id, "course", "add mod", "../mod/{$fromform->modulename}/view.php?id={$fromform->coursemodule}", "{$fromform->modulename} {$fromform->instance}");
    add_to_log($course->id, $fromform->modulename, "add", "view.php?id={$fromform->coursemodule}", "{$fromform->instance}", $fromform->coursemodule);
    // Trigger mod_created/mod_updated event with information about this module.
    $eventdata = new stdClass();
    $eventdata->modulename = $fromform->modulename;
    $eventdata->name = $fromform->name;
    $eventdata->cmid = $fromform->coursemodule;
    $eventdata->courseid = $course->id;
    $eventdata->userid = $USER->id;
    events_trigger($eventname, $eventdata);
    rebuild_course_cache($course->id);
    return 1;
}
/**
 * Add course module.
 *
 * The function does not check user capabilities.
 * The function creates course module, module instance, add the module to the correct section.
 * It also trigger common action that need to be done after adding/updating a module.
 *
 * @param object $moduleinfo the moudle data
 * @param object $course the course of the module
 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
 * @return object the updated module info
 */
function local_ltiprovider_add_moduleinfo($moduleinfo, $course, $mform = null)
{
    global $DB, $CFG;
    $moduleinfo->course = $course->id;
    $moduleinfo = local_ltiprovider_set_moduleinfo_defaults($moduleinfo);
    if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
        $moduleinfo->groupmode = 0;
        // Do not set groupmode.
    }
    if (!course_allowed_module($course, $moduleinfo->modulename)) {
        print_error('moduledisable', '', '', $moduleinfo->modulename);
    }
    // First add course_module record because we need the context.
    $newcm = new stdClass();
    $newcm->course = $course->id;
    $newcm->module = $moduleinfo->module;
    $newcm->instance = 0;
    // Not known yet, will be updated later (this is similar to restore code).
    $newcm->visible = $moduleinfo->visible;
    $newcm->visibleold = $moduleinfo->visible;
    $newcm->groupmode = $moduleinfo->groupmode;
    $newcm->groupingid = $moduleinfo->groupingid;
    $newcm->groupmembersonly = $moduleinfo->groupmembersonly;
    $completion = new completion_info($course);
    if ($completion->is_enabled()) {
        $newcm->completion = $moduleinfo->completion;
        $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
        $newcm->completionview = $moduleinfo->completionview;
        $newcm->completionexpected = $moduleinfo->completionexpected;
    }
    if (!empty($CFG->enableavailability)) {
        $newcm->availablefrom = $moduleinfo->availablefrom;
        $newcm->availableuntil = $moduleinfo->availableuntil;
        $newcm->showavailability = $moduleinfo->showavailability;
    }
    if (isset($moduleinfo->showdescription)) {
        $newcm->showdescription = $moduleinfo->showdescription;
    } else {
        $newcm->showdescription = 0;
    }
    if (!($moduleinfo->coursemodule = add_course_module($newcm))) {
        print_error('cannotaddcoursemodule');
    }
    if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
        $introeditor = $moduleinfo->introeditor;
        unset($moduleinfo->introeditor);
        $moduleinfo->intro = $introeditor['text'];
        $moduleinfo->introformat = $introeditor['format'];
    }
    $addinstancefunction = $moduleinfo->modulename . "_add_instance";
    $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
    if (!$returnfromfunc or !is_number($returnfromfunc)) {
        // Undo everything we can.
        $modcontext = context_module::instance($moduleinfo->coursemodule);
        delete_context(CONTEXT_MODULE, $moduleinfo->coursemodule);
        $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule));
        if (!is_number($returnfromfunc)) {
            print_error('invalidfunction', '', course_get_url($course, $cw->section));
        } else {
            print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $moduleinfo->modulename);
        }
    }
    $moduleinfo->instance = $returnfromfunc;
    $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule));
    // Update embedded links and save files.
    $modcontext = context_module::instance($moduleinfo->coursemodule);
    if (!empty($introeditor)) {
        $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']);
        $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance));
    }
    // Course_modules and course_sections each contain a reference to each other.
    // So we have to update one of them twice.
    $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
    // Make sure visibility is set correctly (in particular in calendar).
    // Note: allow them to set it even without moodle/course:activityvisibility.
    set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible);
    if (isset($moduleinfo->cmidnumber)) {
        // Label.
        // Set cm idnumber - uniqueness is already verified by form validation.
        set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber);
    }
    // Set up conditions.
    if ($CFG->enableavailability) {
        condition_info::update_cm_from_form((object) array('id' => $moduleinfo->coursemodule), $moduleinfo, false);
    }
    $eventname = 'mod_created';
    add_to_log($course->id, "course", "add mod", "../mod/{$moduleinfo->modulename}/view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->modulename} {$moduleinfo->instance}");
    add_to_log($course->id, $moduleinfo->modulename, "add", "view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->instance}", $moduleinfo->coursemodule);
    $moduleinfo = local_ltiprovider_edit_module_post_actions($moduleinfo, $course, 'mod_created');
    return $moduleinfo;
}
Пример #13
0
/**
 * Add course module.
 *
 * The function does not check user capabilities.
 * The function creates course module, module instance, add the module to the correct section.
 * It also trigger common action that need to be done after adding/updating a module.
 *
 * @param object $moduleinfo the moudle data
 * @param object $course the course of the module
 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
 * @return object the updated module info
 */
function add_moduleinfo($moduleinfo, $course, $mform = null)
{
    global $DB, $CFG;
    // Attempt to include module library before we make any changes to DB.
    include_modulelib($moduleinfo->modulename);
    $moduleinfo->course = $course->id;
    $moduleinfo = set_moduleinfo_defaults($moduleinfo);
    if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
        $moduleinfo->groupmode = 0;
        // Do not set groupmode.
    }
    // First add course_module record because we need the context.
    $newcm = new stdClass();
    $newcm->course = $course->id;
    $newcm->module = $moduleinfo->module;
    $newcm->instance = 0;
    // Not known yet, will be updated later (this is similar to restore code).
    $newcm->visible = $moduleinfo->visible;
    $newcm->visibleold = $moduleinfo->visible;
    if (isset($moduleinfo->cmidnumber)) {
        $newcm->idnumber = $moduleinfo->cmidnumber;
    }
    $newcm->groupmode = $moduleinfo->groupmode;
    $newcm->groupingid = $moduleinfo->groupingid;
    $newcm->groupmembersonly = $moduleinfo->groupmembersonly;
    $completion = new completion_info($course);
    if ($completion->is_enabled()) {
        $newcm->completion = $moduleinfo->completion;
        $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
        $newcm->completionview = $moduleinfo->completionview;
        $newcm->completionexpected = $moduleinfo->completionexpected;
    }
    if (!empty($CFG->enableavailability)) {
        $newcm->availablefrom = $moduleinfo->availablefrom;
        $newcm->availableuntil = $moduleinfo->availableuntil;
        $newcm->showavailability = $moduleinfo->showavailability;
    }
    if (isset($moduleinfo->showdescription)) {
        $newcm->showdescription = $moduleinfo->showdescription;
    } else {
        $newcm->showdescription = 0;
    }
    if (!($moduleinfo->coursemodule = add_course_module($newcm))) {
        print_error('cannotaddcoursemodule');
    }
    if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) && isset($moduleinfo->introeditor)) {
        $introeditor = $moduleinfo->introeditor;
        unset($moduleinfo->introeditor);
        $moduleinfo->intro = $introeditor['text'];
        $moduleinfo->introformat = $introeditor['format'];
    }
    $addinstancefunction = $moduleinfo->modulename . "_add_instance";
    $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
    if (!$returnfromfunc or !is_number($returnfromfunc)) {
        // Undo everything we can.
        $modcontext = context_module::instance($moduleinfo->coursemodule);
        context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
        $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule));
        if (!is_number($returnfromfunc)) {
            print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
        } else {
            print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
        }
    }
    $moduleinfo->instance = $returnfromfunc;
    $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule));
    // Update embedded links and save files.
    $modcontext = context_module::instance($moduleinfo->coursemodule);
    if (!empty($introeditor)) {
        $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']);
        $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance));
    }
    // Course_modules and course_sections each contain a reference to each other.
    // So we have to update one of them twice.
    $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
    // Set up conditions.
    if ($CFG->enableavailability) {
        condition_info::update_cm_from_form((object) array('id' => $moduleinfo->coursemodule), $moduleinfo, false);
    }
    // Trigger event based on the action we did.
    $event = \core\event\course_module_created::create(array('courseid' => $course->id, 'context' => $modcontext, 'objectid' => $moduleinfo->coursemodule, 'other' => array('modulename' => $moduleinfo->modulename, 'name' => $moduleinfo->name, 'instanceid' => $moduleinfo->instance)));
    $event->trigger();
    add_to_log($course->id, $moduleinfo->modulename, "add", "view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->instance}", $moduleinfo->coursemodule);
    $moduleinfo = edit_module_post_actions($moduleinfo, $course);
    return $moduleinfo;
}
Пример #14
0
/**
 * Creates a copy of the emarking in the database.
 * 
 * @param unknown $original_emarking
 * @return boolean|multitype:unknown NULL Ambigous <boolean, number>
 */
function emarking_copy_to_cm($original_emarking)
{
    require_once $CFG->dirroot . "/course/lib.php";
    require_once $CFG->dirroot . "/mod/emarking/mod_form.php";
    $emarkingmod = $DB->get_record('modules', array('name' => 'emarking'));
    $emarking = new stdClass();
    $emarking = $original_emarking;
    $emarking->id = null;
    $emarking->id = emarking_add_instance($emarking);
    // Add coursemodule
    $mod = new stdClass();
    $mod->course = $emarking->course;
    $mod->module = $emarkingmod->id;
    $mod->instance = $emarking->id;
    $mod->section = 0;
    $mod->visible = 0;
    // Hide the forum
    $mod->visibleold = 0;
    // Hide the forum
    $mod->groupmode = 0;
    $mod->grade = 100;
    if (!($cmid = add_course_module($mod))) {
        return false;
    }
    $sectionid = course_add_cm_to_section($mod->course, $cmid, 0);
    return array($emarking->id, $cmid, $sectionid);
}
Пример #15
0
function RWSAAQuiz()
{
    global $CFG;
    global $DB;
    global $RWSLB;
    global $RWSUID;
    RWSCMAuth();
    RWSCRAuth();
    RWSCMUSvc();
    RWSCMMaint();
    $r_pm = RWSGSOpt("courseid", PARAM_ALPHANUM);
    if ($r_pm === false || strlen($r_pm) == 0) {
        RWSSErr("2057");
    }
    $r_cid = intval($r_pm);
    $r_crs = RWSCMUCourse($r_cid, true);
    $r_si = false;
    $r_pm = RWSGSOpt("sectionid", PARAM_ALPHANUM);
    if ($r_pm !== false && strlen($r_pm) > 0) {
        $r_si = intval($r_pm);
    }
    if ($r_si === false) {
        $r_sr = 0;
    } else {
        $r_sec = $DB->get_record("course_sections", array("id" => $r_si));
        if ($r_sec === false) {
            RWSSErr("2071");
        }
        if ($r_sec->course != $r_cid) {
            RWSSErr("2072");
        }
        $r_sr = $r_sec->section;
    }
    $r_pm = RWSGSOpt("name", PARAM_TEXT);
    if ($r_pm === false || strlen($r_pm) == 0) {
        RWSSErr("2073");
    }
    $r_qzn = trim(clean_text(strip_tags($r_pm, "<lang><span>")));
    $r_sfl = RWSGSOpt("sfile", RWSPRF);
    if ($r_sfl === false) {
        $r_sn = RWSGSOpt("sname", PARAM_FILE);
        $r_sd = RWSGSOpt("sdata", PARAM_NOTAGS);
        $r_ecd = true;
    } else {
        $r_sn = $r_sfl->filename;
        $r_sd = $r_sfl->filedata;
        $r_ecd = false;
    }
    $r_imp = false;
    if ($r_sd !== false && strlen($r_sd) > 0) {
        if ($r_sn === false || strlen($r_sn) == 0) {
            RWSSErr("2075");
        }
        $r_sn = clean_filename($r_sn);
        $r_imp = true;
    }
    $r_mr = $DB->get_record("modules", array("name" => "quiz"));
    if ($r_mr === false) {
        RWSSErr("2074");
    }
    $r_qiz = new stdClass();
    $r_qiz->name = $r_qzn;
    $r_qiz->section = $r_sr;
    $r_qiz->course = $r_cid;
    $r_qiz->coursemodule = 0;
    $r_qiz->instance = 0;
    $r_qiz->id = 0;
    $r_qiz->modulename = $r_mr->name;
    $r_qiz->module = $r_mr->id;
    $r_qiz->groupmembersonly = 0;
    if (respondusws_floatcompare($CFG->version, 2011120500.0, 2) >= 0) {
        $r_qiz->showdescription = 0;
    }
    $r_cpl = new completion_info($r_crs);
    if ($r_cpl->is_enabled()) {
        $r_qiz->completion = COMPLETION_TRACKING_NONE;
        $r_qiz->completionview = COMPLETION_VIEW_NOT_REQUIRED;
        $r_qiz->completiongradeitemnumber = null;
        $r_qiz->completionexpected = 0;
    }
    if ($CFG->enableavailability) {
        $r_qiz->availablefrom = 0;
        $r_qiz->availableuntil = 0;
        if ($r_qiz->availableuntil) {
            $r_qiz->availableuntil = strtotime("23:59:59", $r_qiz->availableuntil);
        }
        $r_qiz->showavailability = CONDITION_STUDENTVIEW_HIDE;
    }
    RWSSQDefs($r_qiz);
    if ($r_imp) {
        RWSIQSet($r_qiz, $r_sn, $r_sd, $r_ecd);
    }
    if (is_null($r_qiz->quizpassword) && !is_null($r_qiz->password)) {
        $r_qiz->quizpassword = $r_qiz->password;
    }
    $r_qzmi = add_course_module($r_qiz);
    if (!$r_qzmi) {
        RWSSErr("2077");
    }
    $r_qiz->coursemodule = $r_qzmi;
    $r_insi = quiz_add_instance($r_qiz);
    if (!$r_insi || is_string($r_insi)) {
        RWSSErr("2076");
    }
    $r_qiz->instance = $r_insi;
    if (respondusws_floatcompare($CFG->version, 2012120300, 2) >= 0) {
        $r_siu = course_add_cm_to_section($r_qiz->course, $r_qiz->coursemodule, $r_qiz->section);
    } else {
        $r_siu = add_mod_to_section($r_qiz);
    }
    if (!$r_siu) {
        RWSSErr("2078");
    }
    if (respondusws_floatcompare($CFG->version, 2012120300, 2) < 0) {
        $DB->set_field("course_modules", "section", $r_siu, array("id" => $r_qzmi));
    }
    if ($r_si !== false && $r_siu != $r_si) {
        RWSSErr("2078");
    }
    RWSSLBSet($r_qiz);
    set_coursemodule_visible($r_qzmi, $r_qiz->visible);
    if (isset($r_qiz->cmidnumber)) {
        set_coursemodule_idnumber($r_qzmi, $r_qiz->cmidnumber);
    }
    RWSUQGrades($r_qiz);
    if (respondusws_floatcompare($CFG->version, 2014051200, 2) >= 0) {
        $r_qiz->modname = $r_qiz->modulename;
        $r_qiz->id = $r_qiz->coursemodule;
        $r_evt = \core\event\course_module_created::create_from_cm($r_qiz);
        $r_evt->trigger();
    } else {
        $r_evt = new stdClass();
        $r_evt->modulename = $r_qiz->modulename;
        $r_evt->name = $r_qiz->name;
        $r_evt->cmid = $r_qiz->coursemodule;
        $r_evt->courseid = $r_qiz->course;
        $r_evt->userid = $RWSUID;
        events_trigger("mod_created", $r_evt);
    }
    rebuild_course_cache($r_cid);
    grade_regrade_final_grades($r_cid);
    RWSRHXml();
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
    echo "<addquiz>\r\n";
    echo "\t<name>";
    echo utf8_encode(htmlspecialchars(trim($r_qiz->name)));
    echo "</name>\r\n";
    echo "\t<id>";
    echo utf8_encode(htmlspecialchars(trim($r_qzmi)));
    echo "</id>\r\n";
    echo "\t<section_id>";
    echo utf8_encode(htmlspecialchars(trim($r_siu)));
    echo "</section_id>\r\n";
    echo "\t<writable>yes</writable>\r\n";
    if ($RWSLB->mex || $RWSLB->bex) {
        if ($RWSLB->mok) {
            if ($RWSLB->perr) {
                echo "\t<service_warning>3003</service_warning>\r\n";
            }
        } else {
            if ($RWSLB->bok) {
                if ($RWSLB->perr) {
                    echo "\t<service_warning>3003</service_warning>\r\n";
                }
            } else {
                echo "\t<service_warning>3001</service_warning>\r\n";
            }
        }
    } else {
        echo "\t<service_warning>3000</service_warning>\r\n";
    }
    echo "</addquiz>\r\n";
    exit;
}
 $fromform->update = 0;
 $fromform->return = 0;
 $fromform->submitbutton = 'save';
 $returnfromfunc = resource_add_instance($fromform);
 if (!$returnfromfunc) {
     echo 'ng';
 }
 if (!isset($fromform->groupmode)) {
     // to deal with pre-1.5 modules
     $fromform->groupmode = $course->groupmode;
     /// Default groupmode the same as course
 }
 $fromform->instance = $returnfromfunc;
 // course_modules and course_sections each contain a reference
 // to each other, so we have to update one of them twice.
 if (!($fromform->coursemodule = add_course_module($fromform))) {
     echo 'ng';
 }
 if (!($sectionid = add_mod_to_section($fromform))) {
     echo 'ng';
 }
 if (!set_field("course_modules", "section", $sectionid, "id", $fromform->coursemodule)) {
     echo 'ng';
 }
 if (!isset($fromform->visible)) {
     // We get the section's visible field status
     $fromform->visible = get_field("course_sections", "visible", "id", $sectionid);
 }
 // make sure visibility is set correctly (in particular in calendar)
 set_coursemodule_visible($fromform->coursemodule, $fromform->visible);
 add_to_log($course->id, "course", "add mod", "../mod/{$fromform->modulename}/view.php?id={$fromform->coursemodule}", "{$fromform->modulename} {$fromform->instance}");
Пример #17
0
 public function generate_modules($courses)
 {
     global $DB, $CFG;
     // Parse the modules-list variable
     $this->verbose("Generating " . $this->get('number_of_sections') . " sections with " . $this->get('number_of_modules') . " modules in each section, for each course...");
     list($modules_list_sql, $modules_params) = $DB->get_in_or_equal($this->get('modules_list'), SQL_PARAMS_NAMED, 'param0000', true);
     list($modules_ignored_sql, $ignore_params) = $DB->get_in_or_equal($this->modules_to_ignore, SQL_PARAMS_NAMED, 'param2000', false);
     $wheresql = "name {$modules_list_sql} AND name {$modules_ignored_sql}";
     $modules = $DB->get_records_select('modules', $wheresql, array_merge($modules_params, $ignore_params));
     foreach ($modules as $key => $module) {
         $module->count = 0;
         // Scorm, lams and hotpot are too complex to set up, remove them
         if (in_array($module->name, $this->modules_to_ignore) || !in_array($module->name, $this->modules_list)) {
             unset($modules[$key]);
         }
     }
     // Dirty hack for renumbering the modules array's keys
     $first_module = reset($modules);
     array_shift($modules);
     array_unshift($modules, $first_module);
     $modules_array = array();
     if (count($courses) > 0) {
         $libraries = array();
         foreach ($courses as $courseid) {
             // Text resources
             for ($i = 1; $i <= $this->get('number_of_sections'); $i++) {
                 for ($j = 0; $j < $this->get('number_of_modules'); $j++) {
                     $module = new stdClass();
                     // If only one module is created, and we also need to add a question to a quiz, create only a quiz
                     if ($this->get('number_of_modules') == 1 && $this->get('questions_per_quiz') > 0 && !empty($modules[8])) {
                         $moduledata = $modules[8];
                     } else {
                         $moduledata = $modules[array_rand($modules)];
                     }
                     $libfile = "{$CFG->dirroot}/mod/{$moduledata->name}/lib.php";
                     if (file_exists($libfile)) {
                         if (!in_array($libfile, $libraries)) {
                             $this->verbose("Including library for {$moduledata->name}...");
                             $libraries[] = $libfile;
                             require_once $libfile;
                         }
                     } else {
                         $this->verbose("Could not load lib file for module {$moduledata->name}!");
                         if (!$this->get('ignore_errors')) {
                             die;
                         }
                     }
                     // Basically 2 types of text fields: description and content
                     $description = "This {$moduledata->name} has been randomly generated by a very useful script, " . "for the purpose of testing " . "the boundaries of Moodle in various contexts. Moodle should be able to scale to " . "any size without " . "its speed and ease of use being affected dramatically.";
                     $content = 'Very useful content, I am sure you would agree';
                     $module_type_index = 0;
                     $module->introformat = FORMAT_MOODLE;
                     $module->messageformat = FORMAT_MOODLE;
                     // Special module-specific config
                     switch ($moduledata->name) {
                         case 'assignment':
                             $module->intro = $description;
                             $module->assignmenttype = $this->get_module_type('assignment');
                             $module->timedue = mktime() + 89487321;
                             $module->grade = rand(50, 100);
                             break;
                         case 'chat':
                             $module->intro = $description;
                             $module->schedule = 1;
                             $module->chattime = 60 * 60 * 4;
                             break;
                         case 'data':
                             $module->intro = $description;
                             $module->name = 'test';
                             break;
                         case 'choice':
                             $module->intro = $description;
                             $module->text = $content;
                             $module->option = array('Good choice', 'Bad choice', 'No choice');
                             $module->limit = array(1, 5, 0);
                             break;
                         case 'comments':
                             $module->intro = $description;
                             $module->comments = $content;
                             break;
                         case 'feedback':
                             $module->intro = $description;
                             $module->page_after_submit = $description;
                             $module->comments = $content;
                             break;
                         case 'forum':
                             $module->intro = $description;
                             $module->type = $this->get_module_type('forum');
                             $module->forcesubscribe = rand(0, 1);
                             $module->format = 1;
                             break;
                         case 'glossary':
                             $module->intro = $description;
                             $module->displayformat = $this->glossary_formats[rand(0, count($this->glossary_formats) - 1)];
                             $module->cmidnumber = rand(0, 999999);
                             break;
                         case 'label':
                             $module->content = $content;
                             $module->intro = $description;
                             break;
                         case 'lesson':
                             $module->lessondefault = 1;
                             $module->available = mktime();
                             $module->deadline = mktime() + 719891987;
                             $module->grade = 100;
                             break;
                         case 'quiz':
                             $module->intro = $description;
                             $module->feedbacktext = 'blah';
                             $module->feedback = 1;
                             $module->feedbackboundaries = array(2, 1);
                             $module->grade = 10;
                             $module->timeopen = time();
                             $module->timeclose = time() + 68854;
                             $module->shufflequestions = true;
                             $module->shuffleanswers = true;
                             $module->quizpassword = '';
                             break;
                         case 'resource':
                             $module->type = $this->get_module_type('resource');
                             $module->alltext = $content;
                             $module->summary = $description;
                             $module->windowpopup = rand(0, 1);
                             $module->display = rand(0, 1);
                             $module->resizable = rand(0, 1);
                             $module->scrollbars = rand(0, 1);
                             $module->directories = rand(0, 1);
                             $module->location = 'file.txt';
                             $module->menubar = rand(0, 1);
                             $module->toolbar = rand(0, 1);
                             $module->status = rand(0, 1);
                             $module->width = rand(200, 600);
                             $module->height = rand(200, 600);
                             $module->directories = rand(0, 1);
                             $module->files = false;
                             $module->param_navigationmenu = rand(0, 1);
                             $module->param_navigationbuttons = rand(0, 1);
                             $module->reference = 1;
                             $module->forcedownload = 1;
                             break;
                         case 'survey':
                             $module->template = rand(1, 5);
                             $module->intro = $description;
                             break;
                         case 'wiki':
                             $module->intro = $description;
                             $module->summary = $description;
                             break;
                     }
                     $module->name = ucfirst($moduledata->name) . ' ' . $moduledata->count++;
                     $module->course = $courseid;
                     $module->section = $i;
                     $module->module = $moduledata->id;
                     $module->modulename = $moduledata->name;
                     $module->add = $moduledata->name;
                     $module->cmidnumber = '';
                     $module->coursemodule = '';
                     $add_instance_function = $moduledata->name . '_add_instance';
                     $section = get_course_section($i, $courseid);
                     $module->section = $section->id;
                     $module->coursemodule = add_course_module($module);
                     $module->section = $i;
                     if (function_exists($add_instance_function)) {
                         $this->verbose("Calling module function {$add_instance_function}");
                         $module->instance = $add_instance_function($module, '');
                         $DB->set_field('course_modules', 'instance', $module->instance, array('id' => $module->coursemodule));
                     } else {
                         $this->verbose("Function {$add_instance_function} does not exist!");
                         if (!$this->get('ignore_errors')) {
                             die;
                         }
                     }
                     add_mod_to_section($module);
                     $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
                     $this->verbose("A {$moduledata->name} module was added to section {$i} (id {$module->section}) " . "of course {$courseid}.");
                     rebuild_course_cache($courseid);
                     $module_instance = $DB->get_field('course_modules', 'instance', array('id' => $module->coursemodule));
                     $module_record = $DB->get_record($moduledata->name, array('id' => $module_instance));
                     $module_record->instance = $module_instance;
                     if (empty($modules_array[$moduledata->name])) {
                         $modules_array[$moduledata->name] = array();
                     }
                     // TODO Find out why some $module_record end up empty here... (particularly quizzes)
                     if (!empty($module_record->instance)) {
                         $modules_array[$moduledata->name][] = $module_record;
                     }
                 }
             }
         }
         if (!$this->get('quiet')) {
             echo "Successfully generated " . $this->get('number_of_modules') * $this->get('number_of_sections') . " modules in each course!{$this->eolchar}";
         }
         return $modules_array;
     }
     return null;
 }
Пример #18
0
 /**
  * Setup the DB fixture data
  */
 public function setup()
 {
     parent::setUp();
     $tables = array('block_instance', 'cache_flags', 'capabilities', 'context', 'context_temp', 'course', 'course_modules', 'course_categories', 'course_sections', 'files', 'files_cleanup', 'grade_items', 'grade_categories', 'groups', 'groups_members', 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', 'role_capabilities', 'user');
     $this->create_test_tables($tables, 'lib');
     $this->create_test_table('forum', 'mod/forum');
     $this->switch_to_test_db();
     global $DB, $CFG;
     // Insert needed capabilities
     $DB->insert_record('capabilities', array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 14, 'name' => 'moodle/site:backup', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 17, 'name' => 'moodle/site:restore', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16));
     // Insert system context
     $DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1));
     $DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2));
     // Insert site course
     $DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}'));
     // User and capability stuff (stolen from testaccesslib.php)
     $syscontext = get_system_context(false);
     $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
     /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
     assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
     update_capabilities('moodle');
     update_capabilities('mod/forum');
     $contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2)));
     $contexts[0] = $syscontext;
     $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
     $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
     $users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0)));
     $admin = $this->testdb->get_record('role', array('shortname' => 'admin'));
     $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('a' => array($users['a']->id, $admin->id, $contexts[0]->id)));
     $this->switch_global_user_id(1);
     accesslib_clear_all_caches_for_unit_testing();
     // Create a coursecat
     $newcategory = new stdClass();
     $newcategory->name = 'test category';
     $newcategory->sortorder = 999;
     if (!($newcategory->id = $DB->insert_record('course_categories', $newcategory))) {
         print_error('cannotcreatecategory', '', '', format_string($newcategory->name));
     }
     $newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id);
     mark_context_dirty($newcategory->context->path);
     fix_course_sortorder();
     // Required to build course_categories.depth and .path.
     $this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id));
     // Create a course
     $coursedata = new stdClass();
     $coursedata->category = $newcategory->id;
     $coursedata->shortname = 'testcourse';
     $coursedata->fullname = 'Test Course';
     try {
         $this->course = create_course($coursedata);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test course was not correctly deleted
         $this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname));
     }
     // Create a user
     $this->user = new stdClass();
     $this->user->username = '******';
     $this->user->password = '******';
     $this->user->firstname = 'TestUser';
     $this->user->lastname = 'TestUser';
     $this->user->email = '*****@*****.**';
     try {
         $this->user->id = create_user($this->user);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test user was not correctly deleted
         $this->user->id = $DB->get_field('user', 'id', array('username' => $this->user->username));
     }
     // Assign user to course
     // role_assign(5, $this->user->id, 0, get_context_instance(CONTEXT_COURSE, $this->course->id)->id);
     // Create a module
     $module = new stdClass();
     $module->intro = 'Forum used for testing filelib API';
     $module->type = 'general';
     $module->forcesubscribe = 1;
     $module->format = 1;
     $module->name = 'Test Forum';
     $module->module = $DB->get_field('modules', 'id', array('name' => 'forum'));
     $module->modulename = 'forum';
     $module->add = 'forum';
     $module->cmidnumber = '';
     $module->course = $this->course->id;
     $module->instance = forum_add_instance($module, '');
     $this->section = get_course_section(1, $this->course->id);
     $module->section = $this->section->id;
     $module->coursemodule = add_course_module($module);
     add_mod_to_section($module);
     $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
     rebuild_course_cache($this->course->id);
     $this->module = $DB->get_record('forum', array('id' => $module->instance));
     $this->module->instance = $module->instance;
     // Update local copy of course
     $this->course = $DB->get_record('course', array('id' => $this->course->id));
 }
Пример #19
0
/**
 * Purpose: add a Moodle page resource to a course
 *
 * @author Andrew Zoltay
 * date    2011-04-27
 * @global $CFG - configuration settings for CACE
 * @global object $DB Moodle database object
 * @global $CACE_CFG - configuration settings for CACE
 * @param int $courseid
 * @param object $pagedata
 */
function cace_add_page_resource($course, $pagedata)
{
    global $CFG, $DB, $CACE_CFG, $USER;
    require_once "{$CFG->dirroot}/mod/page/lib.php";
    try {
        // Create a new course module for the page.
        $newcm = new stdClass();
        $newcm->course = $course->id;
        $newcm->module = $pagedata->module;
        $newcm->instance = 0;
        // Don't have this value yet, but will update later.
        $newcm->visible = $pagedata->visible;
        $newcm->groupmode = $pagedata->groupmode;
        $newcm->groupingid = $pagedata->groupingid;
        $newcm->groupmembersonly = $pagedata->groupmembersonly;
        $pagedata->coursemodule = add_course_module($newcm);
        // This is lame, but need to create a dummy object for page_add_instance()
        // useless $mform parameter that isn't used in the function.
        $dummyform = new stdClass();
        // Create the page instance.
        $pageid = page_add_instance($pagedata, $dummyform);
        $pagedata->instance = $pageid;
        // Update course_modules table with new instance.
        $DB->set_field('course_modules', 'instance', $pageid, array('id' => $pagedata->coursemodule));
        // Add the module to the correct section of the course
        // course_modules and course_sections each contain a reference
        // to each other, so we have to update one of them twice.
        $sectionid = course_add_cm_to_section($pagedata->course, $pagedata->coursemodule, $pagedata->section);
        $DB->set_field('course_modules', 'section', $sectionid, array('id' => $pagedata->coursemodule));
        set_coursemodule_visible($pagedata->coursemodule, $pagedata->visible);
        // Trigger mod_created event with information about the new module.
        // Use the new events system to log the creation of a resource.
        $eventdata = clone $pagedata;
        $eventdata->modname = $pagedata->modulename;
        $eventdata->name = $pagedata->name;
        $eventdata->id = $pagedata->coursemodule;
        $eventdata->courseid = $course->id;
        $eventdata->userid = $CACE_CFG->admin_user;
        // Use Admin account for event data.
        $event = \core\event\course_module_created::create_from_cm($eventdata);
        $event->trigger();
        return true;
    } catch (Exception $e) {
        return false;
    }
}
Пример #20
0
/**
* basic encapsulation of creating a glossary instance - as would be done in modedit.php
* with glossary_add_instance();
*
* @param int $courseid the id of the course to add forum to
* @param string $glossary_name  name of the glossary
* @param string $description descrition of the glossary
* @return $glossary object
* */
function local_create_glossary($courseid, $glossary_name, $description)
{
    global $CFG;
    require_once $CFG->dirroot . "/mod/glossary/lib.php";
    require_once $CFG->dirroot . "/lib/grouplib.php";
    if (!($course = get_record("course", "id", $courseid))) {
        error("This course doesn't exist");
    }
    $glossary = new object();
    $glossary->course = $courseid;
    $glossary->cmidnumber = 1;
    $glossary->name = $glossary_name;
    $glossary->intro = $description;
    $glossary->entbypage = 10;
    $glossary->mainglossary = 1;
    $glossary->globalglossary = false;
    $glossary->userrating = false;
    $glossary->ratingtime = false;
    if ($CFG->enablerssfeeds && isset($CFG->glossary_enablerssfeeds) && $CFG->glossary_enablerssfeeds) {
        $glossary->rsstype = 2;
        $glossary->rssarticles = 10;
    }
    $glossary->allowduplicatedentries = 0;
    $glossary->allowcomments = 1;
    $glossary->allowprintview = 1;
    $glossary->usedynalink = 1;
    $glossary->defaultapproval = 1;
    $glossary->displayformat = 'faq';
    $glossary->showspecial = 1;
    $glossary->showalphabet = 1;
    $glossary->showall = 1;
    $glossary->editalways = 0;
    $glossary->assesstimestart = time();
    $glossary->assesstimefinish = time();
    $glossary->showall = 1;
    $glossary->showall = 1;
    $glossary->showall = 1;
    $glossary->showall = 1;
    $glossary->groupingid = $course->defaultgroupingid;
    $glossary->groupmembersonly = 0;
    //    gradecat    8   - uncategorised
    $glossary->groupmode = 0;
    $glossary->visible = '1';
    $glossary->module = get_field('modules', 'id', 'name', 'glossary');
    $glossary->id = glossary_add_instance($glossary);
    $glossary->modulename = 'glossary';
    $glossary->instance = $glossary->id;
    $glossary->section = 0;
    // default to first level section
    $glossary->coursemodule = add_course_module($glossary);
    $sectionid = add_mod_to_section($glossary);
    set_field("course_modules", "section", $sectionid, "id", $glossary->coursemodule);
    set_coursemodule_visible($glossary->coursemodule, $glossary->visible);
    set_coursemodule_idnumber($glossary->coursemodule, $glossary->cmidnumber);
    rebuild_course_cache($glossary->course);
    return $glossary;
}
Пример #21
0
 /**
  * Create the coursemodule to hold the file/content that has been uploaded
  */
 protected function create_course_module()
 {
     if (!course_allowed_module($this->course, $this->module->name)) {
         throw new coding_exception("The module {$this->module->name} is not allowed to be added to this course");
     }
     $this->cm = new stdClass();
     $this->cm->course = $this->course->id;
     $this->cm->section = $this->section;
     $this->cm->module = $this->module->id;
     $this->cm->modulename = $this->module->name;
     $this->cm->instance = 0;
     // This will be filled in after we create the instance.
     $this->cm->visible = 1;
     $this->cm->groupmode = $this->course->groupmode;
     $this->cm->groupingid = $this->course->defaultgroupingid;
     if (!($this->cm->id = add_course_module($this->cm))) {
         throw new coding_exception("Unable to create the course module");
     }
     // The following are used inside some few core functions, so may as well set them here.
     $this->cm->coursemodule = $this->cm->id;
     $groupbuttons = ($this->course->groupmode or !$this->course->groupmodeforce);
     if ($groupbuttons and plugin_supports('mod', $this->module->name, FEATURE_GROUPS, 0)) {
         $this->cm->groupmodelink = !$this->course->groupmodeforce;
     } else {
         $this->cm->groupmodelink = false;
         $this->cm->groupmode = false;
     }
 }
Пример #22
0
     $emarking->grademin = 1;
     $emarking->id = emarking_add_instance($emarking);
     $emarkingmod = $DB->get_record('modules', array('name' => 'emarking'));
     // Add coursemodule
     $mod = new stdClass();
     $mod->course = $emarking->course;
     $mod->module = $emarkingmod->id;
     $mod->instance = $emarking->id;
     $mod->section = 0;
     $mod->visible = 0;
     // Hide the forum
     $mod->visibleold = 0;
     // Hide the forum
     $mod->groupmode = 0;
     $mod->grade = 100;
     if (!($cmid = add_course_module($mod))) {
         emarking_json_error('cannotcreateinstanceforteacher');
     }
     $sectionid = course_add_cm_to_section($mod->course, $cmid, 0);
     $emarkingid = $emarking->id;
 }
 if (!($emarking = $DB->get_record('emarking', array('id' => $emarkingid)))) {
     emarking_json_error('Invalid emarking id');
 }
 if (!($cm = get_coursemodule_from_instance('emarking', $emarking->id, $course->id))) {
     emarking_json_error('Invalid course module');
 }
 if (count($_FILES) < 1 || !is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
     emarking_json_error('You must upload a file');
 }
 $extension = strtolower(substr($_FILES['uploadedfile']['name'], strrpos($_FILES['uploadedfile']['name'], "."), strlen($_FILES['uploadedfile']['name']) - strrpos($_FILES['uploadedfile']['name'], ".")));
Пример #23
0
 public function add_file($section, $name, $path, $display = 0)
 {
     global $DB, $CFG, $USER;
     $section = (int) $section;
     $display = (int) $display;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/mod/resource/lib.php';
     require_once $CFG->dirroot . '/mod/resource/locallib.php';
     $params = self::validate_parameters(self::add_file_parameters(), array('section' => $section, 'name' => $name, 'path' => $path, 'display' => $display));
     $section = $DB->get_record('course_sections', array('id' => $section), '*', MUST_EXIST);
     $course = $DB->get_record('course', array('id' => $section->course), '*', MUST_EXIST);
     self::require_access($course->id);
     // finally create the file item
     // first add course_module record because we need the context
     $newcm = new stdClass();
     $newcm->course = $course->id;
     $newcm->module = $DB->get_field('modules', 'id', array('name' => 'resource'));
     // not known yet, will be updated later (this is similar to restore code)
     $newcm->instance = 0;
     $newcm->section = $params['section'];
     $newcm->visible = 1;
     $newcm->groupmode = 0;
     $newcm->groupingid = 0;
     $newcm->groupmembersonly = 0;
     if (!($coursemodule = add_course_module($newcm))) {
         throw new invalid_parameter_exception('Error creating course module');
     }
     $config = get_config('resource');
     $module = new stdClass();
     $module->course = $course->id;
     $module->name = format_string($params['name']);
     $module->intro = '<p></p>';
     $module->introformat = 1;
     $module->coursemodule = $coursemodule;
     if (!$display) {
         $module->display = $config->display;
     } else {
         $module->display = $display;
     }
     $module->popupwidth = $config->popupwidth;
     $module->popupheight = $config->popupheight;
     $module->printheading = $config->printheading;
     $module->printintro = $config->printintro;
     // 'Show size' support only from Moodle 2.3 / OU moodle April 2012
     if (isset($config->showsize)) {
         $module->showsize = $config->showsize;
         $module->showtype = $config->showtype;
     }
     $module->filterfiles = $config->filterfiles;
     $module->section = $section->section;
     //check $params['path'] and create files based on that and attach to $module->files
     //now check $path and obtain $filename and $filepath
     $contextuser = get_context_instance(CONTEXT_USER, $USER->id);
     $fs = get_file_storage();
     $module->files = 0;
     file_prepare_draft_area($module->files, null, null, null, null);
     $fileinfo = array('contextid' => $contextuser->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $module->files, 'filepath' => '/', 'filename' => basename($params['path']), 'timecreated' => time(), 'timemodified' => time(), 'mimetype' => mimeinfo('type', $path), 'userid' => $USER->id);
     if (strpos($params['path'], '://') === false) {
         //this is a path
         if (!file_exists($params['path'])) {
             throw new invalid_parameter_exception('Error accessing filepath - file may not exist.');
         }
         $fs->create_file_from_pathname($fileinfo, $params['path']);
     } else {
         //this is a URL - download the file first.
         $content = download_file_content($params['path']);
         if ($content === false) {
             throw new invalid_parameter_exception('Error accessing file - url may not exist.');
         }
         $fs->create_file_from_string($fileinfo, $content);
     }
     $module->instance = resource_add_instance($module, array());
     $DB->set_field('course_modules', 'instance', $module->instance, array('id' => $coursemodule));
     add_mod_to_section($module);
     rebuild_course_cache($course->id, true);
     return array('id' => $coursemodule);
 }
Пример #24
0
function elluminate_add_instance($elluminate, $facilitatorid = false)
{
    global $CFG;
    global $USER;
    global $COURSE;
    global $DB;
    if (!$facilitatorid) {
        $facilitatorid = $USER->id;
    }
    /// The start and end times don't make sense.
    if ($elluminate->timestart > $elluminate->timeend) {
        $a = new stdClass();
        $a->timestart = userdate($elluminate->timestart);
        $a->timeend = userdate($elluminate->timeend);
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('invalidsessiontimes', 'elluminate', $a), 5);
    }
    if ($elluminate->timestart == $elluminate->timeend) {
        $a = new stdClass();
        $a->timestart = userdate($elluminate->timestart);
        $a->timeend = userdate($elluminate->timeend);
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('samesessiontimes', 'elluminate', $a), 5);
    }
    $timenow = time();
    if ($elluminate->timestart < $timenow) {
        $a = new stdClass();
        $a->timestart = userdate($elluminate->timestart);
        $a->timeend = userdate($elluminate->timeend);
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('starttimebeforenow', 'elluminate', $a), 5);
    }
    $yearinseconds = 31536000;
    $timedif = $elluminate->timeend - $elluminate->timestart;
    if ($timedif > $yearinseconds) {
        $a = new stdClass();
        $a->timestart = userdate($elluminate->timestart);
        $a->timeend = userdate($elluminate->timeend);
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('meetinglessthanyear', 'elluminate', $a), 5);
    }
    $year_later = $timenow + $yearinseconds;
    if ($elluminate->timestart > $year_later) {
        $a = new stdClass();
        $a->timestart = userdate($elluminate->timestart);
        $a->timeend = userdate($elluminate->timeend);
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('meetingstartoverayear', 'elluminate', $a), 5);
    }
    if (empty($elluminate->sessionname)) {
        $elluminate->sessionname = $elluminate->name;
    }
    $originalname = $elluminate->sessionname;
    $search = array("<", "&", "\"", "#", "%");
    $replace = '';
    $strippedname = str_replace($search, $replace, $elluminate->sessionname);
    if (empty($strippedname)) {
        redirect($CFG->wwwroot . '/course/mod.php?id=' . $elluminate->course . '&amp;section=' . $elluminate->section . '&amp;sesskey=' . $USER->sesskey . '&amp;add=elluminate', get_string('meetingnameempty', 'elluminate'), 5);
    }
    if (empty($elluminate->creator)) {
        $elluminate->creator = $USER->id;
    }
    if (empty($elluminate->boundarytimedisplay)) {
        $elluminate->boundarytimedisplay = 0;
    }
    if (empty($elluminate->maxtalkers)) {
        $elluminate->maxtalkers = 1;
    }
    if ($elluminate->sessiontype == 0 || $elluminate->sessiontype == 1) {
        $elluminate->groupmode = 0;
        $elluminate->groupingid = 0;
    } else {
        if ($elluminate->sessiontype == 2) {
            $elluminate->groupingid = 0;
        } else {
            if ($elluminate->sessiontype == 3) {
                $elluminate->groupingid = $elluminate->grouping_id;
            }
        }
    }
    if ($COURSE->groupmodeforce > 0) {
        $elluminate->groupmode = $COURSE->groupmode;
    }
    $elluminate->timemodified = time();
    $elluminate->seats = 0;
    $elluminate->chairlist = $USER->id;
    $elluminate->sessionname = $strippedname;
    $elluminate->groupparentid = '0';
    $elluminate->meetinginit = 0;
    if (!($elluminate->id = $DB->insert_record('elluminate', $elluminate))) {
        return false;
    }
    $mod = new stdClass();
    $mod->course = $elluminate->course;
    $mod->module = $elluminate->module;
    $mod->instance = $elluminate->id;
    $mod->idnumber = null;
    $mod->added = time();
    $mod->score = 0;
    $mod->indent = 0;
    $mod->visible = 1;
    $mod->visibleold = 1;
    $mod->groupmode = $elluminate->groupmode;
    if ($elluminate->grouping_id == NULL) {
        $mod->groupingid = 0;
    } else {
        $mod->groupingid = $elluminate->grouping_id;
    }
    $mod->groupmembersonly = 0;
    $sql = "SELECT cs.* FROM {course_sections} cs WHERE cs.course = :course AND cs.section = :section";
    $sql_params = array('course' => $elluminate->course, 'section' => $elluminate->section);
    $course_sections = $DB->get_records_sql($sql, $sql_params);
    foreach ($course_sections as $course_section) {
        $mod->section = $course_section->id;
    }
    if (!($mod->id = add_course_module($mod))) {
        return false;
    }
    if ($elluminate->sessiontype == 0 || $elluminate->sessiontype == 1) {
        if ($elluminate->groupmode == 0) {
            $create_result = elluminate_create_meeting($elluminate->timestart, $elluminate->timeend, stripslashes($strippedname), '', '', $elluminate->sessiontype, $elluminate->seats, $elluminate->boundarytime, $elluminate->maxtalkers, $elluminate->recordingmode, $mod->id, $USER->id);
            $meetingid = $create_result->DefaultAdapterMeetingResponseShort->meetingId;
            if ($meetingid > 0) {
                $elluminate->meetingid = $meetingid;
                if (!empty($elluminate->meetingid)) {
                    $elluminate->meetinginit = 2;
                }
                $elluminate->chairlist = $create_result->DefaultAdapterMeetingResponseShort->chairList;
                $DB->update_record('elluminate', $elluminate);
            } else {
                elluminate_delete_instance($elluminate->id);
            }
        }
    }
    if (!empty($elluminate->meetingid)) {
        $elluminate->meetinginit = 2;
    }
    $parentsessionid = $elluminate->id;
    elluminate_grade_item_update($elluminate);
    if ($elluminate->sessiontype == 2 || $elluminate->sessiontype == 3) {
        if ($elluminate->groupmode != 0) {
            elluminate_insert_group_records($elluminate);
        } else {
            elluminate_update_events($elluminate);
        }
    } else {
        elluminate_update_events($elluminate);
    }
    $DB->delete_records('course_modules', array('id' => $mod->id));
    return $parentsessionid;
}
Пример #25
0
 /**
  * Create a duplicate course module record so we can create the upgraded
  * setask module alongside the old setaskment module.
  *
  * @param stdClass $cm The old course module record
  * @param int $moduleid The id of the new setask module
  * @param int $newinstanceid The id of the new instance of the setask module
  * @return mixed stdClass|bool The new course module record or FALSE
  */
 private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid)
 {
     global $DB, $CFG;
     $newcm = new stdClass();
     $newcm->course = $cm->course;
     $newcm->module = $moduleid;
     $newcm->instance = $newinstanceid;
     $newcm->visible = $cm->visible;
     $newcm->section = $cm->section;
     $newcm->score = $cm->score;
     $newcm->indent = $cm->indent;
     $newcm->groupmode = $cm->groupmode;
     $newcm->groupingid = $cm->groupingid;
     $newcm->completion = $cm->completion;
     $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber;
     $newcm->completionview = $cm->completionview;
     $newcm->completionexpected = $cm->completionexpected;
     if (!empty($CFG->enableavailability)) {
         $newcm->availability = $cm->availability;
     }
     $newcm->showdescription = $cm->showdescription;
     $newcmid = add_course_module($newcm);
     $newcm = get_coursemodule_from_id('', $newcmid, $cm->course);
     if (!$newcm) {
         return false;
     }
     $section = $DB->get_record("course_sections", array("id" => $newcm->section));
     if (!$section) {
         return false;
     }
     $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section, $cm->id);
     // Make sure visibility is set correctly (in particular in calendar).
     // Note: Allow them to set it even without moodle/course:activityvisibility.
     set_coursemodule_visible($newcm->id, $newcm->visible);
     return $newcm;
 }
Пример #26
0
function hotpot_add_chain(&$hotpot)
{
    /// add a chain of hotpot actiivities
    global $CFG, $course;
    $ok = true;
    $hotpot->names = array();
    $hotpot->summaries = array();
    $hotpot->references = array();
    $xml_quiz = new hotpot_xml_quiz($hotpot, false, false, false, false, false);
    if (isset($xml_quiz->error)) {
        $hotpot->errors['reference'] = $xml_quiz->error;
        $ok = false;
    } else {
        if (is_dir($xml_quiz->filepath)) {
            // get list of hotpot files in this folder
            if ($dh = @opendir($xml_quiz->filepath)) {
                while (false !== ($file = @readdir($dh))) {
                    if (preg_match('/\\.(jbc|jcl|jcw|jmt|jmx|jqz|htm|html)$/', $file)) {
                        $hotpot->references[] = "{$xml_quiz->reference}/{$file}";
                    }
                }
                closedir($dh);
                // get titles
                foreach ($hotpot->references as $i => $reference) {
                    $filepath = $xml_quiz->fileroot . '/' . $reference;
                    hotpot_get_titles_and_next_ex($hotpot, $filepath);
                    $hotpot->names[$i] = $hotpot->exercisetitle;
                    $hotpot->summaries[$i] = $hotpot->exercisesubtitle;
                }
            } else {
                $ok = false;
                $hotpot->errors['reference'] = get_string('error_couldnotopenfolder', 'hotpot', $hotpot->reference);
            }
        } else {
            if (is_file($xml_quiz->filepath)) {
                $filerootlength = strlen($xml_quiz->fileroot) + 1;
                while ($xml_quiz->filepath) {
                    hotpot_get_titles_and_next_ex($hotpot, $xml_quiz->filepath, true);
                    $hotpot->names[] = $hotpot->exercisetitle;
                    $hotpot->summaries[] = $hotpot->exercisesubtitle;
                    $hotpot->references[] = substr($xml_quiz->filepath, $filerootlength);
                    if ($hotpot->nextexercise) {
                        $filepath = $xml_quiz->fileroot . '/' . $xml_quiz->filesubdir . $hotpot->nextexercise;
                        // check file is not already in chain
                        $reference = substr($filepath, $filerootlength);
                        if (in_array($reference, $hotpot->references)) {
                            $filepath = '';
                        }
                    } else {
                        $filepath = '';
                    }
                    if ($filepath && file_exists($filepath) && is_file($filepath) && is_readable($filepath)) {
                        $xml_quiz->filepath = $filepath;
                    } else {
                        $xml_quiz->filepath = false;
                        // finish while loop
                    }
                }
                // end while
            } else {
                $ok = false;
                $hotpot->errors['reference'] = get_string('error_notfileorfolder', 'hotpot', $hotpot->reference);
            }
        }
    }
    if (empty($hotpot->references) && empty($hotpot->errors['reference'])) {
        $ok = false;
        $hotpot->errors['reference'] = get_string('error_noquizzesfound', 'hotpot', $hotpot->reference);
    }
    if ($ok) {
        $hotpot->visible = HOTPOT_YES;
        if (trim($hotpot->name) == '') {
            $hotpot->name = get_string("modulename", $hotpot->modulename);
        }
        $hotpot->specificname = $hotpot->name;
        $hotpot->specificsummary = $hotpot->summary;
        // add all except last activity in chain
        $i_max = count($hotpot->references) - 1;
        for ($i = 0; $i < $i_max; $i++) {
            hotpot_set_name_summary_reference($hotpot, $i);
            $hotpot->reference = addslashes($hotpot->reference);
            if (!($hotpot->instance = insert_record("hotpot", $hotpot))) {
                error("Could not add a new instance of {$hotpot->modulename}", "view.php?id={$hotpot->course}");
            }
            // store (hotpot table) id of start of chain
            if ($i == 0) {
                $hotpot->startofchain = $hotpot->instance;
            }
            if (isset($course->groupmode)) {
                $hotpot->groupmode = $course->groupmode;
            }
            if (!($hotpot->coursemodule = add_course_module($hotpot))) {
                error("Could not add a new course module");
            }
            if (!($sectionid = add_mod_to_section($hotpot))) {
                error("Could not add the new course module to that section");
            }
            if (!set_field("course_modules", "section", $sectionid, "id", $hotpot->coursemodule)) {
                error("Could not update the course module with the correct section");
            }
            add_to_log($hotpot->course, "course", "add mod", "../mod/{$hotpot->modulename}/view.php?id={$hotpot->coursemodule}", "{$hotpot->modulename} {$hotpot->instance}");
            add_to_log($hotpot->course, $hotpot->modulename, "add", "view.php?id={$hotpot->coursemodule}", "{$hotpot->instance}", $hotpot->coursemodule);
            // hide tail of chain
            if ($hotpot->shownextquiz == HOTPOT_YES) {
                $hotpot->visible = HOTPOT_NO;
            }
        }
        // end for ($hotpot->references)
        // settings for final activity in chain
        hotpot_set_name_summary_reference($hotpot, $i);
        $hotpot->reference = addslashes($hotpot->references[$i]);
        $hotpot->shownextquiz = HOTPOT_NO;
        if (isset($hotpot->startofchain)) {
            // redirection only works for Moodle 1.5+
            $hotpot->redirect = true;
            $hotpot->redirecturl = "{$CFG->wwwroot}/mod/hotpot/view.php?hp={$hotpot->startofchain}";
        }
    }
    // end if $ok
    return $ok;
}
 /**
  * Create a migrated turnitin assignment in Moodle
  *
  * @global type $DB
  * @global type $CFG
  * @param array $partids the ids of turnitin assignment to create as parts of new assignment
  * @param int $courseid
  * @param string $assignmentname
  * @return boolean false if failed
  */
 public static function create_migration_assignment($partids, $courseid, $assignmentname)
 {
     global $DB, $CFG, $OUTPUT;
     $config = turnitintooltwo_admin_config();
     $partids = (array) $partids;
     $tempassignment = new turnitintooltwo_assignment(0, '', 'M');
     $newassignment = $tempassignment->update_assignment_from_tii($partids);
     $newassignment["turnitintooltwo"]->course = $courseid;
     $newassignment["turnitintooltwo"]->name = $assignmentname;
     $newassignment["turnitintooltwo"]->numparts = count($partids);
     $newassignment["turnitintooltwo"]->gradedisplay = 1;
     $newassignment["turnitintooltwo"]->shownonsubmission = 1;
     $newassignment["turnitintooltwo"]->usegrademark = $config->usegrademark;
     // Get maximum grade.
     $newassignment["turnitintooltwo"]->grade = 0;
     foreach ($newassignment["parts"] as $part) {
         if ($newassignment["turnitintooltwo"]->grade < $part->maxmarks) {
             $newassignment["turnitintooltwo"]->grade = $part->maxmarks;
         }
     }
     $turnitintooltwoassignment = new turnitintooltwo_assignment(0, $newassignment["turnitintooltwo"]);
     if (!($toolid = $DB->insert_record("turnitintooltwo", $turnitintooltwoassignment->turnitintooltwo))) {
         turnitintooltwo_activitylog(get_string('migrationassignmentcreationerror', 'turnitintooltwo', $courseid), "REQUEST");
         return false;
     } else {
         turnitintooltwo_activitylog(get_string('migrationassignmentcreated', 'turnitintooltwo', $toolid), "REQUEST");
     }
     $module = $DB->get_record("modules", array("name" => "turnitintooltwo"));
     $coursemodule = new stdClass();
     $coursemodule->course = $courseid;
     $coursemodule->module = $module->id;
     $coursemodule->added = time();
     $coursemodule->instance = $toolid;
     $coursemodule->section = 0;
     include_once $CFG->dirroot . "/course/lib.php";
     // Add Course module and get course section.
     if (!($coursemodule->coursemodule = add_course_module($coursemodule))) {
         echo $OUTPUT->notification(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid));
         turnitintooltwo_activitylog(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid), "REQUEST");
         return false;
     }
     if (is_callable('course_add_cm_to_section')) {
         if (!($sectionid = course_add_cm_to_section($coursemodule->course, $coursemodule->coursemodule, $coursemodule->section))) {
             echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST");
             return false;
         }
     } else {
         if (!($sectionid = add_mod_to_section($coursemodule))) {
             echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST");
             return false;
         }
     }
     $DB->set_field("course_modules", "section", $sectionid, array("id" => $coursemodule->coursemodule));
     rebuild_course_cache($courseid);
     foreach ($newassignment["parts"] as $part) {
         $part->turnitintooltwoid = $toolid;
         $part->deleted = 0;
         $part->migrated = -1;
         if ($part->id = $DB->insert_record("turnitintooltwo_parts", $part)) {
             turnitintooltwo_activitylog(get_string('migrationassignmentpartcreated', 'turnitintooltwo', $part->id), "REQUEST");
         }
         if ($turnitintooltwoassignment->create_event($toolid, $part->partname, $part->dtdue)) {
             $part->migrated = 1;
             $DB->update_record("turnitintooltwo_parts", $part);
         } else {
             echo $OUTPUT->notification(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid));
             turnitintooltwo_activitylog(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid), "REQUEST");
         }
     }
 }
Пример #28
0
 $quizdata->modulename = "quiz";
 $quizdata->MAX_FILE_SIZE = 10485760;
 $quizdata->update = 0;
 $quizdata->preferredbehaviour = 'deferredfeedback';
 $quizdata->return = 0;
 if ($oldquizinstancearr = $DB->get_records_sql("SELECT * FROM {quiz} WHERE course= ?  and name= ?", array($courseid, $quizzestoadd_['title']))) {
     while (list($key, $oldquizinstanceid) = each($oldquizinstancearr)) {
         if ($oldquizinsection = $DB->get_record_sql("SELECT * FROM {course_modules} WHERE course= ? and module= ? and instance= ? and visible=1 ", array($courseid, $module->id, $oldquizinstanceid->id))) {
             set_coursemodule_visible($oldquizinsection->id, 0);
         }
     }
 }
 $quizdata->questions = '0,';
 $quizdata->id = $DB->insert_record("quiz", $quizdata);
 $quizdata->instance = $quizdata->id;
 if (!($quizdata->coursemodule = add_course_module($quizdata))) {
     error("Could not add a new course module");
 }
 if (!($sectionid = add_mod_to_section($quizdata))) {
     error("Could not add the new course module to that section");
 }
 if (!$DB->set_field("course_modules", "section", $sectionid, array("id" => $quizdata->coursemodule))) {
     error("Could not update the course module with the correct section");
 }
 if (!isset($quizdata->visible)) {
     // We get the section's visible field status
     $quizdata->visible = $DB->get_field("course_sections", "visible", "id", $sectionid);
 }
 set_coursemodule_visible($quizdata->coursemodule, $quizdata->visible);
 // Trigger mod_updated event with information about this module.
 $eventdata = new stdClass();
Пример #29
0
/**
 * Converts a forum to use the Roles System
 *
 * @global object
 * @global object
 * @param object $forum        a forum object with the same attributes as a record
 *                        from the forum database table
 * @param int $forummodid   the id of the forum module, from the modules table
 * @param array $teacherroles array of roles that have archetype teacher
 * @param array $studentroles array of roles that have archetype student
 * @param array $guestroles   array of roles that have archetype guest
 * @param int $cmid         the course_module id for this forum instance
 * @return boolean      forum was converted or not
 */
function forum_convert_to_roles($forum, $forummodid, $teacherroles=array(),
                                $studentroles=array(), $guestroles=array(), $cmid=NULL) {

    global $CFG, $DB, $OUTPUT;

    if (!isset($forum->open) && !isset($forum->assesspublic)) {
        // We assume that this forum has already been converted to use the
        // Roles System. Columns forum.open and forum.assesspublic get dropped
        // once the forum module has been upgraded to use Roles.
        return false;
    }

    if ($forum->type == 'teacher') {

        // Teacher forums should be converted to normal forums that
        // use the Roles System to implement the old behavior.
        // Note:
        //   Seems that teacher forums were never backed up in 1.6 since they
        //   didn't have an entry in the course_modules table.
        require_once($CFG->dirroot.'/course/lib.php');

        if ($DB->count_records('forum_discussions', array('forum' => $forum->id)) == 0) {
            // Delete empty teacher forums.
            $DB->delete_records('forum', array('id' => $forum->id));
        } else {
            // Create a course module for the forum and assign it to
            // section 0 in the course.
            $mod = new stdClass();
            $mod->course = $forum->course;
            $mod->module = $forummodid;
            $mod->instance = $forum->id;
            $mod->section = 0;
            $mod->visible = 0;     // Hide the forum
            $mod->visibleold = 0;  // Hide the forum
            $mod->groupmode = 0;

            if (!$cmid = add_course_module($mod)) {
                print_error('cannotcreateinstanceforteacher', 'forum');
            } else {
                $sectionid = course_add_cm_to_section($forum->course, $mod->coursemodule, 0);
            }

            // Change the forum type to general.
            $forum->type = 'general';
            $DB->update_record('forum', $forum);

            $context = context_module::instance($cmid);

            // Create overrides for default student and guest roles (prevent).
            foreach ($studentroles as $studentrole) {
                assign_capability('mod/forum:viewdiscussion', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:viewhiddentimedposts', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:replypost', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:rate', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:createattachment', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:deleteownpost', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:deleteanypost', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:splitdiscussions', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:movediscussions', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:editanypost', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:viewqandawithoutposting', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:viewsubscribers', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:managesubscriptions', CAP_PREVENT, $studentrole->id, $context->id);
                assign_capability('mod/forum:postwithoutthrottling', CAP_PREVENT, $studentrole->id, $context->id);
            }
            foreach ($guestroles as $guestrole) {
                assign_capability('mod/forum:viewdiscussion', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:viewhiddentimedposts', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:replypost', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:viewrating', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:rate', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:createattachment', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:deleteownpost', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:deleteanypost', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:splitdiscussions', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:movediscussions', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:editanypost', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:viewqandawithoutposting', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:viewsubscribers', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:managesubscriptions', CAP_PREVENT, $guestrole->id, $context->id);
                assign_capability('mod/forum:postwithoutthrottling', CAP_PREVENT, $guestrole->id, $context->id);
            }
        }
    } else {
        // Non-teacher forum.

        if (empty($cmid)) {
            // We were not given the course_module id. Try to find it.
            if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
                echo $OUTPUT->notification('Could not get the course module for the forum');
                return false;
            } else {
                $cmid = $cm->id;
            }
        }
        $context = context_module::instance($cmid);

        // $forum->open defines what students can do:
        //   0 = No discussions, no replies
        //   1 = No discussions, but replies are allowed
        //   2 = Discussions and replies are allowed
        switch ($forum->open) {
            case 0:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id);
                    assign_capability('mod/forum:replypost', CAP_PREVENT, $studentrole->id, $context->id);
                }
                break;
            case 1:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id);
                    assign_capability('mod/forum:replypost', CAP_ALLOW, $studentrole->id, $context->id);
                }
                break;
            case 2:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:startdiscussion', CAP_ALLOW, $studentrole->id, $context->id);
                    assign_capability('mod/forum:replypost', CAP_ALLOW, $studentrole->id, $context->id);
                }
                break;
        }

        // $forum->assessed defines whether forum rating is turned
        // on (1 or 2) and who can rate posts:
        //   1 = Everyone can rate posts
        //   2 = Only teachers can rate posts
        switch ($forum->assessed) {
            case 1:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:rate', CAP_ALLOW, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('mod/forum:rate', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
            case 2:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:rate', CAP_PREVENT, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('mod/forum:rate', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
        }

        // $forum->assesspublic defines whether students can see
        // everybody's ratings:
        //   0 = Students can only see their own ratings
        //   1 = Students can see everyone's ratings
        switch ($forum->assesspublic) {
            case 0:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
            case 1:
                foreach ($studentroles as $studentrole) {
                    assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
        }

        if (empty($cm)) {
            $cm = $DB->get_record('course_modules', array('id' => $cmid));
        }

        // $cm->groupmode:
        // 0 - No groups
        // 1 - Separate groups
        // 2 - Visible groups
        switch ($cm->groupmode) {
            case 0:
                break;
            case 1:
                foreach ($studentroles as $studentrole) {
                    assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
            case 2:
                foreach ($studentroles as $studentrole) {
                    assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
                }
                foreach ($teacherroles as $teacherrole) {
                    assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
                }
                break;
        }
    }
    return true;
}
Пример #30
0
/**
 * Add course module.
 *
 * The function does not check user capabilities.
 * The function creates course module, module instance, add the module to the correct section.
 * It also trigger common action that need to be done after adding/updating a module.
 *
 * @param object $moduleinfo the moudle data
 * @param object $course the course of the module
 * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance()
 * @return object the updated module info
 */
function add_moduleinfo($moduleinfo, $course, $mform = null)
{
    global $DB, $CFG;
    // Attempt to include module library before we make any changes to DB.
    include_modulelib($moduleinfo->modulename);
    $moduleinfo->course = $course->id;
    $moduleinfo = set_moduleinfo_defaults($moduleinfo);
    if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) {
        $moduleinfo->groupmode = 0;
        // Do not set groupmode.
    }
    // First add course_module record because we need the context.
    $newcm = new stdClass();
    $newcm->course = $course->id;
    $newcm->module = $moduleinfo->module;
    $newcm->instance = 0;
    // Not known yet, will be updated later (this is similar to restore code).
    $newcm->visible = $moduleinfo->visible;
    $newcm->visibleold = $moduleinfo->visible;
    if (isset($moduleinfo->cmidnumber)) {
        $newcm->idnumber = $moduleinfo->cmidnumber;
    }
    $newcm->groupmode = $moduleinfo->groupmode;
    $newcm->groupingid = $moduleinfo->groupingid;
    $completion = new completion_info($course);
    if ($completion->is_enabled()) {
        $newcm->completion = $moduleinfo->completion;
        $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber;
        $newcm->completionview = $moduleinfo->completionview;
        $newcm->completionexpected = $moduleinfo->completionexpected;
    }
    if (!empty($CFG->enableavailability)) {
        // This code is used both when submitting the form, which uses a long
        // name to avoid clashes, and by unit test code which uses the real
        // name in the table.
        $newcm->availability = null;
        if (property_exists($moduleinfo, 'availabilityconditionsjson')) {
            if ($moduleinfo->availabilityconditionsjson !== '') {
                $newcm->availability = $moduleinfo->availabilityconditionsjson;
            }
        } else {
            if (property_exists($moduleinfo, 'availability')) {
                $newcm->availability = $moduleinfo->availability;
            }
        }
    }
    if (isset($moduleinfo->showdescription)) {
        $newcm->showdescription = $moduleinfo->showdescription;
    } else {
        $newcm->showdescription = 0;
    }
    // From this point we make database changes, so start transaction.
    $transaction = $DB->start_delegated_transaction();
    if (!($moduleinfo->coursemodule = add_course_module($newcm))) {
        print_error('cannotaddcoursemodule');
    }
    if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) && isset($moduleinfo->introeditor)) {
        $introeditor = $moduleinfo->introeditor;
        unset($moduleinfo->introeditor);
        $moduleinfo->intro = $introeditor['text'];
        $moduleinfo->introformat = $introeditor['format'];
    }
    $addinstancefunction = $moduleinfo->modulename . "_add_instance";
    try {
        $returnfromfunc = $addinstancefunction($moduleinfo, $mform);
    } catch (moodle_exception $e) {
        $returnfromfunc = $e;
    }
    if (!$returnfromfunc or !is_number($returnfromfunc)) {
        // Undo everything we can. This is not necessary for databases which
        // support transactions, but improves consistency for other databases.
        $modcontext = context_module::instance($moduleinfo->coursemodule);
        context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule);
        $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule));
        if ($e instanceof moodle_exception) {
            throw $e;
        } else {
            if (!is_number($returnfromfunc)) {
                print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section));
            } else {
                print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename);
            }
        }
    }
    $moduleinfo->instance = $returnfromfunc;
    $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule));
    // Update embedded links and save files.
    $modcontext = context_module::instance($moduleinfo->coursemodule);
    if (!empty($introeditor)) {
        $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']);
        $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance));
    }
    // Course_modules and course_sections each contain a reference to each other.
    // So we have to update one of them twice.
    $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section);
    // Trigger event based on the action we did.
    // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it.
    $eventdata = clone $moduleinfo;
    $eventdata->modname = $eventdata->modulename;
    $eventdata->id = $eventdata->coursemodule;
    $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext);
    $event->trigger();
    $moduleinfo = edit_module_post_actions($moduleinfo, $course);
    $transaction->allow_commit();
    return $moduleinfo;
}